function $(objId) {
    return document.getElementById(objId);
}

function AjaxFormer(form) {
	this.form = form;
	this.ajaxSubmitForm = function(callbackfunc,Mask) {
	  var elements = form.elements;
	  var element;
	  var i;

	  var postContent = "";

	  for(i=0;i<elements.length;++i) {
	  	var element=elements[i];

	    if(element.type=="text" || element.type=="textarea" || element.type=="hidden") {
	      postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
	    }
	    else if(element.type=="select-one"||element.type=="select-multiple") {
	      var options=element.options,j,item;
	      for(j=0;j<options.length;++j){
	        item=options[j];
	        if(item.selected) {
	        	postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(item.value) + "&";
			}
	      }
	    } else if(element.type=="checkbox"||element.type=="radio") {
	      if(element.checked) {
	        	postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
			}
		} else if(element.type=="file") {
			if(element.value != "") {
				postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
			}
		} else {
				postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
		}
	  }
	  
	  postContent+="ajaxglobalformid="+form.id;
	  //alert(postContent);

	  this.ajaxSubmit(form.action, form.method, postContent,callbackfunc,Mask);

	}


	this.ajaxSubmit = function(url, method, postContent,callbackfunc,Mask)
	{	

		if (window.XMLHttpRequest)
		{
			xmlhttp=new XMLHttpRequest();
		}

		else if (window.ActiveXObject)
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}

		if(xmlhttp) {
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState==4)
				{
					try {
						if(xmlhttp.status==200) {							
							if(xmlhttp.getResponseHeader("response_script")) {
								eval(unescape(xmlhttp.getResponseHeader("response_script")));
							}else{
								try{
									callbackfunc(eval('('+xmlhttp.responseText+')'));
								}catch(e){
									alert(e+':'+e.description+'\nData:'+xmlhttp.responseText);
								}
							}

						}
						else {
							loadingDiv.innerHTML = "There is something wrong with form submit! ".fontcolor("red") + xmlhttp.status + "=" + xmlhttp.statusText;
						}
					} catch(exception) {
							loadingDiv.innerHTML = "There is something wrong with form submit! ".fontcolor("red") + exception;

					}
				}

			};

			if(method.toLowerCase() == "get") {
				xmlhttp.open("GET", url + "?" + postContent, false);
				xmlhttp.send(null);
			} else if(method.toLowerCase() == "post") {
				xmlhttp.open("POST", url, false);
				xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlhttp.send(postContent);
			}

		} else {
	        loadingDiv.innerHTML = "Can't create XMLHttpRequest object, please check your web browser.";
		}

	}
}



function getRequestObject()
{
	var req = null;
	if (typeof XMLHttpRequest != "undefined")
		req = new XMLHttpRequest();
	if (!req && typeof ActiveXObject != "undefined")
	{
		try
		{
			req=new ActiveXObject("Msxml2.XMLHTTP");
			XMLHttpRequest = function(){return new ActiveXObject("Msxml2.XMLHTTP");}
		}
		catch (e)
		{
			try
			{
				req=new ActiveXObject("Microsoft.XMLHTTP");
				XMLHttpRequest = function(){return new ActiveXObject("Microsoft.XMLHTTP");}
			}
			catch (e2)
			{
				try {
					req=new ActiveXObject("Msxml2.XMLHTTP.4.0");
					XMLHttpRequest = function(){return new ActiveXObject("Msxml2.XMLHTTP.4.0");}
				}
				catch (e3)
				{
					req=null;
				}
			}
		}
	}
	if(!req && window.createRequest)
		req = window.createRequest();
	
	if (!req) alert("Request Object Instantiation failed.");
		
	return req;
}


function getobj(sId)
{
	if (!sId) {
		return null;
	}
	var returnObj = document.getElementById(sId);
	if (!returnObj && document.all) {
		returnObj = document.all[sId];
	}
	return returnObj;
}



