/**
 * @author ANTZ
 */

function reloadCode(){
function $(id){
return window.document.getElementById(id);
}

var obj = $("verifyImg");
obj.id = "";
var img = window.document.createElement("img");
img.src = "http://vip.sina.com.cn/cgi-bin/createcode.php?t=" + new Date().getTime();
img.id = "verifyImg";
img.width = "72";
img.height = "24";
obj.parentNode.replaceChild(img, obj);

img = null;
obj = null;
}

var BASE_URL = {
    verifyCodeURL: "http://vip.sina.com.cn/cgi-bin/createcode.php",
	submitURL:"http://vip.sina.com.cn/register/simreg_vipmail.php",
	submitSuccessURL:"http://pay.mail.sina.com.cn/cgi/login.php?from=promote",
	checkMailURL : "http://vip.sina.com.cn/register/check_user.php"
	//checkMailURL: "http://test.sina.com.cn/RIAShare/zhangpeng/regMail/login.php"
};
var PID = {
	form : "regForm",
	mail:"mail",
	password:"password",
	passwordAgagin : "passwordAgain",
	question:"question",
	customQuestion:"customQuestion",
	answer : "answer",
	showTip : "showTip",
	changeVerifyImg : "changeVerifyImg",
	verifyImg : "verifyImg",
	verify : "verify",
	agreement : "agreement",
	checkMailBtn:"checkMailBtn",
	submit : "submit"
};

function RegMail(){}

RegMail.sucessInfo = {
	mail : "",
	password : "",
	passwordAgain : "两次输入的密码一致",
	answer : "已输入密码查询答案。",
	question : "已选择密码查询问题。",
	customQuestion : "已输入密码查询问题",
	verify : ""
};

RegMail.tipInfo = {
	mail : "",
	password : "密码：6—16位字符（包括6、16），限用英文、数字、半角“.”、“-”、“?”和下划线，区分大小写。建议您使用字母数字和字符的组合",
	passwordAgain : "请再输一遍密码。",
	answer : "密码查询答案：6个字符（或3个汉字）以上，限用字母、数字、汉字、空格（空格不能在首尾）",
	verify : "请输入验证码",
	customQuestion : "密码查询问题：4-32个字母（支持大小写）、数字、空格（空格不能在首尾）或2-16个汉字（包括16个）"
};

//显示提示信息
RegMail.showTip = function(target, msg){
	if(target == $(PID.verify)){
		$(PID.verify + "Info").style.display = "";
		$(PID.verify + "Info").innerHTML = '<div class="txt"><p>' + msg + '</p></div>';
		return true;
	}

	$(PID.showTip).style.display = "";
    $(PID.showTip).innerHTML = '<div class="txt"><p>' + msg + '</p></div>';
	if( $(PID.mail + "Info").style.display === "" || $(PID.mail + "OK").style.display === ""){
		$(PID.showTip).style.top = target.offsetTop + 80 + "px";
	} else {
		$(PID.showTip).style.top = target.offsetTop + 55 + "px";
	}
};

//显示成功信息
RegMail.showSuccessTip = function(obj, msg){
	if(obj == $(PID.mail + "OK")){
		$(PID.mail + "Info").style.display = "none";
		$(PID.mail + "OK").style.display = "";
		$(PID.mail + "OK").innerHTML = msg;
		return;
	}
	obj.innerHTML = '<p class="infoOk">' + msg + '</p>';
};

//显示错误信息
RegMail.showErrorTip = function(obj, msg){
	//var info = '<p class="infoError">' + 请填写登录密码 + "</p>";
	if(obj == $(PID.mail + "Info")){
		$(PID.mail + "OK").style.display = "none";
		obj.style.display = "";
		obj.innerHTML = msg;
		return;
	}
	//alert(msg);
	obj.innerHTML = '<p class="infoError">' + msg + "</p>";
};
//
RegMail.showStrength = function(val){
		var cs = new  PasswordStrength(val);
		var step = cs.checkStrong();
		step = step >= 3 ? 3 : step;
		step *= 2;
		var info = '<div class="psw"  id="passwordStrength"><p>弱<span>中</span><span><strong>强</strong></span></p>' + 
           '<div class="pswstrong"><img src="http://www.sinaimg.cn/rny/09vip/Events/strong.gif" style="width:' + step + '0%" id="strengthInfo"/></div></div>';
		 $(PID.password + "Info").innerHTML = info;
};

RegMail.check = function(id){
	var val = $(id).value;
	var msg;
	switch (id){
		  case PID.mail :
			msg = Check.checkEmail(val);
            break;
        case PID.password : 
			msg = Check.checkPassword(val);
            break;
        case PID.passwordAgagin:
			msg = Check.checkPasswordAgain($(PID.password).value, val);
            break;
        case PID.answer:
			msg  = Check.checkAnswer(val);
            break;
		case PID.customQuestion :
			msg = Check.checkCustomQuestion(val);
			break;
        default:
	}
	//alert("errorMsg:" + msg);
	return msg;
};

