
__Register_Config = window.__Register_Config || null; //验证配置 帐号、密码重输密码必须要有
var WN_Register = (function(){
    var cache = {};
    
    var accAjax = new $.scriptLoader("http://register1.woniu.com/ws/register.do", {
        "method": "validatePassport",
        "jsoncallback": "WN_Register.accBack"
    }).extra({
        $onSuccessed: function(para){
            //			debugger;
            try {
                WN_OFFCIAL_ANALYSIS.countAccVerifyBack();
            } 
            catch (e) {
            }
            
            if (para) {
                this.result = para;
            }
            
            para = para || this.result;
            var acc = getCache("account");
            
            if (para["result"].toUpperCase() == "Y") {
                acc.pass = true;
                acc.check();
            }
            else {
                var ret = "该帐号已被其他用户使用，请重新选择";
                
                acc.pass = ret;
                acc.check();
            }
            
        }
    });
    
    var _defTip = document.createElement("div");
    
    function getCache(nm){
        return cache[nm];
    }
    
    return {
        get: getCache,
        getAccAjax: function(){
            return accAjax;
        },
        accBack: function(dt){
            accAjax.$onSuccessed(dt);
        },
        //		getNickAjax : function() {
        //			return nickAjax;
        //		},
        regFun: function(hand, fun){
            if (window.attachEvent) {
                hand.attachEvent("on" + hand, fun);
            }
            else {
                hand.addEventListener(hand, fun, false);
            }
        },
        submit: function(){
            //提交按钮禁用
            $.log("pass all");
        },
        Item: function(_key, _ipt, _tip){
            this.childs = [];
            
            this.key = _key;
            this.ipt = typeof(_ipt) == "string" ? $(_ipt) : _ipt;
            
            this.tip = (_ipt && typeof(_tip) == "string") ? $(_tip) : (_tip || _defTip);
            if (this.tip) {
                this.tip.def = WN_Register.Tips[_key] || "......"; //this.tip.innerHTML; //默认提示
            }
            
            this.pass = undefined; //undefined 未检测过； true 通过； false(错误信息)； null 检测中...
            cache[_key] = this;
            
            if (this.ipt) {
                this.bindEvent();
            }
            
            if (!_key) {
                this.$onFailed = this.$onCheck = function(){ //保证有未通过的验证时，重新开始验证	//顶层元素要保证每次验证后将pass复位
                    this.pass = undefined;
                };
                this.isTop = true; //顶层
            }
        }
    }
})();

