﻿
document.domain="131.com";
var PassPorthand = document.getElementsByTagName("head")[0];
var OnLoginDelegateHandler; 

var PassPort =
{
	Encode:'',
	Server:'http://passport.131.com/',
	MiniLoginUrl:'service/v1/login.html',
	MiniRegisterUrl:'service/v1/register.html',
	LoginOutUrl:'',
	LoginUrl:'',
	AllUserCount:0,
	Token:null,
	IsLogin:false,
	UID:0,
	UserName:null,
	PassWord:null,
	MsgCount:0,
	Verify:null,
	BaseVerify:null,
	Auth:'',
	Ready:false,
	ErrorCode:null,
	OnLoginDelegate:Array(),
	OnLoginOutDelegate:Array(),
	OnLoginErrorDelegate:Array(),
	Message:Array(
				  '没有输入帐号^_^',
				  '没有输入密码:)',
				  '帐号/密码不匹配^_^',
				  '用户名不存在',
				  '验证码错误'
				  ),
	PageMaxzIndex:0,
	///初始化
	inint:function()
	{
		PassPort.Reday = false;
		var script = document.createElement('script');
		script.id = 'PassPortQuery';
		script.src = 'http://sso.131.com/Script.Aspx?Action=Query&encode='+this.Encode+'&v='+Math.floor(Math.random()*1000+1);		
		var PassPorthand = document.getElementsByTagName("head")[0];
		PassPorthand.appendChild(script);		
		setTimeout('PassPort._SETSTATE();',100);
		delete script;		
	},
	///设置当前站点用户登陆状态
	_SETSTATE:function() 
	{	
		if (!PassPort.Ready)
		{
			setTimeout('PassPort._SETSTATE();',100);
		}
		else
		{				
			if(!this.IsLogin && this.LoginOutUrl!='')
			{
				this.SendRequest(this.LoginOutUrl, PassPort.LocalLoginRequest);
			}
			else if(this.LoginUrl!='')
			{	
				var param = '&uid=' + this.UID;
				param += '&username=' + escape(this.UserName);
				param += '&password=' + escape(this.PassWord);
				param += '&token=' + escape(this.Token);
				param += '&verify=' + escape(this.Verify);
				param += '&auth=' + this.Auth;
				param += '&baseverify=' + this.BaseVerify;
				param += '&IsXml=true';
				this.SendRequest(this.LoginUrl + '?' + param, PassPort.LocalLoginRequest);
			}			
		}
	},	
	///当前站点用户状态设置成功
	LocalLoginRequest:function(request)
	{	
		var global = request.getElementsByTagName('Global')[0];
		
		/*检查当前站点用户状态和从udb获取的状态是否一样*/
		if (PassPort.UID != PassPort._GETElementValue(global.getElementsByTagName('UserInfo')[0],'UID'))
		{
			setTimeout('PassPort._SETSTATE();',100);
		}
		else
		{
			setTimeout('PassPort.RunOnLoginDelegate()',100);
		}
	
	},	
	RunOnLoginDelegate:function()
	{
		if (!PassPort.OnLoginDelegate)
		{
			return ;
		}
		else
		{
			for (var d = 0; d < PassPort.OnLoginDelegate.length; d ++)
			{
				eval(PassPort.OnLoginDelegate[d]);
			}
		}
	},
	///登陆成功事件委托
	AddLoginDelegate:function(el)
	{
		this.OnLoginDelegate.push(el);
	},
	///删除一个登陆成功后的委托事件
	ReMoveLoginDelegate:function(key)
	{
		for (var d = 0; d < PassPort.OnLoginDelegate.length; d ++)
		{
			if(PassPort.OnLoginDelegate[d] == key)
			{
				PassPort.OnLoginDelegate.splice(d,1);
				return;
			}
		}
	},
	///登陆失败事件委托
	AddLoginErrDelegate:function(el)
	{
		this.OnLoginErrorDelegate.push(el);
	},	
	///用户注册连接接口
	Register:function()
	{
		var url = '/App/Redirect.Aspx?UDB=true&to=http://reg.passport.131.com/register.aspx&forward=' + escape(document.location.href);
		document.location.href = url;
	},	
	///用户登陆连接接口
	Login:function()
	{
		var url = '/App/Redirect.Aspx?UDB=true&to=http://passport.131.com/login.aspx&forward=' +  escape(document.location.href);
		document.location.href = url;
	},	
	///用户注销登陆接口
	LoginOut:function()
	{
		var url = '/App/Redirect.Aspx?UDB=true&to=http://udb.131.com/loginout.aspx&forward=' + escape(document.location.href);
		document.location.href = url;
	},	
	
	
	
	CheckLogin:function(username,password,savecookies)
	{
		if (username.value == '')
		{
			alert(this.Message[0]);
			username.focus();
			return false;
		}
		
		if (password.value == '')
		{
			alert(this.Message[1]);
			password.focus();
			return false; 
		}
		
		if (!savecookies)
		{
			savecookies = false;
		}
		
		this.ErrorCode = null;
		this.Reday = false;

		var _loginScript = document.createElement('script');
		_loginScript.src = 'http://passport.131.com/Script.Aspx?Action=Login&encode='+this.Encode+'&username='+escape(username.value)+'&password='+escape(password.value)+'&savecookies='+savecookies+'&v='+Math.floor(Math.random()*1000+1);
		PassPorthand.appendChild(_loginScript);
		setTimeout('PassPort._CHECKLOGIN()',200);
		return false;
	},
	_CHECKLOGIN:function()
	{
		if (!this.Ready )
		{
			setTimeout('PassPort._CHECKLOGIN()',200);			
		}
		else
		{
			if (this.ErrorCode!=null)
			{	
				if (PassPort.OnLoginErrorDelegate.length == 0)
				{
					alert(this.Message[this.ErrorCode]);
				}
				else
				{
					for (var d = 0; d < PassPort.OnLoginErrorDelegate.length; d ++)
					{
						eval(PassPort.OnLoginErrorDelegate[d]);
					}
				}
			}		
			setTimeout('PassPort.inint();',100);
		}
	},
	
	
	/*
	脚本中应用到的一些系统方法封装开始
	
	*/	
	
	//获取浏览器xmlhttprequest对象，兼容ff,ie
	GetXmlHttpRequest:function()
	{
		var req;
		if (window.XMLHttpRequest) 
		{ // Mozilla, Safari,...
            req = new XMLHttpRequest();
            if (req.overrideMimeType) {
                req.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE

			var msxmls = ["MSXML3", "MSXML2", "Microsoft"];
			var returnObj;
	
			for (var i=0; i < msxmls.length; i++) 
			{
				try 
				{
					req = new ActiveXObject(msxmls[i] + ".XMLHTTP");
					break;
				}
				catch (ex)
				{
					if (i==2)
					{						
						alert("JS_CLASS:ERROR:创建" + msxmls[i] + ".XMLHTTP" + "控件失败!");
					}
				}
			}
        }

		if (!req) 
		{
			alert("JS_CLASS:ERROR:组件创建失败\r\n由于您的浏览器版本太低，网站的某些功能无法使用.\r\n您可以升级您的浏览器到IE6.0以上版本");
			return false;
		}
		return req;
	},
	
	
	/*
	passport使用的推送数据，ajax
	*/
	///推送数据
	SendRequest:function(url, Treat)
	{
		 var Obj=this.GetXmlHttpRequest();
		 var s=this.processChech(Obj,Treat);
		 Obj.onreadystatechange = s;

		 if (url.indexOf('?')>-1)
		 {
		 	url = url +"&" + Math.floor(Math.random()*1000+1);
		 }
		 else
		 {
			url = url +"?" + Math.floor(Math.random()*1000+1);	 
		 }
		 //alert(url);
		Obj.open('GET',url,true);
		Obj.send(null);
		delete Obj;
		delete s;
	},	
	///回调方法
	processChech:function(mobject,f)
	{
		return function()
		{	
		  if (mobject.readyState == 4) 
			{				
				var state=mobject.status;
				if (state==404)
				{
					alert("JS_CLASS:ERROR:请求页面不存在");
					return false;					
				}
				else if(state<200)
				{
					alert("JS_CLASS:ERROR:客户端错误:"+state.statusText);
					return false;
				}
				else if(state==200)
				{
					f(mobject.responseXML);
				}
			}
			
		}
	},
	
	_GETElementValue:function(obj,el)
	{
		if (document.all)
		{
			return obj.getElementsByTagName(el)[0].text;
		}
		else
		{
			return obj.getElementsByTagName(el)[0].textContent;
		}
		
	},
	
	/*
	
	获取当前窗口的大小
	
	*/
	getPageSize:function(){
		
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
	
	
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight); 
		return arrayPageSize;
	},
	///获取页面中的最大zindex
	_GetMaxZIndex:function()
	{
		if (this.PageMaxzIndex == 0 )
		{
			var _maxzindex = 0;
			var _el = document.getElementsByTagName("*");
			
			for (var i = 0; i < _el.length; i ++)
			{
				if (_el[i].style.zIndex > _maxzindex)
				{
					_maxzindex = _el[i].style.zIndex;
				}
			}
			
			return _maxzindex;
			this.PageMaxzIndex =  _maxzindex;
		}
		return this.PageMaxzIndex;
	},

	/*
	
	外部调用登陆窗口脚本开始
	主要应用于直接在页面里面弹出一个登陆窗口，无需要跳转到通行证就可以登陆
	
	*/	
	////创建载入窗口
	_CreateLoadWin:function(tx)
	{
		///创建登陆窗口，先是载入窗口，当载入完毕之后，设置登陆窗口
		var _loadwindiv =  document.createElement('DIV');
		_loadwindiv.id = '_loadwindiv';
		_loadwindiv.style.zIndex = parseInt(this.PageMaxzIndex ) + 9;	
		_loadwindiv.style.position = 'absolute';
		_loadwindiv.style.border = ' 1px solid #1f5fa9';
		_loadwindiv.style.backgroundColor = "#aacbee";
		_loadwindiv.style.padding ='5px';	
		_loadwindiv.innerHTML = (tx != null) ? tx : '载入131通行证...';
		_loadwindiv.style.left = (parseInt(document.body.clientWidth) / 2 ) - parseInt(120) / 2  + 'px';
		_loadwindiv.style.top = (parseInt(this.getPageSize()[3]) / 2 ) - parseInt(20) /2 + 'px';
		document.body.appendChild(_loadwindiv);
	},
	_HiddenLoadWin:function()
	{
		if (document.getElementById('_loadwindiv'))
		{
			document.body.removeChild(document.getElementById('_loadwindiv'));
		}
	},
	///设置登陆窗口的大小
	MiniRepaint:function(width,height)
	{
		var obj = document.getElementById('LoginWin');
		obj.style.width = parseInt(width) + 'px';
		obj.style.height = parseInt(height) + 'px';
		obj.style.left = (parseInt(document.body.clientWidth) / 2 ) - parseInt(width) / 2  + 'px';
		obj.style.top = (parseInt(this.getPageSize()[3]) / 2 ) - parseInt(height) /2 + 'px';
		var fobj = document.getElementsByName("frmlogin")[0];
		fobj.width = width;
	    fobj.height = height;
	},
	///弹出登陆窗口
	MiniLoginWin:function(action)
	{	
	
		var MaskDiv = document.createElement('DIV');
		MaskDiv.style.filter="alpha(opacity=80)";
		MaskDiv.style.opacity=0.8;
		MaskDiv.style.backgroundColor = "#FFFFFF";//设置蒙版颜色
		MaskDiv.id = 'MaskDiv_';///蒙版id
		MaskDiv.style.position = 'absolute';///设置蒙版以流的方式呈现，否则，不能覆盖其他物件上面
		MaskDiv.style.zIndex = parseInt(this.PageMaxzIndex ) + 8;	 ///设置zIndex，
		MaskDiv.style.left = 0;
		MaskDiv.style.top = 0;
		MaskDiv.style.width = parseInt( document.body.clientWidth)-2 +'px';//覆盖整个屏幕
		var t = (parseInt(this.getPageSize()[3]) > parseInt(document.body.scrollHeight)) ? parseInt(this.getPageSize()[3])+'px' : parseInt(document.body.scrollHeight)+'px';
		MaskDiv.style.height = t;
		
		document.body.appendChild(MaskDiv);
		///载入界面
		this._CreateLoadWin();
		
		///创建登陆窗口，先是载入窗口，当载入完毕之后，设置登陆窗口
		var _loginwindiv =  document.createElement('DIV');
		_loginwindiv.id = 'LoginWin';
		_loginwindiv.style.zIndex = parseInt(this.PageMaxzIndex ) + 10;		
		_loginwindiv.style.position = 'absolute';
		_loginwindiv.style.border = ' 1px solid #0094c8';
		_loginwindiv.style.backgroundColor = "#99e7ff";
		_loginwindiv.style.padding ='5px';	
		_loginwindiv.style.width = '1px';
		_loginwindiv.style.height = '1px';
		_loginwindiv.action = action;
		_loginwindiv.innerHTML = '<iframe scrolling="no" id="frmlogin" frameborder="0" width="1" height="1" onload="javascript:PassPort._MINILOGINWINFRAMEONLOAD();" name="frmlogin" ></iframe>';
		document.body.appendChild(_loginwindiv);
		document.getElementsByName("frmlogin")[0].src = this.Server+this.MiniLoginUrl;
		///设置登陆成功后的委托事件
		PassPort.AddLoginDelegate('PassPort._MINILOGINOK("'+action+'")');		
	},

	///登陆窗口载入完毕之后触发事件
	_MINILOGINWINFRAMEONLOAD:function()
	{
		///隐藏等待界面
		this._HiddenLoadWin()
	},
	///登陆成功之后触发事件
	_MINILOGINOK:function(action)
	{
		this.MiniLoginClose();
		eval(action);
		this.ReMoveLoginDelegate('PassPort._MINILOGINOK("'+action+'")');	
	},
	MiniLoginClose:function()
	{		
		this.ReMoveLoginDelegate('PassPort._MINILOGINOK("'+document.getElementById('LoginWin').action+'")');
		document.body.removeChild(document.getElementById('LoginWin'));
		//document.getElementById('MaskDiv_').style.filter="alpha(opacity=0)";
		//document.getElementById('MaskDiv_').style.opacity=0;
		document.body.removeChild(document.getElementById('MaskDiv_'));
	}	
	
	/*
	
	外部调用登陆窗口脚本结束
	主要应用于直接在页面里面弹出一个登陆窗口，无需要跳转到通行证就可以登陆
	
	*/
	
	
	/*
	
	*/
}





