var userIdValid = false;
var passwordValid = true;
var selectedImg = null;
var forcus = true;
var isChecking = false;
var defaultValue = {
	nickname:"Your display name in games",
	email:"Input your Email Address"
}

function getXMLHttpRequest(){
	var xmlRequest = null;
	var activeX = ['MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
	if (window.ActiveXObject) {
		for (var i = 0; i < activeX.length; ++i) {
			try {
				xmlRequest = new ActiveXObject(activeX[i]);
				break;
			} 
			catch (e) {
				alert(e.message);
			}
		}
	}
	else if (window.XMLHttpRequest) {
		xmlRequest = new XMLHttpRequest();
	}
	return xmlRequest;
};

function notEmptyValidator(name, msg, defValue){
	this.name = name;
	this.msg = msg;
	this.validate = function(){
		this.valid = true;
		var el = document.getElementsByName(this.name);
		var msgEl = document.getElementById(this.name + "Msg");
		var outer = document.getElementById(this.name + '_outer');
		if (!msgEl && el.length > 0) {
			msgEl = document.getElementById(el[0].id + "Msg");
			outer = document.getElementById(el[0].id + '_outer');
		}
		if (msgEl && el.length > 0 && el[0].type == 'radio') {
			msgEl.innerHTML = this.msg;
			if(outer)
				outer.className = '';
		}
		if (el.length > 0) {
			for (var i = 0; i < el.length; i++) {
				if (el[i].type == "radio") {
					if (el[i].checked) {
						el[i].valid = "true";
						this.valid = true;
						if (msgEl) {
							msgEl.innerHTML = "";
						}
						if(outer)
							outer.className = 'hide';
						return;
					} 
				} else if (el[i].type == "checkbox") {
					if (el[i].checked) {
						el[i].valid = "true";
						this.valid = true;
						if (msgEl) {
							msgEl.innerHTML = "";
						}
						if(outer)
							outer.className = 'hide';
						return;
					} else {
						el[i].valid = "false";
						this.valid = false;
						if (msgEl) {
							msgEl.innerHTML = this.msg;
						}
						if(outer)
							outer.className = '';

					}	
				} else if (el[i].value != "") {
					if(defValue && el[i].value == defValue){
						el[i].valid = "false";
						this.valid = false;
						if (msgEl) {
							msgEl.className = 'errortext';
					   		msgEl.innerHTML = this.msg;
						}
						if(outer)
							outer.className = '';
					}else if (msgEl == null || msgEl.innerHTML == this.msg) {
						el[i].valid = "true";
						this.valid = true;
						if (msgEl) {
							msgEl.className = 'greytext';
							msgEl.innerHTML = "";
						}
						if(outer && outer.className != 'hide')
							outer.className = 'hide';
					}
					return;
				}
			}
			this.valid = false;
		}
	}
}

function regExpressionValidator(name, patten, msg,immediate,defaultMsg){
	var el = document.getElementById(name);
	if (el) {
		check = function(immediate){
			regExInit(name);
			msgDiv = document.getElementById(name + "Msg");
			try{
				if (((immediate === true && el.value == "") || patten.test(el.value)) && 
						regExPreviousError(name, defaultMsg, msg)) {
					if(el.value.search(/^\s*&/))
						regExValid(name, defaultMsg);
					else regExClear(name, defaultMsg);
				} else if (regExPreviousError(name, defaultMsg, msg)) {
					regExError(name, msg);
					if(forcus){
						if(el){
							el.focus();
						}
						forcus = false;
					}
				} else {
					forcus = false;
					regExError(name, null);
				}
			} catch(e) {
				alert(e.message);
			}
		}

		if(immediate){
			check(immediate);
		}else if(!edit_profile){
			el.onchange = check;
		}
	}
}

if(passwordRequired) {
var validators = [

	new notEmptyValidator("nickname","Please enter a nickname",defaultValue.nickname),
	
	new notEmptyValidator("gender","Please select your gender"),
	
	new notEmptyValidator("login_name","Please enter your email",defaultValue.email),

	new notEmptyValidator("password","Please input your password"),
	
	new notEmptyValidator("agree","You must select the checkbox to complete your registration.")

]
} else {
var validators = [

	new notEmptyValidator("nickname","Please enter a nickname",defaultValue.nickname),
	
	new notEmptyValidator("gender","Please select your gender")

]
}

function validateForm(){
	forcus = true;
	var pass = true;
	try{
		for (var i = 0; i < validators.length; i++) {
			validators[i].validate();
			var el = document.getElementById(validators[i].name);
			if (validators[i].valid == false) {
				pass = false;
				var msgEl = document.getElementById(validators[i].name + "Msg");
				if(forcus){
					var name = document.getElementsByName(validators[i].name)[0];
					if(name){
						name.focus();
					}
					forcus = false;
				}
			}
		}
		checkTwoPasswordField(true, 1);
		regExpressionValidators(true);

		var mob = document.getElementById('month');
		var dob = document.getElementById('day');
		var yob = document.getElementById('year');
		var msgEl = document.getElementById("birthdayMsg");
		if(mob.value=='--'||dob.value=='--'||yob.value=='--') {
			if(msgEl)
				msgEl.innerHTML = "Please verify your date of birth.";
			pass = false;
			if(document.getElementsByName("gender")[0].checked || document.getElementsByName("gender")[1].checked){
				if(yob.value=='--'){
					yob.focus();
					dobError();
				}
				if(dob.value=='--'){
					dob.focus();
					dobError();
				}
				if(mob.value=='--'){
					mob.focus();
					dobError();
				}
			}
		}else{
			if(msgEl)
				msgEl.innerHTML = "";
		}
		
	}catch(e){
		alert(e.message);
		return false;
	}
	return pass && userIdValid && passwordValid && forcus;
}


function showAndHidePanel(control){
	if (control.className == "table_Customize") {
		control.className = "Customize_2";
		document.getElementById("customPanel").style.display = "none";
	}
	else {
		control.className = "table_Customize";
		document.getElementById("customPanel").style.display = "block";
	}
}

function checkPassword(f){
	var passwordString = document.getElementById("confirmPassword").value;
	checkTwoPasswordField(0, f);
}

function checkTwoPasswordField(hasFocus, f){
	var el1 = document.getElementById("password");
	var el2 = document.getElementById("confirmPassword");
	passwordInit();

	passwordValid = true;

	if (el1 != null && el2 != null) {
		if (!passwordRequired && el1.value.length == 0 && el2.value.length == 0) {
			passwordValidated(passwordValid);			
		} else if(el1.value.length < 6 || el1.value.length > 16) {
			passwordValid = false;
			passwordLength();
			if(hasFocus && forcus && !passwordValid){
				el1.focus();
			}
		} else if((f||el2.value) && el1.value != el2.value) {
			passwordValid = false;
			if(f&&!/[\S]/.test(el2.value))
				password2Blank();
			if(/[\S]/.test(el2.value))
				passwordMatch();
			if(hasFocus && forcus && !passwordValid){
				el2.focus();
			}
		} else {
			if(f||el2.value)
				passwordValid = true;
			else 
				passwordValid = false;

			passwordValidated(passwordValid);
			if(document.getElementById("passwd"))
				document.getElementById("passwd").value=hex_md5(el1.value);
		}
	}
	return passwordValid;
}


function countryChanged(){
	var country = document.getElementById("country");
	var state = document.getElementById("state");
	if(country.value == "US"){
		state.value = "-1";
		state.disabled = false;
	}else{
		state.value = "-1";
		state.disabled = true;
	}
}

function stateChanged(){
	var country = document.getElementById("country");
	var state = document.getElementById("state");
	if(state.value == "-1"){
		//country.value = "~~";
		//country.options[0].style.display = "none";
	}else{
		country.value = "US";
		//country.options[0].style.display = "block";
	}
}

function fillDefaultValues(id, text, blur){
	var e = document.getElementById(id);
	e.value = text;
	e.onfocus = function(){
		e.style.color = "black";
		if(e.value == text){
			e.value = "";
		}
		this.select();
	}
	if (blur !== undefined && blur !== null){
		e.onblur = function(){
			if(e.value == ""){
				e.style.color = "#CCCCCC";
				e.value = text;
			}else{
				blur(e.id);
				e.style.color = "black";
			}
		}
	} else {
		e.onblur = function(){
			if(e.value == ""){
				e.style.color = "#CCCCCC";
				e.value = text;
			}else{
				e.style.color = "black";
			}
		}
	}
}

function ShowBirthYear(id){
	var date = new Date();
	var start = 1950;
	var end = date.getFullYear() - 13;
	var yearList = document.getElementById(id);
	for(var i = start;i <= end;i++){
		var option = document.createElement("OPTION");
		option.value=i;
		option.text=i;
		if(document.all){
			yearList.add(option);
		}else{
			yearList.appendChild(option);
		}
	}
}

function birthdayMonthChanged(){
	var day31 = ["1","3","5","7","8","10","12"];
	var month = document.getElementById("month").value;
	var dayCount = 30;
	if (month == "2"){
		dayCount = 29;
	} else {
		for(var k=0;k<day31.length;k++){
			if(day31[k] == month){
				dayCount = 31;
				break;
			}
		}
	}
	if(month == ""){
		dayCount = 31;
	}
	var dayList = document.getElementById("day");
	var currentDay = dayList.value;
	if (currentDay > dayCount){
		currentDay = "--";
	}
	dayList.innerHTML = "";
	addOption(dayList,"--","Day");
	for(var i=1;i<=dayCount;i++){
		addOption(dayList,i,i);
	}
	dayList.value = currentDay;
}

function addOption(list,value,text){
	option = document.createElement("OPTION");
	option.value=value;
	option.text=text;
	if(document.all){
		list.add(option);
	}else{
		list.appendChild(option);
	}
}

function birthYearChanged(){
	document.getElementById("year").value = document.getElementById("birth").value;
}

function regExpressionValidators(immediate){
	nickRE = /^((q[a-pr-z0-9._\-@])|([a-pr-z0-9._\-@]q)|([a-pr-z0-9._\-@][a-pr-z0-9._\-@]))([a-z0-9._\-@]){1,14}$/i;
	emailRE = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	nameRE = /^[a-zA-Z]{0,28}$/;
	regExpressionValidator("login_name", emailRE , "The Email is not valid",immediate,'(will be your login ID)');
	regExpressionValidator("email", emailRE, "The Email is not valid",immediate,'');
	regExpressionValidator("nickname", nickRE , "Invalid Nickname. Nicknames may include (A-Z), (0-9),(._-@), and cannot begin with QQ",immediate,'(you can change this later)');
	regExpressionValidator("firstname", nameRE, "The first name is not valid",immediate,'');
	regExpressionValidator("lastname", nameRE, "The last name is not valid",immediate,'');
	regExpressionValidator("nick", nickRE, "Nicknames may include (A-Z),(0-9),(._-@), and cannot begin with QQ",immediate,'');
}

/**
 * check if the email has been registered,modify "checkRegister.txt" to the real url
 */
function checkRegistered(id){
	var userId = document.getElementById(id).value;
	var re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	emailProcessing(id);

	if(re.test(userId)){
		emailResponded(id);
		if (userId != "") {
			isChecking = true;
			var xmlRequest = getXMLHttpRequest();
			var qurl="/cgi-bin/check_uniq_id?login_name="+userId;
			xmlRequest.open("GET",qurl, true);
			xmlRequest.onreadystatechange = function(){
				if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
					isChecking = false;
					if (/user_exist/.test(xmlRequest.responseText) ) {
						userIdValid = false;
						emailRegisteredError(id);
					}
					else if(/user_not_exist/.test(xmlRequest.responseText))
					{
						userIdValid = true;
						emailNotExist(id);
					}
					else
					{
						userIdValid = false;
						emailOtherError(id);
					}
				}
			}
			xmlRequest.send(null);
		}
	} else {
		userIdValid = false;
		emailInvalid(id);
	}
}

/**
 * when press submit button,this function will be invoke
 */
function submitRegister(){
	if (validateForm()) {
		return true;
	}
	//var ob = document.getElementById("login_nameMsg");
	//ob.innerHTML = (!userIdValid && ob.tips?ob.tips:"");
	return false;
}

function ShowBirthDays(){
	var dayList = document.getElementById("day");
	for(var i=1;i<=31;i++){
		addOption(dayList,i,i);
	}
}
