﻿// JScript 文件

//文字模板
var T = {
    MsgDiv : '<div class={0}>{1}&nbsp;&nbsp;{2}</div><div id=msgid_{3} class=msg_txt>{4}</div>',
    FaceTP : '<div style="position:relative;height:6px;"><table id="face_preview" cellspacing="0" border="0" cellpadding="0"><tr><td id="face_preview_img"></td></tr><tr><td id="face_title"></td></tr></table></div>',
    FaceTH : '<table id="face_page_{0}" cellpadding="0" cellspacing="0" border="1" bordercolor="#CCCCCC"  style="margin:0 auto;border-collapse:collapse;border:solid 1px #CCC;"'+
        ' class="{1}" align="center">',
    FaceTD : '<td align="center" valign="middle" style="padding:2px;"><div style="width:{0}px;height:{0}px;border:solid 1px #FFF;background:url(images/faces.gif) no-repeat {1}px 0px;" '+
        'onmouseover="Tool.Face.ItemMouseEvt(this,{2},true)" onmouseout="Tool.Face.ItemMouseEvt(this,{2},false)" onclick="Tool.Face.ItemClick({2})"></div></td>',
    FaceFT : '</table>',
    FaceED : '<div style="padding:8px;color:#999;" onmouseover="Tool.Face.HidePreview()"><div id="face_loading" class=f-l></div><div id="face_pager" class=f-r></div>'+
        '<div class=f-c></div></div>',
    FaceImg : '<img src="images/faces.gif" class="d-n" onload="Tool.Face.OnLoad()" />',
    NoFace : '<td onmouseover="Tool.Face.HidePreview()" style="padding:2px;"><div style="width:{0}px;height:{0}px;border:solid 1px #FFF;"></div></td>',
    UbbUrl : '<a href="{0}" target="_blank" title="{1}">{0}</a>',
    UbbImg : '<a href="{0}" target="_blank" title="{1}"><img border=0 src="{0}" /></a>'
};

//全局变量
var G = {
    XML : [],
    Cid : 0, MeUid : 0, ChatKf : 0, Kfs : [], KfArray : [], Groups : [], GroupArray : [], Config : null,
    Me : { Name : "", Tel : "", QQ : "", Msn : "", Email : "" },
    StatusClass : ['kf_off','kf_on','kf_on'],
    StatusName : [TXT[2],TXT[3],TXT[4]],
    ReplyArray : [TXT[5],
                  TXT[6],
                  TXT[7],
                  TXT[8],
                  TXT[9]],
    VoteArray : [TXT[10],
                 TXT[11],
                 TXT[12],
                 TXT[13],
                 TXT[14]]
};

//实体
function Kf(_uid,_nick,_gid,_isoffdisplay){
    this.firstclick = true;
    this.uid = _uid; this.nick = _nick; this.gid = _gid; this.isoffdisplay = _isoffdisplay; this.isonline = 0;
    this.hasvote = false; this.voteidx = 3; this.voteword = "";
    this.logo = ""; this.tel = ""; this.fax = ""; this.qq = ""; this.msn = ""; this.email = ""; this.memo = "";
    this.fillcard = function(_logo,_tel,_fax,_qq,_msn,_email,_memo){
        this.logo = _logo; this.tel = _tel; this.fax = _fax; this.qq = _qq; this.msn = _msn; this.email = _email; this.memo = _memo;
    }
};
function Evt(){
    this.id = 0; this.cmd = ""; this.fuid = 0; this.fnick = ""; this.content = ""; this.time = "";
    this.fill = function(_id,_cmd,_fuid,_fnick,_content,_time){
        this.id = _id; this.cmd = _cmd; this.fuid = _fuid; this.fnick = _fnick; this.content = _content; this.time = _time;
    }
};

//var isauto = false, autotimer = null;
//function automsg(){
//    isauto = !isauto;
//    if (!isauto) clearInterval(autotimer);
//    else {
//        Chat.Message.CurrentMsgTxt = '消息';
//        autotimer = setInterval('Chat.Request("sendmsg");', 5000);
//    }
//};

