﻿if (typeof (ILP)) {
    ILP.validation = {
        activate: function () {
            $.validator.setDefaults(ILP.validation.defaults);
            // extend validator with popup integration
            $.extend($.validator.prototype, ILP.validation.extensions);
            $.validator.methods.range = function (value, element, param) { //TEMP: override range method to allow autonumeric
                var $el = $(element);
                if ($el.is($.fn.autoNumeric.defaults.className))
                    value = $.fn.autoNumeric.Strip($el.attr('id'));
                return this.optional(element) || (value >= param[0] && value <= param[1]);
            }
        },
        defaults: {
            onfocusin: function (element) {
                // default behavior
                this.elementHasFocus = true;
                this.lastActive = element;
                // hide error label and remove error class on focus if enabled
                if (this.settings.focusCleanup && !this.blockFocusCleanup) {
                    this.settings.unhighlight && this.settings.unhighlight.call(this, element, this.settings.errorClass, this.settings.validClass);
                    this.errorsFor(element).hide();
                }
                // popup behavior
                // if this element is invallid show popup
                //if (this.invalidElements().filter(element).length > 0) {
                if ($(element).hasClass(this.settings.errorClass))
                    this.showPopup(element);
            },
            onfocusout: function (element) {
                // default behavior
                this.elementHasFocus = false;
                if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
                    this.element(element);
                }
                // popup behavior
                var firstError = $("." + this.settings.errorClass + ":first").attr('id');
                if (firstError == element.id)
                    this.showPopup(element);
                else
                    this.hidePopup(element);
            },

            highlight: function (element, errorClass, validClass) {
                // popup behavior
                // if the highlighting element is last active, and invalid, show popup
                if (this.elementHasFocus && this.lastActive && (this.lastActive == element))
                    this.showPopup(element);
                // default behavior
                // add error class
                $(element).addClass(errorClass).removeClass(validClass);
            },
            unhighlight: function (element, errorClass, validClass) {
                // popup behavior
                // when the element is valid, hide popup
                this.hidePopup(element);
                // default behavior
                $(element).removeClass(errorClass).addClass(validClass);
            },
            errorPlacement: function (error, element) {
                /*var errorId = 'span#' + element.attr('id') + '_Validation';
                if (element.parent().find(errorId).length) {
                // Remove any server-side validation messages, duplicating errors is confusing for the user.
                element.parent().find(errorId).remove();
                }*/
            } // override mvc jquery error placement.
        },
        extensions: {
            hasPopup: function (element) {
                return $('.' + $(element).attr('id') + 'formError').length > 0;
            },
            showPopup: function (element) {
                element = this.clean(element);
                //debugger;
                var errorMsg = this.errorMap[element.name] || this.invalid[element.name];

                if (!errorMsg || errorMsg === true) {
                    errorMsg = this.submitted[element.name];
                    //$(element).focus()
                    //return false; //this.showPopup(element);
                }
                if (!this.hasPopup(element))
                    $.validationEngine.buildPrompt(element, errorMsg, "error");
                else {
                    // modified validation engine source because of a performance
                    // issue in this file. See comments in validationEngine.js
                    $.validationEngine.updatePromptText(element, errorMsg);
                    //$('.' + (element.name || element[0].name) + 'formError .formErrorContent').html(errorMsg);
                }
            },
            hidePopup: function (element) {
                var $element = $(element);
                if (this.hasPopup(element)) {
                    $.validationEngine.closePrompt(element);
                }
                else if ($element.is(':radio') && $('div.formError').length > 0) { // radio hack. pull id's by rdo's group name, and hide all linked callouts
                    var radioSelector = '';
                    var name = $element.attr('name');
                    $("input[name='" + name + "']").each(function () {
                        radioSelector += '.' + $.validationEngine.linkTofield(this) + ', ';
                    });
                    var callouts = $(radioSelector);
                    if (callouts.length > 0)
                        $(radioSelector).fadeTo("fast", 0, function () {
                            $(radioSelector).remove();
                        });
                }
            },
            hideAllPopups: function () {
                $.validationEngine.closePrompt(".formError", true);
            },
            focusInvalid: function () { // OVERRIDE default focusInvalid
                if (this.settings.focusInvalid) {

                    try {
                        var $el = $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible");
                        if ($el.length > 0) {
                            var validator = this;
                            //this.settings.onfocusin.call(this, $el[0]);
                            var targetOffset = Math.abs($el.offset().top - 75);
                            var win = $('html,body');
                            var winScrollTop = win[0].scrollTop || win[1].scrollTop;
                            // use difference to calculate animation speed: 
                            // EX: 2ms per pixel is (difference * 2).
                            var difference = Math.abs(winScrollTop - targetOffset);
                            var difWithMultiplier = (difference * 2);
                            //ILP.util.log('targetOffset: %s\nwinScrollTop: %s\ndifference: %s', targetOffset, winScrollTop, difference);
                            win.animate({ scrollTop: targetOffset }, difWithMultiplier > 1000 ? 1000 : difWithMultiplier, function () {
                                validator.settings.onfocusin.call(validator, $el.focus()) /*$el.focus();*/
                            });
                        }
                        //$el.focus();
                    } catch (e) {
                        // ignore IE throwing errors when focusing hidden elements
                    }
                }
            }
        }
    }
}