function openURI(uri, Div)
{
	
	var r;
	if (document.body )	document.body.style.cursor = 'wait';
	window.status = 'Sending Request...';
	getobj(Div).innerHTML='<br><br><br><br><center><b>Loading...</b></center>';
	
	r = getRequestObject();
	if (!r) return false;
	
	r.open("GET", uri, true);
	
	r.onreadystatechange = function()
	{
		if (r.readyState != 4)	return;
		getobj(Div).innerHTML=r.responseText;	
		if (document.body )	document.body.style.cursor = 'default';
	}
	r.send(null);
	return true;
	
}


//将所有对象的属性转为字符串
function allPrpos(obj) {      
	var props = "";     
	for(var p in obj){      
	   if(typeof(obj[p])=="function"){      
			obj[p]();     
	   }else if(typeof(obj[p])=="object"){
		     props+=allPrpos(obj[p]);
		}else{      
			props+= p + "=" + obj[p] + "\n";     
		}      
	}      
	return props;     
}


//给当前对象增加一个Tips
function adddiv(obj){	
	var tipsdiv=document.getElementById(obj.jstipdiv);
	if(!tipsdiv){
		var div = document.createElement("DIV");
		div.innerHTML='<div style="float:left;padding:3px"><IMG SRC="/my/images/helper_arrow2.gif" BORDER="0"></div><div style="border:1px dotted #D5D5D5;background-color:#FFDF90;float:left;padding:4px;width:225px;font-size:9pt">'+obj.jstips+'</div>';
		div.id=obj.jstipdiv;		 
		div.style.display = "none";
		div.style.width="250px";
		div.style.position ="absolute";
		div.style.padding ="0px";  
		div.style.zIndex=200;
		obj.parentNode.appendChild(div);    
	}else{
		tipsdiv.innerHTML='<div style="float:left;padding:3px"><IMG SRC="/my/images/helper_arrow2.gif" BORDER="0"></div><div style="border:1px dotted #D5D5D5;background-color:#FFDF90;float:left;padding:4px;width:225px;font-size:9pt">'+obj.jstips+'</div>';	
	}
}



//建立出错提醒层
function errdiv(sobj,errmsg,status){

	var tipsdiv=document.getElementById(sobj.jstipdiv);
    var div=document.getElementById(sobj.jserrdiv);
	
    if(!div){      
            div = document.createElement("DIV");           
            div.id=sobj.jserrdiv;		 
            div.style.display = "none";
            div.style.fontSize='11px';
            div.style.color='#E75201';
            div.innerHTML='<IMG SRC="/my/images/mandatory.gif" BORDER="0" align="absmiddle" style="margin:3px">'+errmsg;
            div.style.width="215px";
            div.style.position ="absolute";
            div.style.padding ="3px"; 
			div.style.lineHeight="12px";
			div.style.zIndex=199;
            if(status){
				sobj.parentNode.appendChild(div); 
            }
        
    }
    
    if(div){
        div.innerHTML='<IMG SRC="/my/images/mandatory.gif" BORDER="0" align="absmiddle" style="margin:3px">'+errmsg;
        showDiv(div.id,status);
        if (tipsdiv){
            showDiv(tipsdiv.id,false);
        }        
    }

	if(sobj){
		var color;
		color='#CC0000';
		if(status){
			if(sobj.type=='select-one'|| sobj.type=='select-multiple'){
				sobj.style.backgroundColor='#ffe2e0';
			}else{		    
				sobj.style.border="1px double "+color; 
			}	
		}
	}
    
}

//显示/隐藏TIPS层,并隐藏出错信息层
function showTipsDivNew(obj,status){	
	if (obj.jstips)
	{
		adddiv(obj);
		showDiv(obj.jstipdiv,status);  
	}
	if (status)
	{
		showDiv(obj.jserrdiv,false);
	}
}



//显示/隐藏层
function showDiv(id,status){
    var obj=document.getElementById(id);
    if (obj){
        if(status){
            obj.style.display = "inline";
        }else{
            obj.style.display = "none";
        } 
    }
}