//对话类
var Chat = {
    Path : "",
    CurrentUid : -1, IsFirstRequest : true, IsWindowFocus : true, RequestEnable : true,
    IsLW : false, NoReadMsgCount : 0,
    LW : function(chk){
        this.IsLW = typeof(chk) != 'undefined' ? chk : !this.IsLW;
        fillHTML("top_right_lw", this.IsLW ? TXT[15] : TXT[16]);
        $("chat_lw").className = this.IsLW ? "d-b" : "d-n";
        if (!this.IsLW) this.NoReadMsgCount = 0;
        this.SetChatTitle(this.CurrentUid);
    },
    ItemClick : function(uid){
        if (uid == this.CurrentUid) return;
        if (uid > 0 && this.CurrentUid == 0 && G.Kfs[""+uid].isonline == 0){
            Tool.Card.ClickFromItem(uid);
            return;
        }
        Focus("chat_msg_box");
        $("chat_msg_"+uid).className = 'd-b';
        $("chat_msg_"+this.CurrentUid).className = 'd-n';
        this.SetChatTitle(uid);
        this.FirstChat(uid);
        this.Message.ScrollBottom();
        this.CurrentUid = uid;
        this.Request("setchatkf");
    },
    CreateItem : function(uid,s){
        var div = document.createElement('div');
        div.setAttribute("id", "chat_msg_"+uid);
        div.className = "d-n";
        div.innerHTML = s;
        return div;
    },
    SetChatTitle : function(uid){
        if (uid < 0) return;
        var u = G.Kfs[""+uid];
        if (this.IsLW) fillHTML("chat_title", TXT[17]); 
        else if (uid == 0) fillHTML("chat_title", u.nick); 
        else if (u.isonline == 0) fillHTML("chat_title", StrFormat('<b class={0}>&nbsp;</b><a hidefocus href="###" onclick="Tool.Click(\'card\');return false;" title="{1}">{1}</a> {2}',G.StatusClass[u.isonline],u.nick,TXT[18]));
        else fillHTML("chat_title", StrFormat('<b class={0}>&nbsp;</b>{2} <a hidefocus href="###" onclick="Tool.Click(\'card\');return false;" title="{1}">{1}</a> {3}',G.StatusClass[u.isonline],u.nick,TXT[19],TXT[20]));
        
        $("tool_right").className = (uid > 0) ? "d-b" : "d-n";
    },
    FirstChat : function(uid){
        var u = G.Kfs[""+uid];
        if (uid == 0 || !u.firstclick) return;
        u.firstclick = false;
        if (u.isonline > 0){
            if (getChatData.word.beginchat == "") return;
            this.Message.Add(false,uid,u.nick,getChatData.word.beginchat,cvtTime(getTime()));
        }
    },
    Message : {
        Idx : 0, IsInputFocus : false, SendEnable : true, SendDelay : 2, CurrentMsgTxt : "", TipTimer : null, TipHiddenTimer : null, PostKey : 2,
        UBB : function(s){
            s = s.replace(
                /\[:(\d+)?\]/ig, // [:?]
                function($0, $1){ return StrFormat('<img src="face/{0}.gif" alt="{1}" />',$1,Tool.Face.Titles[parseInt($1)-1]);}
            );
            s = s.replace(
                /\[(.*?)\](.*?)\[\/\1\]/i, // [?]?[/?]
                function($0, $1, $2){
                    switch($1.toLowerCase()){
                        case "url": return StrFormat(T.UbbUrl,$2,TXT[61]);
                        case "img": return StrFormat(T.UbbImg,$2,TXT[21]);
                        default: return $0;
                    }
                }
            );
            return s;
        },
        Add : function(isme,uid,nick,msg,time){
            var div = document.createElement("div");
            div.innerHTML = StrFormat(T.MsgDiv,(isme?'nick_f':'nick_t'),nick,time,++this.Idx,this.UBB(msg));
            $("chat_msg_"+uid).appendChild(div);
            delete div;
        },
        Send : function(){
            if (!Chat.RequestEnable) return;
            var u = G.Kfs[""+Chat.CurrentUid];
            if (Chat.CurrentUid == 0){
                this.Tip(TXT[22],3);
                return;
            }
            else if (u.isonline == 0){
                this.Tip(TXT[23],3);
                return;
            }
            var msg = $("chat_msg_box").value.Trim();
            if (msg == ''){
                with($("chat_msg_box")){ value = ''; focus(); }
                this.Tip(TXT[24],3);
                return;
            }
            else if (msg.length > 1000){
                return;
            }
            else if (!this.SendEnable){
                this.Tip(StrFormat(TXT[25],this.SendDelay),this.SendDelay);
                return;
            }
            this.Add(true, Chat.CurrentUid, TXT[26], msg.toHTML(), cvtTime(getTime()));
            this.ScrollBottom();
            this.SendEnable = false;
            window.setTimeout("Chat.Message.SendEnable=true;", this.SendDelay * 1000);
            this.CurrentMsgTxt = msg;
            Chat.Request("sendmsg");
            Chat.InputType.Update();
            with($("chat_msg_box")){value="";focus();};
        },
        SystemTxt : function(uid,txt,type){//type:ok/alert/error
            var div = document.createElement("div");
            div.className = "system_tip";
            div.innerHTML = StrFormat('<b class="icos tip_{0}"></b><div class=system_tip_txt>{1}<br>{2}</div>',type,getTime(),txt);
            $("chat_msg_"+uid).appendChild(div);
            if (uid == Chat.CurrentUid) this.ScrollBottom();
        },
        Tip : function(txt,delay){
            clearTimeout(this.TipTimer);
            clearTimeout(this.TipHiddenTimer);
            with($("chat_tip")){innerHTML = txt+'&nbsp;'; className = "d-b";}
            this.AlphaTip(95);
            this.TipTimer = setTimeout("Chat.Message.HiddenTip(95)", delay * 1000);
        },
        AlphaTip : function(v){
            with($("chat_tip").style){
                filter = "Alpha(Opacity="+v+")";
                MozOpacity = v/100;
            }
        },
        HiddenTip : function(v){
            this.AlphaTip(v);
            if (v>0) this.TipHiddenTimer = setTimeout("Chat.Message.HiddenTip("+(v-5)+")", 30);
            else { $("chat_tip").className = "d-n"; this.AlphaTip(95); }
        },
        SetInputFocus : function(chk){
            this.IsInputFocus = chk;
        },
        KeyPress : function(evt){
            evt = evt || window.event;
            if (evt.altKey && evt.keyCode == 83){
                this.Send(); return false;
            }
            if (this.PostKey == 1){
	            if (!evt.shiftKey && evt.keyCode==13){
	                this.Send(); return false;
	            }
            }
            if (this.PostKey == 2){
                if (evt.ctrlKey && evt.keyCode==13){
                    this.Send(); return false;
                }
            }
            return true;
        },
        Counter : function(el,maxLen){
            if (el.value.length > maxLen){
                el.value = el.value.substr(0,maxLen);
                this.Tip(StrFormat(TXT[27],maxLen),3);
            }
            if (el.value.length > 0) Chat.InputType.Send();
            else if (Chat.InputType.SetMsgPredict && this.SendEnable) Chat.InputType.Send();
        },
        ScrollTop : function(){
            setTimeout(function(){$("chat_msg_body").scrollTop=0;},0);
        },
        ScrollBottom : function(){
            setTimeout(function(){with($("chat_msg_body"))scrollTop=scrollHeight+1000;},0);
        }
    },
    InputType : {
        SendEnable : true, SendTimer : null, HideTimer : null, ShowDelay : 8, SendDelay : 8, IsRapidReply : false,
        IsMsgPredict : false, LastMsg : '', LastSendTimer : null,
        Send : function(){
            clearTimeout(this.LastSendTimer);
            this.LastSendTimer = setTimeout("Chat.InputType.LastSend();", 1000);
            if (!this.SendEnable
                || this.IsRapidReply
                || Chat.CurrentUid == 0
                || Chat.CurrentUid == -1
                || G.Kfs[""+Chat.CurrentUid].isonline < 1) return;
            this.LastMsg = this.IsMsgPredict ? $("chat_msg_box").value.Trim() : '';
            this.SendEnable = false;
            clearTimeout(this.SendTimer);
            clearTimeout(this.LastSendTimer);
            Chat.Request("inputtype");
            this.SendTimer = setTimeout("Chat.InputType.SendEnable=true;", this.SendDelay * 1000);
        },
        LastSend : function(){
            if (!this.IsMsgPredict) return;
            var msg = $("chat_msg_box").value.Trim();
            if (msg != this.LastMsg){
                this.LastMsg = msg;
                Chat.Request("inputtype");
            }
        },
        SetMsgPredict : function(chk){
            this.IsMsgPredict = chk;
            this.SendDelay = chk ? 2 : 8;
        },
        Update : function(){
            clearTimeout(this.SendTimer);
            clearTimeout(this.LastSendTimer);
            this.SendEnable = true;
        },
        Show : function(nodes){
            for (var i=0; i<nodes.length; i++){
                if (nodes[i].fuid == Chat.CurrentUid){
                    clearTimeout(this.HideTimer);
                    with($("chat_input_type")){
                        className = "d-b";
                        innerHTML = StrFormat(TXT[28], G.Kfs[""+Chat.CurrentUid].nick);
                    }
                    this.HideTimer = setTimeout("Chat.InputType.Hide();", this.ShowDelay * 1000);
                    break;
                }
            }
        },
        Hide : function(){
            $("chat_input_type").className = "d-n";
        }
    },
    SoundPlay : function(type){
        if (type < 0 || type > 2) return;
        try { $("swf_sound").getSound(type); }catch(e){}
        if (type == 2) return;
        if (!this.IsWindowFocus) window.focus();
    },
    BuildKfs : function(kfids){
        var kf;
        for (var i=0; i<G.KfArray.length; i++){
            kf = G.Kfs[""+G.KfArray[i]];
            kf.isonline = kfids.inc(""+kf.uid,",") ? 1 : 0;
            $("kf_"+kf.uid).className = G.StatusClass[kf.isonline];
            fillHTML("kf_status_"+kf.uid, G.StatusName[kf.isonline]);
            
            if (kf.isonline == 0 && kf.isoffdisplay == 0){
                $("kf_"+kf.uid).className = "d-n";
            }
        }
    },
    CallBack : {
        count : 0, usersTxt : ["*",""],
        FirstGet : function(){//alert(this.req.responseText);
            G.XML["FirstGet"] = LoadXML(this.req.responseText);
            var nodes = G.XML["FirstGet"].getElementsByTagName("CE");
            if (nodes == null || nodes.item(0).childNodes.length == 0){
                alert(TXT[29]);
                window.close(); 
                return;
            }
            var meNode = nodes.item(0).childNodes;
            G.MeUid  = Math.floor(GetNodeValue(meNode,0));
            G.ChatKf = Math.floor(GetNodeValue(meNode,1));
            Chat.Config.Init(GetNodeValue(meNode,3));
            Chat.CallBack.GetKfs(GetNodeValue(meNode,2));
            
            FirstGet.Save();
            Chat.AfterFirstRequest();
            
            G.XML["FirstGet"] = null; nodes = null;
        },
        GetKfs : function(kfids){
            this.usersTxt[1] = kfids;
            if (this.usersTxt[1] == this.usersTxt[0]) return;
            this.usersTxt[0] = this.usersTxt[1];
            Chat.BuildKfs(kfids);
            
            if (Chat.IsFirstRequest){
                var chk = !$("cbx_isshowwelcome").checked;
                if (chk) Tool.Click('welcome');
                
                if (kfids.length == 0){
                    Chat.LW(true);
                    
                    if (chk && getChatData.word.lwtip == '') Tool.Close();
                    else fillHTML("box_welcome_word", getChatData.word.lwtip);
                }
                else if (chk && getChatData.word.welcome == '') Tool.Close();
            }
            else{
                Chat.SetChatTitle(Chat.CurrentUid);
            }
        },
        GetMsg : function(nodes){
            var e, isCurrentuid = false, firstKfId = 0;
            for (var i=0; i<nodes.length; i++){
                e = nodes[i];
                if (typeof G.Kfs[""+e.fuid] == 'undefined') continue;
                Chat.Message.Add(false,e.fuid,e.fnick,e.content.toHTML(),cvtTime(e.time));
                if (e.fuid == Chat.CurrentUid) isCurrentuid = true;
                if (i == 0) firstKfId = e.fuid;
            }
            if (isCurrentuid) {
                Chat.InputType.Hide();
                Chat.Message.ScrollBottom();
            }
            if (Chat.CurrentUid == 0
                || (Chat.CurrentUid > 0 
                    && Chat.CurrentUid != firstKfId 
                    && G.Kfs[""+Chat.CurrentUid].isonline == 0)
                )
            {
                if (G.Kfs[""+firstKfId] != null){
                    G.Kfs[""+firstKfId].firstclick = false;
                    Chat.ItemClick(firstKfId);
                }
            }
            if (Chat.IsLW){
                Chat.LW(false);
                //Chat.NoReadMsgCount += nodes.length;
                //fillHTML("top_right_lw", TXT[30]+"("+Chat.NoReadMsgCount+")");
            }
            
            PopWin($("cbx_tip_pop").checked);
            PlaySound("msg", $("cbx_tip_sound").checked);
        },
        GetScript : function(nodes){
            for (var i=0; i<nodes.length; i++){
                try{ eval(nodes[i].content); }catch(e){}
            }
        },
        GetError : function(){
            //
        },
        PostError : function(){
            //
        }
    },
    Request : function(state){
        if (!this.RequestEnable) return;
        switch(state){
            case "firstget":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_firstget",
                          "post",
                          StrFormat(
                              "cid={0}&styleid={1}&pointkf={2}&autoassign={3}&chatadvantage={4}&invitekf={5}&clientid={6}&name={7}&tel={8}&qq={9}&msn={10}&email={11}&language={12}&pagetitle={13}&pageurl={14}&tid={15}",
                              G.Cid,
                              getChatData.styleid,
                              G.Config.IsPointKf,
                              G.Config.IsAutoAssign,
                              G.Config.IsChatAdvantage,
                              getChatData.kid,
                              G.MeUid,
                              escape(G.Me.Name),
                              escape(G.Me.Tel),
                              escape(G.Me.QQ),
                              escape(G.Me.Msn),
                              escape(G.Me.Email),
                              getChatData.lan,
                              getChatData.pt,
                              getChatData.pu,
                              getChatData.tid
                          ),
                          this.CallBack.FirstGet,
                          this.CallBack.GetError);
                break;
            case "getevt":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "user_getevt",
                          "post", 
                          StrFormat("cid={0}&meuid={1}&lastid={2}",G.Cid,G.MeUid,this.EvtCommet.LastId),
                          this.EvtCallBack,
                          this.EvtCommet.Error);
                break;
            case "getmulti":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_getmulti",
                          "post",
                          StrFormat("cid={0}&styleid={1}&clientid={2}&chatkf={3}",G.Cid,getChatData.styleid,G.MeUid,G.ChatKf),
                          this.MultiCall.CallBack,
                          this.MultiCall.CallError);
                break;
            case "sendmsg":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_sendmsg",
                          "post", 
                          StrFormat("cid={0}&clientid={1}&tuid={2}&msg={3}&msgid={4}",G.Cid,G.MeUid,this.CurrentUid,this.Message.CurrentMsgTxt.escape(),this.Message.Idx),
                          function(){ },
                          this.CallBack.PostError);
                this.Message.CurrentMsgTxt = "";
                break;
            case "inputtype":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "user_inputtype",
                          "post", 
                          StrFormat("cid={0}&meuid={1}&tuid={2}&msg={3}",G.Cid,G.MeUid,this.CurrentUid,escape(this.InputType.LastMsg)),
                          function(){ },
                          this.CallBack.PostError);
            case "setchatkf":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_setchatkf",
                          "post", 
                          StrFormat("cid={0}&clientid={1}&chatkf={2}",G.Cid,G.MeUid,this.CurrentUid),
                          function(){ },
                          this.CallBack.PostError);
                break;
            case "vote":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_vote",
                          "post", 
                          Tool.Vote.Params,
                          Tool.Vote.CallBack,
                          this.CallBack.PostError);
                break;
            case "lw":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_lw",
                          "post", 
                          LeaveWord.Params,
                          function(){ },
                          this.CallBack.PostError);
                break;
            case "saveconfig":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_saveconfig",
                          "post", 
                          Chat.Config.Params,
                          function(){},
                          this.CallBack.PostError);
                break;
            case "modccname":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_modccname",
                          "post", 
                          StrFormat("cid={0}&clientid={1}&vid={2}",G.Cid,G.MeUid,getChatData.vid),
                          function(){},
                          this.CallBack.PostError);
                break;
            case "adclick":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "user_adclick",
                          "post", 
                          StrFormat("adid={0}",BottomAd.AdId),
                          function(){ },
                          this.CallBack.PostError);
                break;
            case "logout":
                Ajax.Send(this.Path + "WebService/Chat.asmx",
                          "client_logout",
                          "post", 
                          StrFormat("cid={0}&clientid={1}",G.Cid,G.MeUid),
                          function(){ },
                          this.CallBack.PostError);
                break;
        }
    },
    EvtCommet : {
        Enable : true, LastId : 0, LastTime : "", TimeoutTimer : null, TimeoutSeconds : 60, chkFocus : false,
        Connect : function(){
            if (!Chat.RequestEnable) return;
            if (!this.Enable) return;
            this.Enable = false;
            clearTimeout(this.TimeoutTimer);
            this.TimeoutTimer = setTimeout("Chat.EvtCommet.Error();", this.TimeoutSeconds * 1000);
            Chat.Request("getevt");
        },
        ErrorCount : 0, MaxErrorCount : 60,
        Error : function(){
            Chat.EvtCommet.ErrorCount++;
            if (Chat.EvtCommet.ErrorCount > Chat.EvtCommet.MaxErrorCount){
                alert(TXT[31]);
                Chat.EvtCommet.ErrorCount = 0;
            }
            Chat.EvtCommet.Enable = true;
        },
        Recyle : function(){
            this.LastId   = getChatData.LastEvtId;
            this.LastTime = getChatData.now;
            this.Connect();
            setInterval("Chat.EvtCommet.Connect();", 3000); //1000改为3000
        }
    },
    EvtCallBack : function(){//alert(this.req.responseText);
        G.XML["EvtCommet"] = LoadXML(this.req.responseText);
        var nodes = G.XML["EvtCommet"].getElementsByTagName("mod_Evt_item");
        if (nodes == null || nodes.length == 0){
            Chat.EvtCommet.Enable = true;
            G.XML["EvtCommet"] = null;
            return; 
        }
        Chat.EvtCommet.chkFocus = Chat.Message.IsInputFocus;
        var total = nodes.length;
        var evt,evtNode,_MSG=[],_IPT=[],_SCT=[];
        for (var i=0; i<total; i++){
            evt = new Evt();
            evtNode = nodes.item(i).childNodes;
            evt.fill(Math.floor(GetNodeValue(evtNode,0)),
                     GetNodeValue(evtNode,1),
                     Math.floor(GetNodeValue(evtNode,2)),
                     GetNodeValue(evtNode,3),
                     GetNodeValue(evtNode,4),
                     GetNodeValue(evtNode,5));
            switch(evt.cmd){
                case "MSG":
                    _MSG.push(evt);break;
                case "IPT":
                    _IPT.push(evt);break;
                case "SCT":
                    _SCT.push(evt);break;
                default:break;
            }
        }
        if (_MSG.length > 0) Chat.CallBack.GetMsg(_MSG);
        if (_IPT.length > 0) Chat.InputType.Show(_IPT);
        if (_SCT.length > 0) Chat.CallBack.GetScript(_SCT);
        Chat.EvtCommet.LastId = evt.id;
        Chat.EvtCommet.LastTime = evt.time;
        Chat.EvtCommet.Enable = true;
            
        if (Chat.EvtCommet.chkFocus) Focus("chat_msg_box");
        
        G.XML["EvtCommet"] = null; nodes = null;
    },
    MultiCall : {
        Enable : true, Timer : null, TimeoutTimer : null, TimeoutSeconds : 60, chkFocus : false,
        CallBack : function(){//alert(this.req.responseText);
            G.XML["MultiCall"] = LoadXML(this.req.responseText);
            var nodes = G.XML["MultiCall"].getElementsByTagName("CE");
            if (nodes == null || nodes.length == 0){
                Chat.MultiCall.Enable = true;
                G.XML["MultiCall"] = null;
                return; 
            }
            Chat.MultiCall.chkFocus = Chat.Message.IsInputFocus;
            var meNode   = nodes.item(0).childNodes;
            G.ChatKf     = Math.floor(GetNodeValue(meNode,1));
            
            Chat.CallBack.GetKfs(GetNodeValue(meNode,2));
            
            Chat.MultiCall.Enable = true;
            if (Chat.MultiCall.chkFocus) Focus("chat_msg_box");
            
            G.XML["MultiCall"] = null; meNode = null;
        },
        CallError : function(){
            Chat.MultiCall.Enable = true;
        },
        Connect : function(){
            if (!Chat.RequestEnable) return;
            if (!this.Enable) return;
            this.Enable = false;
            clearTimeout(this.TimeoutTimer);
            this.TimeoutTimer = setTimeout("Chat.MultiCall.CallError();", this.TimeoutSeconds * 1000);
            Chat.Request("getmulti");
        },
        Recyle : function(){
            clearInterval(this.Timer);
            this.Connect();
            this.Timer = setInterval("Chat.MultiCall.Connect()", 8000);  //5000改为8000
        }
    },
    InitChatData : function(){
        G.Cid    = getChatData.cid;
        G.Config = getChatData.config;
        var k = getChatData.kfs;
        var g = getChatData.groups;
        var items = [];
        items.push('<ul>');
        for (var i=1; i<g.length; i++){
            G.Groups[""+g[i][0]] = { gid:g[i][0], name:g[i][1], count:0 };
            G.GroupArray.push(g[i][0]);
            if (g[i][0] > 0) items.push(StrFormat('<li id="group_{0}" class="kf_group">{1}</li>', g[i][0], g[i][1]));
            for (var j=1; j<k.length; j++){
                if (g[i][0] != k[j][2]) continue;
                G.Kfs[""+k[j][0]] = new Kf(k[j][0],k[j][1],k[j][2],k[j][3]);
                G.Kfs[""+k[j][0]].fillcard(k[j][4],k[j][5],k[j][6],k[j][7],k[j][8],k[j][9],k[j][10]);
                G.KfArray.push(k[j][0]);
                $("chat_msg_body").appendChild(this.CreateItem(k[j][0],''));
                G.Groups[""+g[i][0]].count++;
                items.push(StrFormat('<li id="kf_{0}" class="{1}" onclick="Chat.ItemClick({0})" title="{2}">{2} (<span id="kf_status_{0}">{3}</span>)</li>', k[j][0], G.StatusClass[0], k[j][1], G.StatusName[0]));
            }
        }
        items.push('</ul>');
        fillHTML("chat_kf_list", items.toString(''));
        for (var i=1; i<g.length; i++){
            if (g[i][0] > 0 && (!G.Config.IsKfListGroupHidden || G.Groups[""+g[i][0]].count == 0)) $("group_"+g[i][0]).className = "d-n";
        }
        G.Kfs["0"] = new Kf(0,TXT[32],0,0);
    },
    AfterFirstRequest : function(){
        this.IsFirstRequest = false;
        $('page_loader').className = 'd-n';
        if (G.ChatKf > 0 && G.Kfs[""+G.ChatKf].isonline==1) this.ItemClick(G.ChatKf);
        else this.ItemClick(0);
        setTimeout("Chat.EvtCommet.Recyle();",0);
        setTimeout("Chat.MultiCall.Recyle();",5000);
        setTimeout("Tool.File.Init();",0);
        if (G.Config.IsClickIcon) SetVisitorState(4);
        else if (G.ChatKf > 0 && !G.Config.IsPointKf) SetVisitorState(1);
        else SetVisitorState(4);
        
        this.InputType.SetMsgPredict(true);
        if (G.Me.Name != "") setTimeout("Chat.Request('modccname');",200); 
    },
    ChangeKf : function(uid){
        G.Kfs[""+uid].firstclick = false;
        this.ItemClick(uid);
        this.Message.SystemTxt(uid, StrFormat(TXT[33],G.Kfs[""+uid].nick), 'alert');
    },
    RedirectKf : function(urlhead,cid,uid){
        getChatData.word.endchat = TXT[34];
        this.End();
        setTimeout(StrFormat('window.location="{0}client.aspx?s=3&cid={1}&style=1&vid=0&kid={2}&pt={3}&pu={4}&t={5}";',urlhead,cid,uid,getChatData.pt,getChatData.pu,Math.random()), 5000);
    },
    Close : function(chk){
        if (!this.RequestEnable){ window.close(); return; }
        if (chk){
            Tool.Vote.ClickBeforeClose();
            if (!confirm(TXT[35])) return;
        }
        this.Request("logout");
        SetVisitorState(6);
        if (G.Config.IsAddFavorite){try{window.external.AddFavorite($("companyurl").innerText,$("companyname").innerText);}catch(e){};}        window.close();
    },
    End : function(){
        if (getChatData.word.endchat != "") this.Message.SystemTxt(this.CurrentUid, getChatData.word.endchat, 'alert');
        this.Request("logout");
        this.RequestEnable = false;
        SetVisitorState(6);
    },
    ReLogin : function(tid){
        if (Math.floor(getChatData.tid) >= Math.floor(tid)) return;
        this.RequestEnable = false;
        $("lw_send").disabled = true;
        alert(TXT[36]);
    },
    Regist : function(chk){
        if (chk){
            G.Me.Name   = $("reg_name").value.Trim();
            G.Me.Tel    = $("reg_tel").value.Trim();
            G.Me.QQ     = $("reg_qq").value.Trim();
            G.Me.Msn    = $("reg_msn").value.Trim();
            G.Me.Email  = $("reg_email").value.Trim();
            
            if (G.Me.Name.length == 0 || G.Me.Name == TXT[60]){
                G.Me.Name = G.Me.Tel = G.Me.QQ = G.Me.Msn = G.Me.Email = "";
                alert(TXT[60]+"\t");
                Focus("reg_name");
                return;
            }
            LeaveWord.Fill();
        }
        
        Tool.Close();
        $("page_box_close").className = "d-b";
        this.Request("firstget");
    },
    Start : function(){
        this.Path = getChatData.VirtualPath;
        
        //init
        PageBox.Init();
        Tool.Init();
        BottomAd.Start();
        LeaveWord.Init();
        
        //getdata
        this.InitChatData();
        if (G.MeUid == 0 && getChatData.config.IsClientRegist) Tool.Click("regist");
        else this.Request("firstget");
        
        //ReleaseCache
        if(Browser.isIE) setInterval(CollectGarbage, 10000);
    }
};

