﻿// IDs of any forms that will be validated
var formIDs = ["addNoteForm", "cardForm", "contactForm", "contactUsForm", "createAccountForm", "myAccountInfoForm", "resetPasswordForm", "memberStoryForm", "addMemberForm", "editAdminForm", "addAdjustmentForm", "couponEntryForm", "couponValidationForm", "quickAccountCreationForm", "frmCardEntry", "loginForm", "osbnOrderForm", "profileBuilderForm", "frmImageDialog", "frmContactDialog", "frmProfileDialog", "frmRewardDialog"];

var isReadyToValidateLocally = false;

// Map error message fragments to their associated input fields
var errorMessageMap = {
    "Please enter your first name.": "FirstName",
    "Please enter your last name.": "LastName",
    "Please enter a valid 5-digit zip code.": "PostalCode",
    "Please enter a city.": "City",
    "Please enter a state.": "StateOrProvince",
    "Please enter your mailing address.": "Address1",
    "Please enter your Postal code.": "PostalCode",
    "Current password is incorrect": "OldPassword",
    "email": "EmailAddress",
    "encountered": "EmailAddress",
    "Please enter your answer to the security question": "SecurityAnswer",
    "enter your security answer": "SecurityAnswer",
    "enter your current password": "OldPassword",
    "security check you entered": "captcha",
    "characters long. Please check the number": "Number",  // partner card number length invalid
    "Please enter only numbers": "Number",
    "The number you've entered is invalid": "Number",
    "entered has already been registered with Override": "Number",
    "Email address is already in use": "EmailAddress",
    "Override Card Number that": "Number",
    "Override Card Numbers that": "NumberConfirm",
    "Security question change was unsuccessful. Please enter password": "Password",
    "You have reached the limit on the number of Override cards that can be linked to a single account.": "Number",
    "You have already registered this Promotional Override Card!": "Number",
    "The Override Card Number that you entered has already been registered. Please try again.": "Number",
    "Please enter the first 11 digits of your Shaw's Rewards Card.": "Number",
    "Please enter the 11 digits of your Shaw's Rewards number, as shown.": "Number",
    "Please enter your Shaw's Rewards Card number.": "Number",
    "Please enter your Coupon Code.": "CouponCode",
    "The reward activation code entered does not exist.": "CouponCode",
    "This reward has already been activated, and cannot be activated again.": "CouponCode",
    "Could not register the Coupon: it may have already been registered.": "CouponCode",
    "That number is already in use": "Number",
    "Cannot add your Shaw's Card: it may already exist, or it may be invalid.  Please contact customer support at 1-800-447-0013.": "FirstName",
    "Cannot register your Coupon: it may already have been registered.  Please contact customer support at 1-800-447-0013.": "FirstName",
    "The Coupon Number that you entered has already been registered.": "CouponCode",
    "This partner number could not be found.  Please check the number and try again.  Or, give us a call at 1-866-774-7975 for help.": "Number",
    "The member already exists!": "EmailAddress",
    "Please use this format: xxx-xxx-xxxx.": "MobilePhone",
    "The promotional program for this coupon has expired.": "CouponCode",
    "Fax number must be in the format: xxx-xxx-xxxx.": "Fax",
    "Phone number must be in the format: xxx-xxx-xxxx.": "Phone"
};

