var LANG={XMLCONTCREATE:'无法创建XMLHTTP对象!',UNEXPECTEDERR: '发生未知错误!'};

/*Try.these 执行一些列函数，直到执行成功*/
var Try = {
  these: function() {
    var returnValue;
    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) { }
    }

    return returnValue;
  }
};

/*Class */
var MyClass=function(){
	var retObj=function(){
		if(this.initialize){
			this.initialize.apply(this,arguments);						
		}else{
			
		}
	}
	return retObj;
	
};

function bind(fun,obj){
	if(typeof(fun)=='function'){
		return function(){
			fun.apply(obj,[]);
		}
	}else{
		return fun;
	}
}

/*Simple Ajax对象*/
var SyAjax=MyClass();
SyAjax.prototype={
	onPosted:null,
	_xmlhttp:null,
	_method:'GET',
	_strPost:'',
	onBeginPost:null,
	_beginTime:null,
	initialize:function(obj){
		if(typeof(obj)=='object'){
			this._xmlhttp=obj;
		}else{
			this._xmlhttp=(Try.these(
				  function() {return new XMLHttpRequest()},
				  function() {return new ActiveXObject('Msxml2.XMLHTTP')},
				  function() {return new ActiveXObject('Microsoft.XMLHTTP')}
				) || false);
		}
	},
	readyStateChange:function(){

		if(this._xmlhttp.readyState==4){
			
			var rt = null;
			
			if(this._xmlhttp.status==200){
				if(this.onPosted) rt = this.onPosted(this._xmlhttp);
			}else{
				if(this.onPosted) rt = this.onPosted(this._xmlhttp.status);
			}
			this._xmlhttp.abort();			                      //*********必须调用此句，否则无法重复调用************
			this._xmlhttp.onreadystatechange=function(){ };
			
			if(typeof(rt)=='function'){
				try{
				rt();
				}catch(e){}
			}
		}
	},
	post:function(url,str){
		var arg1=url;		

		if(typeof(arg1)!="string")
		{	
			return '';
		}
		
		str=(str==undefined?'':str.trim());
		
		if(typeof(this.onBeginPost)=='function'){
			this.onBeginPost();
		}
		
		if(this._method.toLowerCase()=='get'){
			arg1+='?'+str;
		}
		str = '';
		if(typeof(this.onPosted)=='function'){
				this._xmlhttp.onreadystatechange = bind(this.readyStateChange,this);


				//alert(arg1);
				this._xmlhttp.open(this._method,arg1,true);
				arg1 = null;

				this._xmlhttp.setRequestHeader("Content-Length",str.length);			
				if(this._method.toLowerCase()=='post'){
					this._xmlhttp.setRequestHeader("Content-Type","application-www-form-urlencoded");				
				}			

				this._xmlhttp.send(str);			
			
		}else{
			try{				
				this._xmlhttp.open(this._method,arg1,false);
			}catch(e){
				alert(e);
			}
				this._xmlhttp.setRequestHeader("Content-Length",str.length);

				if(this._method.toLowerCase()=='post')
					this._xmlhttp.setRequestHeader("Content-Type","application-www-form-urlencoded");
				
				this._xmlhttp.send(str);
				return this._xmlhttp.responseText;
			
		}
	}
}