//更新监控状态
function SetVisitorState(state){
    if (getChatData.vid == 0) return;
    $("PostImg").src = StrFormat(
        'KfInviteState.aspx?cid={0}&vid={1}&kid={2}&state={3}&t={4}',G.Cid, getChatData.vid, getChatData.kid, state, Math.random()
    );
};

//页面窗口
var PageBox = {
    theDiv : null, divHeight : 0, divWidth : 0, winHeight : 0, winWidth : 0, IsDisplay : false,
    Show : function(){
        if (this.IsDisplay) return;
        $('page_bg').className = 'd-b';
        this.IsDisplay = true;
        this.CenterPos();
    },
    Hide : function(){
        if (!this.IsDisplay) return;
        $('page_bg').className = 'd-n';
        this.IsDisplay = false;
    },
    CenterPos : function(){
        this.divHeight = parseInt(this.theDiv.offsetHeight) + (Browser.isIE?6:0);
        this.divWidth  = parseInt(this.theDiv.offsetWidth) + (Browser.isIE?6:0);;
        this.winHeight = parseInt(document.body.offsetHeight);
        this.winWidth  = parseInt(document.body.offsetWidth);
        this.theDiv.style.left = (this.winWidth - this.divWidth)/2 + "px";
        this.theDiv.style.top  = (this.winHeight - this.divHeight)/2 + "px";
    },
    Init : function(){  
        window.drag_001 = new _Drag("drag_001","page_box","page_box_title");
        this.theDiv = $("page_box");
    }
};