WN_Register.Item.prototype = {
    extra: function(o){
        for (var i in o) {
            this[i] = o[i];
        }
        return this;
    },
    add: function(_item){
        if (_item instanceof (WN_Register.Item)) {
            this.childs.push(_item);
        }
        return this;
    },
    get: function(nm){
        nm = nm || "ipt";
        return this.ipt;
    },
    syncVerify: function(){
        var childs = this.childs;
        for (var i in childs) {
            var ret = childs[i].check();
            if (ret !== true) {
                //				this.$onFailed(ret);	//ret中带有错误提示ret.des
                return undefined;
            }
        }
        
        //		this.$onSuccessed();
        
        return ret || true;
        //		return {index:i, ret : ret};
    },
    check: function(){
        //		var ret = this.pass||this.$verify();	//ret == undefined 用于异步验证 并且优先用于 pass 标示
        //debugger
        var ret;
        if (this.pass === undefined) {
            ret = this.$verify();
        }
        else {
            ret = this.pass;
        }
        
        this.pass = ret; //typeof ret=="string" ? false : ret;		//true|false(错误信息)|undefined|null
        this.pass === true ? this.$onSuccessed() : (this.pass === false || typeof this.pass == "string" ? this.$onFailed(ret) : this.$onCheck());
        return ret;
    },
    /**
     * 待复写的验证函数
     */
    $verify: function(_callBack){
        //		if (!this.isTop) {
        throw new Error("未实现");
        //		}
    },
    $onSuccessed: function(){
        //		this.tip.innerHTML = this.ipt.value.length?"&nbsp;":"";	//"√";	//非必填项不要出√
        //		FT.show(this.tip.def, this.ipt);
        this.tip.className = "reg_chkMsg reg_chkMsg_Suc";
        if (this.isTop) {
            this.pass = undefined;
        }
        $.log(this.ipt.id, this.pass);
        if (this.$cbSucc) {
            this.$cbSucc();
        }
    },
    $onFailed: function(_r){
        //		this.tip.innerHTML = _r||"x";
        var ipt = this.ipt;
        //		if (ipt.value.length) {
        if (WN_Register._tmr) {
            clearTimeout(WN_Register._tmr);
            WN_Register._tmr = null;
        };
        WN_Register._tmr = setTimeout(function(){
            FT.show(_r, ipt);
            ipt.select();
        }, 200);
        //		}
        this.tip.className = "reg_chkMsg reg_chkMsg_Fai";
        this.doBlink();
        //		var me = this;
        
        //		this.ipt.select();
        $.log(this.ipt.id, this.pass);
        if (this.$cbFail) {
            this.$cbFail();
        }
    },
    $onCheck: function(){
        this.pass = null; //on checking
        //		this.tip.innerHTML = "检测中...";	//"√";
        this.tip.className = "commonRegTcTs";
        $.log(this.ipt.id, this.pass);
        if (this.$cbCheck) {
            this.$cbCheck();
        }
    },
    $tip: function(str){
        if (this.tip) {
            this.tip.style.display = "";
        }
        //		var _str = this.tip.def || str;
        //		this.tip.innerHTML = _str;
        //		
        //		this.tip.className = "commonRegTcTs";
        //		this.tip.blurTip = this.pass;	
        //		if (this.pass===undefined) {		//如果尚未验证过
        
        //		if (typeof this.pass != "string") { //防止验证失败的提示被覆盖
        var _str = "";
        if (typeof this.pass == "string") {
            _str = this.pass;
        }
        else {
            _str = (this.tip && this.tip.def) || str;
        }
        var ipt = this.ipt;
        setTimeout(function(){
            FT.show(_str, ipt);
        }, 200);
        
        //		}
        //			this.tip.innerHTML = _str;			
        //		} else {
        //			
        //		}	
    },
    /**
     * 绑定提示事件
     */
    bindEvent: function(){
        var me = this;
        if (!this.ipt) 
            return;
        //		this.ipt.verify = this.$verify;
        this.ipt.onfocus = function(){
            me.$tip();
        }; /*this.___focusTip;*/
        var tag = this.ipt.type.toLowerCase();
        if (tag == "checkbox" || tag == "radio") {
            this.ipt.onclick = function(){
                me.pass = undefined;
                me.check();//??
            };
        }
        else {
            this.ipt.onchange = function(){
                me.pass = undefined;
                me.check();
            };
        } /*this.___changeVerify;*/
        if (this.blurFun) {
            this.ipt.onblur = this.blurFun.bind(this);
        }
        
        if (this.tip) {
            this.tip.style.display = "none";
        }
        
        return this;
    },
    /**
     * 输入容器闪烁
     */
    doBlink: function(){
        //		WN_Register.gameOptTips(this.ipt);
    }
};