function loadtipsdata(obj,form,debug){
	
	for(var p in obj){
        if (typeof(obj[p].check)=='object'){
            errdiv(obj[p].jserrdiv,'',false);
        }  
    }
	

    //建立Tips提示信息层
    for(var p in obj){
        var formobj;	

		if(obj[p].type!='checkbox' && obj[p].type!='radio'){		

			formobj=document.getElementById(p);
			if(formobj){
				if(obj[p].tips){
					formobj.jstips=obj[p].tips;
				}

				if(obj[p].type){
					formobj.jstype=obj[p].type;
				}				
				
				if (typeof(obj[p].check)=='object')
				{
					formobj.jscheck=obj[p].check;
				}
				
				if (obj[p].jstipdiv)
				{
					formobj.jstipdiv='_tips_'+obj[p].jstipdiv;
				}

				if (obj[p].jserrdiv)
				{
					formobj.jserrdiv='_errs_'+obj[p].jserrdiv;
				}	
				

				formobj.onclick=function()
				{
					showTipsDivNew(this,true);
				} 
				formobj.onfocus=formobj.onclick;

				
				formobj.onblur=function()
				{
					showTipsDivNew(this,false);    
					if(this.jscheck){
						var s=checkValue(this);
						if (s)
						{
							clearErrDiv(this);
						}
					}						
				}
			}else{
				if (debug)
				{
					alert(p+' not object');
				}
			}
		}		


    }
}

//清除出错信息
function clearErrDiv(sobj){	
	showDiv(sobj.jserrdiv,false);
	if(sobj.type=='select-one'|| sobj.type=='select-multiple'){
		sobj.style.backgroundColor='#FFFFFF';
	}else{		    
		sobj.style.border="1px solid #7F9DB9"; 
	}	
}

//根据情情况进行表单检测,返回真假值并用DIV显示出出错提示
function checkValue(obj){
	var x=getFieldValue(obj);
	for(var func in obj.jscheck){
		var result=false;
		if(func=='null'){
			result=checkNull(x.value,obj.jscheck[func].defaultval);		
		}else if(func=='letternum'){
			result=checkLetternum(x.value);	
		}else if(func=='letter'){
			result=checkLetter(x.value);	
		}else if(func=='num'){
			result=checkNum(x.value);	
		}else if(func=='verify'){
			result=checkVerify(x.value,obj.jscheck[func].to);
		}else if(func=='unique'){
			result=checkUnique(x.value,obj.jscheck[func].url,obj,obj.jscheck[func].errmsg);
		}else if(func=='email'){
			result=checkEmail(x.value);	
		}else if(func=='maxlen'){
			result=checkMaxlen(x.value,obj.jscheck[func].len);	
		}else if(func=='minlen'){
			result=checkMinlen(x.value,obj.jscheck[func].len);	
		}else if(func=='maxselect'){
			result=checkMaxselect(x.checkCount,obj.jscheck[func].maxselect);
		}else if(func=='minselect'){
			result=checkMinselect(x.checkCount,obj.jscheck[func].minselect);
		}
		if(!result){
			errdiv(obj,obj.jscheck[func].errmsg,true);
			return false;
		}
	}

	return true;
}

function checkUnique(str,url,obj,msg){
	var r,context;
	r = getRequestObject();
	if (!r) return false;
	
	context="checkvalue="+str;
	r.open("POST", url, true);
	r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	
	r.onreadystatechange = function()
	{
		if (r.readyState != 4)	return;
		if(r.responseText==1){			
			errdiv(obj,'',false);
		}else{
			errdiv(obj,msg,true);
		}
		//alert(r.responseText);
	}
	r.send(context);
	return true;	
}

function checkNull(str,defaultval){
	if (str.length<=0 || str==defaultval)
	{
		return false;
	}else{
		return true;
	}
}

function checkLetternum(str){
	var reg=/[^A-Za-z0-9_]/g; 
	if (reg.test(str)){ 
		return false; 
	}else{ 
		return true;
	}
}

function checkLetter(str){
	var reg=/[^A-Za-z]/g; 
	if (reg.test(str)){ 
		return false; 
	}else{ 
		return true;
	}
}