//工具栏
var Tool = {
    CurrentId : "", First : [],
    IdArray : ["welcome","face","url","pic","file","reply","set","vote","card"],
    Init : function(){
        with($("page_box_close_btn")){
            onmouseover = function(){ this.className='icos3 ovr'; };
            onmouseout  = function(){ this.className='icos3 out'; };
            onmousedown = function(){ this.className='icos3 dwn'; };
            onclick     = function(){ Tool.Close(); };
        }
        with($("chat_msg_box")){
            onkeydown  = function(){ Chat.Message.KeyPress(event); };
            onfocusin  = function(){ Chat.Message.SetInputFocus(true) };
            onfocusout = function(){ Chat.Message.SetInputFocus(false) };
            onpropertychange = function(){ Chat.Message.Counter(this,1000); };
        }
        with($("chat_msg_send")){
            onmouseover = function(){ this.className='icos3 ovr'; };
            onmouseout  = function(){ this.className='icos3 out'; };
            onclick     = function(){ Chat.Message.Send(); };
        }
        for(var i=1; i<this.IdArray.length; i++){
            eval(StrFormat('$("tool_{0}").onclick=function(){Tool.Click("{0}");return false;};',this.IdArray[i]));
        }
        with($("tool_down")){
            onclick = function(){ SaveRecord(); };
        }
        with($("reg_name")){
            value       = TXT[60];
            style.color = "#999999";
            onfocusin   = function(){ if(this.value==TXT[60]){this.value='';this.style.color="#333333";} };
            onfocusout  = function(){ if(this.value==''){this.value=TXT[60];this.style.color="#999999";} };
        }
        if (!getChatData.config.IsVote){
            $("tool_vote").parentNode.className = "d-n";
        }
    },
    Click : function(id){
        if (this.CurrentId == id){ PageBox.Show(); return; }
        //窗口显示前
        switch(id){
            case "welcome":
                this.Welcome.Show();
                break;
            case "face":
                this.Face.Show();
                break;
            case "file":
                this.File.Check();
                fillHTML("page_box_title",event.srcElement.title);
                break;
            case "reply":
                this.Reply.Show();
                break;
            case "vote":
                this.Vote.Show();
                break;
            case "card":
                this.Card.Show(Chat.CurrentUid);
                fillHTML("page_box_title",TXT[37]);
                break;
            case "regist":
                $("page_box_close").className = "d-n";
                fillHTML("page_box_title",TXT[59]);
                break;
            default:
                fillHTML("page_box_title",event.srcElement.title);
        }
        $("box_"+id).className = "d-b";
        $("box_"+this.CurrentId).className = "d-n";
        PageBox.Show();
        //窗口显示后
        switch(id){
            case "url":
                $("input_url").select();
                break;
            case "pic":
                $("input_pic").select();
                break;
            default:
                break;
        }
        this.CurrentId = id;
    },
    Close : function(){
        switch(this.CurrentId){
            case "file":
                this.File.Reset();
                break;
        }
        PageBox.Hide();
        $("box_"+this.CurrentId).className = "d-n";
        this.CurrentId = "";
    },
    Welcome : {
        Show : function(){
            if (!Tool.First["welcome"]) {
                Tool.First["welcome"] = true;
                fillHTML("box_welcome_word", getChatData.word.welcome);
            }
            fillHTML("page_box_title",getChatData.cname);
        }
    },
    Face : {
        Titles : TXT["FaceTitles"],
        Enable : false, ImgWidth : 24, Count : 0, RowItems : 11, PageRows : 5, PageItems : 0, PageIndex : 1, PageCount: 0,
        Show : function(){
            if (!Tool.First["face"]) {
                Tool.First["face"] = true;
                this.Count = this.Titles.length;
                this.PageItems = this.RowItems*this.PageRows;
                this.PageCount = Math.floor(this.Count/this.PageItems)+(this.Count%this.PageItems==0?0:1);
                var t = [], k, w;
                t.push(T.FaceTP);
                for (var p=1; p<=this.PageCount; p++){
                    t.push(StrFormat(T.FaceTH,p,p==1?(Browser.isFirefox?'v-v':'d-b'):'d-n'));
                    for (var i=0; i<this.PageRows; i++){
                        t.push('<tr>');
                        for (var j=0; j<this.RowItems; j++){
                            k = j + i * this.RowItems + (p-1) * this.PageItems;
                            w = this.ImgWidth + (Browser.isFirefox?-1:1);
                            if (k+1 <= this.Count)
                                t.push(StrFormat(T.FaceTD, w, -k*24, k+1));
                            else
                                t.push(StrFormat(T.NoFace, w));
                        }
                        t.push('</tr>');
                    }
                    t.push(T.FaceFT);
                }
                t.push(T.FaceED);
                fillHTML("box_face",t.toString(''));
                fillHTML("face_loading","<span class=loader>"+TXT[58]+"</span>"+T.FaceImg);
            }
            fillHTML("page_box_title",TXT[38]);
        },
        OnLoad : function(){
            fillHTML("face_loading",TXT[1]);
            this.SetPager();
            this.Enable = true;
        },
        SetPager : function(){
            var t = [];
            t.push(this.PageIndex + '/' + this.PageCount + ' &nbsp; ');
            t.push(this.PageIndex > 1 ? '<a href="###" onclick="Tool.Face.GotoPage('+(this.PageIndex-1)+');return false;">'+TXT[39]+'</a>' : TXT[39]);
            t.push(' &nbsp;');
            t.push(this.PageIndex < this.PageCount ? '<a href="###" onclick="Tool.Face.GotoPage('+(this.PageIndex+1)+');return false;">'+TXT[40]+'</a>' : TXT[40]);
            fillHTML("face_pager",t.toString(''));
        },
        GotoPage : function(v){
            if (!this.Enable) return;
            $("face_page_"+v).className = (Browser.isFirefox?'v-v':'d-b');
            $("face_page_"+this.PageIndex).className = 'd-n';
            this.PageIndex = v;
            this.SetPager();
        },
        HidePreview : function(){
            if (!this.Enable) return;
            $("face_preview").style.display = "none";
        },
        ItemMouseEvt : function(obj,v,chk){
            if (!this.Enable) return;
            if (chk){
                obj.style.borderColor = "Blue";
                $("face_preview").style.display = "block";
                var t = v % this.RowItems;
                $("face_preview").className = (t>0&&t<=Math.floor(this.RowItems/2))?"face_preview_r":"face_preview_l";
                $("face_preview_img").innerHTML = '<img src="face/'+v+'.gif" border="0" />';
                $("face_title").innerHTML = this.Titles[v-1];
            }
            else{
                obj.style.borderColor = "#FFF";
            }
        },
        ItemClick : function(v){
            if (!this.Enable) return;
            $("chat_msg_box").value += StrFormat('[:{0}]',v);
            if (!event.ctrlKey){
                this.HidePreview();
                Tool.Close();
            }
            Focus("chat_msg_box");
        }
    },
    Pic : {
        DefaultUrl : 'http://',
        Insert : function(){
            var url = $("input_pic").value.Trim();
            if (url == '' || url == this.DefaultUrl){
                with($("input_pic")){ value=this.DefaultUrl; select(); }
                return;
            }
            $("chat_msg_box").value += StrFormat('[IMG]{0}[/IMG]',url);
            this.Cancel();
            Focus("chat_msg_box");
        },
        Cancel : function(){
            $("input_pic").value = this.DefaultUrl;
            Tool.Close();
        }
    },
    Url : {
        DefaultUrl : 'http://',
        Insert : function(){
            var url = $("input_url").value.Trim();
            if (url == '' || url == this.DefaultUrl){
                with($("input_url")){ value=this.DefaultUrl; select(); }
                return;
            }
            $("chat_msg_box").value += StrFormat('[URL]{0}[/URL]',url);
            this.Cancel();
            Focus("chat_msg_box");
        },
        Cancel : function(){
            $("input_pic").value = this.DefaultUrl;
            Tool.Close();
        }
    },
    File : {
        Init : function(){
            if (getChatData.IsPostFile) this.Reset();
            else $("tool_file").parentNode.className = "d-n";
        },
        PostCallBack : function(fileinfo,error,isok){
            this.Cancel();
            if (isok) Chat.Message.SystemTxt(Chat.CurrentUid, StrFormat(TXT[62], fileinfo), "ok");
            else Chat.Message.SystemTxt(Chat.CurrentUid, StrFormat(TXT[63], fileinfo, error), "error");
            Focus("chat_msg_box");
        },
        Check : function(){
            try {
                var win = $("FileIframe").contentWindow;
                var uid = Chat.CurrentUid;
                win.$("filepost_btn").disabled = uid == 0 || G.Kfs[""+uid].isonline == 0;
            }catch(e){}
            
        },
        Reset : function(){
            try {
                $("FileIframe").src = StrFormat("ClientPostFile.aspx?cid={0}&clientid={1}&lan={2}", getChatData.cid, G.MeUid, getChatData.lan);
            }catch(e){}
        },
        Cancel : function(){
            Tool.Close();
        },
        Get : function(uid, filename, filesize, filekey){
            Chat.Message.SystemTxt(uid, StrFormat(TXT[64], filename, filesize, filekey), "alert");
            
            PopWin($("cbx_tip_pop").checked);
            PlaySound("msg", $("cbx_tip_sound").checked);
        }
    },
    Reply : {
        Show : function(){
            if (!Tool.First["reply"]) {
                Tool.First["reply"] = true;
                var t = [];
                t.push('<ul>');
                for (var i=0; i<G.ReplyArray.length; i++){
                    t.push(StrFormat('<li><a href="###" onclick="Tool.Reply.Send(this);return false;" title="{0}">{0}&nbsp;</a></li>',G.ReplyArray[i]));
                }
                t.push('</ul>');
                fillHTML("box_reply", t.toString(''));
            }
            fillHTML("page_box_title",TXT[41]);
        },
        Send : function(o){
            var inputobj = $("chat_msg_box");
            var msg = inputobj.value;
            Chat.InputType.IsRapidReply = true;
            inputobj.value = o.innerText;
            Chat.Message.Send();
            inputobj.value = msg;
            Chat.InputType.IsRapidReply = false;
            Tool.Close();
        }
    },
    Vote : {
        Params : '',
        Show : function(){
            if (!Tool.First["vote"]) {
                Tool.First["vote"] = true;
                var t = [];
                t.push('<span id="vote_title"></span><ul>');
                for (var i=0; i<G.VoteArray.length; i++){
                    t.push(StrFormat('<li><input id="vote_{0}" type="radio" name="vote" /><label id="vote_l_{0}" for="vote_{0}"><em>{1}</em></label></li>',i+1,G.VoteArray[i]));
                }
                t.push('</ul><input id="vote_word" type="txt" class="input-txt" maxlength="100" style="width:220px;"> ');
                t.push('<input id="vote_btn" type="button" class="input-btn" value=" '+TXT[44]+' " onclick="Tool.Vote.Send()" />');
                fillHTML("box_vote", t.toString(''));
            }
            fillHTML("page_box_title",TXT[45]);
            this.Fill();
        },
        Fill : function(){
            var u = G.Kfs[""+Chat.CurrentUid];
            fillHTML("vote_title", u.hasvote ? TXT[46] : u.isonline == 0 ? StrFormat(TXT[47],u.nick) : StrFormat(TXT[48],u.nick));
            $("vote_"+u.voteidx).checked = true;
            $("vote_word").value = u.voteword;
            $("vote_btn").disabled = u.hasvote || u.isonline == 0;
        },
        ClickBeforeClose : function(){
            if (!G.Config.IsVote) return;
            if (Chat.CurrentUid == 0) return;
            var u = G.Kfs[""+Chat.CurrentUid];
            if (!u.hasvote && u.isonline > 0) Tool.Click("vote");
        },
        Send : function(){
            var u = G.Kfs[""+Chat.CurrentUid];
            for (var i=0; i<G.VoteArray.length; i++){
                if ($("vote_"+(i+1)).checked){
                    u.voteidx = i+1; break;
                }
            }
            u.voteword = $("vote_word").value.Trim();
            this.Params = StrFormat('cid={0}&clientid={1}&kid={2}&voteidx={3}&voteword={4}',G.Cid,G.MeUid,Chat.CurrentUid,u.voteidx,escape(u.voteword));
            Chat.Request("vote");
            Tool.Close();
        },
        CallBack : function(){//alert(this.req.responseText);
            G.XML["Vote"] = LoadXML(this.req.responseText);
            var nodes = G.XML["Vote"].getElementsByTagName("int");
            if (nodes == null || nodes.length == 0){
                G.XML["Vote"] = null;
                return;
            }
            var kid = Math.floor(nodes.item(0).firstChild.nodeValue);
            
            if (kid > 0){
                G.Kfs[""+kid].hasvote = true;
                Chat.Message.Tip(TXT[49], 3);
            }
            
            G.XML["Vote"] = null; nodes = null;
        }
    },
    Card : {
        Uid : 0,
        Show : function(uid){
            fillHTML("page_box_title",TXT[37]);
            this.Fill(uid);
        },
        Fill : function(uid){
            if (this.Uid == uid) return;
            this.Uid = uid;
            var u = G.Kfs[""+this.Uid];
            $("card_logoimg").src = u.logo == "" ? "images/u_logo.gif" : getChatData.imageurl + "upload/logoimg/" + u.logo;
            fillHTML("card_nick", u.nick);
            fillHTML("card_tel", u.tel);
            fillHTML("card_fax", u.fax);
            fillHTML("card_qq", u.qq);
            fillHTML("card_msn", u.msn);
            fillHTML("card_email", u.email);
            fillHTML("card_memo", u.memo);
        },
        ClickFromItem : function(uid){
            Tool.Click('card');
            this.Fill(uid);
        }
    }
};