$.extra({
    init: function(){
        this.initForm();
        
        this.loadVerifyImg();
    },
    getParas: function(){
        //		debugger
        //		var basic = $.$("#ipt{account password spreadName verify}").vals();
        //		var extra = $.$("#ipt{email nickName realName identity}").vals();
        //		var sex = $("ipt.sex_1").checked ? "1" : "0";
        //		var all = $.extra(basic, extra, true);
        //		all.sex = sex;
        //		return basic;
    },
    initForm: function(){
        this.ctrls = {};
        var account = new WN_Register.Item("account", "ipt.account", "tip.account").extra({
            $verify: function(){
                var val = this.ipt.value;
                var flag = Reg_Verify.account(val);
                if (flag == true) {
                    try {
                        WN_OFFCIAL_ANALYSIS.countAccVerify();
                    } 
                    catch (e) {
                    }
                    
                    WN_Register.getAccAjax().ask({
                        account: val,
                        userName: val
                    });
                }
                else {
                    return flag;
                }
            }
        });
        this.ctrls.account = account;
        var password = new WN_Register.Item("password", "ipt.password", "tip.password").extra({
            $verify: function(){
                var rv = $("ipt.rpwd").value;
                var v = this.ipt.value;
                if (rv.length && v != rv) { //如果确认密码填写后 修改了密码，验证之前的确认密码
                    WN_Register.get("rpwd").pass = undefined;
                    WN_Register.get("rpwd").check();
                }
                return Reg_Verify.password(v, $("ipt.account").value, rv);
            },
            blurFun: function(){
                if (this.pass == true) {
                    this.pass = undefined;
                    this.check();
                }
            }
        }).bindEvent();
        this.ctrls.password = password;
        
        
        
        var rpwd = new WN_Register.Item("rpwd", "ipt.rpwd", "tip.rpwd").extra({
            $verify: function(){
                return Reg_Verify.rpwd(this.ipt.value, $("ipt.password").value);
            },
            $cbFail: function(){
                this.pass = undefined;
            },
            blurFun: function(){
                if (this.pass == true) {
                    this.pass = undefined;
                    this.check();
                }
            }
        }).bindEvent();
        this.ctrls.rpwd = rpwd;
        var realname = new WN_Register.Item("realname", "ipt.realname", "tip.realname").extra({
            $verify: function(){
                return Reg_Verify.realname(this.ipt.value);
            }
        }).bindEvent();
        this.ctrls.realname = realname;
        
        var identity = new WN_Register.Item("identity", "ipt.identity", "tip.identity").extra({
            $verify: function(){
                return Reg_Verify.identity(this.ipt.value);
            }
        }).bindEvent();
        this.ctrls.identity = identity;
        //---------------------------------------
        var verify = new WN_Register.Item("verify", "ipt.verify", "tip.verify").extra({
            $verify: function(){
                return Reg_Verify.verify(this.ipt.value);
            },
            $cbSucc: function(){ //验证码不提示√
                this.tip.className = "reg_chkMsg";
            }
        });
        this.ctrls.verify = verify;
        
        var email = new WN_Register.Item("email", "ipt.email", "tip.email").extra({
            $verify: function(){
                return Reg_Verify.email(this.ipt.value);
            },
            $cbSucc: function(){
                this.tip.className = "reg_chkMsg";
            }
        });
        this.ctrls.email = email;
        
        var agree = new WN_Register.Item("agree", "ipt.agree", "tip.agree").extra({
            $verify: function(){
                return this.ipt.checked ? true : "请选择接受协议";
            },
            $cbSucc: function(){ //不提示√
                this.tip.className = "reg_chkMsg";
            }
        });
        this.ctrls.agree = agree;
        
        var form = new WN_Register.Item().extra({
            $verify: function(){
                return this.syncVerify();
            },
            $onSuccessed: function(){
                $.log("pass all");
                return true;
                //				var postVars = WN_Register.getParas();
                //				var extraVars = WN_Register.getExtraParas();
                //				$.extra(extraVars, postVars);
                //				WN_Register.getRegAjax().asyncAsk(postVars);
                this.pass = undefined; //复位标示*imp
            }
        });
        this.ctrls.form = form;
        
        if (!__Register_Config) {
            form.add(account).add(password).add(rpwd)/*.add(verify)*/.add(realname).add(identity)/*.add(email)*/.add(agree);
        }
        else {
            for (var i in __Register_Config) {
                var cfg = this.ctrls[__Register_Config[i]];
                form.add(cfg);
            }
        }
        
    },
    
    loadVerifyImg: function(){
        var verifyImg = $("reg.verifyImg");
        if (!verifyImg) {
            return
        }
        if (!WN_Register.verifySrc) {
            WN_Register.verifySrc = verifyImg.src;
        }
        
        if (!verifyImg.onclick) {
            var verifyLink = $("reg.verifyLink");
            verifyImg.onclick = function(){
                var _baseSrc = WN_Register.verifySrc || 'http://act.woniu.com/reg/php/checkpic.php';
                var src = _baseSrc + "?t=" + new Date().getTime();
                setTimeout(function(){
                    verifyImg.src = src;
                }, 50);
                //				this.style.backgroundImage = 'url(0)'.replace('0',src);				
            };
            verifyLink.onclick = function(){
                verifyImg.onclick();
            }
        };
        
        verifyImg.onclick();
    },
    check: function(){
        var _ret = this.ctrls.form.check();
        try {
            WN_OFFCIAL_ANALYSIS.countRegister();
        } 
        catch (e) {
        }
        
        return _ret || false;
    }
    
}, WN_Register);


