/// <reference path="Plugins/jquery-1.3.2-vsdoc.js" />
/*
20110223
Validation of  a new user 
*/

//check if text/string is empty

var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;


function validateText(ref) {

    if (ref.val()) {
        return true;
    }
    else {
        return false;
    }
}


//check if text/string is less then 6 characters
function validatePassword(ref) {

    if (ref.val().length < 6)
        return false;

    else
        return true;
}


//check if text/string is less then 6 characters
function validatePasswordExtended(ref) {

    if (ref.val().length < 6 || !/\d/.test(ref.val()))
        return false;

    else
        return true;
}



//check if text/string is less then 6 characters and its the same as password
function validatePasswordRepeat(ref) {

    if (ref.val().length > 5 && ref.val() == $('#Password').val())
        return true;
    else
        return false;
}

//check if text/string is less then 6 characters and its the same as password
function validatePasswordRepeatExtended(ref) {

    if (ref.val().length > 5 && /\d/.test(ref.val()))
        return true;
    else
        return false;
}




//check if email is empty or has a valid format
function validateEmail(ref) {


    //check if email is empty
    if (!ref.val()) {
        return false;
    }


    if (!reg.test(ref.val())) {
        return false;
    }

    return true;
}

//Show this view if input is ok
function okView(ref) {
    $(ref).parent().siblings('#' + ref.attr('id') + 'Mandatory').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Optional').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ServerError').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ClientError').hide()
    $(ref).parent().siblings('#' + ref.attr('id') + 'Error').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Ok').show();
    if (ref.attr('type') == "password")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputOkSmall');
    else if (ref.attr('type') == "textarea")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputOkArea');
    else {
        $(ref).parent('#' + ref.attr('id') + 'Box').removeClass().addClass('inputOk okBox');
        $(ref).parent().parent('#' + ref.attr('id') + 'Box').removeClass().addClass('inputOk okBox');
    }
}


//Show this view if input is clienterror duplicate
function errorViewClient(ref) {
    $(ref).parent().siblings('#' + ref.attr('id') + 'Mandatory').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Optional').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ServerError').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Error').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ClientError').show();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Ok').hide();
    if (ref.attr('type') == "password")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputErrorSmall');
    else if (ref.attr('type') == "textarea")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputErrorArea');
    else
        $(ref).parent('#' + ref.attr('id') + 'Box').removeClass().addClass('inputError errorBox');
}



//Show this view if input is required
function requiredView(ref) {
    $(ref).parent().siblings('#' + ref.attr('id') + 'Mandatory').show();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Optional').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ServerError').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Error').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Ok').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ClientError').hide();
    if (ref.attr('type') == "password")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputRequiredSmall');
    else if (ref.attr('type') == "textarea")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputRequiredArea');
    else {
        $(ref).parent('#' + ref.attr('id') + 'Box').removeClass().addClass('inputRequired');
    }
}

//Show this view if required input is missing
function errorView(ref) {
    $(ref).parent().siblings('#' + ref.attr('id') + 'Mandatory').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Optional').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ServerError').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Ok').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Error').show();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ClientError').hide();
    if (ref.attr('type') == "password")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputErrorSmall');
    else if (ref.attr('type') == "textarea")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputErrorArea');
    else
        $(ref).parent('#' + ref.attr('id') + 'Box').removeClass().addClass('inputError');
}

//Show this view if required input is mising after serverposting
function serverErrorView(ref) {
    $(ref).parent().siblings('#' + ref.attr('id') + 'Mandatory').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Optional').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Ok').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Error').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ServerError').show();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ClientError').hide();
    if (ref.attr('type') == "password")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputErrorSmall');
    else if (ref.attr('type') == "textarea")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputErrorArea');
    else
        $(ref).parent('#' + ref.attr('id') + 'Box').removeClass().addClass('inputError');
}

//Show this view if input is optional
function optionalView(ref) {    
    $(ref).parent().siblings('#' + ref.attr('id') + 'Mandatory').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ServerError').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Ok').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Error').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'ClientError').hide();
    $(ref).parent().siblings('#' + ref.attr('id') + 'Optional').show();
    if (ref.attr('type') == "password")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputOptionalSmall');
    else if (ref.attr('type') == "textarea")
        $('#' + ref.attr('id') + 'Box').removeClass().addClass('inputOptionalArea');
    else
        $(ref).parent('#' + ref.attr('id') + 'Box').removeClass().addClass('inputOptional');

}