//留言
var LeaveWord = {
    Params : '', Items : [0,0,0,0],
    Post : function(){
        var title   = $("lw_title").value.Trim();
        var name    = $("lw_name").value.Trim();
        var tel     = $("lw_tel").value.Trim();
        var qq      = $("lw_qq").value.Trim();
        var msn     = $("lw_msn").value.Trim();
        var email   = $("lw_email").value.Trim();
        var word    = $("lw_word").value.Trim();
        
        if (title == ""){
            alert(TXT[50]);
            Focus("lw_title");
        }
        else if (name == ""){
            alert(TXT[51]);
            Focus("lw_name");
        }
        else if (this.Items[0] == 1 && tel == ""){
            alert(TXT[52]);
            Focus("lw_tel");
        }
        else if (this.Items[1] == 1 && qq == ""){
            alert(TXT[53]);
            Focus("lw_qq");
        }
        else if (this.Items[2] == 1 && msn == ""){
            alert(TXT[54]);
            Focus("lw_msn");
        }
        else if (this.Items[3] == 1 && email == ""){
            alert(TXT[55]);
            Focus("lw_email");
        }
        else if (word == ""){
            alert(TXT[56]);
            Focus("lw_word");
        }
        else {
            this.Params = StrFormat(
                'cid={0}&styleid={1}&clientid={2}&title={3}&name={4}&tel={5}&qq={6}&msn={7}&email={8}&word={9}',
                G.Cid, getChatData.styleid, G.MeUid, escape(title), escape(name), escape(tel), escape(qq), escape(msn), escape(email), escape(word)
            );
            Chat.Request("lw");
            $("lw_send").disabled = true;
            setTimeout(
                function(){
                    $("lw_send").disabled = false;
                    fillHTML("chat_title", StrFormat("<font color=Green>{0}</span>",TXT[57])); 
                    alert(TXT[57]+'\t');
                    setTimeout('fillHTML("chat_title", TXT[17]);', 3000);
                    with($("lw_word")){ value = ''; focus(); }
                    var mailimg = new Image();
                    mailimg.src = "SysSendMail.aspx?" + Math.random();
                }, 300);
        }
    },
    Fill : function(){
        $("lw_name").value  = G.Me.Name;
        $("lw_tel").value   = G.Me.Tel;
        $("lw_qq").value    = G.Me.QQ;
        $("lw_msn").value   = G.Me.Msn;
        $("lw_email").value = G.Me.Email;
    },
    Init : function(){
        this.Items = getChatData.config.LeaveWordItems;
        
        // 0,1项互换
        var t = this.Items[0]; this.Items[0] = this.Items[1]; this.Items[1] = t;
        
        for (var i=0; i<this.Items.length; i++){
            if (this.Items[i] == 1) $("lw_item_"+i).className = "";
        }
    }
};