WN_Register.Tips = {
    "account": "长度为6～25位，必须由字母（不区分大小写）、数字或下划线组成，或直接使用邮箱进行注册",
    "password": "密码由6-20个字符组成，建议使用英文字母加数字的组合密码",
    "rpwd": "请再次输入密码",
    "realname": "请如实填写您的真实姓名和身份证号，如果填写有误将会被纳入防沉迷体系，影响您正常体验游戏。",
    "identity": "真实姓名和身份证号将作为判断帐号归属的最终标准，如果填写有误，遇到帐号丢失等问题，可能将无法为您提供服务。",
    "email": "取回密码的重要途径",
    "verify": "请输入验证码"

};


Reg_Verify = {
    trim: function(s){
        return (s || "").replace(/^\s+|\s+$/, "");
    },
    account: function(v, tp){
        v = this.trim(v);
        tp = this.trim(tp);
        var ret;
        
        //通用验证方法
        if (!v) {
            return "请输入帐号"
        }
        
        if (v.length < 6) {
            return "帐号至少为6位，由英文、数字或下划线组成"
        }
        
        //common帐号验证方法(之前还区分邮箱帐号和手机帐号)
        
        if (/^\d+$/.test(v)) {
            return "帐号不能全为数字"
        }
        
        if (v.length > 25) {
            return "帐号不能多于25个字符"
        }
        
        if (/^woniu/i.test(v)) {
            return "帐号不能以'woniu'开头"
        }
        
        if (/^snail/i.test(v)) {
            return "帐号不能以'snail'开头"
        }
        
        if (/^gm/i.test(v)) {
            return "帐号不能以'gm'开头"
        }
        
        if (/^d1xn/i.test(v)) {
            return "帐号不能以'd1xn'开头"
        }
        
        if (/^dixn/i.test(v)) {
            return "帐号不能以'dixn'开头"
        }
        
        if (/^dlxn/i.test(v)) {
            return "帐号不能以'dlxn'开头"
        }
        
        if (/^dyxn/i.test(v)) {
            return "帐号不能以'dyxn'开头"
        }
        
        if (!(/^\w{6,25}$/.test(v) || /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(v))) {
            return "帐号只能是英文、数字、下划线的组合（不能为全角字符）或有效电子邮箱"
        }
        
        return true;
        
    },
    
    password: function(v, acc, rv){
        //		v = this.trim(v);
        acc = this.trim(acc);
        if (!v) {
            return "请输入密码"
        }
        
        if (v == acc) {
            return "帐号和密码不能相同"
        }
        
        if (v.length < 6) {
            return "密码至少为6位"
        }
        
        if (v.length > 20) {
            return "密码不能多于20个字符"
        }
        
        if (!/^[0-9a-zA-Z]{6,20}$/.test(v)) {
            return "密码只能使用英文（区分大小写）和数字"
        }
        
        if (/^(\w)\1*$/.test(v)) {
            return "密码不能是完全相同的字母或数字"
        }
        
        for (var i = 1, c = [v.charCodeAt(0)], cd = [v.charCodeAt(0)], cu = [v.charCodeAt(0)]; i < v.length; i += 1) {
            cd[i] = cd[i - 1] - 1;
            cu[i] = cu[i - 1] + 1;
            c[i] = v.charCodeAt(i);
        }
        c = c.join(":");
        if (c == cd.join(":") || c == cu.join(":")) {
            return "你不能使用该密码，非常容易被猜测！"
        }
        
        //		if(rv.length && v!=rv) {
        //			return '';
        //		}
        
        return true;
        
    },
    rpwd: function(a, b){
        if (!a) {
            return "请输入确认密码";
        }
        
        if (a != b) {
            return '两次密码输入不一致';
        }
        
        return true;
    },
    //////////////////////////////////////////////////////////////////
    realname: function(v){
        var V = this.trim(v);
        if (!V) {
            return "请输入您的真实姓名";
        }
        if (!/^[\u4E00-\u9FA5]{2,}$/.test(V)) {
            return "真实姓名为2～5位的中文字符";
        }
        return true;
    },
    
    identity: function(v){
        var V = this.trim(v);
        if (!V) {
            return "请输入身份证号码";
        }
        if (!validateIdentity(V)) {
            return "您输入的身份证格式不正确";
        }
        return true;
    },
    /////////////////////////////////////////////////////////////
    verify: function(v){
        if (!v) {
            return "请输入验证码";
        }
        
        if (!/^[0-9a-zA-Z]{4}$/.test(v)) {
            return "验证码格式不正确";
        }
        
        return true;
    },
    email: function(v){
        var v = this.trim(v);
        if (!v) {
            return true
        }
        
        if (!v) {
            return "请输入您的电子邮箱";
        }
        
        if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(v) || v.length < 6 || v.length > 25) {
            return "邮箱格式不正确，请确认后重新输入";
        }
        
        return true;
    },
    mobile: function(v){
        v = this.trim(v);
        if (!v) { //可不填			
            return true;
        }
        else 
            if (!/^(13[0-9]|15[0|3|6|7|8|9]|18[8|9])\d{8}$/.test(v) || v.length < 6 || v.length > 25) {
                return "您的手机号格式不正确，请重新填写";
            }
        
        return true;
    }
};