//Validate input from textbox
function validateTextBox(ref) {
    $('#generalErrorClient').fadeOut('slow');

    //check if tag has a validationtype of string
    if (ref.is('.validationtype\\.text')) {


        if (validateText(ref)) {
            okView(ref);
        }

        else {
            errorView(ref);
        }
    }

    //check if tag has a validationtype of email
    if (ref.is('.validationtype\\.email')) {

        if (validateEmail(ref)) {
            okView(ref);
        }

        else {
            errorView(ref);
        }

    }

    //check if tag has a validationtype of password
    if (ref.is('.validationtype\\.password')) {

        if (validatePassword(ref)) {
            okView(ref);
        }

        else {
            errorView(ref);
        }

    }


    //check if tag has a validationtype of extended password
    if (ref.is('.validationtype\\.passwordExtended')) {

        if (validatePasswordExtended(ref)) {
            okView(ref);
        }

        else {
            errorView(ref);
        }

    }



    //check if tag has a validationtype of passwordRepeat
    if (ref.is('.validationtype\\.passwordRepeat')) {

        if (validatePasswordRepeat(ref)) {
            okView(ref);
        }

        else {
            errorView(ref);
        }

    }

    //check if tag has a validationtype of passwordRepeat
    if (ref.is('.validationtype\\.passwordRepeatExtended')) {

        if (validatePasswordRepeatExtended(ref)) {

            if (ref.val() == $('#NewPassword').val())
                okView(ref);
            else
                errorViewClient(ref);
        }

        else {
            errorView(ref);
        }

    }
}