/*User login consol*/
var UserLogin={
	loginURL       : '',				//用户登录验证URL
	validURL       : '',
	loginOutURL    : '',
	ajaxObj		   : null,
	cookieName     : 'xl_validUname',
	onBeforeLogin  : null,
	onAfterLogin   : null,	
	onAfterValid   : null,
	onBeforeValid  : null,
	onBeforeLogOut : null,
	onAfterLogOut  : null,

	initialize:function(obj){
		if(obj){
			try{
				this.ajaxObj = new SyAjax(obj);			    
			}catch(e){
				this.ajaxObj._xmlhttp = null;
			}
		}
	},

	setXMLAgent:function(obj){
		//设置Ajax代理对象
		if(obj){
			UserLogin.ajaxObj._xmlhttp=obj;
		}
	},


	validUserCookie:function(){
		if(!this.getCookie(this.cookieName))
			return false;
		else
			return true;
	},
		
    loginOut:function(uname,gameid){
				
		if(typeof(this.onBeforeLogOut) == 'function'){
			this.onBeforeLogOut();
		}
        
		UserLogin.createAjaxObj();

		if(!this.loginOutURL || !UserLogin.ajaxObj._xmlhttp){
			if(typeof(this.onAfterLogOut)=='function'){
				this.onAfterLogOut(-11);
			}
			return false;
		}

		var postStr='';
		postStr = 'username=' + encodeURIComponent(uname);
		postStr += '&gameid=' + encodeURIComponent(gameid);
        this.ajaxObj.onPosted = this.onAfterLogOut;
        this.ajaxObj.post(this.loginOutURL,postStr);

	},

	login:function(uname,upwd,validcode,seeds,gameid){	
		var retFlag=-11;
		if(typeof(this.onBeforeLogin)=='function'){
			this.onBeforeLogin();
		}
		//创建Ajax对象
		UserLogin.createAjaxObj();		
		
		if(seeds==undefined || seeds.isEmpty())
			seeds = '';
		
		//如果不存在ajax对象则直接回调登陆完毕。
		if(UserLogin.ajaxObj._xmlhttp){
		   var postStr='';
		   postStr = 'username=' + encodeURIComponent(uname);
		   postStr+= '&password=' + encodeURIComponent(upwd);
		   postStr+= '&vcodestr=' + encodeURIComponent(validcode);
		   postStr+= '&vcode='    + encodeURIComponent(UserLogin.getValidvercode());
		   postStr+= '&Random=' + seeds;
		   postStr+= '&gameid=' + gameid;
		   this.ajaxObj.onPosted = this.onAfterLogin;		  
		   this.ajaxObj.post(this.loginURL,postStr);

		}else{
           if(typeof(UserLogin.onAfterLogin)=='function'){
			 //存在回调
             onAfterLogin(retFlag);
           }else{
			 //不存在回调则弹出提示
			 alert(LANG[XMLCONTCREATE]);
             return false;
           }
		}
		return true;
	},

	validLoginCache:function(gameid){
		/*
		根据Cookie内容验证用户登录状态
		*/
		//alert('dd');

		if(typeof(this.onBeforeValid)=='function'){
			this.onBeforeValid();
		}		
		
		var uname=this.getCookie(this.cookieName);		
		if(!uname){
			if(typeof(this.onAfterValid)=='function'){
				this.onAfterValid(-11);
				return false;
			}
		}

		UserLogin.createAjaxObj();
		if(UserLogin.ajaxObj._xmlhttp){
		  
		  var postStr='username='+encodeURIComponent(uname);
		  postStr+='&gameid='+encodeURIComponent(gameid);
		  this.ajaxObj.onPosted = this.onAfterValid;
		  this.ajaxObj.post(this.validURL,postStr);

		}else{
          alert(LANG[XMLCONTCREATE]);
		}
	},
    
	setCookie:function(ckname,ckvalue,timeout){
	  /*
		设置Cookie
	  */
      var strVal=escape(ckname)+'='+escape(ckvalue);
	  

	  if(!isNaN(timeout) && timeout!==null && timeout!==undefined){
		  var expireDate=new Date(new Date().getTime()+timeout*1000);
	  }else{
		  var expireDate=new Date(new Date().getTime()+3600000);
	  }
	  strVal+='; path=/; domain=.xunlei.com ; expires='+expireDate.toGMTString();

	  document.cookie=strVal;
	},

	getCookie:function(ckname){
	  /*
		读取cookie值
	  */
	  var ck=document.cookie;
	  var reg=new RegExp(escape(ckname)+'=([^;$]*)','gi');
	  if(!reg.test(ck)){
	    return '';
	  }
	  var a=ck.match(reg);
	  if(a.length>0)
	    return (RegExp.$1);
	  else
	    return '';
	},

	removeCookie:function(ckname){
		this.setCookie(ckname,'',0);
	},
	
	createAjaxObj:function(){		
		if(!UserLogin.ajaxObj){
			UserLogin.ajaxObj = new SyAjax();
		}
		UserLogin.ajaxObj._method='GET';
	},

	getValidvercode:function (){
		var start1 = document.cookie.indexOf("VERIFY_KEY=");
		if(start1== -1) return "";
		start=document.cookie.indexOf("=",start1)+1;
		var end = document.cookie.indexOf(";",start);
		if(end==-1) end=document.cookie.length;
		var value=unescape(document.cookie.substring(start,end));
		return value;
	}
};