//底部广告
var BottomAd = {
    LH : 0,    //text-lineheight px
    Obj : null,
    Top : 0,
    Height : 0,
    Scroll : function(){
        this.Obj.scrollTop = this.Top;
        if (this.Top%this.LH == 0){
            setTimeout("BottomAd.Scroll()", 5000);
        }
        else{
            setTimeout("BottomAd.Scroll()", 15);
        }
        if (this.Top >= this.Height){
            this.Top = 1;
        }
        else if (this.Top%this.LH >= this.LH - 20){
            this.Top += 4;
        }
        else{
            this.Top++;
        }
    },
    Start : function(){
        this.LH = 28;
        this.Obj = $("foot_ad_content");
        var _h = this.Obj.scrollHeight;

        if (_h > this.LH){
            this.Obj.innerHTML += "<br />" + this.Obj.innerHTML;
            this.Height = _h;
            this.Scroll();
        }
    },
    AdId : 0,
    Click : function(v){
        this.AdId = v;
        Chat.Request("adclick");
    }
};

//相关设置
Chat.Config = {
    Params : '', SaveDelay : 5, SaveTimer : null,
    Init : function(items){
        var ss = items.split(',');
        if (ss.length != 4) ss = [1,1,1,2];
        
        $("cbx_isshowwelcome").checked  = ss[0] == 0;
        $("cbx_tip_pop").checked        = ss[1] == 1;
        $("cbx_tip_sound").checked      = ss[2] == 1;
        $("post_key_1").checked         = ss[3] == 1;
        
        this.PostKey(ss[3]);
        
        var s = [
            "cbx_isshowwelcome",
            "cbx_tip_pop",
            "cbx_tip_sound",
            "post_key_1",
            "post_key_2"
            ];
        for (var i=0; i<s.length; i++){
            bindEvent("onclick", $(s[i]), function(){Chat.Config.Update();});
        }
    },
    PostKey : function(v){
        Chat.Message.PostKey = v;
        with ($("chat_msg_send")){
            if (v == 1) title = TXT[42];
            else if (v == 2) title = TXT[43];
        }
    },
    Save : function(){
        this.Params = StrFormat(
            'cid={0}&clientid={1}&config={2},{3},{4},{5}',
            G.Cid,
            G.MeUid,
            $("cbx_isshowwelcome").checked ? 0 : 1,
            $("cbx_tip_pop").checked ? 1 : 0,
            $("cbx_tip_sound").checked ? 1 : 0,
            $("post_key_1").checked ? 1 : 2
        );
        Chat.Request("saveconfig");
    },
    Update : function(){
        clearTimeout(this.SaveTimer);
        this.SaveTimer = setTimeout("Chat.Config.Save()", this.SaveDelay * 1000);
    }
};