jQuery(function($) {
    // Keep track of the last element to have focus
    var lastFocusEl;

    // Figure out the ID of the form for which we'll be setting up validation
    var currentForm;
    for (var i = 0; i < formIDs.length; i++) {
        if ($("#" + formIDs[i]).length > 0) {
            currentForm = formIDs[i];
            break;
        }
    }

    // Set up form validator options
    $("#" + currentForm).validate({
        errorPlacement: function(error, element) {
            if (element.is(":checkbox")) {
                // Define special placement for the terms agreement checkbox error
                error.insertAfter("#termsLabel");
            } else {
                error.insertAfter(element);
            }

            // Wrap error label in a container for styling purposes
            error.wrap("<div class=\"errorContainer\"></div>");

            /* This is a very hacky IE6 fix. If you research the IE6 selectbox z-index bug
            you will find that an iframe is the only element that will allow appear over a select box
            in IE6. This will dynamically place an iframe between the error box and the input/select.
            it then finds the size of the corresponding error box, sizes the iframe to the exact size 
            of the error box, and places the errorbox over the iframe.
            THIS IS VERY HACKY, BUT ONLY OCCURS IN IE6 - I DO BELIEVE THIS TO BE A PRETTY
            GOOD METHOD CONSIDERING THE OBSTICLE */

            if ($.browser.msie && $.browser.version < 7) {
                error.parent().prepend('<iframe src="javascript:false;" tabindex="-1"></iframe>');
                $('.errorContainer iframe').each(function() {
                    var errorHeight = error[0].offsetHeight;
                    error.parent().find('iframe').height(errorHeight);
                });
                $("input, select, textarea").focus(function() {
                    if ($(this).hasClass('error')) {
                        error.parent().find('iframe').css('visibility', 'hidden');
                        $(this).parent().find('iframe').css('visibility', 'visible');
                    }

                    setInterval(function() {
                        var errorHeight = error[0].offsetHeight;
                        error.parent().find('iframe').height(errorHeight);
                    }, 100);

                });
            } /* END ie6 HACK */
        },
        focusInvalid: true,
        invalidHandler: function(form, validator) {
            IsPostAllowed = true;
        }
    });

    $("input, select, textarea").blur(function() {
        // Only handle blur events if we're ready to validate, or if we're not IE6.
        if (isReadyToValidateLocally || !$.browser.msie || $.browser.version >= 7) {
            var errorLabel; // Error label element

            /*+++
            if ($(this).hasClass("error")) {
            $("label.error").hide(); // Hide all other errors

                errorLabel = $(this).parent().find("div.errorContainer").find("label.error")[0];
            if (errorLabel != undefined) {
            $(errorLabel).show();
            }
            }
            */
        }
    });

    // Display error message callout if focus is given to a field that contains an error
    $("input, select, textarea").focus(function() {
        // Only handle focus events if we're ready to validate, or if we're not IE6.
        if (isReadyToValidateLocally || !$.browser.msie || $.browser.version >= 7) {
            var errorLabel; // Error label element

            /*+++
            if ($(this).hasClass("error")) {
            $("label.error").hide(); // Hide all other errors

                errorLabel = $(this).parent().find("div.errorContainer").find("label.error")[0];
            if (errorLabel != undefined) {
            $(errorLabel).show();
            }
            }
            */
        }
    });

    // Hide errors until window is completely loaded
    $(".errorContainer").hide();

    // Create callouts for server validation errors.
    bindServerErrors(errorMessageMap);
});

$(window).load(function() {
    // Now that window is completely loaded, show the errors
    $(".errorContainer").show();

    try {
        // Find and give focus to the first input that has an error label next to it
        var firstErrorInput = $("input.error:first")[0];

        if (firstErrorInput != undefined && $(firstErrorInput)) {
            // Use the setTimeout and force no focus/blur handling to
            // prevent the server message from being lost in IE6.
            if ($.browser.msie && $.browser.version < 7) {
                setTimeout(function() { isReadyToValidateLocally = false; firstErrorInput.focus(); isReadyToValidateLocally = true; }, 0);
            }
            else {
                // If not IE6, just give it focus: the other browsers are more well behaved.
                firstErrorInput.focus();
            }
        }
    }
    catch (exception) {

    }

    // Get rid of the server validation error list, unless there are still errors in the list
    // that weren't able to be associated with an input
    if ($(".field-validation-error ul li").length == 0) {
        $("div.field-validation-error").remove();
    } else {
        // Error list is styled as hidden to start of with, so unhide it
        $("div.field-validation-error").show();
    }
});

function bindServerErrors(errMap) {
    // Pluck individual error messages from server validation error list and insert each into the
    // node containing the error's associated input field
    $(".field-validation-error ul li").each(function () {
        var errMsg = $(this).text();
        var errFormId = undefined;
        var errKey;
        
        for (errKey in errMap) {
            if (errMsg.indexOf(errKey) > -1) {
                errFormId = errMap[errKey];
                break;
            }
        }
        
        if (errFormId != undefined) {  
            // Create clientside validation rule that basically states
            $("#" + errFormId).rules("add", {
                notEqualToValue: $("#" + errFormId).val(),
                messages: { notEqualToValue: "<span></span>" + errMsg }
		    });
            
            // remove error from server validation error list
            $(this).remove();
            
            // run validator on this input
            $("#" + errFormId).valid()
        }
    });
}