function checkNum(str){
	var reg=/[^0-9]/g; 
	if (reg.test(str)){ 
		return false; 
	}else{ 
		return true;
	}
}


function checkMaxlen(str,len){
	if(str.length>len){
		return false;
	}else{
		return true;
	}	
}

function checkMinlen(str,len){
	if(str.length<len){
		return false;
	}else{
		return true;
	}	
}

function checkMaxselect(currentsel,maxselect){
	if(currentsel>maxselect){
		return false;
	}else{
		return true;
	}
}

function checkMinselect(currentsel,minselect){
	if(currentsel<minselect){
		return false;
	}else{
		return true;
	}
}

function checkEmail(str){
	var reg=/^(?:[a-zA-Z0-9]+[_\-\+\.]?)*[a-zA-Z0-9]+@(?:([a-zA-Z0-9]+[_\-]?)*[a-zA-Z0-9]+\.)+([a-zA-Z]{2,})+$/; 
	if (reg.test(str)){ 
		return true; 
	}else{ 
		return false;
	}
}

function checkVerify(str,id){
	if (document.getElementById(id).value==str)
	{
		return true;
	}else{
		return false;	
	}
}

//获取表单元素值与选中的个数据,多项数据用"|^^|"分隔开(取消radio与checkbox类型的取值)
function getFieldValue(element){	
	var resultObj = new Object;
	var tempobject;
	resultObj.value='';
	resultObj.checkCount=0;

	if(element.type=="text" || element.type=="textarea" || element.type=="hidden" || element.type=='password' || element.type=="hidden" || element.type=='file'){
		resultObj.value=element.value;		
	}else if(element.type=="select-one") {
		if(element.selectedIndex>=0){
			resultObj.value=element.options[element.selectedIndex].value;
			resultObj.checkCount=1;
		}			
	}else if(element.type=="select-multiple"){
		for(i=0;i<=element.options.length-1;i++){
	        var item=element.options[i];
	        if(item.selected) {
				if(resultObj.checkCount>0){
					resultObj.value+='|^^|';	
				}
				resultObj.value+=tempobject[i].value;
				resultObj.checkCount++;	        	
			}
	      }	
	}else{
		resultObj.value=element.value;
	}
	return resultObj;
}


//初始化tips
function inittips(jsonstring,form,debug,callbackfunc){
    if ( document.addEventListener ) { 
            document.addEventListener( "DOMContentLoaded", function(){ 
                loadtipsdata(jsonstring,form,debug);
				if(callbackfunc){
					callbackfunc(jsonstring,form,debug);
				}
            }, false ); 
     
    } else if ( document.attachEvent ) { 
            document.attachEvent("onreadystatechange", function(){ 
                if ( document.readyState === "complete" ) { 
                    loadtipsdata(jsonstring,form,debug);     
					if(callbackfunc){
						callbackfunc(jsonstring,form,debug);
					}
                } 
            }); 

    } 
}


//网页跳转
function gotopage(url){
    window.location.href=url;
}