$.extra({
    FloatTip: function(offset){
        this.tipDom = $.CNs(["div", {
            className: "reg_chkMsgLay",
            style: {
                display: "none"
            }
        }, [["p", {
            className: "reg_descIcon"
        }], ["div", {
            ref: "Ctt",
            innerHTML: "...",
            className: "reg_chkDesc"
        }]]]);
        document.body.appendChild(this.tipDom);
        
        this.diff = offset ||
        {
            x: 0,
            y: 0
        };
        
        try {
            document.body.attachEvent("onclick", function(){
                FT.hide();
            })
        } 
        catch (e) {
            document.body.addEventListener("click", function(){
                FT.hide();
            }, false)
        }
    }
}, WN_Register);

WN_Register.FloatTip.prototype = {
    show: function(str, dom){
        //get pos
        var pos = $(dom, "getCoord");
        this.tipDom.refs.Ctt.innerHTML = str;
        this.tipDom.style.left = pos.left + this.diff.x + "px";
        this.tipDom.style.top = pos.top + this.diff.y + "px";
        this.tipDom.style.display = "";
    },
    hide: function(){
        this.tipDom.style.display = "none";
    }
};

!function(){
    FT = new WN_Register.FloatTip({
        x: 185,
        y: -10
    });
    var fromUrl = $.getQuery("fromurl") || $.getQuery("fromUrl");
    if (fromUrl) {
        $("Reg.fromUrl").value = fromUrl;
    }
    WN_Register.init();
    
    var counter = new Image();
    //	var games = document.domain.split(".");	//取域名
    var game = $("Reg.game").value; //games.length>3 ? games[1] : game;
    var pagename = $("Reg.pagename").value;
    var reffer = encodeURIComponent(document.referrer || "");
    counter.src = "http://act.woniu.com/reg/php/fangwen.php?game=" + game + "&pagename=" + pagename + "&fromurl=" + fromUrl + "&reffer=" + reffer;
    
    try {
        if (WN_Register.get("account").ipt.getAttribute("noFocus")) {
            setTimeout(function(){
                WN_Register.get("account").ipt.focus();
            }, 500);
        }
        
    } 
    catch (e) {
    }
}();

