/*!
 * jQuery Reginx Form Validate
 * http://reginx.com
 *
 * Copyright 2012,reginx
 */
(function($){
    $.fn.rvf = function(opts){
        // rule
        var patrn = {
            'uid'       : /^[A-Za-z0-9]{1}[A-Za-z0-9_\-]+$/i,
            'int'       : /^\d+$/,
            'number'    : /^\d*?(\.+)?$/,
            'date'      : /^\d{4}\-\d{1,2}\-\d{1,2}$/,
            'price'     : /^\d+(\.\d{1,2})?$/,
            'require'   : /^.+$/,
            'email'     : /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/i,
            'phone'     : /^\+?(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/,
            'mobile'    : /^\+?(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/,
            'english'   : /^[A-Za-z]+$/i,
            'url'       : /^((https|http)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
            'cuname'    : /^[\u4E00-\u9FA5\uF900-\uFA2D-a-zA-Z0-9]+$/
        };

        // config 
        opts = jQuery.extend({
            'submitId'   : 'submitBtn',
            'className'  : '.req',
            'vCallBack'  : function(){return true;},
            'dCallBack'  : function(){return true;}
        },opts);
        
        var cForm  = $(this);
        var isExec = false;
        window.isPass = true;
        
        cForm.find(opts.className).bind('blur',function(){
            var ret = vData(this);
            $('#' + $(this).attr('msgid')).removeClass('rvfErr').html('').hide();
            if(!ret.code){
                window.isPass = false;
                $('#' + $(this).attr('msgid')).show().html(ret.msg);
                $('#' + $(this).attr('msgid')).addClass('rvfErr').show();
            }else{
                window.isPass = window.isPass && true;
            }
        });
        
        cForm.find(opts.className).bind('focus',function(){
            cForm.find(".rvfErr").removeClass("rvfErr").html('').hide();
            if($(this).val() == '' && $(this).attr('notmust') == undefined){
                if($(this).attr('msgid') != undefined){
                    $('#' + $(this).attr('msgid')).removeClass('rvfErr').html($(this).attr("nullmsg")).show();
                }
            }
        });

        $('#' + opts.submitId).bind('click',function(event){
            window.isPass = true;
            event.stopPropagation();
            cForm.find(opts.className).trigger('blur');
            if(window.isPass || cForm.find(opts.className).length == 0){
                if(opts.vCallBack()){
                    cForm.get(0).submit();
                    opts.dCallBack();
                }
            }
        });

        function vData(obj){
            var msg  = $(obj).attr('errmsg');
            var code = false;
            if($(obj).val() == '' && $(obj).attr('notmust') != undefined){
                code = true;
            } else if($(obj).val() != '' && $(obj).attr('rule') != undefined && $(obj).attr('rule') != ''){
                // regular
                var regu = null;
                if($(obj).attr('rule') != undefined && $(obj).attr('rule') != null){
                    if(patrn[$(obj).attr('rule')] != undefined){
                        regu = patrn[$(obj).attr('rule')];
                    }else{
                        regu = new RegExp($(obj).attr('rule'));
                    }
                }else{
                    regu = /.*/;
                }
                if(regu.exec($(obj).val())){
                    if(vMinLen(obj) && vMaxLen(obj)){
                        if($(obj).attr('ajaxUrl') != undefined && $(obj).attr('ajaxUrl') != ''){
                            var ret = {code:'1',msg:'服务器繁忙!'};
                            $.ajax({
                                type     : "POST",
                                url      : $(obj).attr('ajaxUrl'),
                                data     : $(obj).attr('id') + "=" + $(obj).val(),
                                dataType : "json",
                                async    : false,
                                success  : function(d){
                                    ret = d;
                                }
                            });
                            if(ret.code != '0'){
                                code = false;
                                msg = ret.msg;
                            }else{
                                code = true;
                                msg = ret.msg;
                            }
                        }else{
                            code = true;
                        }
                    }
                }
            }else{
                code = false;
                msg  = $(obj).attr('nullmsg');
            }
            return {code:code , msg: msg};
        }

        
        // Max Length
        function vMaxLen(obj){
            if($(obj).attr('maxlimit') != undefined && $(obj).attr('maxlimit') != ''){
                var len = $(obj).attr('wlen') != undefined ? parseInt(strlen($(obj).val())) : parseInt($(obj).val().length);
                if(len > parseInt($(obj).attr('maxlimit'))){
                    return false;
                }
            }
            return true;
        }
         
        // Min Length 
        function vMinLen(obj){
            if($(obj).attr('minlimit') != undefined && $(obj).attr('minlimit') != ''){
                var len = $(obj).attr('wlen') != undefined ? parseInt(strlen($(obj).val())) : parseInt($(obj).val().length);
                if(len < parseInt($(obj).attr('minlimit'))){
                    return false;
                }
            }
            return true;
        }
        
        function strlen(str) {
            var clen = 0;
            var wlen = 0;
            for(var i = 0; i < str.length; i++) {
                clen += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? 1 : 0;
                wlen += str.charCodeAt(i) > 0 && str.charCodeAt(i) < 255 ? 0.5 : 0;
            }
            return (wlen+clen) % 1 == 0 ? (wlen + clen):(wlen + clen + 0.5);
        }

    };
})(jQuery);