//Methord:getStart()\getSound()\saveClient(str)
var FirstGet = {
    IsCookie : false, ErrorCount : 0, AllowCount : 5,
    Start : function(){
        G.Cid = getChatData.cid;
        if (GetCookie("clientid_" + G.Cid) != null){
            this.IsCookie = true;
            G.MeUid = Math.floor(GetCookie("clientid_" + G.Cid));
            this.GetFinish();
        }
        else {
            this.GetFromFlash();
        }
    },
    GetFromFlash : function(){
        try { 
            $("swf_sound").getStart(); 
        }
        catch(e){
            if (this.ErrorCount <= this.AllowCount){
                this.ErrorCount++;
                setTimeout("FirstGet.GetFromFlash()", 200);
            }
            else this.GetFinish();
        }
    },
    FlashReturn : function(clientId){
        //alert("JS函数调用成功!");
        G.MeUid = Math.floor(clientId);
        this.GetFinish();
    },
    GetFinish : function(){
        if(G.MeUid > 0) G.MeUid = 0;
        Chat.Start();
    },
    Save : function(){
        SetCookie("clientid_" + G.Cid, G.MeUid);
        try {
            $("swf_sound").saveClient(""+G.MeUid);
        }
        catch(e) {}
    }
};

//弹出窗口
function PopWin(chk){
    if (!chk || Chat.EvtCommet.chkFocus || Chat.MultiCall.chkFocus) return;
    window.focus();
}

