﻿(function($) {
    $.fn.attachValidator = function(settings) {
        settings = $.extend({
            erriconclass: 'erricon',
            okiconclass: 'okicon',
            noiconclass: 'noicon',
            errmsgclass: 'errmsg',
            errmsgokclass: 'infomsg',
            okfieldclass: 'okfield',
            errfieldclass: 'errfield',
            actfieldclass: 'actfield',
            container: '<div class="fleft" id="vf_{2}"><div class="fleft"></div><div class="fleft vficon {1}"></div><div class="fleft vfmsg txtSmaller txtGray {0}"></div></div>',
            defaulterrmsg: '',
            defaultValue: '',
            defaultValueOverlay: '',
            customvalidator: null,
            root: null
        }, settings);
        
        if (this.get(0).jValSettings !== undefined) {
            alert('already attached');
            return;
        }

        return this.each(function() {
            var me = $(this);
            this.jValSettings = settings;
            var id = me.attr('id');
            //me.addClass('fleft');
            var s = jQuery.format(settings.container, settings.errmsgokclass, settings.noiconclass, id);
            if (settings.root != null)
                settings.root.wrap(s);
            else
                me.wrap(s);
            //find container
            this.jValContainer = $('#vf_' + id);
            //attach act handler                  
            if (settings.defaulterrmsg) {
                var msg = this.jValContainer.find(".vfmsg");
                msg.text(settings.defaulterrmsg);
            }
            me.activeOnFocus({ okfieldclass: settings.okfieldclass, errfieldclass: settings.errfieldclass, actfieldclass: settings.actfieldclass });
            //me.defaultOverlay({ defaultValue: settings.defaultValue, defaultValueOverlay: settings.defaultValueOverlay });
        });
    };    

    $.fn.activeOnFocus = function(settings) {
        settings = $.extend({
            okfieldclass: 'okfield',
            errfieldclass: 'errfield',
            actfieldclass: 'actfield'
        }, settings);

        return this.each(function() {
            var me = $(this);
            me.focus(function() {
                if (me.hasClass(settings.okfieldclass) || me.hasClass(settings.errfieldclass))
                    return;
                me.addClass(settings.actfieldclass);
            });
            me.blur(function() {
                if (me.val().length == 0 && settings.defaultValue != undefined && settings.defaultValue.length > 0) {
                    df.show();
                }
                me.removeClass(settings.actfieldclass);
            });
        });
    }

    $.fn.validatedOk = function() {
        setvalid(this, true, this[0].jValSettings.defaulterrmsg, this[0].jValSettings, this[0].jValContainer);
    }

    $.fn.validatedError = function(text) {
        setvalid(this, false, text, this[0].jValSettings, this[0].jValContainer);
    }

    $.fn.customValidator = function(val, el, params) {
        var settings = el[0].jValSettings;
        if (settings.customvalidator !== null)
            return settings.customvalidator(el, val, params);
        else
            return true;
    }

    var setvalid = function (me, valid, text, settings, container) {
        //mark edit element
        me.removeClass(settings.actfieldclass);
        me.removeClass(valid ? settings.errfieldclass : settings.okfieldclass);
        me.addClass(valid ? settings.okfieldclass : settings.errfieldclass);
        //find message        
        var msg = container.find(".vfmsg");
        msg.removeClass(settings.errmsgclass + ' ' + settings.errmsgokclass);
        msg.addClass(valid ? settings.errmsgokclass : settings.errmsgclass);
        msg.text(text);
        var label = container.find(".vficon");
        label.removeClass(valid ? settings.erriconclass : settings.okiconclass);
        label.removeClass(settings.noiconclass);
        label.addClass(valid ? settings.okiconclass : settings.erriconclass);
    }

})(jQuery);

//custom rules
$.validator.addMethod('nicknamerx', function(value, element) {
    return this.optional(element) || /^[\f\n\r\x20-_a-~¡£¥§¿ÄÅÆÇÉÑÖØÜßàäåæèéìñòöøùü¤€ΔΦΓΛΩΠΨΣΘΞęąśłżźćńĘĄŚŁŻŹŃóÓćĆ]+$/.test(value); //\węąśłżźćńĘĄŚŁŻŹŃóÓ \[\\\^\$\.\|\?\*\+\(\)
});

$.validator.addMethod('custom', function(value, element, params) {
    var jelement = $(element);
    return jelement.customValidator(value, jelement, params);
});
$.validator.addMethod('equals', function(value, element, params) {
    return this.optional(element) || value === params;
});

$.validator.phoneValidators = {
    '48s': /^[5678]\d{8}$/,
    '48': function(value) {
        return $.validator.phoneValidators['48s'].test(value);
    }    
}

$.validator.addMethod('phone', function(value, element, params) {
    var cc = '48';
    var f = $.validator.phoneValidators[cc];
    if (f === undefined)
        return false;
    else
        return this.optional(element) || f(value);
});

function installValidator(fname, vcarray, settings, onpostabckclb) {
    var form = $('#' + fname);
    if ($.data(form[0], 'dopostback') == undefined && typeof __doPostBack !== 'undefined')
        $.data(form[0], 'dopostback', __doPostBack)


    var valobj = null;

    if (form.hasvalidator()) {
        form.clearvalidator();
        $.validator.removeMethod('trigger');
    }

    var valobj = form.validate(settings);

    var chkform = function() {
        //alert('checking form');
        return valobj.form();
    }

    __doPostBack = function(t, a) {
        if ($.inArray(t, vcarray) >= 0)
            if (!chkform())
            return;
        if (onpostabckclb !== undefined)
            if (!onpostabckclb())
            return;
        $.data(form[0], 'dopostback')(t, a);
    }

    return valobj;
}

(function($) {

    $.fn.filterInput = function(regex, pulseon, required) {
        $.data(this, 'firegex', regex);
        $.data(this, 'fipval', this.val());
        var ispulse = pulseon;
        var isrequired = required === undefined ? true : required;
        var that = this;
        var p = null;

        function validate() {
            var regex = $.data(that, 'firegex');
            var s = that.val();
            if (s.length == 0 && isrequired)
                return true;
            if (regex.test(s)) {
                $.data(that, 'fipval', s);
                return true;
            }
            else {
                that.val($.data(that, 'fipval'));
                if (ispulse)
                    pulse(that, true);
            }
        };

        function pulse(el, again) {
            if (p) {
                window.clearTimeout(p);
                p = null;
            };
            el.animate({ opacity: 0.1 }, 100, function() {
                $(this).animate({ opacity: 1.0 }, 100);
            });
            if (again) {
                p = window.setTimeout(function() { pulse(el) }, 200);
            };
        };

        return this.each(function() {
            $(this)

				.bind("keyup", function() { validate(); })
				.bind("focus", function() { validate(); })
				.bind("paste", function() {
				    setTimeout(function() { validate(); }, 10);
				});
            if (this.addEventListener) {
                this.addEventListener('input', function() { validate(); }, false);
            };
        });
    };

    $.fn.filterInputChangeFilter = function(regex) {
        $.data(this, 'firegex', regex);
        var s = this.value();
        if (!regex.test(s)) {
            $.data(this, 'fipval', '');
            this.value('');
        }
    }

})(jQuery);