//检测单个表单
RegMail.checkIt = function(id){
	//检测select是否被选择
	if(id == PID.question){
		RegMail.showErrorTip($(id + "Info"),  "");
		if( $(PID.customQuestion + "TR").style.display == "none"){
			if($(id).value == 0){
				RegMail.showErrorTip($(id + "Info"),  "请选择密码查询问题。");
				return "error";
			}
		}
		return "ok";
	}
	
	if(id == PID.customQuestion && $(PID.customQuestion + "TR").style.display == "none"){
		return "ok";
	}
	
	if(id == PID.verify){
		var v = $(PID.verify).value;
		if(v.length <= 1 || v.length >= 5){
			$(PID.verify + "Error").style.display = "";
			return "error";
		}
		return "ok";
	}

	var msg = RegMail.check(id);
	if(msg == "ok"){
		//因為mail成功不需要提示
		if(id == PID.mail){
			return msg;
		}
		if (id == PID.password) {
			RegMail.showStrength($(id).value);
		} else {
			RegMail.showSuccessTip($(id + "Info"), RegMail.sucessInfo[id]);
		}
	} else {
			RegMail.showErrorTip($(id + "Info"),  msg);
	}
	return msg;
};

RegMail.checkAll = function(){
	if($(PID.agreement).checked !== true){
		alert("请阅读并同意新浪网络服务使用协议和邮箱服务条款");
		return false;
	}
	
	var sucess = true;
	var msg;
	//alert("onsubmit");
	for (var i = 0; i < $(PID.form).elements.length; i++) {
		var ele = $(PID.form).elements[i];
		//alert(ele);
		if(ele.getAttribute("check") == "T"){
				msg = RegMail.checkIt(ele.id);
				if(msg != "ok"){
					sucess = false;
				}
		}
	}
	
	if(!sucess){
		alert("您填入的信息有误，请根据页面红字提示修改。");
	}
	return sucess;
};
//返回验证码图片地址
RegMail.getVerifyCode = function (){
    function onVerifyCodeLoaded(responseText){
    
    }
    getRequestObject(BASE_URL.verifyCodeURL, {
        method: 'GET',
        onCompletedListener: onVerifyCodeLoaded
    });
};

RegMail.checkMailAvailable = function(){
	if (RegMail.checkIt(PID.mail) != "ok") {
		return;
	}

	var mailName = $(PID.mail).value;
	var param = "from=vipmail&name=" + mailName + "&utf82gbk=0";
	getRequestObject( BASE_URL.checkMailURL, {method:'POST', onError:onError, onCompletedListener : onSucess,  data:param});
	
	function onSucess(responseText){
		//yes 用户名已占用 no 用户名可用 defer 查询次数过多(1分钟大于10次, 1分钟后解除限制) error 参数错误或系统错误
		switch (responseText) {
			case "no" :
				RegMail.showSuccessTip($(PID.mail  + "OK"), "邮箱名可用");
				break;
			case "yes" :
				RegMail.showErrorTip($(PID.mail + "Info"), "抱歉！该邮箱名已被占用，请重新选择一个。");
				break;
			case "defer" :
				RegMail.showErrorTip($(PID.mail + "Info"), "您的查询次数过多，请一分钟后再查询。");
				break;
			case "error" :
				//TODO:需要错误提案
				RegMail.showErrorTip($(PID.mail + "Info"), "抱歉，查询失败。");
				break;
		}
	}
	
	function onError(){
		//TODO:需要错误提案
		RegMail.showErrorTip($(PID.mail + "Info"), "抱歉，查询失败。");
	}
	
	return false;
};

RegMail.collectInfo = function(){
	var data = {};
	for (var i = 0, len = $(PID.form).elements.length; i < len; i++) {
		var ele = $(PID.form).elements[i];
		if (ele.type == "image" || ele.type == "checkbox" || ele.id == "passwordAgain" || ele.value === "") {
			continue;
		}
		if (ele.type == "radio") {
			if (ele.checked === true) {
				data[ele.name] = ele.value;
			}
			continue;
		}
		if (ele.name == "pswqa_q" && ele.value !== "") {
			data[ele.name] = ele.value;
			continue;
		}
		
		data[ele.name] = ele.value;
	}
	
	for(var k in data){
		//alert(k + ":" + data[k]);
	}
	return data;
};
//当input focus
RegMail.onFocus = function (){
//	alert("onFocus!");
    var evt = EventUtils.getEvent();
	var id =  evt.target.id;

	if(id == PID.mail){
		//$(id + "Info").style.display = "none";
	} else if(id == PID.verify){
		RegMail.showTip($(evt.target.id),  RegMail.tipInfo[evt.target.id]);
		$(PID.verify + "Error").style.display = "none";
	} else {
		RegMail.showErrorTip($(id + "Info"), "");
		RegMail.showTip($(evt.target.id + "TR"),  RegMail.tipInfo[evt.target.id]);
	}
};

