/**
 * jValue jQuery plugin
 * Author: Sitnikov Ihor
 * based from
 * ------------------------------------------------------
 * jVal - dynamic jquery form field validation framework
 *      version 0.1.5
 * Author: Jim Palmer
 * Released under MIT license
 */
$(document).ready(function(){
    var strReplace = function( obj, options ) {
        if( typeof options == 'undefined' )
            eval('var options = ' + $(obj).attr('jValue') + ';');
        var str = '';
        $.map($(obj).val().split(""), function(n, i){
            if(n.match(options.valid)) str = str + n;
        });
        $(obj).val(str);
    }
    var keyFunc = function (e) {
        eval('var options = ' + $(this).attr('jValue') + ';');
        var ek = (typeof(e.keyCode) != 'undefined'),
            ec = (typeof(e.charCode) != 'undefined'),
            k = e.keyCode,
            c = e.charCode,
            ks = k.toString();
        // return if invalid regex
        if ( !(options.valid instanceof RegExp) )
            return false;
        // test for ENTER key and cF being valid function otherwise return true
        if ( /^13$/.test(String(k || c)) ) {
            try {(this[cF]) ? this[cF](cA) : eval(cF);} catch(e) {return true;}
            return false;
        }
        // otherwise test for valid keys supported by the regex allowing meta keys by default
        if ( e.ctrlKey || 
             e.shiftKey ||
             e.metaKey ||
             ( ek && k > 0 && options.valid.test(String.fromCharCode(k)) ) ||
             ( ec && c > 0 && String.fromCharCode(c).search(options.valid) != (-1) ) ||
             ( ec && c != k && ek && ks.search(/^(8|9|45|46|35|36|37|39)$/) != (-1) ) ||
             ( ec && c == k &&
               ek && ks.search(/^(8|9)$/) != (-1) ||
               ( !ec && ek && ks.search(/^(8|9|45|46|35|36|37|39)$/) != (-1) )
             )
        ) {
            strReplace(this, options);
            return true;
        } else {
            return false;
        }
    }
    $('[jValue]').bind('keypress keyup', keyFunc).bind('blur', function(e){
        eval('var options = ' + $(this).attr('jValue') + ';');
        $(this).val($.trim($(this).val()));
        if(typeof options.validValue != 'undefined' && (options.validValue instanceof RegExp) ) {
            if( !$(this).val().match(options.validValue) ) {
                if( typeof options.validMessage != 'undefined' ) {
                    alert(options.validMessage);
                } else if ( typeof options.validFn != 'undefined' && $.isFunction(options.validFn) ) {
                    options.validFn();
                }
            }
        }
    }).bind(($.browser.msie ? 'paste' : 'input'), function(){
        var that = this;
        setTimeout(function(){
            strReplace(that);
        }, 5);
    });
});