//播放声音
function PlaySound(type, chk){
    if (!chk) return;
    try{
        switch(type){
            case "msg":  $("swf_sound").getSound(); break;
        }
    }catch(e){}
}

//保存聊天记录
function SaveRecord(){
    if (Chat.CurrentUid <= 0) return;
    var u = G.Kfs[""+Chat.CurrentUid];
    var html = 
        '<html>'+
        '<head>'+
        '<title>{0} - {1}</title>'+
        '<style type="text/css">'+
        'html,body{padding:10px 20px;font-size:12px;color:#666;font-family:Tahoma,Verdana,Arial,Helvetica;}'+
        '.title{font-size:14px;}'+
        '.nick_f,.nick_t{line-height:22px;}'+
        '.nick_f{color:Green;}'+
        '.nick_t{color:Blue;}'+
        '.msg_txt{margin:0px 0px 10px 15px;padding:0px 2px;line-height:20px;word-break:break-all;}'+
        '.msg_txt a{color:#666;text-decoration:underline;}'+
        '.system_tip{padding:5px 10px;line-height:20px;border:solid 1px #CCC;background-color:#FFD;}'+
        '</style>'+
        '</head>'+
        '<body><b class=title>{0} - {1}</b><hr size=1>{2}</body>'+
        '</html>';
    var title = StrFormat('{0} ({1})', u.nick, cvtDate(getTime()));
    try {
        var win = window.open("about:blank","_blank");
        win.document.write(StrFormat(html, title, getChatData.cname, $("chat_msg_"+u.uid).innerHTML));
        if (Browser.isIE){
            win.document.execCommand("SaveAs", false, title+".html");
            win.close();
        }
    }catch(e){}
}