//http://act.woniu.com/reg/php/fangwen.php?game=tz&pagename=reg2010.2.3&fromurl=client.1.1



function validateIdentity(value){
    // 提取日期和校验的正则表达式
    var ReDate15 = /\d{6}(\d{6})\d{3}/;
    var ReDate18 = /\d{6}(\d{8})\d{3}/;
    // 验证各位字符是否合法的正则表达式
    var ReDigital15 = /\d{15}/;
    var ReDigital18 = /\d{17}[0-9xX]{1}/;
    
    switch (value.length) {
        case 15:
            // 特殊处理
            if (value == "111111111111111") {
                return false;
            }
            if (ReDigital15.test(value) == false) {
                return false;
            }
            Arr = ReDate15.exec(value);
            strDate = "19" + Arr[1];
            // 15位身份证号的日期范围(1900年-2000年)
            if (CheckDate(strDate, new Date(1900, 0, 1), new Date(1999, 11, 31)) == false) {
                return false;
            }
            break;
            
        case 18:
            if (ReDigital18.test(value) == false) {
                return false;
            }
            Arr = ReDate18.exec(value);
            strDate = Arr[1];
            // 18位身份证号的日期范围(1900年-至今)
            if (CheckDate(strDate, new Date(1900, 0, 1), new Date()) == false) {
                return false;
            }
            if (CheckSum(value) == false) {
                return false;
            }
            break;
        case 0:
            return false;
            break;
            
        default:
            return false;
            break;
    }
    
    return true;
    
}

function CheckDate(strDate, DateFrom, DateTo){
    // 手动日期验证正则表达式
    ReDigital8 = /\d{8}/;
    // 自动日期验证正则表达式
    ReAutoDate = /\d{4}-{1}\d{1,2}-\d{1,2}/;
    // 自动日期提取正则表达式
    // ReGetDate = /(\d{4})-{1}(\d{1,2})-(\d{1,2})/;
    
    if (strDate.indexOf("-") > -1) {
        if (ReAutoDate.test(strDate) == false) 
            return false;
        Arr = strDate.split("-");
        strDate = (Arr[0]) + "" + (Arr[1].length < 2 ? "0" : "") + Arr[1] +
        (Arr[2].length < 2 ? "0" : "") +
        (Arr[2]);
    }
    
    if (strDate.length != 8) 
        return false;
    if (ReDigital8.test(strDate) == false) 
        return false;
    MyDate = eval(strDate.replace(/^(\d{4})(\d{2})(\d{2})$/, "new Date($1,$2-1,$3)"));
    strMyDate = MyDate.getFullYear() + (MyDate.getMonth() < 9 ? "0" : "") +
    (MyDate.getMonth() + 1) +
    "" +
    (MyDate.getDate() <= 9 ? "0" : "") +
    MyDate.getDate();
    // 日期有效性验证
    if (strMyDate != strDate) 
        return false;
    // 日期范围验证
    if (MyDate >= DateFrom && MyDate <= DateTo) 
        return true;
    else 
        return false;
}

function CheckSum(strID){
    // 18位数字提取正则表达式
    Re18Digital = /(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})([0-9xX]{1})/;
    Arr = Re18Digital.exec(strID);
    var Wi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    Sum = 0;
    for (i = 0; i <= 16; i++) 
        Sum += Arr[i + 1] * Wi[i];
    ArrCheckSum = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    strCheckSum = ArrCheckSum[Sum % 11];
    if (strCheckSum == Arr[18].toUpperCase()) 
        return true;
    else 
        return false;
}