//注册第一步提交动作
function submitform(){   
        var formID = document.getElementById("regForm");
		var today = new Date();
		var cookieExpires = new Date();
		cookieExpires.setTime(today.getTime() + 1000*60*60*24);	
		
		document.cookie="regnickname=" + formID.nickname.value+";expires=" + cookieExpires.toGMTString();		
		document.cookie="regfirst_name=" + formID.first_name.value+";expires=" + cookieExpires.toGMTString();
		document.cookie="reglast_name=" + formID.last_name.value+";expires=" + cookieExpires.toGMTString();
		document.cookie="regemail=" + formID.email.value+";expires=" + cookieExpires.toGMTString();
		if(formID.gender[0].checked){
			document.cookie="reggender=M"+";expires=" + cookieExpires.toGMTString();
		}

        if(formID.gender[1].checked){
			document.cookie="reggender=F"+";expires=" + cookieExpires.toGMTString();	
		}
		document.cookie="regcountry=" + formID.country.options[formID.country.selectedIndex].value+";expires=" + cookieExpires.toGMTString();
		document.cookie="regbirthday_y=" + formID.birthday_y.options[formID.birthday_y.selectedIndex].value+";expires=" + cookieExpires.toGMTString();
		document.cookie="regbirthday_m=" + formID.birthday_m.options[formID.birthday_m.selectedIndex].value+";expires=" + cookieExpires.toGMTString();
		document.cookie="regbirthday_d=" + formID.birthday_d.options[formID.birthday_d.selectedIndex].value+";expires=" + cookieExpires.toGMTString();
		document.cookie="regmarry=" + formID.marry.options[formID.marry.selectedIndex].value+";expires=" + cookieExpires.toGMTString();		
		document.cookie="regage1=" + formID.age1.options[formID.age1.selectedIndex].value+";expires=" + cookieExpires.toGMTString();
		document.cookie="regage2=" + formID.age2.options[formID.age2.selectedIndex].value+";expires=" + cookieExpires.toGMTString();
		document.cookie="regus_client=" + formID.us_client.options[formID.us_client.selectedIndex].value+";expires=" + cookieExpires.toGMTString();

        $('screen_width').value=window.screen.width;
        $('screen_height').value=window.screen.height;
        $('screen_colors').value=window.screen.colorDepth;

        if($('agree').checked==false){
            alert("Sorry,\nyou must agree to the terms and conditions of use before creating your account!");
            return false;
        }
		
		if(checkFormData($('regForm'),true)){
			$('regForm').submit();
			//var former = new AjaxFormer($('regForm'));
			//former.ajaxSubmitForm(callback,false);   
		}
}


//通用的表单提交后的数据处理.
function callback(data){
   if(data.status){
        alert("OK");
   }else{
	    var i=0;
        for (p in data.errlist)
        {
			var obj=document.getElementById(p);
            errdiv(obj,data.errlist[p],true);
			
			if(i<=0){
				var firstObj=p;	
			}
			
			i++;
        }
        alert('Please check if all fields are filled and correct!');	

		var obj=document.getElementById(firstObj);
		obj.focus();
   }   
}



//提交前对整个表单进行检查
function checkFormData(form,showJsMsg,AlertMsg){
    var checkstatus=true;
	var p=0;
    for(i=0;i<form.elements.length;i++){
        var element=form.elements[i];   
        if(element.jscheck){
			var s=checkValue(element);
		    if (s)
		    {
			    clearErrDiv(element);
		    }else{
                checkstatus=false;
				if(p<=0){
					var firstObj=i;	
				}
				p++;
            }               
	    }       
    }


    if(checkstatus==false){		
        if(showJsMsg){
            if(AlertMsg){
                alert(AlertMsg);   
            }else{
               alert('Please check if all fields are filled and correct!');   
            }
			form.elements[firstObj].focus();
        }
    }

    return checkstatus; 
}


//网页中显示一个帮助层
function ShowTips(obj,MsgDivId,divwidth){
        var div=document.getElementById('_temptips_'+obj.id);
		var divmsg=document.getElementById(MsgDivId);

		if(!divwidth){
			divwidth=200;
		}
        if(!div){
            div = document.createElement("DIV");
            div.innerHTML='<div style="float:left;background-color:lightyellow;padding:8px;border:2px solid gray;text-decoration: none;width:'+divwidth+'px;margin-left: 5px">'+divmsg.innerHTML+'</div>';
            div.id='_temptips_'+obj.id;		 
            div.style.display = "inline";
            div.style.position ="absolute";
            div.style.padding ="0px";  
			div.style.zIndex=200;
			div.onmouseover=function(){
				this.style.display='inline';
			}

			div.onmouseout=function(){
				this.style.display='none';
			}
			obj.parentNode.appendChild(div);            
        }else{
			div.style.display='inline';
		}
		obj.onmouseout=function(){
			HideTips(this);
		}			
}

function HideTips(obj){
   var div=document.getElementById('_temptips_'+obj.id);
   if(div){
		div.style.display='none';
	}			
}
