var secondFormValidation = false;

$(document).ready(function() {

    // at the page load, disable all form submit buttons
    // that depend on cbox-general-conditions checkbox
    $('.submit').not('.submit-custom').each(function() {
        var formName = $(this).metadata().form;
        //(window.console && window.console.log('enable/disable control', formName, this, $('.' + formName + ' .cbox-general-conditions')));
        if (formName && $('.' + formName + ' .cbox-general-conditions').size() > 0) {
            $(this).addClass('disabled');
        }
    });

    // create a handler for cbox-general-conditions checkbox that
    // controls the state (enabled/disabled) of the form submit buttons
    $('input.cbox-general-conditions:checkbox, .cbox-general-conditions input:checkbox').click(function() {
        var formName = '';
        if ($(this).hasClass('cbox-general-conditions')) {
            formName = $(this).metadata().form;
        } else {
            formName = $(this).parents('.cbox-general-conditions').metadata().form;
        }
        var submitButton = $('.' + formName + ' .submit');

        if (this.checked) {
            submitButton.removeClass('disabled');
        } else {
            submitButton.addClass('disabled');
        }
    });

    // prevent form submit by clicking on the cancel button in case
    // an appropriate email input field is empty
    $('.button.cancel, .button-close').each(function() {
        var logicalForm = $(this).parents('.logical-form');
        var email = $(this).metadata().cancelCheckCtrl;
        var emailRegex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
        if (email) {
            $(this).bind('click', function(e) {
                var emailVal = $('input[name$=' + email + ']', logicalForm).val();
                if (!emailRegex.test(emailVal)) {
                    e.preventDefault();
                    return false;
                }
            });
        }
    });

    // there can be only one, well, validator per page
    // global validationRules and validationMessages have to be defined previously
    // each logical form has to trigger validation explicitelly
    // example:
    //
    //		$('.subform1 a.submit').click(function() {
    //			var validator = $('form').validate();
    //			validator.settings.ignore = ":not('.subform1 *')";
    //			var isValid = validator.form();
    //		});
    $('#aspnetForm').validate({

        debug: false,

        rules: validationRules,

        messages: validationMessages,

        onsubmit: false,

        onkeyup: false,

        errorContainer: $('.box_error'),

        errorElement: 'em',

        errorPlacement: function(error, element) {

            if (!element.parents('.formfield').length && element.is(':radio'))
                error.prependTo(element.parents('dl:first')).
					wrap('<div class="formfield level-1 alert"></div>'); // make generic
            else
                error.prependTo(element.parents('.formfield').addClass('alert'));

        },

        showErrors: function(errorMap, errorList) {

            this.defaultShowErrors();

            $('.formfield em:empty, .formfield em:hidden').remove();

            $('.formfield').each(function() {
                if (!$(this).find('em').length)
                    $(this).removeClass('alert');
            });

            if (!$('.formfield em').length)
                $('.box_error').hide();

        },

        logErrors: function(errorMap) {
            setTimeout(function() {
                $.each(errorMap, function(key, value) {
                    // send call to omniture
                    var s = s_gi(s_account);
                    s.linkTrackVars = 'prop11';
                    s.prop11 = value.substring(0, 100);
                    s.tl(true, 'o', 'notification');
                });
            }, 1);
        }


    });

    var formSubmitted = false;
    $('.submit').not('.submit-custom, .custom-submit').mousedown(function(e) {
        (window.console && window.console.log('form submit mousedown'));
        formSubmitted = false;

        try {
            var $t = $(this);

            if ($t.hasClass('disabled')) {
                e.preventDefault();
                return false;
            }

            var validator = $('#aspnetForm').validate();
            //(window.console && window.console.log('validator2', $t, ":not('." + $t.metadata().form + " *')", validator));

            validator.settings.ignore = ":not('." + $t.metadata().form + " *')";
            var isValid = validator.form();
            //(window.console && window.console.log('submit ', ":not('." + $t.metadata().form + " *')", $("." + $t.metadata().form + " input"),'isValid:', isValid));

            // trigger validation again in order to show errors created by remote rules
            window.secondFormValidation = true;
            var isValid = validator.form();
            window.secondFormValidation = false;
            (window.console && window.console.log('isValid', isValid));

            if (!isValid) {
                e.preventDefault();
                return false;
            }

            formSubmitted = true;
            if ($(this).attr('href')) {
                window.location = $(this).attr('href');
            }

        } catch (err) {
            (window.console && window.console.log('isValid', isValid));
            alert(err);
            e.preventDefault();

            return false;
        }
    }).click(function(e) {
        (window.console && window.console.log('form submit click'));
        if (formSubmitted === true) {
            formSubmitted = false;
        } else {
            e.preventDefault();
            return false;
        }
    });

    // within M52 two logical form are combined. this is a logic that switch validation rules
    // for those two forms
    function switchRule(on, rule, rules) {
        if (on) {
            if (rules[rule + '_off']) {
                rules[rule] = rules[rule + '_off'];
                delete rules[rule + '_off'];
            }
        } else {
            if (rules[rule]) {
                rules[rule + '_off'] = rules[rule];
                delete rules[rule];
            }
        }
    }

    function switchOnM52RegisterForm() {
        var validator = $('#aspnetForm').validate();
        var rules = validator.settings.rules;

        resetValidationErrors();

        $('input[name$=tboxM52LoginEmail], input[name$=tboxM52LoginEmailPassword]').val('');
        switchRule(true, 'tboxM52RegisterEmail', rules);
        switchRule(true, 'tboxM52RegisterPassword', rules);
        switchRule(true, 'tboxM52RegisterConfirmPassword', rules);
        switchRule(false, 'tboxM52LoginEmail', rules);
        switchRule(false, 'tboxM52LoginEmailPassword', rules);
    }

    function switchOnM52LoginForm() {
        var validator = $('#aspnetForm').validate();
        var rules = validator.settings.rules;

        resetValidationErrors();

        $('input[name$=tboxM52RegisterEmail], input[name$=tboxM52RegisterPassword], input[name$=tboxM52RegisterConfirmPassword]').val('');
        switchRule(false, 'tboxM52RegisterEmail', rules);
        switchRule(false, 'tboxM52RegisterPassword', rules);
        switchRule(false, 'tboxM52RegisterConfirmPassword', rules);
        switchRule(true, 'tboxM52LoginEmail', rules);
        switchRule(true, 'tboxM52LoginEmailPassword', rules);
    }

    var m52RegisterForm = true;
    switchOnM52RegisterForm();

    $('input[name$=tboxM52LoginEmail], input[name$=tboxM52LoginEmailPassword]').focus(function(e) {
        if (m52RegisterForm) {
            m52RegisterForm = false;
            switchOnM52LoginForm();
			// clear the M46 email address 1
			$('input[name$=tboxM46EmailAddress1]').val('');
        }
    });

    $('input[name$=tboxM52RegisterEmail], input[name$=tboxM52RegisterPassword], input[name$=tboxM52RegisterConfirmPassword]').focus(function(e) {
        if (!m52RegisterForm) {
            m52RegisterForm = true;
            switchOnM52RegisterForm();
			// clear the M46 email address 1
			$('input[name$=tboxM46EmailAddress1]').val('');
        }
    });

    /* Issue #22017 - no prevention of TAB key should be in place; TabIndex should be used instead
    $('input[name$=tboxM52RegisterConfirmPassword]').bind('keydown', function(e) {
    if (e.keyCode == 9 && !e.shiftKey) {
    return false;
    }
    });
    */
});

function validateLogicalForm() {
		var $t = $(this);

		var validator = $('#aspnetForm').validate();
		
		validator.settings.ignore = ":not('." + $t.metadata().form + " *')";
		var isValid = validator.form();
		
		// trigger validation again in order to show errors created by remote rules
		var isValid = validator.form();
		(window.console && window.console.log('isValid', isValid));
		
		return isValid;
}
	
function resetValidationErrors() {
		var validator = $('#aspnetForm').validate();
		validator.reset.call(validator);
		validator.toHide = validator.toHide.add(validator.settings.errorElement);
		validator.invalid = {};
		validator.lastActive = null;
		validator.lastElement = null;
		validator.showErrors.call(validator);
}
