/* 注意，该文件内的资源引用都必须为 images.sohu.com/passport/v3/cardstyle/images 目录 */
function b64_423(str)
{
    b64table = new Array(
            'A','B','C','D','E','F','G','H',
            'I','J','K','L','M','N','O','P',
            'Q','R','S','T','U','V','W','X',
            'Y','Z','a','b','c','d','e','f',
            'g','h','i','j','k','l','m','n',
            'o','p','q','r','s','t','u','v',
            'w','x','y','z','0','1','2','3',
            '4','5','6','7','8','9','-','_');
    var binary = new String();
    for (var i = 0; i < str.length; i ++) {
        for (var j = 0; j < 64; j++) {
            if (str.charAt(i) == b64table[j]) {
                var bin = j.toString(2);
                binary += ("000000" + bin).substr(bin.length);
                break;
            }
        }
        if (j == 64) {
            if (i == 2) {
                /* 去掉 4 个 0 */
                return binary.substr(0, 8);
            } else {
                /* 去掉 2 个 0 */
                return binary.substr(0, 16);
            }
        }
    }
    return binary;
}

function b2i(str)
{
    var x = 0;
    var k = 128;
    for (var i = 0; i < 8; i++, k=k/2) {
        if (str.charAt(i) == "1") {
            x += k;
        }
    }
    return String.fromCharCode(x)
}

function b64_decodex(str)
{
    var ret = new Array();
    var i;
    var x = "";
    for (i = 0; i < str.length; i += 4) {
        x += b64_423(str.substr(i, 4));
    }
    for (i = 0; i < x.length; i += 8) {
        ret += b2i(x.substr(i, 8));
    }
    return ret;
}

function utf8to16(str) 
{ 
    var out, i, j, len, c, c2, c3, c4, s; 

    out = []; 
    len = str.length; 
    i = j = 0; 
    while (i < len) { 
        c = str.charCodeAt(i++); 
        switch (c >> 4) {  
            case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: 
                // 0xxx xxxx 
                out[j++] = str.charAt(i - 1); 
                break; 
            case 12: case 13: 
                // 110x xxxx   10xx xxxx 
                c2 = str.charCodeAt(i++); 
                out[j++] = String.fromCharCode(((c  & 0x1f) << 6) | 
                        (c2 & 0x3f)); 
                break; 
            case 14: 
                // 1110 xxxx  10xx xxxx  10xx xxxx 
                c2 = str.charCodeAt(i++); 
                c3 = str.charCodeAt(i++); 
                out[j++] = String.fromCharCode(((c  & 0x0f) << 12) | 
                        ((c2 & 0x3f) <<  6) | 
                        (c3 & 0x3f)); 
                break; 
            case 15: 
                switch (c & 0xf) { 
                    case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: 
                        // 1111 0xxx  10xx xxxx  10xx xxxx  10xx xxxx 
                        c2 = str.charCodeAt(i++); 
                        c3 = str.charCodeAt(i++); 
                        c4 = str.charCodeAt(i++); 
                        s = ((c  & 0x07) << 18) | 
                            ((c2 & 0x3f) << 12) | 
                            ((c3 & 0x3f) <<  6) | 
                            (c4 & 0x3f) - 0x10000; 
                        if (0 <= s && s <= 0xfffff) { 
                            out[j] = String.fromCharCode(((s >>> 10) & 0x03ff) | 0xd800, 
                                    (s         & 0x03ff) | 0xdc00); 
                        } 
                        else { 
                            out[j] = '?'; 
                        } 
                        break; 
                    case 8: case 9: case 10: case 11: 
                        // 1111 10xx  10xx xxxx  10xx xxxx  10xx xxxx  10xx xxxx 
                        i+=4; 
                        out[j] = '?'; 
                        break; 
                    case 12: case 13: 
                        // 1111 110x  10xx xxxx  10xx xxxx  10xx xxxx  10xx xxxx  10xx xxxx 
                        i+=5; 
                        out[j] = '?'; 
                        break; 
                } 
        } 
        j++; 
    } 
    return out.join(''); 
}

//得到字符串的长度，一个汉字算2个字节
function getStringLen(str)
{
    var cArr = str.match(/[^\x00-\xff]/ig);
    return str.length + (cArr == null ? 0 : cArr.length);
}