//当 input blur
RegMail.onBlur = function (){
	$(PID.showTip).style.display = "none";
    var evt = EventUtils.getEvent();
	var id = evt.target.id;
	
	if(id == PID.verify){
		$(PID.verify + "Info").style.display = "none";
		var v = $(PID.verify).value;
		if(v.length <= 1 || v.length >= 5){
			$(PID.verify + "Error").style.display = "";
		}
		return;
	}
	
	if(id == PID.mail){
		return;
	}
	RegMail.checkIt(id);
	
};

RegMail.submitInfo = function(info){
	/*
	 * err=uid_exists #用户名已存在
	   err=uid_err #用户名不合法
       err=pwd_err #密码不合法
       err=pincode_err #验证码错误
       err= post_limit #提交次数过多
       系统繁忙,请您稍后再试.
	 */
	var param = "";
	for (var k in info) {
		var temp =  k + "=" + info[k] + "&";
		param += temp;
	}
	param = param.substr(0, param.length - 1);
	//alert(param);
	getRequestObject( BASE_URL.submitURL, {method:'POST', onError:onError, onCompletedListener : onSucess,  data:param});
	//
	function onSucess(responseText){
		//alert("onsucess:" + responseText);
		var tempArr = responseText.split("=");
		if(tempArr[1] == "succ"){
			window.location.href = BASE_URL.submitSuccessURL;
			return;
		}
		var erorMsg = responseText.split("&")[1].split("=")[1];
		reloadCode(); 
		switch (erorMsg) {
			case "mail_exists" :
				alert("用户名已存在, 请您选择其他的用户名.");
				break;
			case "param_mail_err" :
				alert("用户名不合法, 请您重新输入.");
				break;
			case "param_psw_err" :
				alert("密码不合法, 请您重新输入.");
				break;
			
			case "pincode_err" :
				alert("验证码错误, 请您重新输入.");
				break;
			case "post_limit" :
				alert("提交次数过多, 请稍后再试.");
				break;
			default: alert("系统繁忙, 请您稍后再试.");
		}
	}
	
	function onError(){
		alert("系统繁忙,请您稍后再试.");
	}
	
};

RegMail.onSubmit = function (){
	var sucess = RegMail.checkAll();
	if(sucess){
		var info = RegMail.collectInfo();
		RegMail.submitInfo(info);
	}
	
	return false;
};

RegMail.onClick = function(){
	var evt = EventUtils.getEvent();
	var id = evt.target.id;
	switch(id){
		case PID.changeVerifyImg:
			$(PID.verifyImg).src = BASE_URL.verifyCodeURL;
			break; 
		case PID.checkMailBtn :
			//TODO 
			RegMail.checkMailAvailable();
			break;
		case PID.submit :
			RegMail.onSubmit();
		//	return false;
			break;
		case PID.verify :
			$(PID.verify).value = "";
			break;
	}
	
};

RegMail.onChange = function(){
	evt = EventUtils.getEvent();
	
	if (evt.target.value !== 0) {
		$(PID.question + "Info").innerHTML = "";
	}
	
	if(evt.target.value == 9){
		$(PID.customQuestion + "TR").style.display = "";
	} else {
		$(PID.customQuestion + "TR").style.display = "none";
	}
};
//注册事件
RegMail.addEvtListener = function(){

	for (var i = 0; i < $(PID.form).elements.length; i++) {
        var t = $(PID.form).elements[i];
		
        if ((t.type == "text" || t.type == "password") && t.id != "mailForPassword") {
       	    EventUtils.addEventListener(t, "focus", RegMail.onFocus);
            EventUtils.addEventListener(t, "blur", RegMail.onBlur);
        }
    }
	
	EventUtils.addEventListener($(PID.changeVerifyImg), "click", RegMail.onClick);
	EventUtils.addEventListener($(PID.checkMailBtn), "click", RegMail.onClick);
	EventUtils.addEventListener($(PID.submit), "click", RegMail.onClick);
	EventUtils.addEventListener($(PID.verify), "click", RegMail.onClick);
	EventUtils.addEventListener($(PID.question), "change", RegMail.onChange);
	//EventUtils.addEventListener($(PID.form), "submit", RegMail.onSubmit);

	$(PID.form).onsubmit = function(){
		return false;
	};
};

//程序入口
RegMail.main = function (){
	//alert("main")
	//注册事件
	RegMail.addEvtListener();
	
};
window.onload = RegMail.main;