$(function () {

    $('#generalErrorClient').hide();

    //unqiue fields for register catalogue start
    $('#ChooseCatalogueError').hide();

    //handler to verify if at least one catalogue is choosen from orderCatalogueview
    $("#orderCatalogueTable").click(function () {
        var isChoosen = false;
        $("#orderCatalogueTable input[type=checkbox]").each(function () {
            if ($(this).is(':checked'))
                isChoosen = true;
        }
);
        if (isChoosen) {
            $('#ChooseCatalogueError').hide();
            $('#ChooseCatalogueOk').show();
        }
        else {
            $('#ChooseCatalogueOk').hide();
            $('#ChooseCatalogueError').show();
        }

    });

    //enable email event for register catalogue
    $('#viewData_ReplyTo').keyup(function () {

        if (validateEmail($(this))) {
            okView($('#viewData_ReplyTo'));
        }
        else
            requiredView($('#viewData_ReplyTo'));
    });


    $('#ReplyTo').keyup(function () {

        if (validateEmail($(this))) {
            okView($('#ReplyTo'));
        }
        else
            requiredView($('#ReplyTo'));
    });

    //unqiue fields for register catalogue end


//    $('#email').keyup(function () {

//        if (validateEmail($(this))) {
//            okView($('#email'));
//        }
//        else
//            requiredView($('#email'));
//    });

    //enable email event for register customer
    $('#Email').keyup(function () {        
        if (validateEmail($(this))) {            
            $.post("/SelfRegister/VerifyEmails", { emailInput: $('#Email').val() }, function (data) {
                if (data.validatedAnswer == "1") {
                    errorViewClient($('#Email'));
                    $('#generalErrorClient').show();
                }
                else if (data.validatedAnswer == "0")
                    okView($('#Email'));
                $('#generalErrorClient').hide();
            });

        }
        else
            requiredView($('#Email'));


    });


    //show or hide panel DeliveryAdressPanel if checkbox hideDeliveryAddress is marked
    $('#DeliveryAdressPanel').hide();
    $('#hideDeliveryAddress').click(function () {

        if ($('#hideDeliveryAddress').is(':checked')) {

            $('#DeliveryAdressPanel').hide();

        }

        else {

            $('#DeliveryAdressPanel').show();
        }
    });

    $('#InvoiceAdressPanel').hide();
    $('#hideInvoiceAddress').click(function () {

        if ($('#hideInvoiceAddress').is(':checked')) {

            $('#InvoiceAdressPanel').hide();

        }

        else {

            $('#InvoiceAdressPanel').show();
        }
    });


    //initilize settings 
    $('.validationrule\\.required,.validationrule\\.optional').each(function () {


        //initilize serverErrorfields
        if ($(this).is('.validationrule\\.required.serverError')) {

            serverErrorView($(this));
        }

        //initilize required fields
        else if ($(this).is('.validationrule\\.required')) {
            requiredView($(this));
        }

        //initilize optional fields
        else if ($(this).is('.validationrule\\.optional')) {

            optionalView($(this));
        }
    });

    //attach eventhandler for required textbox/runtime
    $('input[type=text].validationrule\\.required,input[type=password].validationrule\\.required,textarea.validationrule\\.required').keyup(function (e) {


        //disable event for email-input
        if ($(this).attr('id') == "Email" || $(this).attr('id') == "viewData_ReplyTo" || $(this).attr('id') == "ReplyTo" || $(this).attr('id') == "email" || $(this).attr('id') == "viewData_ZipCode")
            return false;


        if ($('#InvoiceAddress_City_temp').length && ($(this).attr('id') == "InvoiceAddress_PostalCode" || $(this).attr('id') == "DeliveryAddress_PostalCode"))
            return false;

        if ($('#PostAddress_City_temp').length && $(this).attr('id') == "PostAddress_PostalCode")
            return false;

        if ($('#City_temp').length && $(this).attr('id') == "PostalCode")
            return false;


        if (!(e.keyCode == 9 && !$(this).val()))
            validateTextBox($(this));
    }
    );

    var emailtext = $("#Email").val();
    if (typeof (emailtext) != 'undefined' && emailtext.length > 0) {
        if (validateEmail($("#Email"))) {
            okView($('#Email'));
        }
        else
            requiredView($('#Email'));
    }


    if ($('#registerNewsletterButton').length > 0) {
        $('#registerNewsletterButton').bind('click', ValidateOnSubmit);
    }

    if ($('.submitCustomer').length > 0) {
        $('form').bind('submit', ValidateOnSubmit);
    }



    if ($('.SendCatalogue').length > 0)
        $('.SendCatalogue #submitSend').bind('click', ValidateOnSubmit);


    if ($('#contactUsSubmit').length > 0)
        $('#contactUsSubmit #submitSend').bind('click', ValidateOnSubmit);



    //$('#submitAddUser').live('click', ValidateOnSubmitThickBox);

    $('#SubmitDeliveryAdd').live('click', ValidateOnSubmitThickBox);

    //$('#EditUser').live('click', ValidateOnSubmitThickBox);



    $('#SubmitEditPassword').live('click', ValidateOnSubmitThickBox);

    /*
    $('#OldPassword').bind('keyup', function(e) {

    if ($('#OldPassword').val().length > 5) {
    //börja tester
            

    errorView($('#OldPassword'));
    }

    });

    */

    //Validate required fields before posting thickboxes
    function ValidateOnSubmitThickBox() {

        var noErrors = true;
        /*
        if ($('#SubmitEditPassword').length > 0) {
          

            

        }
        */
        if ($('#SubmitDeliveryAdd').length > 0) {

            $('.validationrule\\.required').each(function () {

                if ($(this).is('.validationtype\\.text')) {
                    if (!validateText($(this)))
                        noErrors = false;
                }

            });


        }
        if (!noErrors) {

            $('#generalErrorClient').show();
            return false;
        }
    }

    //Validate required fields before posting
    function ValidateOnSubmit() {

        //disable validation for globalsearch
        if ($(this).attr('id') == "searchForm")
            return true;

        var noErrors = true;

        if ($('#Email').val() && reg.test($('#Email').val())) {
            $.post("/SelfRegister/VerifyEmails", { emailInput: $('#Email').val() }, function (data) {
                if (data.validatedAnswer == "1") {
                    noErrors = false;
                }

            });
        }


        //Validate every input that is marked as validationrule.required
        $('.validationrule\\.required').each(function () {


            if ($('#hideDeliveryAddress').is(':checked'))
                if ($("#DeliveryAdressPanel").find("#" + $(this).attr("id")).length > 0)
                    return false;

            if ($('#hideInvoiceAddress').is(':checked'))
                if ($("#InvoiceAdressPanel").find("#" + $(this).attr("id")).length > 0)
                    return false;


            if ($(this).is('.validationtype\\.text')) {
                if (!validateText($(this)))
                    noErrors = false;
            }

            else if ($(this).is('.validationtype\\.email')) {
                if (!validateEmail($(this)))
                    noErrors = false;
            }

            else if ($(this).is('.validationtype\\.password')) {
                if (!validatePassword($(this)))
                    noErrors = false;
            }

            else if ($(this).is('.validationtype\\.passwordRepeat')) {
                if (!validatePasswordRepeat($(this)))
                    noErrors = false;
            }

        });

        if ($('.SendCatalogue').length > 0) {
            //unqiue field from orderCatalogue when submitted  start 
            var isChoosen = false;
            $("#orderCatalogueTable input[type=checkbox]").each(function () {
                if ($(this).is(':checked'))
                    isChoosen = true;
            }
);
            if (!isChoosen)
                noErrors = false;

            if (!$('#viewData_ReplyTo').val() || !reg.test($('#viewData_ReplyTo').val())) {
                noErrors = false;
            }
            //unqiue field from orderCatalogue when submitted end
        }


        if ($('#contactUsSubmit').length > 0) {

            if (!$('#ReplyTo').val() || !reg.test($('#ReplyTo').val())) {
                noErrors = false;
            }

        }

        //disable submit if there is some errors in validation
        if (!noErrors) {

            if ($('#contactUsSubmit').length > 0)
                $('html, body').animate({ scrollTop: 1400 }, 'slow');

            else
                $('html, body').animate({ scrollTop: 300 }, 'slow');
            $('#generalErrorClient').show();
            return false;
        }

    };

});