var login_status = "";
var logout_status = "";
var renew_status = "";
var PassportSC_modifyed = {
    cvsid: "$Id: pp18030_1.js,v 1.6 2007/04/04 02:34:14 shunzhiyu Exp $",
    appid: 9999,
    //一个汉字算2个字节
    max_line_length: 30,
    domain: "",
    cookie: false,
    email: "",
    autopad: "",              /* 自动填写域名后缀 */
    autoRedirectUrl: "",      /* 首页时是否自动跳转 */
    loginRedirectUrl: "",     /* 登录后是否自动跳转 */
    selectorTitle: "",
    registerUrl: "http://reg.tl.sohu.com/reg/contract.jsp",               /*申请通行证的URL*/
    recoverUrl: "http://sde.game.sohu.com/reg/changepwd.jsp",               /*忘记密码的URL*/ 
    usehttp: 0,
    postru: "",
    emailPostfix: false,
    bindDomainSelector: true,
    curDSindex: -1,

    rootElement: false,
    dsElement: false,
    sElement: false,
    cElement: false,
    dsAnchor: false,
    emailInput: false,
    passwdInput: false,
    pcInput: false,
    loginMsg: false,
    iElement: false,

    eInterval: false,
    maxIntervalCount: 100,
    intervalCount: 0,

    defaultApp: "",
    domainPool: ["chinaren.com", "sogou.com"],
    //自动提示的所有域名的列表
    domainList: ["game.sohu.com", "sohu.com", "chinaren.com", "sogou.com", "vip.sohu.com", "17173.com", "focus.cn"],
    appList: {"1000":"mail","1005":"alumni","10050":"chinaren","1019":"blog", "1017":"pp", "1001":"club", "1038":"crclub", "1039":"xiaonei","1021":"music", "1010":"say", "1042":"cbbs"},
    appName: {"mail":"邮件","alumni":"校友录","chinaren":"ChinaRen","blog":"博客", "pp":"相册", "club":"搜狐社区", "crclub":"CR社区", "xiaonei":"校内","music":"音乐盒", "say":"说吧", "cbbs":"校友论坛"},
    appUrl: {"mail":"","alumni":"http://alumni.chinaren.com","chinaren":"","blog":"http://blog.sohu.com/", "pp":"http://pp.sohu.com/", "club":"http://club.sohu.com", "crclub":"http://club.chinaren.com", "xiaonei":"http://xiaonei.chinaren.com", "say":"http://passport.sogou.com/sso/autopassport.jsp?ru=http://s.sogou.com", "music":"http://passport.sogou.com/sso/autopassport.jsp?ru=http://d.sogou.com/coo/blog/loginMusicBox.so", "cbbs":"http://cbbs.chinaren.com"},
    appPool: false,
    bottomRow: [],
    recomServ: [],          /* Passport推荐其的服务 */

    getDomain: function()
    {
        var hostname = document.domain.split('.');
        var l = hostname.length;
        if (l <= 2) {
            return document.domain;
        }
        else{
        	return "game.sohu.com";  //强制返回 game.sohu.com的后缀，做为帐号后缀的首选
	        //return hostname[l-2] + '.' + hostname[l-1]; //支持 focus.cn/sohu.com/chinaren.com/17173.com/sogu.com
	    }
    },
    addCookie: function(name,value,expireHours)
    {
    	if(this.domain == "") this.domain = this.getDomain();
      	var cookieString=name+"="+escape(value)+ "; path=/; domain=."+this.domain+";";
      	//判断是否设置过期时间
		if(expireHours>0)
		{
		     var date=new Date();
		     date.setTime(date.getTime()+expireHours*3600*1000);
		     cookieString=cookieString+"expire="+date.toGMTString()+";";
		}
		document.cookie=cookieString;
	},
	getCookie: function(name)
	{
        var str = document.cookie;
        for(var i=0;i <= str.length;i++) {
            var end = i + name.length;
            if(str.substring(i, end) == name){
                var valueStart = end + 1;
                var valueEnd = str.indexOf(";",valueStart);
                if (valueEnd < valueStart){
                    valueEnd = str.length;
                }
                return str.substring(valueStart, valueEnd);
            }
        }
        return "";
    },
    deleteCookie: function(name)
    {
    	if(this.domain == "") this.domain = this.getDomain();
        var exp = new Date();   
        exp.setTime(exp.getTime() - 100000);
        var cval = this.getCookie(name);
        document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString()+"; path=/; domain=."+this.domain+";"; 
    },
    preventEvent: function(evt)
    {
        evt.cancelBubble = true;
        evt.returnValue = false;
        if (evt.preventDefault) {
            evt.preventDefault();
        }
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
    },

    getPosition: function(ele, name)
    {
        var pos=0;
        while(ele) {
            pos += ele[name];
            ele = ele.offsetParent;
        }
        return pos;
    },

    getTime:function ()
    {
 	    var x = new Date();
        return x.getTime();
    },
	strip: function (s)
    {
        return s.replace(/^\s+/, '').replace(/\s+$/, '');
    },
	reportMsg: function(code)
	{
		var msg = '';
		switch(code)
		{
			case '1':
				msg += '请输入通行证用户名';
				break;
			case '2':
				msg += '通行证用户名为邮件地址格式';
				break;
			case '3':
				msg += '用户名后缀必须为'+arguments[1];
				break;
			case '4':
				msg += '请输入通行证密码';
				break;
			case '5':
				msg += '用户名或密码错误';
				break;
			case '6':
				msg += '登录超时，请稍后重试';
				break;
			case '7':
				msg += '登录失败，请重试';
				break;
			case '8':
				msg += '网络故障，退出失败，请重新退出';	
				break;
            case '9':
                msg += '登录失败，请稍后重试';
                break;
            case '10':
                msg += '暂时不可登录，请稍后重试';
                break;
            default:
                msg += '登录错误，请稍后重试';
		}
		this.showMsg(msg);
	},

	showMsg: function(msg)
	{
         if (!this.loginMsg) 
         	return;
         this.loginMsg.innerHTML = msg;
	},

    parsePassportCookie: function ()
    {
        var cookies = document.cookie.split('; ');
        for (var i = 0; i < cookies.length; i++)
        {
            if (cookies[i].indexOf('passport=') == 0)
            {
                var cookievalue = cookies[i].substr(9);
                break;
            }
            if (cookies[i].indexOf('ppinfo=') == 0)
            {
                var cookievalue = cookies[i].substr(7);
                break;
            }   
        }
        if(i == cookies.length)
        {
        	this.cookie = false;
        	return;
        }
    	try
    	{
            var x = unescape(cookievalue).split('|');
            if (x[0] == '1') 
            { 
                var cookie_raw_info = utf8to16(b64_decodex(x[3]));
                this._parsePassportCookie(cookie_raw_info);
                return;
            }
        }
        catch (e) {}
    },

    //可以由外部的产品来调用该函数，返回userid
    cookieHandle: function ()
    {
        if (!this.cookie) {
            this.parsePassportCookie();
        }
        if (this.cookie && this.cookie['userid'] != '') 
        {
            return this.cookie['userid'];
        }
        else
        {
            return "";
        }
    },

    _parsePassportCookie: function (str) 
    {
        var keyStart_offset;
        var eq_offset;
        var lenEnd_offest;
        this.cookie = new Object;

        keyStart_offset = 0;
        eq_offset = str.indexOf(':', keyStart_offset);
        while (eq_offset != -1) {
            var k;
            var l;
            var v;
            k = str.substring(keyStart_offset, eq_offset);
            lenEnd_offset = str.indexOf(':', eq_offset + 1);
            if (lenEnd_offset == -1) {
                break;
            }
            l = parseInt(str.substring(eq_offset + 1, lenEnd_offset));
            v = str.substr(lenEnd_offset + 1, l);
            if (str.charAt(lenEnd_offset + 1 + l) != '|') {
                break;
            }
            this.cookie[k] = v;
            keyStart_offset = lenEnd_offset + 2 + l;
            eq_offset = str.indexOf(':', keyStart_offset);
        }

        try {
            this.cookie['service'] = new Object;
            var x = this.cookie['service'];
            x['mail'] = 0;
            x['alumni'] = 0;
            //chinaren是一个虚拟的东西
            x['chinaren'] = 0;
            x['blog'] = 0;
            x['pp'] = 0;
            x['club'] = 0;
            x['crclub'] = 0;
            x['xiaonei'] = 0;
            x['say'] = 0;
            x['music'] = 0;


            var y = this.cookie['serviceuse'];
            if (y.charAt(0) == 1) {
                x['mail'] = 'sohu';
            } else if (y.charAt(2) == 1) {
                x['mail'] = 'sogou';
            } else if (y.charAt(6) == 1) {
                x['mail'] = 'chinaren';
            }

            if (y.charAt(1) == 1) {
                x['alumni'] = 1;
            }

            if (y.charAt(3) == 1) {
                x['blog'] = 1;
            }
            if (y.charAt(4) == 1) {
                x['pp'] = 1;
            }

            if (y.charAt(5) == 1) {
                x['club'] = 1;
            }

            if (y.charAt(7) == 1) {
                x['crclub'] = 1;
            }
            if (y.charAt(8) == 1) {
                x['xiaonei'] = 1;
            }

            if (y.charAt(9) == 1) {
                x['say'] = 1;
            }
            if (y.charAt(10) == 1) {
                x['music'] = 1;
            }
        } catch (e) { }
    },

    getBottomRow: function () 
    {
        var i = 0;
        var length = this.max_line_length - getStringLen(this.defaultApp);
        this.bottomRow[0] = new Array();
        this.bottomRow[1] = new Array();

        //判断cookie是否存在
        if(!this.cookie)
            return;
        //以下生成底下的2行文字服务
        i = this._getBottomRow(this.bottomRow[0], length, 0);
        length = this.max_line_length;
        i = this._getBottomRow(this.bottomRow[1], length, i);
    },

    _getBottomRow: function (row, len, offset) 
    {
        var app, j;
        var x = this.cookie['service'];
        var y = this.appPool;
        var i = offset;
        var strlen;
        for (j = 0 ; i < y.length; i++) {
            app = y[i]["app"];
            //由于prototype对object进行了扩展，所以在此判断一下
            if(typeof(app) != 'string' )
                continue;
            if(typeof(x[app]) == "undefined")
                continue;
            if (x[app] != 0) {
                strlen = getStringLen(y[i]["name"]);
                if (len - strlen < 0) break;
                len -= (strlen + 2);
                row[j] = y[i];
                if (app == "mail") {
                    if (x["mail"] == "sohu") {
                        row[j]["url"] = "http://mail.sohu.com";
                    } else if (x["mail"] == "sogou") {
                        row[j]["url"] = "http://mail.sogou.com/2gmail/login.jsp";
                    } else {
                        row[j]["url"] = "http://mail.chinaren.com";
                    }
                }
                j++;
            }
            else
            {
                if(y[i]["name"]=="ChinaRen")
                {
                    continue;
                }
                var relen = this.recomServ.length;
                this.recomServ[relen] = y[i];
                //对于没有开通mail服务的帐号，目前只可能是chinaren的
                if (app == "mail")
                {
                    this.recomServ[relen]["url"] = "http://mail.chinaren.com";
                }
            }
        }
        return i;
    },

    // 根据lastdomain生成 emailPostfix 
    parseLastDomain: function (list)
    {
        this.emailPostfix = new Array();
        var lastdomain_ar = new Array();
        var lastdomain = "",useridar = "",lastdomain_ar;
        var cookies = document.cookie.split('; ');
        for (var i = 0; i < cookies.length; i++) {
            if (cookies[i].indexOf('lastdomain=') == 0) {
                try {
                    lastdomain_ar = unescape(cookies[i].substr(11)).split('|');
                } catch (e) { }
                break;
            }
        }

        var j = 0;
        //如果|分割开的数据小于3个，则直接返回
        if(lastdomain_ar.length>=3)
        {
            var userid_raw_info = utf8to16(b64_decodex(lastdomain_ar[1]));
            var userid_ar = userid_raw_info.split("|");
            //解析userid，cookie中的第一个是最新登录的userid
            for(var i=0;i<userid_ar.length;i++)
            {
                if(userid_ar[i]!="")
                {
                    this.emailPostfix[j] = userid_ar[i];
                    j++;
                }
            }
        }
        //实际上现在的lastdomain变量一直为空
        if (lastdomain != "") 
        {
            this.emailPostfix[j] = lastdomain; j++;
            if (lastdomain != this.domain) { 
                this.emailPostfix[j] = this.domain; j++;
            }
        }
        else
        {
            this.emailPostfix[j] = this.domain; j++;
        }

        for (var i in list)
        {
            if(typeof(list[i]) != 'string' ) continue;
            if (list[i] != lastdomain && list[i] != this.domain)
            {
                this.emailPostfix[j] = list[i]; j++;
            }
        }
    },

    parseAppid: function () 
    {
        var id = this.appid.toString();
        var i = 0;
        this.appPool = new Array();
        for (var j in this.appList) {
            var x = this.appList[j];
            if(typeof(x) != 'string' ) continue;
            if (j == id) {
                this.defaultApp = this.appName[x];
            } else {
                this.appPool[i] = {"app":x, "name":this.appName[x], "url":this.appUrl[x]}; 
                i++;
            }
        }
    },

    /* 下面是 Login/Logout 函数 */
    doPost: function ()
    {
        for (var i = 0; i < document.forms.length; i++) {
            if (document.forms[i].name == "loginform") {
                break;
            }
        }
        if (i == document.forms.length) {
            document.location.href = "http://passport.sohu.com";
            return false;
        }
        document.forms[i].action = "http://passport.sohu.com/sso/login_js.jsp?appid="+this.appid+"&ru="+this.postru;
        document.forms[i].submit();
        return false;
    },
    
    doLogin: function () 
    {
        if (this.eInterval) return; // 必须判断一下，避免连续两次点击
        login_status = "";
        this.intervalCount = 0;
        this.sElement.innerHTML = "";

        this.email = this.strip(this.emailInput.value);
        var email = this.email;
        var password = this.strip(this.passwdInput.value);
        var pc = 0;

        if (this.pcInput.checked == true) pc = 1;
        if (email == "")
        {
            this.reportMsg('1');
            this.emailInput.focus();
            return false;
        }
        if (email.indexOf('@') == -1) 
        {
            if (this.autopad != "")
            {
                email = email + '@' + this.autopad;
            }
            else
            {
                this.reportMsg('2');
                this.emailInput.focus();
                return false;
            }
        }
        //如果autopad不为空，则限制只能输入本域的用户
        if (this.autopad != "") 
        {
            var dpostfix = email.substr(email.indexOf('@')+1);
            if(this.autopad!=dpostfix)
            {
                this.reportMsg('3',this.autopad);
                this.emailInput.focus();
                this.passwdInput.value="";
                return false;
            }
        }
        if (password == "") {
            this.reportMsg('4');
            this.passwdInput.value = "";
            this.passwdInput.focus();
            return false;
        }

        if (this.usehttp == 1) {
            return this.doPost();
        }
        //显示Passport等待状态框，执行后将破坏 document.forms
        this.drawPassportWait('正在登录搜狐通行证，请稍候...');
        return this.loginHandle(email,password,pc,PassportSC_modifyed.sElement,PassportSC_modifyed.loginFailCall,PassportSC_modifyed.loginSuccessCall);
    },

    //可以由外部的产品调用该js来实现登录，参数为一个node
    loginHandle: function (user_id,pwd,pc,ele,lfc,lsc)
    {
        //判断ele是否是对象类型的
        if (typeof(ele) != "object") 
        {
            return false;
        }
        //得到当前输入域的domain 
        if(this.domain == "")
        {
            this.domain = this.getDomain();
        }
        var ra = this.getTime();
        try
        {
        	var url = "https://passport.sohu.com/sso/login.jsp?userid=" + encodeURIComponent(user_id) + "&password=" + encodeURIComponent(pwd) + "&appid=" + this.appid + "&persistentcookie=" + pc + "&s=" + ra;
        }
        catch(e)
        {
        	var url = "https://passport.sohu.com/sso/login.jsp?userid=" + user_id + "&password=" + pwd + "&appid=" + this.appid + "&persistentcookie=" + pc + "&s=" + ra;
        }
        if (this.domain != "sohu.com") 
        {
            url += "&domain="+this.domain;
        }
        var newScript = document.createElement("script");
        newScript.src = url;
        ele.appendChild(newScript);
        this.eInterval = setInterval(function(){PassportSC_modifyed.loginIntervalProc(lfc,lsc,ele)},100);
        return false;
    },

    loginIntervalProc: function (lfc,lsc,ele) 
    {
        if (login_status == "" && this.intervalCount < this.maxIntervalCount) {
            this.intervalCount ++;
            return;
        }

        /* 此时有返回结果，或者已经超时。clear..... */
        clearInterval(this.eInterval);
        this.eInterval = false;

        if (login_status != "success" || this.intervalCount >= this.maxIntervalCount)
        {
            lfc();
            return;
        }
        //非自动跳转的页面才种其它域的cookie
        if(PassportSC_modifyed.loginRedirectUrl == "")
        {
        	this.autoProcAllDomain("login",ele);	
        }
        //自动跳转的，则设置cookie
        else
        {
        	this.addCookie("crossdomain",this.getTime(),336);
        }
        lsc();
    },

    //登录失败后的回调函数; 这里面不能引用 this 代表 PassportSC_modifyed
    loginFailCall: function ()
    {
        PassportSC_modifyed.sElement.innerHTML = "";
        PassportSC_modifyed.drawLoginForm();
        //console.info("loginFailCall login_status: "+login_status);
        if (PassportSC_modifyed.intervalCount >= PassportSC_modifyed.maxIntervalCount) {
            PassportSC_modifyed.reportMsg('6');
            PassportSC_modifyed.emailInput.focus();
        } else if (login_status == 'error3' || login_status == 'error2') {
            PassportSC_modifyed.reportMsg('5');
            PassportSC_modifyed.passwdInput.focus();
        } else if (login_status == 'error5') {
            PassportSC_modifyed.reportMsg('10');
            PassportSC_modifyed.passwdInput.focus();
        } else {
            PassportSC_modifyed.reportMsg('9');
            PassportSC_modifyed.passwdInput.focus();
        }
    },

    //登录成功后回调函数
    loginSuccessCall: function ()
    {
        PassportSC_modifyed.parsePassportCookie();
        //console.info("loginSuccessCall login_status: "+login_status);
        if (PassportSC_modifyed.cookie && PassportSC_modifyed.cookie['userid'] != '')
        {
            PassportSC_modifyed.email = "";
            //登录成功后是否自动跳转
            if(PassportSC_modifyed.loginRedirectUrl != "")
            {
                //如果是自动跳转，需要判断是否是mail登录用户，然后判断本域的用户登录
                if(PassportSC_modifyed.cookie['service']['mail'] != "0" && (PassportSC_modifyed.appid=="1000" || PassportSC_modifyed.appid=="1014" || PassportSC_modifyed.appid=="1037"))
                {
                    //如果不是本域的用户，则让它重新登录
                    if(PassportSC_modifyed.domain.indexOf(PassportSC_modifyed.cookie['service']['mail'])==-1)
                    {
                        PassportSC_modifyed.drawLoginForm();
                    }
                    else
                    {
                        /*不需要等待，种其它域的cookie放在自动跳转后的页面来完成*/
                        document.location.href = PassportSC_modifyed.loginRedirectUrl;
                    }
                }
                else
                {

	                if (document.location.href == PassportSC_modifyed.loginRedirectUrl)
	                {
	                    document.location.reload();
	                }
	                else
	                {
	                    document.location.href = PassportSC_modifyed.loginRedirectUrl;
	                }
                }
            }
            //不需要自动跳转，就画卡片
            else
            {
                //Cookie验证成功后再生成下面的服务文字
                PassportSC_modifyed.getBottomRow();
                PassportSC_modifyed.drawPassportCard();
            }
        }
        else
        {
            PassportSC_modifyed.drawLoginForm();
            PassportSC_modifyed.reportMsg('7');
        }
    },

    doLogout: function () 
    {
        if (this.eInterval) return; // 必须判断一下，避免连续两次点击退出
        logout_status = "";
        this.intervalCount = 0;
        this.sElement.innerHTML = "";
        this.logoutHandle(this.sElement,PassportSC_modifyed.logoutFailCall,PassportSC_modifyed.logoutSuccessCall);
    },
    //可以由外部产品来调用退出
    logoutHandle: function(ele,lfc,lsc)
    {
        //判断ele是否是对象类型的
        if (typeof(ele) != "object") 
        {
            return false;
        }
        //得到当前输入域的domain 
        if(this.domain == "")
        {
            this.domain = this.getDomain();
        }
        var ra = this.getTime();
        if (document.location.protocol == 'http:') {
            var url = 'http://passport.sohu.com/sso/logout.jsp?s=' + ra;
        } else {
            var url = 'https://passport.sohu.com/sso/logout.jsp?s=' + ra;
        }
        if (this.domain != "sohu.com" ) {
            url += "&domain="+this.domain;
        }
        var newScript = document.createElement("script");
        newScript.src = url;
        ele.appendChild(newScript);
        this.eInterval = setInterval(function(){PassportSC_modifyed.logoutIntervalProc(lfc,lsc,ele)}, 100);
    },

    logoutIntervalProc: function (lfc,lsc,ele) 
    {
        if (logout_status == "" && PassportSC_modifyed.intervalCount < PassportSC_modifyed.maxIntervalCount) {
            PassportSC_modifyed.intervalCount ++;
            return;
        }
        /* 此时有返回结果，或者已经超时。clear..... */
        clearInterval(PassportSC_modifyed.eInterval);
        PassportSC_modifyed.eInterval = false;
        //退出失败
        if (logout_status != "success" || PassportSC_modifyed.intervalCount >= PassportSC_modifyed.maxIntervalCount)
        {
            lfc();
            return;
        }

        /* 无论退出结果如何，都继续执行退出 */
        PassportSC_modifyed.autoProcAllDomain("logout",ele);
        lsc();
    },

    //登录失败后的回调函数
    logoutFailCall: function () 
    {
        PassportSC_modifyed.sElement.innerHTML = "";
        PassportSC_modifyed.reportMsg('8');
    },

    //登录成功后回调函数
    logoutSuccessCall: function ()
    {
        //再重新生成一次domanselect list
        PassportSC_modifyed.parseLastDomain(PassportSC_modifyed.domainList); 
        PassportSC_modifyed.drawLoginForm();
        //退出成功后，在调用其它产品的提供的一个方法
        try
        {
            logoutApp();
        }
        catch (e) 
        {
        }
    },
    //重新生成cookie，该函数可由外部产品来进行调用
    renewCookie: function(ele,lfc,lsc)
    {
    	//判断ele是否是对象类型的
        if (typeof(ele) != "object") 
        {
            return false;
        }
        //得到当前输入域的domain 
        if(this.domain == "")
        {
            this.domain = this.getDomain();
        }
        var ra = this.getTime();
        var url = "http://passport.sohu.com/sso/renew.jsp?s=" + ra;
        if (this.domain != "sohu.com") 
        {
            url += "&domain="+this.domain;
        }
        var newScript = document.createElement("script");
        newScript.src = url;
        ele.appendChild(newScript);
        this.eInterval = setInterval(function(){PassportSC_modifyed.renewIntervalProc(lfc,lsc,ele)},100);
        return false;
    },
    renewIntervalProc: function (lfc,lsc,ele) 
    {
        if (renew_status == "" && this.intervalCount < this.maxIntervalCount) {
            this.intervalCount ++;
            return;
        }

        /* 此时有返回结果，或者已经超时。clear..... */
        clearInterval(this.eInterval);
        this.eInterval = false;

        if (renew_status != "success" || this.intervalCount >= this.maxIntervalCount)
        {
        	try{lfc();} catch(e){}
            return;
        }
        //console.info("loginIntervalProc login_status: "+login_status);
        this.autoProcAllDomain("renew",ele);
        try{lsc();} catch(e){}
    },
    //设置其它所有域的cookie
    autoProcAllDomain: function (action,ele)
    {
        var newScript, url, x, domain;
        for (x in this.domainPool) {
            domain = this.domainPool[x];
            if(typeof(domain) != 'string' ) continue;
            if(this.domain == "") this.domain = this.getDomain();
            if (this.domain == domain) continue;
            url = PassportSC_modifyed.crossDomainUrl(action,domain);
            if (url)
            {
                iframe = document.createElement("iframe");
                iframe.src = url;
                iframe.style.width = "0";
                iframe.style.height = "0";
                ele.appendChild(iframe);
            }
        }
    },
    //该函数由自动跳转后的页面来调用，从而完成跨域种其它域的cookie
    setCrossDomainCookie: function (action,ele)
    {
    	//判断是否需要跨域设置cookie
    	var cookie = this.getCookie("crossdomain");
    	if(cookie == "" || cookie == "0") return;
        var newScript, url, x, domain;
        for (x in this.domainPool) {
            domain = this.domainPool[x];
            if(typeof(domain) != 'string' ) continue;
            if(this.domain == "") this.domain = this.getDomain();
            if (this.domain == domain) continue;
            url = PassportSC_modifyed.crossDomainUrl(action,domain);
            if (url)
            {
                iframe = document.createElement("iframe");
                iframe.src = url;
                iframe.style.width = "0";
                iframe.style.height = "0";
                ele.appendChild(iframe);
            }
        }
        this.deleteCookie("crossdomain");
    },
    crossDomainUrl: function(action,domain)
    {
    	var curtime = PassportSC_modifyed.getTime();
        if (document.location.protocol == 'http:') 
        {
            var vurl = "http://passport.sohu.com/sso/crossdomain.jsp?s="+curtime+"&action="+action+"&domain=" +domain;
        }
        else
        {
        	var vurl = "https://passport.sohu.com/sso/crossdomain.jsp?s="+curtime+"&action="+action+"&domain=" + domain;
        }
        return vurl;
    },
    //设置某个域的cookie，该函数可由外部产品来调用
	setDomainCookie: function(ele,domain,lsc,lfc)
    {
    	login_status = "";
    	crossdomain_status = "";
    	var curl = PassportSC_modifyed.crossDomainUrl("login",domain);
        if (curl)
        {
            newScript = document.createElement("script");
            newScript.src = curl;
            ele.appendChild(newScript);
        }
        PassportSC_modifyed.eInterval = setInterval(function(){PassportSC_modifyed.setCookieIntervalProc(ele,lsc,lfc)},100);
    },
    setCookieIntervalProc: function(ele,lsc,lfc)
    {	
    	if(crossdomain_status!="")
    	{
    		clearInterval(PassportSC_modifyed.eInterval);
        	PassportSC_modifyed.eInterval = false;
        	lfc();
    		return;
    	}
    	if (login_status == "" && PassportSC_modifyed.intervalCount < PassportSC_modifyed.maxIntervalCount)
    	{
            PassportSC_modifyed.intervalCount ++;
            return;
        }

        /* 此时有返回结果，或者已经超时。clear..... */
        clearInterval(PassportSC_modifyed.eInterval);
        PassportSC_modifyed.eInterval = false;

        if (login_status != "success" || this.intervalCount >= this.maxIntervalCount)
        {
            lfc();
            return;
        }
        //console.info("loginIntervalProc login_status: "+login_status);
        lsc();
    },
    /* 下面这一部分函数是用于 domain select 提示的 */
    downDSindex: function () 
    {
        var x = this.dsAnchor.firstChild.rows;
        var i = 0;
        for (; i < x.length; i++) {
            if (x[i].firstChild.idx == this.curDSindex) break;
        }
        if (i >= x.length - 1) { // 没有找到，或者最后一个 
            this.curDSindex = x[0].firstChild.idx;
        } else {
            this.curDSindex = x[i+1].firstChild.idx;
        }
    },
    upDSindex: function () 
    {
        var x = this.dsAnchor.firstChild.rows;
        var last = -1;
        var i = 0;
        for (; i < x.length; i++) {
            if (x[i].firstChild.idx == this.curDSindex) break;
            last = x[i].firstChild.idx;
        }
        if (i == x.length) { // 没有找到
            this.curDSindex = x[0].firstChild.idx;
        } else if (last == -1) { // 第一个
            this.curDSindex = x[x.length-1].firstChild.idx;
        } else {
            this.curDSindex = last;
        }
    },
    findDSindex: function (index) 
    {
        try {
            var x = this.dsAnchor.firstChild.rows;
            for (var i = 0; i < x.length; i++) {
                if (x[i].firstChild.idx == index) return x[i].firstChild;
            }
        } catch (e) {}
        return false;
    },

    clearFocus: function (index) 
    {
        if (typeof(index) != "number") index = this.curDSindex;
        try {
            var x = this.findDSindex(index);
			x.className = '';
			x.style.fontWeight = 'normal';
        } catch (e) {}
    },

    setFocus: function (index) 
    {
        if (typeof(index) != "number") index = this.curDSindex;
        try {
            var x = this.findDSindex(index);
			x.className = 'active';
        } catch (e) {}
    },

    //输入字符的同时，填充下面的列表
    fillEmailSelect: function ()
    {
        var e = this.emailInput.value;
        if (e == "")
        {
            this.dsElement.style.display = "none";
            return;
        }

        var x_postfix = "";
        var x_prefix = "";
        var x_index = e.indexOf("@");
        if (x_index < 0) {
            x_prefix = e;
        } else if (x_index == e.length - 1) { /* 第一次输入 @ */
            x_prefix = e.substr(0, x_index);
        } else {
            x_prefix = e.substr(0, x_index);
            x_postfix = e.substr(x_index + 1);
        }
        var mleft = this.getPosition(this.emailInput,"offsetLeft") - this.getPosition(this.cElement,"offsetLeft");
        if (document.all && !document.addEventListener) { // 处理 IE 浏览器的盒式模型 bug
            mleft += 1;
        }
        this.dsElement.style.marginLeft = mleft + "px";
        this.dsElement.style.marginTop = (this.getPosition(this.emailInput,"offsetTop") - this.getPosition(this.cElement,"offsetTop") + this.emailInput.offsetHeight)+ "px";
        /* version 2 this.dsElement.style.marginLeft = this.getPosition(this.emailInput,"offsetLeft") - this.getPosition(this.rootElement,"offsetLeft") + "px";
           this.dsElement.style.marginTop = this.getPosition(this.emailInput,"offsetTop") - this.getPosition(this.rootElement,"offsetTop") + this.emailInput.offsetHeight+ "px";
         */
        //this.dsElement.style.left = this.getPosition(this.emailInput, "offsetLeft") + "px";
        //this.dsElement.style.top = this.getPosition(this.emailInput, "offsetTop") + this.emailInput.offsetHeight + "px";
        this.dsElement.style.zIndex="2000";
        this.dsElement.style.paddingRight="0";
        this.dsElement.style.paddingLeft="0";
        this.dsElement.style.paddingTop="0";
        this.dsElement.style.paddingBottom="0";
        this.dsElement.style.backgroundColor="white";
        this.dsElement.style.display = "block";

        var myTable = document.createElement("TABLE");
        myTable.width = "100%";
        myTable.cellSpacing = 0;
        myTable.cellPadding = 3;
        var tbody = document.createElement("TBODY");
        myTable.appendChild(tbody);

        var j = 0;
        var haveCurrent = false;
        var isUserid = false;
        var firstItem = -1;
        var userid_postfix = "",userid_prefix = "";
        //从emailPostfix中依次取出userid和domain的list，userid位于前3个
        for (var i = 0; i < this.emailPostfix.length; i++)
        {
            var postfix = this.emailPostfix[i];
            if(typeof(postfix) != 'string' ) continue;
            if(x_postfix != "")
            {
                if (postfix.indexOf(x_postfix) != 0) 
                    continue;
            }
            //包含@，表明是从lastdomain中取出的userid
            if(postfix.indexOf("@")>0)
            {
                if(this.autopad!="" && this.autopad!=postfix.substring(postfix.indexOf("@")+1))
                {
                    continue;
                }
                userid_prefix = postfix.substring(0,postfix.indexOf("@"));
                //Cookie的Userid中不包含已经输入的字符，则跳过即可
                if(userid_prefix.indexOf(x_prefix)!=0)
                {
                    continue;
                }
                //Cookie的Userid的前缀完全等于已经输入的字符，需要标志一下，过滤掉下面的重复的记录
                if(userid_prefix == x_prefix)
                {
                    userid_postfix = postfix.substring(postfix.indexOf("@")+1);
                }
                isUserid = true;
            }
            //不是从lastdomain中取出的
            else
            {
                //对于设置了autopad的，只显示autopad域的域名，其它的不予提示
                if(this.autopad!="" && this.autopad!=postfix)
                {
                    continue;
                }
            }
            //过滤掉重复的后缀
            if(postfix==userid_postfix)
            {
                continue;
            }
            j ++;
            if (firstItem == -1) firstItem = i;
            if (this.curDSindex == i) haveCurrent = true;
            var tr = document.createElement("TR");
            var td = document.createElement("TD");
            td.nowrap = "true";
            td.align = "left";
            //判断emailPostfix的项是否是从cookie中读取的userid，这时不需要在额外增加@...了
            if(isUserid == false)
            {
                td.innerHTML = x_prefix + "@" + postfix;
            }
            else
            {
                td.innerHTML = postfix;
            }

            td.id = "email_postfix_" + i;
            td.idx = i;
            td.onmouseover = function () {
                PassportSC_modifyed.clearFocus();
                PassportSC_modifyed.curDSindex = this.idx;
                PassportSC_modifyed.setFocus();
                this.style.cursor = "hand";
            };

            td.onmouseout = function() {
            };

            td.onclick = function () {
                PassportSC_modifyed.doSelect();
            };

            tr.appendChild(td);
            tbody.appendChild(tr);
            isUserid = false;
        }

        if (j > 0) {
            this.dsAnchor.innerHTML = "";
            this.dsAnchor.appendChild(myTable);
            if (haveCurrent == false) this.curDSindex = firstItem;
            this.setFocus();
        } else {
            this.dsElement.style.display = "none";
            this.curDSindex = -1;
        }
    },

    doSelect: function (setPWfocus) 
    {
        this.dsElement.style.display = "none";
        if(this.emailInput.value=="") return;
        var x = this.findDSindex(this.curDSindex);
        if (x) this.emailInput.value = x.innerHTML;
    },
    //这里的KeyDown事件主要处理IE的上下箭头事件,IE 必须用 keydown 事件，否则判断不出来 'Up/Down'
    checkKeyDown: function (event)
    {
        var keyCode = event.keyCode;
        if (keyCode == 38 || keyCode == 40)
    	{
    		PassportSC_modifyed.clearFocus();
	        if (keyCode == 38)
	        {
	        	PassportSC_modifyed.upDSindex();
	        }
	        else if (keyCode == 40)
	        {
	        	PassportSC_modifyed.downDSindex();
	        }
	        PassportSC_modifyed.setFocus();
	    }
    },
    //这里的KeyPress事件主要处理FIREFOX的上下箭头事件和TT的BUG产生的olns四个字符
    checkKeyPress: function (event)
    {
        var keyCode = event.keyCode;
        if (keyCode == 13)
        {
            PassportSC_modifyed.preventEvent(event);
        }
        //上下箭头
        else if (keyCode == 38 || keyCode == 40)
    	{
    		PassportSC_modifyed.clearFocus();
	        if (keyCode == 38)
	        {
	        	PassportSC_modifyed.upDSindex();
	        }
	        else if (keyCode == 40)
	        {
	        	PassportSC_modifyed.downDSindex();
	        }
	        PassportSC_modifyed.setFocus();
        }
        //TT的Bug的四个字符
        else if(keyCode == 108 || keyCode == 110 || keyCode == 111 || keyCode == 115)
        {
        	setTimeout("PassportSC_modifyed.fillEmailSelect()", 10);					
        }
    },
    //响应用户的输入，填充下拉列表
	checkKeyUp: function (event)
    {
    	var keyCode = event.keyCode;
    	if (keyCode == 13)
    	{
        	PassportSC_modifyed.doSelect();
        }
        else
        {
			PassportSC_modifyed.fillEmailSelect();
		}
    },
    init: function (element) 
    {
        if (this.selectorTitle == "") {
            var title = "请选择您的用户帐号类型";
        } else {
            var title = this.selectorTitle;
        }
        this.rootElement = element;
        this.rootElement.innerHTML = '<div class="ppselecter" style="position: absolute; display: none;"><table width="100%" cellspacing="0" cellpadding="0"><tbody><tr><td style="" class="ppseltit">' + title + '</td></tr><tr><td height="2" /></tr><tr><td /></tr></tbody></table></div><div style="display: none;"></div><div class="passport"></div>';
        this.dsElement = this.rootElement.childNodes[0];
        this.sElement = this.rootElement.childNodes[1];
        this.cElement = this.rootElement.childNodes[2];
        this.dsAnchor = this.dsElement.firstChild.rows[2].firstChild;

        //得到当前输入域的domain
        this.domain = this.getDomain();
        this.parseLastDomain(this.domainList); // 生成domanselect list
        this.parseAppid();
        /* 必须执行 parseAppid 后才能 parsePassportCookie */
        this.parsePassportCookie();
        //解析完Cookie后，再生成下面的服务文字
        this.getBottomRow();

        //这里还差一些代码.. 需要分析 URL，看看是不是 http post 失败跳转回来的页面
        if (this.postru == "") {
            this.postru = document.location.href;
        }
    },

    drawPassportCard: function () 
    {
        var html = '<font color="red"><b>请您刷新页面！</b></font>';
        this.cElement.innerHTML = html;
        this.$iElement();
    },

    $iElement: function()
    {
        var x = this.cElement.getElementsByTagName("div");
        for (var i = 0; i < x.length; i ++) {
            if (x[i].className == "listContA") {
                this.iElement = x[i]; break;
            }
        }
    },

    drawPassportWait: function (str) 
    {
        this.cElement.innerHTML = '<div class="pptitle" name="pptitle">\
                                  <div class="pptLeft">搜狐<span class="color01">通行证</span></div>\
                                  <div class="pptRight"><img src="http://images.sohu.com/passport/v3/cardstyle/images/spacer.gif" alt="" /></div>\
                                  </div>\
                                  <div class="ppContA">\
                                  <div id="ppWaitMsg" class="txt">' + str + '</div>\
                                  </div>';
    },

    drawPassportInfo: function ()
    {
        this.iElement.innerHTML = "";
    },

    getRanServ: function()
    {
        var relen = this.recomServ.length;
        if(relen==0) return "";
        var i = Math.floor(relen * (Math.random()));
        var rtn = '<a href="'+this.recomServ[i]['url']+'" target="_blank">'+this.recomServ[i]['name'] + "</a>";
        if(relen==1) return rtn;
        var j = Math.floor(relen * (Math.random()));
        while(i==j)
        {
            j = Math.floor(relen * (Math.random()));
        }
        rtn += ' | <a href="'+this.recomServ[j]['url']+'" target="_blank">'+this.recomServ[j]['name'] + "</a>";
        return rtn;
    },




    //===========================================================
    
    //内部方框
    //===========================================================
    
    drawLoginForm: function () 
    {
        this.cElement.innerHTML = '<input name="email" type="text" size="19"  autocomplete="off" disableautocomplete    onblur="" >'; 
        var inputs = this.cElement.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].name == "email") this.emailInput = inputs[i];
        }

        this.bindSelector(); //抽象出来，给狐首 pi18030 调用
        this.emailInput.value = this.email; //登录失败后自动填入错误的用户名
        if (this.emailInput.value == "")
            setTimeout(function () {PassportSC_modifyed.emailInput.focus()}, 50);
        else
            setTimeout(function () {PassportSC_modifyed.passwdInput.focus()}, 50);
    },


    bindSelector: function ()
    {
        if (this.bindDomainSelector) {
            this.curDSindex = -1;
            this.emailInput.onblur = function() {
                PassportSC_modifyed.doSelect();
            };
            try
            {
            	//FireFox使用addEventListener
                this.emailInput.addEventListener('keypress',this.checkKeyPress, false);
                this.emailInput.addEventListener('keyup',this.checkKeyUp, false);
            }
            catch (e)
            {
                try 
                { 
                    //IE使用attachEvent
                    this.emailInput.attachEvent("onkeydown", this.checkKeyDown);
                    this.emailInput.attachEvent("onkeypress", this.checkKeyPress);
                    this.emailInput.attachEvent("onkeyup", this.checkKeyUp);
                } catch (e) {}
            }
        }
    },

    drawPassport: function (element)
    {
        if (typeof(element) != "object")
        {
            return;
        }
        this.init(element);
        if (this.cookie && this.cookie['userid'] != '') 
        {
            if (this.autopad != "") {
                // 邮箱页面登录
                var at = this.cookie['userid'].indexOf("@");
                if (at > 0) {
                    if (this.autopad != this.cookie['userid'].substr(at + 1)) {
                        this.drawLoginForm();
                        return;
                    }
                }
            }
            //判断首页是否自动跳转
            if(PassportSC_modifyed.autoRedirectUrl != "")
            {
                document.location.href = this.autoRedirectUrl;
            }
            //不需要自动跳转，则直接画卡片
            else
            {
                this.drawPassportCard();
            }
        }
        else
        {
            this.drawLoginForm();
        }
    },
    
    autoHTTPS: function ()
    {
        if (document.location.protocol == 'http:') {
            this.usehttp = 1;
        }
    }
};

if (typeof encodeURIComponent == "undefined") { // < IE 5.5
    PassportSC_modifyed.usehttp = 1;
}	