function resultAddUserContentLoad(isAjax, context, element) {
    if (isAjax) {
        var data = ParseValidateJson(context, "resultAddUserContent");

        var emailErrors = eval(data.EmailMessage);

        if (emailErrors[0] == "1") {
            errorViewClient($('#Email'));
        }
        else if (emailErrors[0] == "2") {
            errorView($('#Email'));
        }
    }
}


function resultEditUserContentLoad(isAjax, context, element) {

    if (isAjax) {
        var data = ParseValidateJson(context, "resultEditUserContent");
        if (data.Email == "1") {
            errorViewClient($('#Email'));
        }
        else if (data.Email == "2") {
            errorView($('#Email'));
        }
    }
}



function resultAddDeliveryAdressContentLoad(isAjax, context, element) {

    if (isAjax) {
        var data = ParseValidateJson(context, "resultAddDeliveryAdressContent");

        if (data.City == "1")
            errorViewClient($('#City'));

        if (data.Street == "1")
            errorViewClient($('#Street'));

        if (data.PostalCode == "1")
            errorViewClient($('#PostalCode'));
    }

}

function resultEditDeliveryAdressContentLoad(isAjax, context, element) {

    $('.validationrule\\.required').each(function() {
        if ($(this).is('.validationtype\\.text')) {
            if (validateText($(this)))
                okView($(this));
            else
                errorView($(this));
        }

    });

    if (isAjax) {
        var data = ParseValidateJson(context, "resultEditDeliveryAdressContent");

        if (data.City == "1") {
            errorViewClient($('#City'));
        }
        if (data.Street == "1") {
            errorViewClient($('#Street'));
        }
        if (data.PostalCode == "1") {
            errorViewClient($('#PostalCode'));
        }
    }
}


function resultEditPasswordContentLoad(isAjax, context, element) {
    if (isAjax) {
        var data = ParseValidateJson(context, "resultEditDeliveryAdressContent");
        if (data.PasswordValidationMessage == "3") {
            errorViewClient($('#OldPassword'));
        }
    }
}

function ParseValidateJson(context, element) {

    var data;

    if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
        data = JSON.parse(context.text());
    else
        data = eval('(' + context.text() + ')');

    var frame = GetQueryStringValue("frame");

    if (data.Status == "Ok" || data.Status == "Error")
        $('#' + element).hide();

    if (data.Status == "Ok") {

        if (frame == "edit") {
            parent.location.reload(1); // = "/Checkout/EditShippingAddress";
            return data;
        }
        else if ($(".address-add").size() > 0) {
            self.location.reload(1); // = "/Checkout/EditShippingAddress";
            return data;
        }
        else {
            $('#generalErrorClient').fadeOut('slow');
            parent.location.reload(1);
        }
        if ($(".address-search").size() == 0) {
            parent.location.reload(1);
        }
        else {
            window.location.reload(1);
        }
    }
    else {
        $('#generalErrorClient').fadeIn('slow');
    }
    return data;
}

