var agent = window.navigator.userAgent.toLowerCase();

var OAuth = {
    oauthURL: function (url) {
        return url;
    }
};
function etchat_callback(retDate)
{

    gtjawebEtUI.closeScreenPicBox();
    $("#et_box .chat-main").each(function (index, element) {
        var $chatMain = $(this);
        if ($chatMain.is(":visible"))
        {
            gtjawebEtUI.sendScreenPicCallBack(retDate,$chatMain);

        }
    });


}
var gtjawebEtUI = {
    sendScreenPicCallBack:function(retDate,$chatMain)
    {
        var receiverId = $chatMain.attr("id");
        if (remotegtjawebet.isConnectSuccess() == false) {

            gtjawebEtUI.writeReceiveMessage('sys', '正在登录ET服务器，请稍候...', receiverId);
            gtjaWebEtLoginApi.checkLogin();
            return;

        }
        //{ucCode: 920008, MD5: "0b467557492f1fd07827a75b39129cd8.png"}
        if(retDate&&retDate.ucCode==920008)
        {
            var content = '<img src="' +
                OAuth.oauthURL(gtjaWebEtLoginApi.weblogicserver + 'manage/fileUploadAction.do?method=downLoadFile&MD5=' + retDate.MD5 + '&type=screen&fileSize=') +

                '"/>'




            var receiver = $chatMain.attr('receiverto');

            var toname = $chatMain.attr('username');

            if (~receiver.indexOf("@kf95521.chat.gtja.com")) {
                var ConnectKfStatus = $chatMain.attr('ConnectKfStatus');
                if (ConnectKfStatus != '2') {

                    gtjawebEtUI.SendKf95521Request($chatMain);
                    return;
                }
            }
            toname = '' + "|" + toname;



            // 接收区域写消息
            gtjawebEtUI.writeReceiveMessage('me', content, receiverId);


            var sthread = $chatMain.attr('KfThread');
            var msgbody = {};


            msgbody.body = retDate.MD5;
            msgbody.to = receiver;
            msgbody.fromname = gtjawebEtUI.myusername;
            msgbody.toname = gtjawebEtUI.kfUserName;
            msgbody.thread = sthread;
            msgbody.subject = 'customservice_screen';
            var cmdtypebrand = $chatMain.attr('cmdtypebrand');
            if (cmdtypebrand != null && cmdtypebrand != '')
                msgbody.cmdtypebrand = cmdtypebrand;
            var cmdtypecmd = $chatMain.attr('cmdtypecmd');
            if (cmdtypecmd != null && cmdtypecmd != '')
                msgbody.cmdtypecmd = cmdtypecmd;

            remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
                if (ret == 'success') {
                	//首次发消息时,更新查历史的起止时间,防止查出重复消息
					            var _endtime = $chatMain.attr('_endtime')|| '';
				              if(_endtime=='')
				              {
					              if(data&&data.sendTime)
					              {
					             	   $chatMain.attr("_endtime",data.sendTime);
					              }
				              	
				              }

                } else {

                }
            });

        }
        else
        {
            gtjawebEtUI.writeReceiveMessage('sys', '图片发送失败,请重试...', receiverId);
        }
    },

    handleMessage: function (msg) {
        if (msg._attrib.type && msg._attrib.type != 'chat' && msg._attrib.type != '')
            return;
        var user = msg._attrib.from;
        var userto = msg._attrib.to;


        var content = gtjawebEtUI.GetChildVal(msg, 'body');
        var subject = gtjawebEtUI.GetChildVal(msg, 'subject');

        if (subject == '' && content == '' && gtjawebEtUI.GetChildVal(msg, 'active') != '') {
            //$.WebIM.zxgzHandler(user, aJSJaCPacket.getChildVal('active'),aJSJaCPacket.getThread());
            return;
        }

        var fromname = msg._attrib.fromname;
        var sthread = gtjawebEtUI.GetChildVal(msg, 'thread');
        var toname = msg._attrib.toname;
        if (fromname && fromname != '')
            gtjawebEtUI.kfUserName = fromname;


        gtjawebEtUI.messageHandler(user, content, fromname, toname, subject, sthread, userto, msg);
    },
    msgTipTimertimer: null,
    startMsgTipTimer: function () {
        gtjawebEtUI.stopMsgTipTimer();
        gtjawebEtUI.msgTipTimertimer = setInterval(gtjawebEtUI.msgTipTimerFunc, 1100);
        gtjawebEtUI.blinkTitleStart();
    },
    stopMsgTipTimer: function () {
        if (gtjawebEtUI.msgTipTimertimer != null)
            window.clearInterval(gtjawebEtUI.msgTipTimertimer);
        gtjawebEtUI.msgTipTimertimer = null;
    },
    msgTipTimerFunc: function () {

     
        //$("#et_box .list ul .li_class").removeClass('hasnewmsg');
        //$("#et_box .list ul .li_class.newmsgflag").addClass('hasnewmsg');


        window.setTimeout(function () {
            $("#et_box .list ul .li_class.currentchat.hasnewmsg .chat_msgtip").text('');
            $("#et_box .list ul .li_class.currentchat.hasnewmsg").removeClass('hasnewmsg');

            if ($(".ETUI-chat-main .hasnewmsg").get(0)) {
                gtjawebEtUI.showTips();
            }

        }, 700);
    },
    msgTitletimer: null,
    msgTipTitle: null,
    msgTipCount: -1,
    blinkTitleStart: function () {
        if (gtjawebEtUI.msgTitletimer != null) {
            window.clearInterval(gtjawebEtUI.msgTitletimer);
            gtjawebEtUI.msgTitletimer = null;
        }
        gtjawebEtUI.msgTipTitle = document.title;
        var a = 0,
            b = document.title;

        gtjawebEtUI.msgTitletimer = setInterval(function () {
            {
                if (gtjawebEtUI.msgTipCount >= 0) {
                    if (gtjawebEtUI.msgTipCount == 0) {
                        document.title = gtjawebEtUI.msgTipTitle;
                    } else {
                        a++, 3 == a && (a = 1), 1 == a && (document.title = "\u3010\u3000\u3000\u3000\u3011" + b), 2 == a && (document.title = "\u3010\u65b0\u6d88\u606f\u3011" + b);
                    }

                    gtjawebEtUI.msgTipCount--;

                }
            }

        }, 500);


    },
    showTips: function () {
        gtjawebEtUI.msgTipCount = 10;
        var chat_msgtip=$("li.hasnewmsg .chat_msgtip"),msgTip=0;
        $.each(chat_msgtip,function(){
            var num=$(this).text();
            // console.log(num);
            if(num){
                msgTip+=parseInt(num);
            }
        });

        if(msgTip!=0){
            $(".msgtipcount_showtips").html(msgTip).show();
        }else{
            $(".msgtipcount_showtips").hide();
        }
        //console.log(chat_msgtip.length);
    },
    //设置左侧响应人未读消息数
    get_showTips: function (ehrId,empmsgCount) {
        var str =ehrId.split("@");
        var kfjid=str[0]+".1_4@chat.gtja.com";
        var kfname=str[1];
        var userID = "uroster" + sha256_digest(kfjid);
        var $rosterItem= $("li."+userID);
        if( $rosterItem.get(0) ){
            $rosterItem.find(".chat_msgtip").text(empmsgCount);
            $rosterItem.addClass("hasnewmsg");
        }else{
            gtjawebEtUI.addChatWin(kfjid, kfname, false);
            var $rosterItem= $("li."+userID);
            if( $rosterItem.get(0) ){
                $rosterItem.find(".chat_msgtip").text(empmsgCount);
                $rosterItem.addClass("hasnewmsg");
            }
        }
    },
    //设置未读消息数
    setXXZXUnreadNum: function (typeID,unreadCount) {
    	  var userID = "urosterXXZX" + sha256_digest(typeID);
    	  
        var $rosterItem= $("#et_box #change_ul li."+userID);
        if( $rosterItem.get(0) ){
        	  if(unreadCount&&unreadCount!=''&&unreadCount!='0')
        	  {
                $rosterItem.find(".chat_msgtip").text(unreadCount);
                if(!$rosterItem.hasClass("hasnewmsg"))
                  $rosterItem.addClass("hasnewmsg");
        	  	
        	  }
        	  else
        	  {
               $rosterItem.removeClass("hasnewmsg");        	  		
        	  }
        }
    },
    //设置最近消息记录
    setXXZXRecentTips: function (typeID,stime,content_tipsDiv) {
    	  var userID = "urosterXXZX" + sha256_digest(typeID);
    	  
        var $rosterItem= $("#et_box #change_ul li."+userID);
        if( $rosterItem.get(0) ){
        	 $("#et_box .list ul ." + userID + "  .magtime").text(stime);
           $("#et_box .list ul ." + userID + "  .content_tips").text(content_tipsDiv);
        }
    },
    clickModuleMsgZX: function(zxUrl)
    {
    	 //如果url为空表示,君弘app消息,提示在君弘app中查看
        // console.log(zxUrl);
        window.location.href = "http://www.treeid/GTJAJY_COMM=COMM_INNERURL|URL=http://www.treeid/dlg"+zxUrl+"&tdxmyietitle=%e5%9b%bd%e6%b3%b0%e5%90%9b%e5%ae%89%e8%af%81%e5%88%b8-%e5%af%8c%e6%98%93%e8%b5%84%e8%ae%af&tdxmyiewidth=730&tdxmyieheight=510";
    },
    clickModuleMsgGN: function(gnUrl)
    {    	
    	 //如果url为空表示,君弘app消息,提示在君弘app中查看
    	// console.log(gnUrl);
        if(gnUrl == ''){
            alert("请下载君弘使用该功能！");
        }else{
            window.location.href = gnUrl;
        }
    },
    clickModuleMsgLC: function(riskLevel,prodType,lcUrl)
    {
    	 //如果url为空表示,君弘app消息,提示在君弘app中查看
    	 //riskLevel 风险等级,prodType 产品类型,lcUrl 产品url
    	if(lcUrl == '' || prodType == '0'){
            window.location.href = "http://www.treeid/GTJAJY_COMM=COMM_INNERURL|URL=http://www.treeid/dlglocalurl##homepath##yht\\search\\junhongLicai.html?prodcode=&tdxmyietitle=%e5%af%8c%e6%98%93%e6%8f%90%e7%a4%ba&tdxmyiewidth=740&tdxmyieheight=690";
        }else{
            var confirmQFII = ['2', '7', '8', '9']; //需确认合格投资者的理财产品类型
            if(exports){
                exports.getUserInfo().then(function(userInfo){
                    // console.log("USERINFO:"+JSON.stringify(userInfo));
                    var userInfo = userInfo.list[userInfo.USERCOUNT];
                    userInfo.USER_LONG_CUSTID = '03' + ('000000000000000000000' + userInfo.USER_CUSTID).substr(-12);
                    userInfo.USER_LONG_FUNDID = '03' + userInfo.USER_ORGID + ('0000000000' + userInfo.USER_FUNDID).substr(-10);
                    // var terminalinfo = getEncryptTerminalInfo();
                    var terminalinfo = '';
                    var prodURL = 'https://mall.gtja.com/otc/nso?target_url='+lcUrl+'&clientId='+userInfo.USER_LONG_CUSTID+'&cifAccount='+userInfo.USER_CIFACCOUNT+'&user_code='+userInfo.USERCODE+'&businAccount='+userInfo.USER_LONG_FUNDID+'&cid=Fuyi-new&terminalinfo='+terminalinfo;
                    // console.log("理财跳转:"+prodURL);
                    if(confirmQFII.indexOf(prodType) != -1){
                        var QFIIURL = 'http://www.treeid/dlglocalurl##homepath##yht\\search\\QFII.html?produrl='+prodURL+'&tdxmyietitle=%e5%90%88%e6%a0%bc%e6%8a%95%e8%b5%84%e8%80%85%e8%ae%a4%e5%ae%9a&tdxmyiewidth=770&tdxmyieheight=510';
                        window.location.href = 'http://www.treeid/GTJAJY_COMM=COMM_INNERURL|URL='+QFIIURL;
                    }else{
                        window.location.href = 'http://www.treeid/GTJAJY_COMM=COMM_INNERURL|URL='+prodURL;
                        // window.location.href = 'http://www.treeid/GTJAJY_COMM=COMM_INNERURL|URL=https://mall.gtja.com/otc/nso?target_url=https://mall.gtja.com/otc/g3060/detail?prodCode=486002&clientId=03000003535460&cifAccount=860007560212&user_code=21502781&businAccount=0331060088020981&cid=Fuyi-new&terminalinfo=';
                    }
                });
            }
        }
    },
    
    getContentHtml: function(fromname,subject,body,isMe,cmdtype,jsonData)
    {
    	
    	var content=body||'';
    	if (subject == 'custEvaluate') {
            jsonData = jsonData.replace(/\r\n/g, "\n");
            jsonData = jsonData.replace(/\n/g, " ");
            var evaluateJson = JSON.parse(jsonData);     //
    		  var isCommit=false;
    		  var start0="0";
    		  var start1="0";
    		  var start2="0";
    		  var starAll0="5";
    		  var starAll1="5";
    		  var starAll2="5";
    		  
    		  var start0Tips="";
    		  var start1Tips="";
    		  var start2Tips="";
    		  var start2Tips="";
    		  if(evaluateJson&&evaluateJson.serviceAttitude&&evaluateJson.serviceAttitude!='')
    		  {
    		  	isCommit=true;
    		  	start0=evaluateJson.serviceAttitude;
    		  	start0Tips=start0+'分';
    		  	start1=evaluateJson.businessLevel;
    		  	start1Tips=start1+'分';
    		  	start2=evaluateJson.serviceResponse;
    		  	start2Tips=start2+'分';
    		  	
    		  	starAll0=start0;
	    		  starAll1=start1;
	    		  starAll2=start2;
    		  }
         content='<p class="assess_title">请对我的服务做出评价</passess>'+
                 //'<p style=" border: 0.3px solid #e0e0e0;top: 21px;position:  relative;"></p>'+
                 '<div class="BOX">'+
		                '<div id="star0" class="star starDiv_'+evaluateJson.custEvaluateId+'" data-key="">'+
					                '<span>服务态度:</span>'+
							            '<ul class="star_UL" sid="'+start0+'">';
							            for(var tempi=1;tempi<=starAll0;tempi++)
				                     content=content+ '<li class="'+(start0>=tempi?'on':'')+'" ><a href="javascript:;">'+tempi+'</a></li>';
                 		    content=content+
				                '</ul>'+
							            '<span  class="star_result_span">'+
							                '<strong>'+start0Tips+'</strong>&nbsp;&nbsp;<a></a>'+
							            '</span>'+
					           '</div>'+
					           '<div id="star1" class="star" data-key="">'+
					                '<span>业务水平:</span>'+
							            '<ul class="star_UL" sid="'+start1+'">';
							            for(var tempi=1;tempi<=starAll1;tempi++)
				                     content=content+ '<li class="'+(start1>=tempi?'on':'')+'" ><a href="javascript:;">'+tempi+'</a></li>';
                 		    content=content+
				                '</ul>'+
							            '<span  class="star_result_span">'+
							                '<strong>'+start1Tips+'</strong>&nbsp;&nbsp;<a></a>'+
							            '</span>'+
					            '</div>'+

					            '<div id="star2" class="star" data-key="">'+
					              '<span>服务响应:</span>'+
						            '<ul class="star_UL" sid="'+start2+'">';
							            for(var tempi=1;tempi<=starAll2;tempi++)
				                     content=content+ '<li class="'+(start2>=tempi?'on':'')+'" ><a href="javascript:;">'+tempi+'</a></li>';
                 		    content=content+
				                '</ul>'+
						            '<span  class="star_result_span">'+
						                '<strong>'+start2Tips+'</strong>&nbsp;&nbsp;<a></a>'+
						            '</span>'+
		                 '</div>'+
                 '</div>';//+
                // '<hr style="border: 0.5px solid #e0e0e0;" />';
                 if(isCommit)
                  {
                 	      content=content+  '<div class="starTips" style="text-align: center">'+evaluateJson.remarks+'</div>'+
		                    '<div class="starBut" style="text-align: center"><span class="starButtonOk" custEvaluateId='+evaluateJson.custEvaluateId+'>已提交</span></div>';
                  }
                 else
                 	{
                 		    content=content+
				                 '<div class="suggest" style="text-align: left">'+
				                    '<i></i>'+
				                    '<textarea placeholder="说说其他应改进的地方..." style="width: 280px;border-radius:  5px;"></textarea>'+
				                 '</div>'+  
				                 '<div class="starTips" style="text-align: center">您的评价会让客服做的更好</div>'+
		                     '<div class="starBut" style="text-align: center"><span class="starButton" custEvaluateId='+evaluateJson.custEvaluateId+'>提交</span></div>';
                 		
                 	}
		                 
                
                
         }else if (subject == 'questionSurvey') {
         		var evaluateJson = eval('(' + jsonData + ')'); 
    		    var isCommit=false;
    		      if(evaluateJson&&evaluateJson.result&&evaluateJson.result!='')
    		      {
    		      	var tips="否";
    		      	if(evaluateJson.result=='1')
    		      	  tips='是';
                 content='<p class="assess_title2">'+content+'</p>'+   
		               '<div class="starBut" style="text-align: center">'+
		               '<span class="starButtonOk" >'+tips+'</span></div>';
    		      }
    		      else
    		      {
    		      	
              content='<p class="assess_title2">'+content+'</p>'+    
		               '<div class="starBut" style="text-align: center">'+
		               '<span class="btn_solve yessolve" custEvaluateId='+evaluateJson.questionSurveyId+'>是</span>'+
		               '<span class="btn_solve" custEvaluateId='+evaluateJson.questionSurveyId+'>否</span>&nbsp;&nbsp;</div>';
    		      		
    		      }
               // '<span class="btn_solve yessolve">是</span>'+
                //'<span class="btn_solve">否</span>';
        }else if (subject == 'acceptFile') {
            userName = '系统消息';
            if (isMe)
                content = '您已成功接收您的文件[' + content + ']!';
            else
                content = '对方已成功接收您的文件[' + content + ']!';

        } else if (subject == 'refuseFile') {
            userName = '系统消息';
            if (isMe)
                content = '您拒绝接收您的文件[' + content + ']!';
            else
                content = '对方拒绝接收您的文件[' + content + ']!';

        } else if (subject == 'fileupload') {
            userName = '系统消息';
            var filearry = content.split('|');

            if (isMe)
                content = '您给对方发送文件您的文件<A href="' +
                    OAuth.oauthURL(gtjaWebEtLoginApi.weblogicserver + 'manage/fileUploadAction.do?method=downLoadFile&MD5=' + filearry[0] + '&type=upload&fileSize=' + filearry[1] + '&fileName=' + encodeURIComponent(filearry[2])) +
                    '" rel=nofollow target=_blank><U>[' + filearry[2] + ']</U></A>!';
            else
                content = '对方给您发送文件您的文件<A href="' +
                    OAuth.oauthURL(gtjaWebEtLoginApi.weblogicserver + 'manage/fileUploadAction.do?method=downLoadFile&MD5=' + filearry[0] + '&type=upload&fileSize=' + filearry[1] + '&fileName=' + encodeURIComponent(filearry[2])) +
                    '" rel=nofollow target=_blank><U>[' + filearry[2] + ']</U></A>!';

           
        } else if (subject == 'voice'){
            content = '[语音]，请在国泰君安君弘app上查看！';
        } 
        else if (subject == 'moduleMsg_zx'){ //	资讯消息
        	 var moduleMsg = eval('(' + jsonData + ')'); 
        	 
            content =[
            '<div class="moduleMsg_zx" onClick="gtjawebEtUI.clickModuleMsgZX(',"'",moduleMsg.fyUrl,"'",');" >',
             '<a href="javascript:void(0)"  onclick="return false;"  target="_blank">',
               '<h3>',moduleMsg.title,'</h3>',
             '</a> ',
             '<p style="color: rgb(137, 137, 137);">来源：',moduleMsg.source,'</p> ',
             (
               (moduleMsg.pic&&moduleMsg.pic!='')?               
               '<a href="javascript:void(0)" onclick="return false;" target="_blank"><img src="'+moduleMsg.pic+'" style="margin-top: 5px;"></a>'
               :''
             ),
            '</div>'
            
            ].join('');
            
        } 
        else if (subject == 'moduleMsg_gn'){ //功能消息
        	var moduleMsg = eval('(' + jsonData + ')');         	 
            content =[
            '<div  class="moduleMsg_gn" onClick="gtjawebEtUI.clickModuleMsgGN(',"'",moduleMsg.fyUrl,"'",');"  >',
              '<a href="javascript:void(0)" onclick="return false;" target="_blank">',
                '<h3>',moduleMsg.title,'</h3>',
              '</a> ',
              '<p style="color: rgb(137, 137, 137);">位置：',moduleMsg.fyPosition,'</p> ',
              '<p style="color: rgb(137, 137, 137);">简介：',moduleMsg.description,'</p> ',
             // '<p style="color: rgb(137, 137, 137);">股票：深康佳Ａ(SZ000016)</p> ',
              '<a href="javascript:void(0)" onclick="return false;" target="_blank">',
                '<img src="',moduleMsg.pic,'" style="margin-top: 5px;">',
              '</a>',
            '</div>'
            
            ].join('');
            
        } 
        else if (subject == 'moduleMsg_lc'){ //理财消息
           var moduleMsg = eval('(' + jsonData + ')');
           console.log(JSON.stringify(moduleMsg))
            content =[
            '<div class="moduleMsg_lc" onClick="gtjawebEtUI.clickModuleMsgLC(',"'",moduleMsg.riskLevel,"','",moduleMsg.prodType,"','",moduleMsg.fyUrl,"'",');" >',
             '<a href="javascript:void(0)"  onclick="return false;"  target="_blank">',
               '<h3>',moduleMsg.name,'(',moduleMsg.code,')','</h3>',
             '</a> ',
             (
               (moduleMsg.description&&moduleMsg.description!='')?               
               '<p style="color: rgb(137, 137, 137);">简介：'+moduleMsg.description+'</p> '
               :''
             ),
             (
               (moduleMsg.pic&&moduleMsg.pic!='')?               
               '<a href="javascript:void(0)" onclick="return false;" target="_blank"><img src="'+moduleMsg.pic+'" style="margin-top: 5px;"></a>'
               :''
             ),
            '</div>'
            
            ].join('');
            
        } 
        else if (subject == 'shake_window') {
            userName = '系统消息';

            if (isMe)
                content = '您给对方发了窗体抖动！';
            else
                content = '对方给您发了窗体抖动！';
        } else if (subject == 'customservice_screen') {
            var screenUrl = gtjaWebEtLoginApi.weblogicserver + 'manage/fileUploadAction.do?method=downLoadFile&MD5=' + content + '&type=screen&fileSize=';

            screenUrl = OAuth.oauthURL(screenUrl);

            content = '<img src="' +
                screenUrl +

                '"/>'
        } else {
            if (fromname == '智能客服') {
               if (cmdtype == '16') {
                    //var cmdcontent= aJSJaCPacket.getChildValByAttr('command','cmdtype','cmdcontent');
                    var cmdcontent = gtjawebEtUI.GetChildCmdVal(msg, 'cmdcontent');


                    //图文混排消息解析
                    // var rootArticles;// = this._parseResponse(req);
                    var rootArticles = JSJaCPacket._parseTree(cmdcontent);
                    if (!rootArticles || rootArticles.tagName == 'parsererror') {
                        content = '[系统消息]当前不支持图文消息展示。';
                    } else {
                        var rootArticlesPacket = new JSJaCPacket;
                        rootArticlesPacket._replaceNode(rootArticles);
                        if (!rootArticlesPacket) {
                            content = '[系统消息]当前不支持图文消息展示。';
                        } else {
                            var itemNodes = rootArticlesPacket.getChilds('item');
                            if (itemNodes && itemNodes.length > 0) {
                                function getItemNodeVal(node, name) {
                                    var ret = '';
                                    if (node && node.hasChildNodes()) {
                                        for (var i = 0; i < node.childNodes.length; i++) {
                                            var childNodeItem = node.childNodes.item(i);
                                            if (childNodeItem.nodeName == name) {
                                                if (childNodeItem.nodeValue) {
                                                    ret = childNodeItem.nodeValue;
                                                    break;

                                                } else if (childNodeItem.hasChildNodes()) {
                                                    ret = childNodeItem.childNodes.item(0).nodeValue;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    return ret;
                                }
                                if (itemNodes.length == 1) //单图文
                                {
                                    var itemNode = itemNodes.item(0);
                                    var articlesTitle = getItemNodeVal(itemNode, 'Title');
                                    //rootArticlesPacket.getChildVal('Title');
                                    var articlesDescription = getItemNodeVal(itemNode, 'Description');
                                    //rootArticlesPacket.getChildVal('Description');
                                    var articlesPicUrl = getItemNodeVal(itemNode, 'PicUrl');
                                    //rootArticlesPacket.getChildVal('PicUrl');
                                    var articlesUrl = getItemNodeVal(itemNode, 'Url');
                                    //rootArticlesPacket.getChildVal('Url');
                                    content = ['<div class="single-graphic_content"  id="tuwen" articlesUrl="',
                                        articlesUrl,
                                        '">',
                                        '<p class="single-graphic_title"><b>',
                                        $("<div></div>").text(articlesTitle).html(),
                                        '</b></p>',
                                        '<img class="single_picture" width="268" height="171" omnerror="this.src=\'' + gtjawebEtUI.ETImagePath + 'newspic.gif\'" src="',
                                        articlesPicUrl,
                                        '">',
                                        '<div><p class="single-graphic_title">',
                                        $("<div></div>").text(articlesDescription).html(),
                                        '</p></div>',
                                        '<span  class="single_articles" >详情</span>',
                                        '<span class="single_right"><img src="' + gtjawebEtUI.ETImagePath + 'right_logo.png" style="padding-top:4px;"/></span></div>'
                                    ].join("");
                                } else //多图文
                                {
                                    var zitem = itemNodes.item(0);
                                    var articlesUrl = getItemNodeVal(zitem, 'Url');
                                    content = ['<div class="single-graphic_content">',
                                        //大图片

                                        '<span class="" id="tuwen" articlesUrl="',
                                        articlesUrl,
                                        '">',,
                                        '<img width="268" height="171" style="position: relative;" onerror="this.src=\'' + gtjawebEtUI.ETImagePath + 'newspic.gif\'" src="',
                                        getItemNodeVal(zitem, 'PicUrl'),
                                        '">',

                                        //文章标题
                                        '<span class="picmoreinfo_summary txthidden"><b>',

                                        $("<div></div>").text(getItemNodeVal(zitem, 'Title')).html(),
                                        '</b></span>',
                                        '</span>',
                                        $("<div></div>").text(getItemNodeVal(zitem, 'Description')).html(),
                                    ].join("");
                                    for (var i = 1; i < itemNodes.length; i++) {
                                        var itemNode = itemNodes.item(i);
                                        var articlesTitle = getItemNodeVal(itemNode, 'Title');
                                        var articlesDescription = getItemNodeVal(itemNode, 'Description');
                                        var articlesPicUrl = getItemNodeVal(itemNode, 'PicUrl');
                                        var articlesUrl = getItemNodeVal(itemNode, 'Url');
                                        content += [
                                            //小图片
                                            '<div class="img-cont">',
                                            '<span class="" id="tuwen" articlesUrl="',
                                            articlesUrl,
                                            '">',
                                            //   '<a class="" href="#" title="">',
                                            '<img width="40" height="40"style="float:right" onerror="this.src=\'' + gtjawebEtUI.ETImagePath + 'newspic.gif\'" src="',
                                            articlesPicUrl,
                                            '">',
                                            //  '</a>',
                                            //图片简介
                                            '<div class="txthidden"style="line-height: 60px;">',
                                            $("<div></div>").text(articlesTitle).html(),
                                            '</div>',
                                            '</span>',
                                            '</div>',
                                        ].join("");

                                    }
                                    content += ['</div>'].join("");
                                }

                            }



                        }
                    }

                } else //
                {
                    content = content.replace(/\r\n/g, "\n");
                    content = content.replace(/\n/g, "\n<br>");
                    content = "<br>" + content + "\n";
                    content = content.replace(/<br>\[(\d+)\] ([ \S]+)\n/g, "<br>[$1] <span id='questionno' znkfno='' style='color:#4fa4ff;;text-decoration: underline;cursor: pointer;'>$2</span>");
                    content = content.replace(/<br>\[a\]([\S]+)\n<br>\[b\]([\S]+)\n/g, "<br>[a] <span id='questionno' znkfno='a' style='color:#4fa4ff;;text-decoration: underline;cursor: pointer;'>$1</span><br>[b] <span id='questionno' znkfno='b' style='color:#4fa4ff;text-decoration: underline;cursor: pointer;'>$2</span>");
                    content = content.substr(4);
                    content = content.replace(/\[stock:sh,(\d+),([\S]{2,5})\/\]/g, "<span style='color:#4fa4ff;;text-decoration: underline;cursor: pointer;'>$2($1)</span>");
                    content = content.replace(/\[stock:sz,(\d+),([\S]{2,5})\/\]/g, "<span style='color:#4fa4ff;;text-decoration: underline;cursor: pointer;'>$2($1)</span>");                    
                }

                
            } else {
                content = $("<div></div>").text(content).html();
                //转表情
                var arr;
                var src = content;
                var re = /\[img:(\d+)\]/g;
                //创建正则表达式对象。
                while ((arr = re.exec(src)) != null) {

                    var s = [
                        "<img  class='emotion' src='",
                        gtjawebEtUI.faceImagePath,
                        arr[1],
                        ".gif'/>"

                    ].join("");
                    src = src.replace(/\[img:(\d+)\]/, s);
                }
                content = src;
                
            }
        }
          return content;
    },
    //点击提交响应人评价按钮
    starButtonClick:function($chatMain,$msgdiv)
    {
    	 $msgdiv.find(".starButton").click(function () {
                  var msgbody = {};
    	 	          var divT=$msgdiv.find(".BOX > div");
							    var starTips=$msgdiv.find(".starTips"),ss=false;
							  /*  $.each(divT,function(i,$item) {
							        var sidNumN = $item.find(".star_UL").attr('sid');
							        if(sidNumN=="0"){
							            $(starTips).html("请先做评价");
							            return ss=true;
							        }
							    });
							    if(ss==true){
							        return;
							    }*/
							    var custEvaluateId=$msgdiv.find(".starButton").attr('custevaluateid');//": "3F18813BD486E992C9F8F4D9791EBACC",//与评价工单编号一致,只支持48小时内的评价,以评价工单生成时间为准
									var serviceAttitude=$msgdiv.find("#star0 .star_UL").attr('sid');//": "3", //服务太度,1~5星
									var businessLevel=$msgdiv.find("#star1 .star_UL").attr('sid');//": "4", //业务水平,1~5星
									var serviceResponse=$msgdiv.find("#star2 .star_UL").attr('sid');//": "5", //服务响应,1~5星
									if(serviceAttitude=="0"||businessLevel=="0"||serviceResponse=="0")
									{
										  $(starTips).html("请先做评价");
							        return;
									}
									var remarks=$msgdiv.find(".suggest textarea").val();//":"业务规则不满意" //当低于3星时,可以输入不满意原因, 100字以内
							    msgbody.subject='commitEvaluate';
							    msgbody.jsonData='{'
																		+'"custEvaluateId": "'+custEvaluateId+'",'//与评价工单编号一致,只支持48小时内的评价,以评价工单生成时间为准
																		+'"serviceAttitude": "'+serviceAttitude+'",' //服务太度,1~5星
																		+'"businessLevel": "'+businessLevel+'",' //业务水平,1~5星
																		+'"serviceResponse": "'+serviceResponse+'",' //服务响应,1~5星
																		+'"remarks":"'+remarks+'"' //当低于3星时,可以输入不满意原因, 100字以内
																	 +'}';
			    
                if (remotegtjawebet.isConnectSuccess() == false) {

                    gtjawebEtUI.writeReceiveMessage('sys', '正在登录ET服务器，请稍候...', receiverId);
                    gtjaWebEtLoginApi.checkLogin();
                    return;

                }

                var receiver = $chatMain.attr("receiverto");

                var toname = $chatMain.attr('username');

                if (~receiver.indexOf("kf95521.chat.gtja.com")) {
                   
                }


                var sthread = $chatMain.attr("KfThread");

                msgbody.body = '客户已对您进行满意度评价,请升级到最新版本查看...';
                msgbody.to = receiver;
                msgbody.fromname = gtjawebEtUI.myusername;
                msgbody.toname = toname;
                msgbody.thread = sthread;

                remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
                    if (ret == 'success') {
                    	 //首次发消息时,更新查历史的起止时间,防止查出重复消息
					            var _endtime = $chatMain.attr('_endtime')|| '';
				              if(_endtime=='')
				              {
					              if(data&&data.sendTime)
					              {
					             	   $chatMain.attr("_endtime",data.sendTime);
					              }
				              	
				              }
				              
                      if($(".submit-toast")){
                        $(".submit-toast").css("display", "block");
                        setTimeout(function(){
                          $(".submit-toast").css("display","none");
                        }, 2000);                        
                      }

									    $msgdiv.find(".starButton").attr("class","starButtonOk").html(" 已提交");
                                        var thanksStr = (remarks=='')?'感谢您的评价':remarks;
									    $(starTips).html(thanksStr);
									    gtjawebEtUI.loadStar($chatMain,$msgdiv);

                    } else {

                    }
                });


            });

    },

    //悬浮显示响应人对应评价
    assessClick:function($chatMain,$msgdivAll){
    	       gtjawebEtUI.btn_solveClick($chatMain,$msgdivAll);
    	       
    	       if (!$msgdivAll.find(".starButton").get(0))
    	          return;
    	       $msgdivAll.find(".starButton").each(function(){
						    $msgdiv =$(this).parents('.replyclient_recordtext');
											    
											     gtjawebEtUI.starButtonClick($chatMain,$msgdiv);
									    //var stars=setTimeout(function (){
									        var arrStars = $msgdiv.find('.BOX > div');//  几组星星
									        for(var k = 0; k < $msgdiv.find('.BOX > div').length; k++){
									            $(arrStars[k]).attr('data-key','star0'+k) ;
									            var star_arrLi = $msgdiv.find('div[data-key=star0'+[k] +'] > .star_UL > li');//  几个星星
									            var star_strong = $msgdiv.find('div[data-key=star0'+[k] +'] > .star_result_span > strong');//星星后面的分数
									            var star_a = $msgdiv.find('div[data-key=star0'+[k] +'] > .star_result_span a');//星星后面的满意的程度

									            fun(star_arrLi, star_strong ,star_a,$msgdiv);
									        }
									   // },100);

									function fun(arrLi,strong ,strong_a,$msgdiv ){
									    for (var i =0; i<arrLi.length; i++) {
									        arrLi[i].index = i+1;
									        arrLi[i].onmouseover = function(){
									        	   if (!$msgdiv.find(".starButton").get(0))
					    	                  return;
									            ShowTars(this.index);
									            //strong.text(this.index + '分');
									        };

									        //鼠标离开后恢复到上次显现的几个星星
									        arrLi[i].onmouseout = function() {
									        	  if (!$msgdiv.find(".starButton").get(0))
					    	                  return;
									            var sidNum = $(this).parents('ul').attr('sid');

									            if(sidNum == 0){
									             //   strong.text("");
									                strong_a.text("");
									            }else{
									             //   strong.text(sidNum + '分');
									            }
									            ShowTars(sidNum);
									        };

									        //点击后进行评分处理
									        arrLi[i].onclick = function() {
									        	  if (!$msgdiv.find(".starButton").get(0))
					    	                  return;
									            var box=$msgdiv.find(".BOX > div"),data=[],ss=false,xT=0;
									            var starId=$(this).parents(".star").attr("id");
									            strong.text(this.index + '分');
									            $(this).parents('ul').attr('sid',this.index);
									            $.each(box,function() {
									                var sidNumN = $(this).find(".star_UL").attr('sid');
									                data.push(sidNumN);
									                if(sidNumN=="0"){
									                    return ss=true;
									                }
									            });
									            if(ss==true){
									                return;
									            }
									            console.log(data.length);
									            for(var j=0;j<data.length;j++){
									                if(data[j]<=3){
									                    console.log("小于3");
									                    $msgdiv.find(".suggest").show();
									                    $msgdiv.find(".starTips").hide();
									                    return;
									                }else{
									                    xT+=1;
									                    console.log("大于3")
									                }
									            }
									            console.log(xT);
									            if(xT==data.length){
									                $msgdiv.find(".suggest").hide();
									                $msgdiv.find(".starTips").show();
									            }
									        };
									    }

									    // 显现值几个星星
									    function ShowTars(num) {
									        for(var i = 0; i < arrLi.length; i++)
									            arrLi[i].className = i < num ? "on" : "";
									    };
									};
						  });
    	     
    },
    loadStar:function ($chatMain,$msgdiv){
    
    for(var i=0;i<=3;i++)
     {
        var $sidNumN = $msgdiv.find("#star"+i+" .star_UL");
        var num=$sidNumN.attr('sid'),numN="";
        if(num=="0"){
            numN=num
        }else{
            numN=num-1
        }
        var liList=$msgdiv.find("#star"+i+" .star_UL > li");
        //console.log(sidNumN.attr('sid'));
        //var liStrong=$msgdiv.find("#star"+i+" .star_result_span > strong");
        for(var j = 0; j < liList.length; j++){
            liList[j].className = j < num ? "on" : "none";
        }
        //liStrong.text(num + '分');

    };
    $msgdiv.find(".suggest").hide();
		$msgdiv.find(".starTips").show();
    $msgdiv.find(".star_UL").attr("class","star_ULno");
},
//点击提交问卷调查按钮
    btn_solveClick:function($chatMain,$msgdivAll)
    {
    	 if (!$msgdivAll.find(".btn_solve").get(0))
    	          return;
    	 $msgdivAll.find(".btn_solve").click(function () {
    	 	
                  var msgbody = {};
    	 	         $msgdivBtn=$(this);
							    var custEvaluateId=$msgdivBtn.attr('custevaluateid');//": "3F18813BD486E992C9F8F4D9791EBACC",//与评价工单编号一致,只支持48小时内的评价,以评价工单生成时间为准
							    var result="0";
							    var resultTips="否";
							    if($msgdivBtn.hasClass("yessolve"))
							    {
							       result="1";
							    	resultTips="是";
							    }
									msgbody.subject='commitSurvey';
							    msgbody.jsonData='{'
																		+'"questionSurveyId": "'+custEvaluateId+'",'//与评价工单编号一致,只支持48小时内的评价,以评价工单生成时间为准
																		+'"result": "'+result+'",'
																		+'"remarks":""' //当低于3星时,可以输入不满意原因, 100字以内
																	 +'}';
			    
                if (remotegtjawebet.isConnectSuccess() == false) {

                    gtjawebEtUI.writeReceiveMessage('sys', '正在登录ET服务器，请稍候...', receiverId);
                    gtjaWebEtLoginApi.checkLogin();
                    return;

                }

                var receiver = $chatMain.attr("receiverto");

                var toname = $chatMain.attr('username');

                if (~receiver.indexOf("kf95521.chat.gtja.com")) {
                   
                }


                var sthread = $chatMain.attr("KfThread");

                msgbody.body = '';
                msgbody.to = receiver;
                msgbody.fromname = gtjawebEtUI.myusername;
                msgbody.toname = toname;
                msgbody.thread = sthread;

                remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
                    if (ret == 'success') {
                    	 //首次发消息时,更新查历史的起止时间,防止查出重复消息
					            var _endtime = $chatMain.attr('_endtime')|| '';
				              if(_endtime=='')
				              {
					              if(data&&data.sendTime)
					              {
					             	   $chatMain.attr("_endtime",data.sendTime);
					              }
				              	
				              }

                      if($(".submit-toast")){
                        $(".submit-toast").css("display", "block");
                        setTimeout(function(){
                          $(".submit-toast").css("display","none");
                        }, 2000);
                      }
                      
				              var $msgdivBtnDiv=$msgdivBtn.parent("div");
		                  $msgdivBtnDiv.find(".yessolve").remove();
									    $msgdivBtnDiv.find(".btn_solve").attr("class","starButtonOk").html(resultTips);
									    

                    } else {

                    }
                });


            });

    },
    // 远程发送消息时执行函数
    messageHandler: function (user, content, fromname, toname, subject, stheard, userto, msg) {

        var msgTime = gtjawebEtUI.GetChildOfflineTime(msg);
        var flag = false;
        user = gtjawebEtUI.userAddress(user);
        var sendEmpId = ''; //发送人工号
        var sendName = fromname; //发送人姓名
        var sendEmpJid = user; //发送人jid
        var winChatJid = user; //聊天窗口jid(即接收窗口唯一标识

        if (gtjawebEtUI.userAddressNoIdentity(user) == remotegtjawebet.connection.jid)
            flag = true;
        var userName = fromname + ' 说';
        if (flag)
            userName = '我 说';
        var content_tipsDiv='';
        var winChatTitleName = ''; //窗口标题
        
        var sendSys = flag ? "me" : "friend";
        
        if (subject == 'acceptFile'||subject == 'refuseFile'||subject == 'fileupload'||subject == 'shake_window') {
            
            sendSys = 'sys';
        }
        else if (fromname == '智能客服')
        	 sendSys = 'znkf';
        if (subject == 'shake_window'&&msgTime == '') {
               gtjawebEtUI.shakeWin();
        } 
        var cmdtype = gtjawebEtUI.GetChildCmdVal(msg, 'cmdtype');
        content = gtjawebEtUI.getContentHtml(fromname,subject,content,flag,cmdtype, msg._attrib.jsonData);

        
        var tempUser = user;

        /* if (~tempUser.indexOf("/")) {

         tempUser = tempUser.substr(0, tempUser.indexOf("/"));

         }*/

        var isZNKFSTATUS = true;
        if (flag) {
            tempUser = gtjawebEtUI.userAddress(userto);
        }

        var userJID = "u" + sha256_digest(tempUser);
        if (~tempUser.indexOf("@chat.gtja.com")) {
            var cmdcontent = gtjawebEtUI.GetChildCmdVal(msg, 'cmd');
            if (cmdcontent == '' || cmdcontent == 'ztg')
                isZNKFSTATUS = false;
        }

        // 首次初始webIM

        if (!$("#et_box #" + userJID).get(0)) {

            // 初始IM面板；

            gtjawebEtUI.openChatWin(tempUser, fromname, false);

            if (flag) {
                $("#et_box #" + userJID).attr('msgmeflag', '1');
            } else if (isZNKFSTATUS)
                $("#et_box #" + userJID).attr('cmdtypecmd', 'XiaoJun');

        } else {
            if (isZNKFSTATUS == false)
                $("#et_box #" + userJID).attr('cmdtypecmd', '');

            if ($("#et_box #" + userJID).attr('msgmeflag') == '1') {
                $("#et_box #" + userJID).attr('msgmeflag', '');
                if (gtjawebEtUI.GetChildCmdVal(msg, 'cmd') == 'XiaoJun')
                    $("#et_box #" + userJID).attr('cmdtypecmd', 'XiaoJun');
            }
        }

        if (stheard && stheard != '') {
            $("#et_box #" + userJID).attr("KfThread", stheard);
        }
        gtjawebEtUI.writeReceiveMessage(sendSys, content, userJID, msgTime,user);
        //gtjawebEtUI.assessClick();
        
        var rosterID = "uroster" + sha256_digest(tempUser);
        var stime = gtjawebEtUI.getDatetime();
        $("#et_box .list ul ." + rosterID + "  .magtime").text(stime.substr(11,5));
        content_tipsDiv=$("<div>"+content+"</div>").text();
        $("#et_box .list ul ." + rosterID + "  .content_tips").text(content_tipsDiv);
        // 消息提示
        
        {

            if ($("#et_box .list ul ." + rosterID).hasClass('hasnewmsg')) {
                var msgnum = parseInt($(".list ul ." + rosterID + "  .chat_msgtip").text(), 10);
                msgnum++;
                $("#et_box .list ul ." + rosterID + "  .chat_msgtip").text(msgnum + '')

                $("#et_box .list ul ." + rosterID).removeClass('hasnewmsg');
            } else {
                $("#et_box .list ul ." + rosterID + "  .chat_msgtip").text('1')
            }

            $("#et_box .list ul ." + rosterID).addClass('hasnewmsg');
            
           
             if ($("#et_box .list ul ." + rosterID).hasClass('currentchat')) 
             {
             	    $("#et_box .list ul li." + rosterID+".currentchat").removeClass('hasnewmsg');

                     //1秒后消失
                    
					    	   /*window.setTimeout(function () {

					               $("#et_box .list ul li." + rosterID+".currentchat").removeClass('hasnewmsg');
                                   gtjawebEtUI.showTips();
					            }, 1000);*/
             }


            gtjawebEtUI.showTips();

        }

    },
    moremessagelist: function ($chatMain) {
        var _endtime = $chatMain.attr('_endtime')|| '';
        var _itemjid =  $chatMain.attr('receiver');
        var _state =  $chatMain.attr('_state')|| '';
        if (_state == '') {
            remotegtjawebet.getChatHisMsg(_itemjid, _endtime, function (ret, tips, data) {
                if (data && data.msgList && data.msgList.length > 0) {
                    $chatMain.attr('_endtime', data.msgList[data.msgList.length - 1].sendTime);
                    //加载历史消息
                    var _html = [];
                    var tempTime='';
                    var localMsgList=data.msgList;
                    localMsgList.reverse();
                    $.each(localMsgList, function (i, item) {
                    	
                        var _curuser = '';
                        if(remotegtjawebet&&remotegtjawebet.connection&&remotegtjawebet.connection._custId)
                           _curuser=remotegtjawebet.connection._custId+"."+remotegtjawebet.connection._custType;
                        var isMe=false;
                        if (item.from.indexOf(_curuser) ==0) 
                           isMe=true;
                        
                        var _contenthtml = [];
                        var content = gtjawebEtUI.getContentHtml(item.fromname,item.subject,item.body,isMe,null,item.jsonData);
                        
                        var stime = (item.sendTime||'').substr(0, 16);
                        if(tempTime!=stime)
                        {
                        	  tempTime=stime;
                        	  _contenthtml.push(' <div class="replytime"><span>' + tempTime + '</span> </div>');
                        }

                        if (isMe) {
                            _contenthtml.push('<div class="replyme"><img src="' + gtjawebEtUI.ETImagePath + 'wo.png">');
                            _contenthtml.push('<div class="replyme_recordtextbg"></div>');
                            _contenthtml.push('<div class="replyme_recordtext">' + content + '</div> </div>');
                        } else {
                        	 if(item.fromname=='智能客服')
                              _contenthtml.push('<div class="replyclient">  <img src="' + gtjawebEtUI.ETImagePath + 'xiaojun.png">');
                           else
                           {
                           	   var empid='';
                           	   if (~item.from.indexOf("@chat.gtja.com"))
                           	      empid = item.from.substr(0, item.from.indexOf("\."));
                           	   if(empid!='')
        	  	                    _contenthtml.push('<div class="replyclient">  <img class="userp" onerror="javascript:this.src='+"'"+gtjawebEtUI.ETImagePath + 'kehu_duihuakuang.png'+"';"+'" src="http://dl.app.gtja.com/baishitong/userphoto/'+empid+'.png"/>');
        	  	                 else          		
                                  _contenthtml.push('<div class="replyclient">  <img src="' + gtjawebEtUI.ETImagePath + 'kehu_duihuakuang.png">');
                           }
                            _contenthtml.push('<div class="replyclient_recordtextbg"></div>');
                            _contenthtml.push(' <div class="replyclient_recordtext"><span class="replyspan"></span>' + content + '</div> </div>');
                        }
                        _html.push(_contenthtml.join(''));
                    });
                    
                   var $msgdiv = $(_html.join(''));
                    //绑定单击事件
                   gtjawebEtUI.bindClickEvent($chatMain,$msgdiv);

                   $chatMain.find('.et_message_more_list').prepend($msgdiv);
                   $chatMain.find('.hismsgbottom').show();
                    try {
                       var $chatcontent=$chatMain.find(".chat01_content");
                             $chatcontent.scrollTop($msgdiv.last().offset().top - $chatcontent.offset().top + $chatcontent.scrollTop());
                        } catch (e) {}
                } else {
                    $chatMain.attr('_state', 'isend');
                    $chatMain.find('.et_message_more_btn').remove();
                }

            });
        }
    },
    /*assessClick:function(){

        var assesss=setTimeout(function (){
            var arrassesss = $('.BOX > div');//  几组星星
            for(var k = 0; k < $('.BOX > div').length; k++){
                $(arrassesss[k]).attr('data-key','assess0'+k) ;
                var assess_arrLi = $('div[data-key=assess0'+[k] +'] > .assess_UL > li');//  几个星星
                var assess_strong = $('div[data-key=assess0'+[k] +'] > .assess_result_span > strong');//星星后面的分数
                var assess_a = $('div[data-key=assess0'+[k] +'] > .assess_result_span a');//星星后面的满意的程度

                fun(assess_arrLi, assess_strong ,assess_a);
            }
        },100);

        function fun(arrLi,strong ,strong_a ){
            for (var i =0; i<arrLi.length; i++) {
                arrLi[i].index = i+1;
                arrLi[i].onmouseover = function(){
                    ShowTars(this.index);
                    strong.text(this.index + '分');
                };

                //鼠标离开后恢复到上次显现的几个星星
                arrLi[i].onmouseout = function() {
                    var sidNum = $(this).parents('ul').attr('sid');

                    if(sidNum == 0){
                        strong.text("");
                        strong_a.text("");
                    }else{
                        strong.text(sidNum + '分');
                    }
                    ShowTars(sidNum);
                };

                //点击后进行评分处理
                arrLi[i].onclick = function() {
                    strong.text(this.index + '分');
                    $(this).parents('ul').attr('sid',this.index);
                };
            }

            // 显现值几个星星
            function ShowTars(num) {
                for(var i = 0; i < arrLi.length; i++)
                    arrLi[i].className = i < num ? "on" : "";
            };
        };

    },*/
    loadassess: function (){
        var divT=$(".BOX > div");
        $.each(divT,function(){
            var sidNumN = $(this).find(".assess_UL");
            var num=sidNumN.attr('sid'),numN="";
            if(num=="0"){
                numN=num
            }else{
                numN=num-1
            }
            var liList=$(this).find(".assess_UL > li");
            console.log(sidNumN.attr('sid'));
            var liStrong=$(this).find(".assess_result_span > strong");
            for(var i = 0; i < liList.length; i++){
                liList[i].className = i < num ? "on" : "none";
            }
            liStrong.text(num + '分');
        });
        $(".assess_UL").attr("class","assess_ULno");
    },
    initEtPresence: function () {
        if (remotegtjawebet.connection._presence && remotegtjawebet.connection._presence != null) {

        } else {
            remotegtjawebet.connection._presence = 'chat';
            remotegtjawebet.sendMsg('setPresence', {
                presence: 'chat'
            }, function (ret, tips, data) {

            });

        }
    },
    // 聊天界面html元素
    chatLayoutTemplate: function (userJID,
                                  //sender,
                                  receiver, chattitle) {

        var username = '';
        var KfThread = '';
        if (~receiver.indexOf("@kf95521.chat.gtja.com")) {
            username = '在线客服';
        } else {
            username = chattitle;
            if (~username.indexOf("[")) {

                username = username.substr(0, username.indexOf("["));

            }
            KfThread = "fy" + sha256_digest(receiver + gtjawebEtUI.getDatetime());
        }


        return [

            '<div class="chat-main" zxgzcontent="" cmdtypebrand="fy"  cmdtypecmd="XiaoJun" ConnectKfStatus="" id="', userJID,

            //'" sender="', sender,
            '" receiver="', receiver, '" receiverto="', receiver, '" username="', username, '" KfThread="', KfThread, '" chattitle="', chattitle, '" style=" width:auto;" >',


            '<div class="chat01">',
            '<div class="chat01_content">',
            '<div style="text-align:center;color:#1097e8;cursor:pointer;margin-top: 10px;" class="et_message_more_btn" ><img src="' + gtjawebEtUI.ETImagePath + 'time.png" style="left: -4px;position: relative;top: 1px;">查看更多消息</div>',
            '<div class="message_box mes3" style="display: block;">',
            '</div>',
            '<div class="et_message_more_list"></div>',
            '<div class="replysys hismsgbottom" style="display:none;">--------------------以上是历史消息--------------------</div>',

            '</div>',
            '</div>',

            ' <div class="chat02">',
            '<div class="chat02_title">',

            '<a class="chat02_title_btn ctb01" href="javascript:;">',
            '<img  src="', gtjawebEtUI.ETImagePath, 'face.png"/>						</a>',


            '<a class="chat02_title_btn ctb02"  href="javascript:;">',
            '<img src="', gtjawebEtUI.ETImagePath, 'icon-phone.png"/>						</a>',


            '<a class="chat02_title_btn ctb03" id="box1" href="javascript:;">',
            '<img src="', gtjawebEtUI.ETImagePath, 'zhen.png"/>						</a>',




            '<div class="wl_faces_box">',
            '<div class="wl_faces_content">',


            '<div class="title">',
            '   <ul>',
            '   <li class="title_name">常用表情</li><li class="wl_faces_close"><span>&nbsp;</span></li></ul>',
            ' </div>',



            ' <div class="wl_faces_main">',
            '<ul>',
            ' </ul>',
            '  </div>',
            ' </div>',

            ' <div class="wlf_icon">                            </div>',
            ' </div>',
            '  </div>',


            '<div class="chat02_content">',
            '   <div class="textarea" id="textarea" contenteditable="true"></div>',
            ' </div>',



            ' <div class="chat02_bar">',
            '    <ul>',

            '     <li style="right: 15px; top: 8px;">',
            '<a href="javascript:;">',
            '              发送							</a>							</li>',
            '    </ul>',
            '  </div>',
            ' </div>',
            '  </div>'

        ].join("");

    },
    mybranchname: '',
    //接收个人名片信
    handleUserVCard: function (data) {

        //取姓名
        var tmpvalue = gtjawebEtUI.GetChildVal(gtjawebEtUI.GetChild(data, 'N'), 'GIVEN');
        gtjawebEtUI.myusername = tmpvalue;


        tmpvalue = gtjawebEtUI.GetChildVal(data, 'BRANCHNAME');
        gtjawebEtUI.mybranchname = tmpvalue;


    },
    //添加类别中心
    addXXZXTypeList: function (typeArray) {
        if(Object.prototype.toString.call(typeArray)=='[object Array]')
        {
            for(var i=0;i<typeArray.length;i++){
                var msg = typeArray[i];
                if( typeof(msg)=="object" ){

                    var userID = "urosterXXZX" + sha256_digest(msg.typeID);

                    var itemObj = {};
                    itemObj.itemjid = msg.typeID;
                    itemObj.parentID = msg.parentID;
                    itemObj.isShow = msg.isShow;
                    itemObj.itemrealname = msg.typeName;
                    itemObj.itemstatus = 'useroffline';
                    itemObj.userID = userID;
                    itemObj.titlename = msg.typeName;
                    itemObj.kftype = 'xxzxMsg';
                    itemObj.typeimg=msg.typeimg;
                    itemObj.recentlyMsyContent=msg.recentlyMsyContent;
                    itemObj.recentlyMsgTime=msg.recentlyMsgTime;
                    itemObj.unreadMsgCount=msg.unreadMsgCount;
                    //if(itemObj.typeimg==""){
                    //    itemObj.headImg = gtjawebEtUI.ETImagePath + 'xxzxMsg.png';
                    //}else{
                        itemObj.headImg = gtjawebEtUI.ETImagePath + msg.typeimg;
                    //}

                    if (gtjawebEtUI.rosterList[userID] == null) {
                        gtjawebEtUI.rosterList[userID] = itemObj;
                    } else {
                        itemObj = gtjawebEtUI.rosterList[userID];
                        isNeedGetVCard = false;
                    }
                    if (!$("#et_box #change_ul ." + userID).get(0)) {
                        gtjawebEtUI.addRoster(itemObj);

                    }
                }
            }
        }


    },
    //添加收藏中心
    addXXZXTypeListSC: function (typeArraySC) {
        if(Object.prototype.toString.call(typeArraySC)=='[object Array]')
        {
            for(var i=0;i<typeArraySC.length;i++){
                var msg = typeArraySC[i];
                if( typeof(msg)=="object" ){

                    var userID = "urosterXXZXSZ" + sha256_digest(msg.msgID);

                    var itemObj = {};
                    itemObj.itemjid = msg.msgID;
                    itemObj.itemrealname = msg.msgTitle;
                    itemObj.itemstatus = 'useroffline';
                    itemObj.userID = userID;
                    itemObj.titlename = msg.msgTitle;
                    itemObj.kftype = 'xxzxMsgSZ';
                    itemObj.recentlyMsyContent=msg.msgSummary;
                   
                    itemObj.recentlyMsgTime=msg.msgTime;
                    
                    //初始化收藏默认显示最后一条
                    gtjawebEtUI.selectSZId=userID;

                    itemObj.headImg = gtjawebEtUI.ETImagePath + 'zhang.png';

                    if (gtjawebEtUI.rosterList[userID] == null) {
                        gtjawebEtUI.rosterList[userID] = itemObj;
                    } else {
                        itemObj = gtjawebEtUI.rosterList[userID];
                        isNeedGetVCard = false;
                    }
                    if (!$("#et_box #change_ul ." + userID).get(0)) {
                        gtjawebEtUI.addRoster(itemObj);

                    }
                }
            }
        }


    },
    isShowXX:true,
    selectId:'',
    selectSZId:'',    
//查看消息类型
    viewType: function (typeID)
    {
        var userID = "urosterXXZX" + sha256_digest(typeID);
              
        $("#navmessage").click();
        var  $rosters= $("#et_box #change_ul ." + userID);
        
        if( $rosters.get(0) ){
        	 
            gtjawebEtUI.rosteritemclick($rosters, false);
        }
        gtjawebEtUI.showEtChat();
    },
    /*查看收藏*/
    viewTypeSC: function (msgID)
    {
        var userID = "urosterXXZXSZ" + sha256_digest(msgID);
        $("#navcollection").click();
        if( $("#et_box #change_ul ." + userID).get(0) ){
            gtjawebEtUI.rosteritemclick($("#et_box #change_ul ." + userID), false);

        }
        gtjawebEtUI.showEtChat();

    },
    
    /*删除收藏*/
    delSCMsg: function (msgID)
    {
        var userID = "urosterXXZXSZ" + sha256_digest(msgID);
        var $rosters=$("#et_box #change_ul ." + userID);
        if( $rosters.get(0) ){
            var itemjid = $rosters.attr('itemjid');
            gtjawebEtUI.delRoster(itemjid, $rosters);
        }

    },
    addChatWin: function (kfjid, kfname, isZNKFSTATUS)
    {
    	  var isNeedGetVCard = true;
        var kftype = '';
        var titlename = '';
        var itemstatus = 'useroffline';
        var headImg = gtjawebEtUI.ETImagePath + 'kehu_duihuakuang.png';
        if (kfjid == null || kfjid == '') {
            kfjid = '49@kf95521.chat.gtja.com';
            kfname = '灵犀客服';
            kftype = 'zykf';
            titlename = kfname;
            headImg = gtjawebEtUI.ETImagePath + 'lingxi.png';
            isNeedGetVCard = false;
        } else if (~kfjid.indexOf("@kf95521.chat.gtja.com")) {
            kftype = 'zykf';
            headImg = gtjawebEtUI.ETImagePath + 'jun.png';
            isNeedGetVCard = false;
        }else if (~kfjid.indexOf("_4@chat.gtja.com")) {
            kftype = 'khjl';
            titlename = kfname + '[' + '响应人' + ']';
        } else {
            kfjid = '49@kf95521.chat.gtja.com';
            kfname = '灵犀客服';
            kftype = 'zykf';
            headImg = gtjawebEtUI.ETImagePath + 'jun.png';

            isNeedGetVCard = false;
        }
        var userID = "uroster" + sha256_digest(kfjid);

        var itemObj = {};
        itemObj.itemjid = kfjid;
        itemObj.itemrealname = kfname;
        itemObj.itemstatus = itemstatus;
        itemObj.userID = userID;
        itemObj.titlename = titlename;
        itemObj.kftype = kftype;
        itemObj.headImg = headImg;
        itemObj.isNeedGetVCard=isNeedGetVCard;

        if (gtjawebEtUI.rosterList[userID] == null) {
            gtjawebEtUI.rosterList[userID] = itemObj;
        } else {
            itemObj = gtjawebEtUI.rosterList[userID];
            isNeedGetVCard = false;
        }
        if (!$("#et_box #change_ul ." + userID).get(0)) {
            gtjawebEtUI.addRoster(itemObj);
        }
        return itemObj;
    },
    openChatWin: function (kfjid, kfname, isZNKFSTATUS) {
    	  // $("#navmessage").click();
        
        var itemObj=gtjawebEtUI.addChatWin(kfjid, kfname, isZNKFSTATUS);
        gtjawebEtUI.rosteritemclick($("#et_box #change_ul ." + itemObj.userID), isZNKFSTATUS);


        gtjawebEtUI.showEtChat();


        if (itemObj.isNeedGetVCard) {
            if (remotegtjawebet.isConnectSuccess())
                gtjawebEtUI.getVCard(itemObj);
        }

    },

    getVCard: function (itemObj) {
        var sendData = {};

        sendData.to = itemObj.itemjid;

        remotegtjawebet.sendMsg('getVCard', sendData, function (ret, tips, data) {
            if (ret == 'success') {
                //取姓名
                var username = gtjawebEtUI.GetChildVal(gtjawebEtUI.GetChild(data, 'N'), 'GIVEN');
                itemObj.itemrealname = username;
                 var txtType='';
        	 
                if (itemObj.kftype == 'khjl')
                {
                	txtType='客户经理-';
                    itemObj.titlename = username + '[' + '响应人' + ']';
                }
                else
                    itemObj.titlename = username;

                gtjawebEtUI.rosterList[itemObj.userID] = itemObj;

                var receiverId = "u" + sha256_digest(itemObj.itemjid);
                var $chatMain = $("#et_box #" + receiverId);
                var $rosteritem = $("#et_box #change_ul ." + itemObj.userID);

                $rosteritem.attr('realname', itemObj.itemrealname);
                $rosteritem.attr('titlename', itemObj.titlename);
                $rosteritem.find('.rostertxt').text(txtType+itemObj.itemrealname);

                $chatMain.attr('username', itemObj.itemrealname);
                $chatMain.attr('chattitle', itemObj.titlename);

                if ($chatMain.is(":visible")) {
                    $('#et_box .title .span1').text(itemObj.titlename);
                }

            } else {

            }
        });
    },


    showEtChat: function () {
        $("#faqbg").css({
            display: "block",
            height: "auto",
            width: "100%"
        });
        var yscroll = document.documentElement.scrollTop;
        //var winHeight=$(document).height();
        //var winWidth=$(document).width();
        //var chatleft=(winWidth-$("#et_box").width())/2;
        //var chattop=(winHeight-$("#et_box").height())/2;
        //$("#et_box").css("top",chattop+"px");
        //$("#et_box").css("left",chatleft+"px");
        $("#et_box").css("display", "block");
        document.documentElement.scrollTop = 0;
    },
    showHideRoster: function () {
        //始终显示左则列
        /*
         if ($("#et_box #change_ul li").length > 1) {

         if ($('#et_box .chat_whole').hasClass('single_chat'))
         $('#et_box .chat_whole').removeClass('single_chat');

         } else {
         if (!($('#et_box .chat_whole').hasClass('single_chat')))
         $('#et_box .chat_whole').addClass('single_chat');


         }
         */
    },
    delRoster: function (itemjid, $roster) {
        var userID = "uroster" + sha256_digest(itemjid);
        var receiverId = "u" + sha256_digest(itemjid);
        var $chatMain = $("#et_box #" + receiverId);
        if (~itemjid.indexOf("@kf95521.chat.gtja.com")) {
            var ConnectKfStatus = $chatMain.attr('ConnectKfStatus');
            if (ConnectKfStatus == '2' || ConnectKfStatus == '5' || ConnectKfStatus == '6') {
                var KfThread = $chatMain.attr('KfThread');
                remotegtjawebet.sendMsg('kf95521', {
                    kf95521type: "VisitorClose",
                    to: itemjid,
                    thread: KfThread
                }, function (ret, tips, data) {
                    if (ret == 'success') {

                    } else {

                    }
                });
            }

        }
        $chatMain.remove();
        
        var classsz='xiaoxiLi';
        if($("#et_box #change_ul").hasClass("showSZ"))
            classsz='szli';
        
            var $rostersNext= $roster.next("li."+classsz) ;
            if(!$rostersNext.get(0))
               $rostersNext= $roster.prev("li."+classsz) ;
               
               
        $roster.remove();
                
            if($rostersNext.get(0))
                gtjawebEtUI.rosteritemclick($rostersNext, false);


        gtjawebEtUI.showHideRoster();


    },
    addRoster: function (itemObj) {
        var time=itemObj.recentlyMsgTime,timemonth="",timeday="",recentlyMsgTime="";
      /*  var chatEl =
            '<div class="khjlmsgcontent">'+
            '<div class="replykhjlshowbg"></div>'+
            '<div class="khjl_msg_close"><span>&nbsp;</span></div>'+
            '<div class="xxzxTypeContent_show">'+
            '<p>姓名：'+itemObj.titlename+'</p>'+
            '</div>'+
            '</div>';*/
        if(time=="undefined"||time==""||time==null){
            timemonth="";
            timex="";
            recentlyMsgTime="";
        }else{
        	   
             timemonth=time.substr(4,2);
             timex=time.substr(6,2);
             
        	   if(time.length>=14)
        	   {
        	   	  var stime = gtjawebEtUI.getDatetime();
        	   	  if(stime.substr(0,4)==time.substr(0,4)&&stime.substr(5,2)==time.substr(4,2)&&stime.substr(8,2)==time.substr(6,2))
        	   	  {
        	   	  	recentlyMsgTime=time.substr(9,5)
        	   	  }
        	   	  else
        	   	  	recentlyMsgTime=timemonth+'/'+timex;
              }
              else
              
                 recentlyMsgTime=timemonth+'/'+timex;
        }
        var strRosterItem ='';
        if(itemObj.kftype=='xxzxMsg'&&(itemObj.parentID&&itemObj.parentID!=''))
        {
        	 var txtType='';
        	  var headImgHtml='';
        	
        		strRosterItem= '<li class="li_class xiaoxiLi ' + itemObj.userID +
            '" itemjid="' + itemObj.itemjid + '" itemUserId="'+itemObj.userID +'"  kftype="' + itemObj.kftype +
            '" realname="' + $("<div></div>").text(itemObj.itemrealname).html() +
            '"  titlename="' + $("<div></div>").text(itemObj.titlename).html() + '" style="height: 34px;">'+headImgHtml+'<div class="xiaoxi_class">' +
            $("<div></div>").text(txtType+itemObj.itemrealname).html() + '</div><span class="magtime">'+recentlyMsgTime+'</span><span class="content_tips">'+$("<div></div>").text(itemObj.recentlyMsyContent).html() +'</span><span class="chat_msgtip">'+$("<div></div>").text(itemObj.unreadMsgCount).html() +'</span><span class="chat_close"></span></li>';

        }
        else if(itemObj.kftype=='xxzxMsgSZ') {
            strRosterItem = '<li class="li_class szli ' + itemObj.userID +
                '" itemjid="' + itemObj.itemjid + '" itemUserId="'+itemObj.userID +'" kftype="' + itemObj.kftype +
                '" realname="' + $("<div></div>").text(itemObj.itemrealname).html() +
                '"  titlename="' + $("<div></div>").text(itemObj.titlename).html() + '"><img class="userp" src="' + itemObj.headImg + '"/><div class="rostertxt">' +
                $("<div></div>").text(itemObj.itemrealname).html() + '</div><span class="magtime">'+recentlyMsgTime+'</span><span class="content_tips">'+$("<div></div>").text(itemObj.recentlyMsyContent).html() +'</span><span class="chat_close"></span></li>';
        } 
        else
        {
        	  var txtType='';
        	  var headImgHtml='<img class="userp" src="' + itemObj.headImg + '"/>';
        	  if(itemObj.kftype=='khjl')
        	  {
        	    txtType='客户经理-';
        	    var empid = itemObj.itemjid.substr(0, itemObj.itemjid.indexOf("\."));
        	  	headImgHtml='<img class="userp" onerror="javascript:this.src='+"'"+itemObj.headImg+"';"+'" src="http://dl.app.gtja.com/baishitong/userphoto/'+empid+'.png"/>';
        	  }
        		strRosterItem= '<li class="li_class xiaoxiLi ' + itemObj.userID +
            '" itemjid="' + itemObj.itemjid + '" itemUserId="'+itemObj.userID +'"  kftype="' + itemObj.kftype +
            '" realname="' + $("<div></div>").text(itemObj.itemrealname).html() +
            '"  titlename="' + $("<div></div>").text(itemObj.titlename).html() + '">'+headImgHtml+'<div class="rostertxt">' +
            $("<div></div>").text(txtType+itemObj.itemrealname).html() + '</div><span class="magtime">'+recentlyMsgTime+'</span><span class="content_tips">'+$("<div></div>").text(itemObj.recentlyMsyContent).html() +'</span><span class="chat_msgtip">'+$("<div></div>").text(itemObj.unreadMsgCount).html() +'</span><span class="chat_close"></span></li>';

        }
        
        
        if(itemObj.kftype=='khjl'||itemObj.kftype=='zykf'){
            var stime=gtjawebEtUI.getDatetime(),timemonthtwo="",timeday="",recentlyMsgTime="";
            if(stime=="undefined"||stime==""||stime==null){
                timemonthtwo="";
                timetwo="";
                MsgTimes="";
            }else{
                timemonthtwo=stime.substr(5,2);
                timetwo=stime.substr(8,2);
                MsgTimes=timemonthtwo+'/'+timetwo;
            }

         /*   strRosterItem = '<li class="li_class xiaoxiLi ' + itemObj.userID +
                '" itemjid="' + itemObj.itemjid + '" itemUserId="'+itemObj.userID +'"  kftype="' + itemObj.kftype +
                '" realname="' + $("<div></div>").text(itemObj.itemrealname).html() +
                '"  titlename="' + $("<div></div>").text(itemObj.titlename).html() + '"><img class="+userp icclass+" src="' + itemObj.headImg + '"/><div class="rostertxt">' +
                $("<div></div>").text(itemObj.itemrealname).html() + '</div><span class="magtime">'+MsgTimes+'</span><span class="content_tips">'+$("<div></div>").text(itemObj.recentlyMsyContent).html() +'</span><span class="chat_close"></span></li>';
*/
        }
        var $rosters = $(strRosterItem);

        if(itemObj.kftype=='khjl')
        {
            $rosters.insertAfter("#et_box #chat_whole #change_ul li.change_ulXianYinRen");
          //  $rosters.append(chatEl);
            $("#et_box .list ul .li_class."+itemObj.userID+" img").mouseover(function(){
               gtjawebEtUI.initkhjlshowDiv(itemObj.itemjid,itemObj.userID)
                $("#et_box #cardUserId"+itemObj.userID+".khjlmsgcontent").show();

            }).mouseout(function(){
                $("#et_box #cardUserId"+itemObj.userID+".khjlmsgcontent").hide();
            });


        }
        else if(itemObj.kftype=='zykf')
        {
            $rosters.insertAfter("#et_box #chat_whole #change_ul li.change_ulLingXi");
        }
        else if(itemObj.kftype=='xxzxMsg')
        {
        	  if(itemObj.parentID&&itemObj.parentID!='')
        	  {
	        	  	$rosters.addClass('xxzzParentID'+itemObj.parentID);
	        	  	
	        	  	$rosters.attr('xxzzParentUserID',"urosterXXZX" + sha256_digest(itemObj.parentID));
	        	  	
	        	  	if(itemObj.isShow==false)
	        	  	{
	        	  		$rosters.hide();
	        	  	}
        	  }
        	  else
        	  {
        	  	   $rosters.attr('isShowChild','false');
        	  	   //var isShow=false;
        	  	   /*
        	  		 $rosters.click(function (e) {
        	  		 	
        	  		 	   var isShow=$rosters.attr('isShowChild');
                     if(isShow=='true')
                     {
                        $('#et_box #chat_whole #change_ul li.xxzzParentID'+itemObj.itemjid).hide();
                        $rosters.attr('isShowChild','false');
                     	
                     }
                     else
                     {
                        $('#et_box #chat_whole #change_ul li.xxzzParentID'+itemObj.itemjid).show();
                        $rosters.attr('isShowChild','true');
                     		
                     }
			            });*/
        	  }
                    
            $rosters.attr('recentlyMsgTime',itemObj.recentlyMsgTime);
            $rosters.attr('recentlyMsyContent',itemObj.recentlyMsyContent);
            $rosters.insertBefore("#et_box #chat_whole #change_ul li.change_ulxxzxMsgEnd");
            // 消息未读提示
            /*if(itemObj.unreadMsgCount!=null&&itemObj.unreadMsgCount!=''&&itemObj.unreadMsgCount!='0')
            {

                $rosters.find(".chat_msgtip").attr(itemObj.unreadMsgCount);

                $rosters.addClass('hasnewmsg');
                gtjawebEtUI.showTips();

            }*/

        } else if(itemObj.kftype=='xxzxMsgSZ')
        {
            $rosters.attr('recentlyMsgTime',itemObj.recentlyMsgTime);
            $rosters.attr('msgSummary',itemObj.recentlyMsyContent);
            $rosters.insertAfter("#et_box #chat_whole #change_ul li.change_ulxxzxMsg");
            $rosters.find(".chat_msgtip").attr('recentlyMsgTime');
            // 消息未读提示
            //if(itemObj.unreadMsgCount!==null)
            //{

                //$rosters.find(".chat_msgtip").attr(itemObj.recentlyMsgTime);

                //$rosters.addClass('newmsgflag');
               // gtjawebEtUI.showTips();

            //}

        }
        else
            $("#et_box #chat_whole #change_ul2").append($rosters);


        //拖动改变li 暂时屏蔽,与富易框架 angular.js冲突
        //$( "#et_box #change_ul" ).sortable();
        //$( "#et_box #change_ul" ).disableSelection();
        //当点击时切换不同的聊天对象
        //var arr = document.getElementById("change_ul").getElementsByTagName("li");
        //arr[0].style.background="#fff";
        $rosters.click(function () {


            gtjawebEtUI.rosteritemclick($(this), true);
        });
        //点击li使显示关闭推图标
        $rosters.hover(function () {
                //$(this).children(".chat_close").css("display","block");
                // $rosters.removeClass('chat_hover');
                // $rosters.addClass('chat_hover');
            },
            function () {
                //$(this).children(".chat_close").css("display","none");
                // $rosters.removeClass('chat_hover');
            });

        //当点击close标签时li消失
        $rosters.find(".chat_close").each(function (index, element) {
            var $rosterclose = $(this);
            $rosterclose.click(function (e) {
                var itemjid = $rosters.attr('itemjid');
                gtjawebEtUI.delRoster(itemjid, $rosters);

            });
        });

        gtjawebEtUI.showHideRoster();
    },
    rosterList: {},
    initRoster: function (data) {

        if (data._subTagCount > 0) {
            //$("#chat_whole #change_ul").html('');
            var groupid = '';
            var strRosterItem = '';

            for (var i = 0; i < data._subNodes.length; i++) {
                var rosteritem = data._subNodes[i];
                if (rosteritem._tagName != 'item') {

                    continue;
                }

                var itemjid = rosteritem._attrib.jid;
                var itemrealname = rosteritem._attrib.realname;
                var itemstatus = 'useroffline';
                var headImg = gtjawebEtUI.ETImagePath + 'kehu_duihuakuang.png';


                var userID = "uroster" + sha256_digest(itemjid);
                var titlename = itemrealname;

                var kftype = '';
                if (~itemjid.indexOf("@kf95521.chat.gtja.com")) {
                    kftype = 'zykf';
                    headImg = gtjawebEtUI.ETImagePath + 'jun.png';

                    //itemrealname=itemrealname+'['+'专业客服'+']';
                } else if (~itemjid.indexOf("_3@chat.gtja.com")) {
                    kftype = 'tzgw';
                    titlename = itemrealname + '[' + '投资顾问' + ']';
                } else if (~itemjid.indexOf("_4@chat.gtja.com")) {
                    kftype = 'khjl';
                    titlename = itemrealname + '[' + '客户经理' + ']';
                } else
                    continue;

                var itemObj = {};
                itemObj.itemjid = itemjid;
                itemObj.itemrealname = itemrealname;
                itemObj.itemstatus = itemstatus;
                itemObj.userID = userID;
                itemObj.titlename = titlename;
                itemObj.kftype = kftype;
                itemObj.headImg = headImg;

                gtjawebEtUI.rosterList[userID] = itemObj;

                if (!$("#et_box #change_ul ." + userID).get(0)) {
                        gtjawebEtUI.addRoster(itemObj);

                }

            }

            // gtjawebEtUI.startMsgTipTimer();

        }

    },
    rosteritemclick: function ($rosteritem, isZNKFSTATUS) {
        $(".single-msg").animate({left:'2000px'});
    	 if( !$rosteritem.get(0) )
    	    return;

        $("#et_box #change_ul li").removeClass('currentchat');
        $rosteritem.addClass('currentchat');
       // $rosteritem.removeClass('newmsgflag');
        // $rosteritem.removeClass('hasnewmsg');
        // $rosteritem.find(" .chat_msgtip").text('');

        var kftype = $rosteritem.attr('kftype');
        var realname = $rosteritem.attr('realname');
        //子菜单隐藏功能
        {
        	 
        	  var parentUserId=$rosteritem.attr('xxzzParentUserID');
        	  //单击的为子菜单
        	  if(parentUserId&&parentUserId!='')
        	  {
        	  	//该子菜单的父菜单展示显示
        	  	var  $rostersParent= $("#et_box #change_ul ." + parentUserId);
        	  	if( $rostersParent.get(0) ){
        	  		
        	  		 var isshow=$rostersParent.attr('isShowChild');
        	  		 var parentitemjid=$rostersParent.attr('itemjid');
        	  		 if(isshow=='false')
        	  		 {
        	  		 	 $('#et_box #chat_whole #change_ul li.xxzzParentID'+parentitemjid).show();
                   $rostersParent.attr('isShowChild','true');
        	  		 }
        	  	}
        	  	
        	  }
        	  else //单击的一级菜单
        	  {
        	  		 var isShowChild=$rosteritem.attr('isShowChild');
        	  		 var curitemjid=$rosteritem.attr('itemjid');
        	  		 if(isShowChild=='true')
                 {
                        $('#et_box #chat_whole #change_ul li.xxzzParentID'+curitemjid).hide();
                        $rosteritem.attr('isShowChild','false');
                     	  parentUserId = "urosterXXZX" + sha256_digest(curitemjid);
                 }
                 else  if(isShowChild=='false')
                 {
                        $('#et_box #chat_whole #change_ul li.xxzzParentID'+curitemjid).show();
                        $rosteritem.attr('isShowChild','true');                     		
                     	  parentUserId = "urosterXXZX" + sha256_digest(curitemjid);
                 }
        	  }
        	  //隐藏其它子菜单
             $("#et_box .chat_whole #change_ul li").each(function (index, element) {
                var $rosteritemTemp = $(this);
                var isShowChild=$rosteritemTemp.attr('isShowChild');
                 if(isShowChild=='true')
                 {
                 	   if (parentUserId==null||parentUserId==''|| !$rosteritemTemp.hasClass(parentUserId))
                 	   {
        	  		        var curitemjid=$rosteritemTemp.attr('itemjid');
                        $('#et_box #chat_whole #change_ul li.xxzzParentID'+curitemjid).hide();
                        $rosteritemTemp.attr('isShowChild','false');
                 	   	
                 	   }   
                 }
            });
        	
        }

        if(kftype=='xxzxMsg'||kftype=='xxzxMsgSZ')//消息中心消息
        {
            var sub_itemjid = $rosteritem.attr('itemjid');
            var sub_userID = "u" + sha256_digest(sub_itemjid);
            if(kftype=='xxzxMsgSZ')
               gtjawebEtUI.selectSZId=$rosteritem.attr('itemUserId');
            else
            	 gtjawebEtUI.selectId=$rosteritem.attr('itemUserId');
            

            var typeName = realname;
            if(kftype=='xxzxMsg'){
                TDAPP.onEvent("消息中心", typeName+'点击');
            }
            
            var recentlyMsyContent = $rosteritem.attr('recentlyMsyContent');
            var recentlyMsgTime = $rosteritem.attr('recentlyMsgTime');
            var typeID =sub_itemjid;
            var msgID=sub_itemjid;
            // 首次初始消息中心
            if (!$("#et_box #" + sub_userID).get(0)) {
                // 初始IM面板；
                gtjawebEtUI.initXXZXTypegDiv(sub_userID, sub_itemjid, recentlyMsgTime, typeName,typeID,kftype);

            }
            else {

                if(kftype=='xxzxMsgSZ'){
				            gtjawebEtUI.getXXZXSCLayoutTemplate(typeID,$("#et_box #" + sub_userID).find(".xxzxTypeContent"));
				        }
				        if(kftype=='xxzxMsg')//消息中心消息
				        {
				            gtjawebEtUI.getXXZXLayoutTemplate(typeID,$("#et_box #" + sub_userID).find(".xxzxTypeContent"));
				        }
                if ($("#et_box #" + sub_userID + " .title").hasClass('currntChat')) {
                    $("#et_box #" + sub_userID + " .title").removeClass('hasnewmsg');
                    $("#et_box #" + sub_userID + " .title").addClass('hasnewmsg');
                }
            }
            gtjawebEtUI.showChatWin(sub_userID);
            gtjawebEtUI.showTips();

        }
        else
        {
            //TD埋点下线
            // if(kftype == 'zykf'){
            //     TDAPP.onEvent("消息中心", '灵犀客服点击');
            // }else{
            //     TDAPP.onEvent("消息中心", '客户经理点击');
            // }
            
            var sub_itemjid = $rosteritem.attr('itemjid');
            var sub_userID = "u" + sha256_digest(sub_itemjid);
            gtjawebEtUI.selectId=$rosteritem.attr('itemUserId');
            // 首次初始webIM
            if (!$("#et_box #" + sub_userID).get(0)) {
                //if(remotegtjawebet.isConnectSuccess())
                // {
                // 初始IM面板；
                gtjawebEtUI.initWebIM(sub_userID, sub_itemjid, realname, isZNKFSTATUS);


                // }
                //else
                //	{
                //	return;
                //alert('您当前已离线,请重新登录');
                //}

            } else {

                if ($("#et_box #" + sub_userID + " .title").hasClass('currntChat')) {
                    $("#et_box #" + sub_userID + " .title").removeClass('hasnewmsg');
                    $("#et_box #" + sub_userID + " .title").addClass('hasnewmsg');
                }
                if (~sub_itemjid.indexOf("kf95521.chat.gtja.com")) {
                    var $chatMain = $("#et_box #" + sub_userID);
                    var ConnectKfStatus = $chatMain.attr('ConnectKfStatus');
                    if (ConnectKfStatus != '2') {
                        gtjawebEtUI.SendKf95521Request($chatMain);
                    }
                }
                //如果是聊天窗口,则清除消息提示
                 $rosteritem.removeClass('hasnewmsg');
            }
            if (~sub_itemjid.indexOf("1_4@chat.gtja.com"))
                {
                      var realname=$rosteritem.attr('realname');
                      var empid = sub_itemjid.substr(0, sub_itemjid.indexOf("\."));
                        var ehrid = empid+'@'+realname;
                        try
                        {
                                        exports.setUnReadEhrId(ehrid).then(function(res){
                                        }) 
                            
                        } catch(e)
                        {
                            
                        }
                }
            
            gtjawebEtUI.showChatWin(sub_userID);
            gtjawebEtUI.showTips();

        }

        //页面浏览神策埋点
        if(typeof(sensors) != 'undefined'){
            if(realname != '灵犀客服' && realname != '系统推送'){
                sensor_infocent_funcview('客户经理');
            }else{
                sensor_infocent_funcview(realname);
            }            
        }

    },
    createFaceElement: function ($chat) {

        var faces = [];
        //var maxFaceid=190;
        var maxFaceid = 160;
        for (var i = 101; i <= maxFaceid; i++) {

            faces.push(this.faceElTpl(i));
        }

        $chat.find(".wl_faces_main ul").html(faces.join(""));


    },
    getXXZXLayoutTemplate:function(typeID,$templateDiv)
    {
        //模拟异步
    	   window.setTimeout(function () {

                 //收藏内容
                 var $xxzxSCmsg= $('<div>'+typeID+'</div>');
					        //事件
					        //
                 $templateDiv.append($xxzxSCmsg);
                 
            }, 100);
    },
    getXXZXSCLayoutTemplate:function(msgID,$templateDiv)
    {
    	   //模拟异步
    	   window.setTimeout(function () {

                 //收藏内容
                 var $xxzxSCmsg= $('<div>'+msgID+'</div>');
					        //事件
					        //
                 $templateDiv.append($xxzxSCmsg);
                 
            }, 100);
      
    },
    //展示响应人基本信息
    getkhjlshowLayoutTemplate:function(kfjid,$templateDiv)
    {
    	 //模拟异步
    	   window.setTimeout(function () {

                  //显示内容
					        var $khjlshow= $('<span>'+kfjid+'</span>');
					        //事件
					        //
                 $templateDiv.append($khjlshow);
                 
            }, 100);
    },
    //响应人详细信息
   initkhjlshowDiv:function(kfjid,cardUserId)
    {
        if(! $("#et_box .li_class #cardUserId"+cardUserId).get(0)){
            var chatEl = $([
                '<div id="cardUserId'+cardUserId+'" class="khjlmsgcontent">'+
                '<div class="replykhjlshowbg"></div>'+
                '<div class="khjl_msg_close"><span>&nbsp;</span></div>'+
                '<div class="xxzxTypeContent_show">'+
                '</div>'+
                '</div>'
            ].join(""));
            gtjawebEtUI.getkhjlshowLayoutTemplate(kfjid,chatEl.find(".xxzxTypeContent_show"));

            $("#et_box .list ul .li_class."+cardUserId).append(chatEl);
            //关闭按钮
            $("#et_box .khjl_msg_close").click(function () {
                $(".khjlmsgcontent").hide();
            });

        }


    },
    //类型中心窗口
    initXXZXTypegDiv:function(sub_userID, sub_itemjid, recentlyMsgTime,typeName,typeID,kftype)
    {
        var chatEl = $([

            '<div class="chat-main"  id="', sub_userID,

            //'" sender="', sender,
            '" receiver="', sub_itemjid, '" receiverto="', sub_itemjid, '" username="', typeName, '"   chattitle="', typeName, '" style=" width:auto;" >',
            '<div class="xxzxTypeContent">',
            '</div>',
            '  </div>'

        ].join(""));
        if(kftype=='xxzxMsg')//消息中心消息
        {
            gtjawebEtUI.getXXZXLayoutTemplate(typeID,chatEl.find(".xxzxTypeContent"));
        }else if(kftype=='xxzxMsgSZ'){
            gtjawebEtUI.getXXZXSCLayoutTemplate(typeID,chatEl.find(".xxzxTypeContent"));
        }

        $("#etchats").append(chatEl);
    },

//绑定单击事件
    bindClickEvent:function($chatMain,$msgdiv)
    {
    	 $msgdiv.find("#tuwen").click(function () {
                var articlesUrl = $(this).attr('articlesUrl');
                window.open(articlesUrl, '_blank');
            });

            $msgdiv.find("a").attr('target', '_blank');
            
            gtjawebEtUI.assessClick($chatMain,$msgdiv)  ;

            $msgdiv.find("#questionno").click(function () {
                var receiverId = $chatMain.attr("id");
                if (remotegtjawebet.isConnectSuccess() == false) {

                    gtjawebEtUI.writeReceiveMessage('sys', '正在登录ET服务器，请稍候...', receiverId);
                    gtjaWebEtLoginApi.checkLogin();
                    return;

                }

                var znkfno = $(this).attr('znkfno');
                if (znkfno == '')
                    znkfno = $(this).text();

               


                var content = znkfno;



                var sender = '我 说';

                //var receiverId = $chatMain.attr("id");
                var receiver = $chatMain.attr("receiverto");

                var toname = $chatMain.attr('username');

                if (~receiver.indexOf("kf95521.chat.gtja.com")) {
                    var ConnectKfStatus = $chatMain.attr('ConnectKfStatus');
                    if (ConnectKfStatus != '2') {

                        if (ConnectKfStatus == '4') {
                            var html = "当前没有客服在线,正在为您重新接入，请稍候！";
                            gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
                        } else if (ConnectKfStatus == '3') {
                            var html = "会话已经结束,正在为您重新接入，请稍候";
                            gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
                        }

                        gtjawebEtUI.SendKf95521Request($chatMain);
                        return;
                    }
                    toname = $chatMain.attr('sservicejid') + "|" + toname;
                }

                // 接收区域写消息
                var writeContent = $(this).text();

                // 接收区域写消息
                gtjawebEtUI.writeReceiveMessage('me', writeContent, receiverId);


                var sthread = $chatMain.attr("KfThread");
                var msgbody = {};

                msgbody.body = content;
                msgbody.to = receiver;
                msgbody.fromname = gtjawebEtUI.myusername;
                msgbody.toname = toname;
                msgbody.thread = sthread;
                var cmdtypebrand = $chatMain.attr('cmdtypebrand');
                if (cmdtypebrand != null && cmdtypebrand != '')
                    msgbody.cmdtypebrand = cmdtypebrand;
                var cmdtypecmd = $chatMain.attr('cmdtypecmd');
                if (cmdtypecmd != null && cmdtypecmd != '')
                    msgbody.cmdtypecmd = cmdtypecmd;

                remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
                    if (ret == 'success') {
                    	 //首次发消息时,更新查历史的起止时间,防止查出重复消息
					            var _endtime = $chatMain.attr('_endtime')|| '';
				              if(_endtime=='')
				              {
					              if(data&&data.sendTime)
					              {
					             	   $chatMain.attr("_endtime",data.sendTime);
					              }
				              	
				              }

                    } else {

                    }
                });


            });
    },


    initWebIM: function (userJID, receiver, chattitle, isZNKFSTATUS) {


        var chatEl = $(gtjawebEtUI.chatLayoutTemplate(userJID, receiver, chattitle));
        if (isZNKFSTATUS == false)
            chatEl.attr('cmdtypecmd', '');

        gtjawebEtUI.createFaceElement(chatEl);

        if(chattitle == '灵犀客服')
        {
            var t = chatEl.find('#textarea'); //获取到文本域对象
            t.css("color", "#BEBEBE"); //设置文本域的样式
            t.text("请输入问题内容(CTRL+V粘贴)"); //设置默认显示文字
            var default_value = t.text(); //把默认显示的文字赋给一个变量

            t.focus(function () { //当鼠标点击文本域时修改文本域的样式，判断文本域内的文字是否等于默认值，如果等于就把文本域内设空
                t.css("color", "black");
                if (t.text() == default_value) {
                    t.html('');
                }
            });

            t.blur(function () { //当文本域失去鼠标焦点时判断文本域中的值是否为空，如果为空就把文本域的值设置为默认显示的文字并修改样式
                t.css("color", "black");
                if (t.text() == '' && t.html() == '') {
                    t.text(default_value);
                    t.css("color", "#BEBEBE");
                }
            });


            chatEl.find(".ctb01").mouseover(function () {
                chatEl.find(".wl_faces_box").show();
                // this.style.background = "#d9d9d9";

            }).mouseout(function () {
                chatEl.find(".wl_faces_box").hide();
                this.style.background = "#f4f4f4";
            });

            chatEl.find(".ctb02").mouseover(function () {
                // this.style.background = "#d9d9d9";
            }).mouseout(function () {
                this.style.background = "#f4f4f4";
            });

            chatEl.find(".ctb03").mouseover(function () {
                // this.style.background = "#d9d9d9";
            }).mouseout(function () {
                this.style.background = "#f4f4f4";
            });

            chatEl.find(".wl_faces_box").mouseover(function () {
                chatEl.find(".wl_faces_box").show();
            }).mouseout(function () {
                chatEl.find(".wl_faces_box").hide();
            });
            chatEl.find(".wl_faces_close").click(function () {
                chatEl.find(".wl_faces_box").hide();
            });
            chatEl.find(".wl_faces_main img").click(function () {
                var a = $(this).attr("src");
                var t = chatEl.find('#textarea');
                var default_text = "请输入问题内容(CTRL+V粘贴)";
                if (t.text() != default_text) {
                    chatEl.find("#textarea").html(chatEl.find("#textarea").html() + "<img class='emotion' src='" + a + "'/>");
                    chatEl.find("#textarea").focusEnd();
                    chatEl.find(".wl_faces_box").hide();
                } else {
                    chatEl.find("#textarea").html("<img class='emotion' src='" + a + "'/>");
                    chatEl.find("#textarea").focusEnd();
                    chatEl.find(".wl_faces_box").hide();
                }
            });


            chatEl.find(".ctb03").click(function () {

                gtjawebEtUI.writeReceiveMessage('sys', '您给对方发了窗体抖动！', userJID);

                gtjawebEtUI.shakeWin();

                gtjawebEtUI.sendSharkMsg(userJID);

            });
             chatEl.find(".et_message_more_btn").click(function () {                
                 gtjawebEtUI.moremessagelist(chatEl);
            });

            chatEl.find(".chat02_bar a").click(function () {
                gtjawebEtUI.sendHandler(chatEl);
            });
            gtjawebEtUI.moremessagelist(chatEl);
        }else{
            var t = chatEl.find('#textarea'); //获取到文本域对象
            t.css("color", "#999"); //设置文本域的样式
            t.css("background", "#F6F6F6");
            t.text("尊敬的客户您好，目前该功能正在升级中，如需与您的客户进行沟通，请通过君弘APP-我的客户经理进行交流，感谢您的理解与支持。");           
            var default_value = t.text();
            t.focus(function () { //当鼠标点击文本域时修改文本域的样式，判断文本域内的文字是否等于默认值，如果等于就把文本域内设空
                return
            });
            t.attr('contenteditable', false)

            chatEl.find(".chat02_bar").css('display', 'none');

            chatEl.find(".ctb01").mouseover(function () {
                chatEl.find(".wl_faces_box").show();
                // this.style.background = "#d9d9d9";

            }).mouseout(function () {
                chatEl.find(".wl_faces_box").hide();
                this.style.background = "#f4f4f4";
            });

            chatEl.find(".ctb02").mouseover(function () {
                // this.style.background = "#d9d9d9";
            }).mouseout(function () {
                this.style.background = "#f4f4f4";
            });

            chatEl.find(".ctb03").mouseover(function () {
                // this.style.background = "#d9d9d9";
            }).mouseout(function () {
                this.style.background = "#f4f4f4";
            });

            chatEl.find(".wl_faces_box").mouseover(function () {
                chatEl.find(".wl_faces_box").show();
            }).mouseout(function () {
                chatEl.find(".wl_faces_box").hide();
            });
            chatEl.find(".wl_faces_close").click(function () {
                chatEl.find(".wl_faces_box").hide();
            });
            // chatEl.find(".wl_faces_main img").click(function () {
            //     var a = $(this).attr("src");
            //     var t = chatEl.find('#textarea');
            //     var default_text = "请输入问题内容(CTRL+V粘贴)";
            //     if (t.text() != default_text) {
            //         chatEl.find("#textarea").html(chatEl.find("#textarea").html() + "<img class='emotion' src='" + a + "'/>");
            //         chatEl.find("#textarea").focusEnd();
            //         chatEl.find(".wl_faces_box").hide();
            //     } else {
            //         chatEl.find("#textarea").html("<img class='emotion' src='" + a + "'/>");
            //         chatEl.find("#textarea").focusEnd();
            //         chatEl.find(".wl_faces_box").hide();
            //     }
            // });


            chatEl.find(".ctb03").click(function () {

                gtjawebEtUI.writeReceiveMessage('sys', '您给对方发了窗体抖动！', userJID);

                gtjawebEtUI.shakeWin();

                gtjawebEtUI.sendSharkMsg(userJID);

            });
             chatEl.find(".et_message_more_btn").click(function () {                
                 gtjawebEtUI.moremessagelist(chatEl);
            });

            chatEl.find(".chat02_bar a").click(function () {
                gtjawebEtUI.sendHandler(chatEl);
            });
            gtjawebEtUI.moremessagelist(chatEl);            
        }

        $("#etchats").append(chatEl);
        if (remotegtjawebet.isConnectSuccess()) {
            if (~receiver.indexOf("kf95521.chat.gtja.com")) {
                gtjawebEtUI.SendKf95521Request(chatEl);
            } else if (isZNKFSTATUS) {
                var sthread = chatEl.attr('KfThread');
                var msgbody = {};

                msgbody.body = '欢迎语';
                msgbody.to = chatEl.attr("receiverto");
                msgbody.fromname = gtjawebEtUI.myusername;
                msgbody.toname = chatEl.attr("username");
                msgbody.thread = sthread;
                var cmdtypebrand = chatEl.attr('cmdtypebrand');
                if (cmdtypebrand != null && cmdtypebrand != '')
                    msgbody.cmdtypebrand = cmdtypebrand;
                var cmdtypecmd = chatEl.attr('cmdtypecmd');
                if (cmdtypecmd != null && cmdtypecmd != '')
                    msgbody.cmdtypecmd = cmdtypecmd;
                msgbody.cmdtypeflag = 'hyy';

                remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
                    if (ret == 'success') {
                    	  //首次发消息时,更新查历史的起止时间,防止查出重复消息
					            var _endtime = chatEl.attr('_endtime')|| '';
				              if(_endtime=='')
				              {
					              if(data&&data.sendTime)
					              {
					             	   chatEl.attr("_endtime",data.sendTime);
					              }
				              	
				              }

                    } else {

                    }
                });
            }
        }

        

    },
    shakeWin: function () {
        return;
        //发送抖动事件
        var shaketimer = null;
        var offset = 0.20 * ($(window).width());
        var posData = [offset, 50];
        var i = 0;
        clearInterval(shaketimer);
        shaketimer = setInterval(function () {
            i++;
            var $chatbox = $('#et_box');
            $chatbox.css('left', (posData[0] + ((i % 2) > 0 ? -2 : 2) + 'px'));
            $chatbox.css('top', (posData[1] + ((i % 2) > 0 ? -2 : 2) + 'px'));
            if (i >= 30) {
                clearInterval(shaketimer);
                $chatbox.css('left', (posData[0] + 'px'));
                $chatbox.css('top', (posData[1] + 'px'));
            }
        }, 30);
    },
    showChatWin: function (userJID) {
        $chatMain = $("#et_box #" + userJID);
        if (!$chatMain.get(0))
            return;
        var chattitle = $chatMain.attr('chattitle');
        if (!chattitle)
            chattitle = '在线客服';
        try {
            if (window.TDXQuery) {
                var request = {
                    Method: 'ChangeTitle',
                    FuncName: '',
                    Param: chattitle
                };
                window.TDXQuery({
                    request: JSON.stringify(request),
                    onSuccess: function () {},
                    onFailure: function (errCode, errInfo) {}
                });
            }
        } catch (e) {}
        $('#et_box .title .span1').text(chattitle);
        $('#et_box .chat-main').hide();
        $chatMain.show();

        //$("#" + userJID+" .title").removeClass('newmsgflag');
        //$(".ETUI-chat-main .title").removeClass('currntChat');
        //$("#" + userJID+" .title").addClass('currntChat');

    },
    //登录成功回调函数
    handleConnected: function () {

        gtjawebEtUI.myusername = '游客' + remotegtjawebet.connection._custId;

        gtjawebEtUI.UIMainJid == remotegtjawebet.connection.jid;

        if (gtjawebEtUI.reconnectTips == '1') {
            gtjawebEtUI.writeReceiveMessage('sys', '重新登录成功。', '');
        }

        {
            //读取好友
            if(remotegtjawebet.connection._custType=='3') //交易用户才取响应人列表
            remotegtjawebet.sendMsg('getRoster', {}, function (ret, tips, data) {
                if (ret == 'success') {
                    gtjawebEtUI.initRoster(data);
                    //gtjawebEtUI.UIMainJid=remotegtjawebet.connection.jid;

                    remotegtjawebet.sendMsg('getVCard', {}, function (ret, tips, data) {
                        if (ret == 'success') {
                            gtjawebEtUI.handleUserVCard(data);
                        } else {

                        }
                    });
                    //调用富易接口,读取未读消息数
                    try
                    {
                    	 if(exports)
                    	 exports.getUnReadEhrId().then(function(res){
										        for(var i=0; i<res.RNUM; i++){
										            var kf = decode_title_content(res.list[i].ehrid);       //格式为：016206@凌宏健
										            var kfMsgNum = res.list[i].count;
										            gtjawebEtUI.get_showTips(kf,kfMsgNum);
										        }									        
									        });
                    }
                    catch(e)
                    {
                    	
                    }

                    //登陆成功
                    gtjawebEtUI.initEtPresence();

                    //打开第一个窗口
                    //gtjawebEtUI.rosteritemclick($('#change_ul li:first'));
                } else {

                }
            });
        }
        gtjawebEtUI.reconnectTips = '';

        if (gtjawebEtUI.openParam) {
            window.setTimeout(function () {

                if (gtjawebEtUI.openParam) {
                    gtjawebEtUI.openChatWin(gtjawebEtUI.openParam.kfjid, gtjawebEtUI.openParam.kfname, gtjawebEtUI.openParam.isZNKFSTATUS);
                    gtjawebEtUI.openParam = null;
                }

            }, 100);
        }


    },
    UIMainJid: '',

    datetimeFormat: function (v) {

        if (~~v < 10) {

            return "0" + v;

        }

        return v;

    },

    getDatetime: function () {

        // 设置当前发送日前

        var date = new Date();

        var datetime = "";

        datetime =gtjawebEtUI.datetimeFormat(date.getFullYear())
            + "-" + gtjawebEtUI.datetimeFormat(date.getMonth()+1)
            + "-" + gtjawebEtUI.datetimeFormat(date.getDate())
            + " " +gtjawebEtUI.datetimeFormat(date.getHours())
            + ":" + gtjawebEtUI.datetimeFormat(date.getMinutes());




        return datetime;

    },

    lastSendTime: '',

    writeTime: function (receiverId, offsendtime) {
        var $chatMain = $("#et_box #" + receiverId);
        if (!$chatMain.get(0))
            return;

        if (offsendtime && offsendtime != '') {
            var stime = offsendtime;
            if (offsendtime.length > 16)
                stime = offsendtime.substr(0, 16);
            var lastoffsendtime = $chatMain.attr("lastoffsendtime");
            if (stime != lastoffsendtime) {
                if (!$("#et_box #" + receiverId + " .chat01_content .replysys.hismsgbottom").get(0)) {
                    var hismsgdiv = '<div class="replysys hismsgtop">--------------------以下是历史消息--------------------</div>' + '<div class="replysys hismsgbottom">--------------------以上是历史消息--------------------</div>';
                    $("#et_box #" + receiverId + " .chat01_content").append($(hismsgdiv));
                }
                $chatMain.attr("lastoffsendtime", stime);

                var $msgdiv = $('<div class="replytime"><span>' + stime + '</span> </div>');

                $msgdiv.insertBefore("#et_box #" + receiverId + " .chat01_content .replysys.hismsgbottom");

            }
        } else {
            var stime = gtjawebEtUI.getDatetime();
            var lastsendtime = $chatMain.attr("lastsendtime");
            if (stime != lastsendtime) {
                $chatMain.attr("lastsendtime", stime);

                var $msgdiv = $('<div class="replytime"><span>' + stime + '</span> </div>');

                $("#et_box #" + receiverId + " .chat01_content").append($msgdiv);

            }
        }
    },
    // 向接收消息iframe区域写消息

    writeReceiveMessage: function (flag, content, receiverId, msgTime,from) {

        if (content) {

            gtjawebEtUI.writeTime(receiverId, msgTime);
            var headimage = '';
            if (flag == 'me') {
                headimage = '<div class="replyme">   <img src="' + gtjawebEtUI.ETImagePath + 'wo.png">  <div class="replyme_recordtextbg"></div> <div class="replyme_recordtext">' + content + '</div> </div>'
            } else if (flag == 'friend') {
            	  var empid='';
            	  if(from!=null&&from!='')
            	  {
                    if (~from.indexOf("@chat.gtja.com"))
                        empid = from.substr(0, from.indexOf("\."));
                }
                if(empid!='')
        	  	      headimage = '<div class="replyclient">  <img class="userp" onerror="javascript:this.src='+"'"+gtjawebEtUI.ETImagePath + 'kehu_duihuakuang.png'+"';"+'" src="http://dl.app.gtja.com/baishitong/userphoto/'+empid+'.png"/> <div class="replyclient_recordtextbg"></div>  <div class="replyclient_recordtext"><span class="replyspan"></span>' + content + '</div> </div>'
        	  	  else  
        	  	  	  headimage = '<div class="replyclient">  <img src="' + gtjawebEtUI.ETImagePath + 'kehu_duihuakuang.png"> <div class="replyclient_recordtextbg"></div>  <div class="replyclient_recordtext"><span class="replyspan"></span>' + content + '</div> </div>'

            } else if (flag == 'znkf') {
                headimage = '<div class="replyclient">  <img width="32" height="32" src="' + gtjawebEtUI.ETImagePath + 'xiaojun.png"> <div class="replyclient_recordtextbg"></div>  <div class="replyclient_recordtext"><span class="replyspan"></span>' + content + '</div> </div>'

            } else {
                headimage = '<div class="replysys"> ' + content + ' </div>';
            }


            // 发送消息的样式
            var $msgdiv = $(headimage);

             // 设置消息接受者的名称

            var   $chatMain = $("#et_box #" + receiverId);
            //绑定单击事件
             gtjawebEtUI.bindClickEvent($chatMain,$msgdiv);

                // 首次初始webIM

                if (!$("#et_box #" + receiverId).get(0)) {
                    return;
                }

                // 设置消息接受者的名称

                $chatMain = $("#et_box #" + receiverId);


                

            if (msgTime && msgTime != '') {
                $msgdiv.insertBefore("#et_box #" + receiverId + " .chat01_content .replysys.hismsgbottom");
            } else
                $("#et_box #" + receiverId + " .chat01_content").append($msgdiv);
            try {
                $("#et_box #" + receiverId + " .chat01_content").scrollTop($msgdiv.offset().top - $("#et_box #" + receiverId + " .chat01_content").offset().top + $("#et_box #" + receiverId + " .chat01_content").scrollTop());
            } catch (e) {}           

        }

    },
    sendSharkMsg: function (receiverId) {
        if (!$("#et_box #" + receiverId).get(0)) {
            return;
        }

        // 设置消息接受者的名称

        $chatMain = $("#et_box #" + receiverId);


        var content = '';



        var sender = '我 说';

        //var receiverId = $chatMain.attr("id");
        var receiver = $chatMain.attr("receiverto");

        var toname = $chatMain.attr('username');

        if (~receiver.indexOf("kf95521.chat.gtja.com")) {
            var ConnectKfStatus = $chatMain.attr('ConnectKfStatus');
            if (ConnectKfStatus != '2') {

                if (ConnectKfStatus == '4') {
                    var html = "当前没有客服在线,正在为您重新接入，请稍候！";
                    gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
                } else if (ConnectKfStatus == '3') {
                    var html = "会话已经结束,正在为您重新接入，请稍候";
                    gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
                }
                gtjawebEtUI.SendKf95521Request($chatMain);
                return;
            }
            toname = $chatMain.attr('sservicejid') + "|" + toname;
        }



        var sthread = $chatMain.attr("KfThread");
        var msgbody = {};

        msgbody.body = '';
        msgbody.subject = 'shake_window';
        msgbody.to = receiver;
        msgbody.fromname = gtjawebEtUI.myusername;
        msgbody.toname = toname;
        msgbody.thread = sthread;
        var cmdtypebrand = $chatMain.attr('cmdtypebrand');
        if (cmdtypebrand != null && cmdtypebrand != '')
            msgbody.cmdtypebrand = cmdtypebrand;
        var cmdtypecmd = $chatMain.attr('cmdtypecmd');
        if (cmdtypecmd != null && cmdtypecmd != '')
            msgbody.cmdtypecmd = cmdtypecmd;

        remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
            if (ret == 'success') {
            	//首次发消息时,更新查历史的起止时间,防止查出重复消息
					            var _endtime = $chatMain.attr('_endtime')|| '';
				              if(_endtime=='')
				              {
					              if(data&&data.sendTime)
					              {
					             	   $chatMain.attr("_endtime",data.sendTime);
					              }
				              	
				              }

            } else {

            }
        });
    },
    // 数字转表情
    getReplaceFace: function (code) {

        return "[img:" + code + "]";


    },
    //通过编码得到表情gif文件
    getFaceGIFByCode: function (code) {
        //return "<img alt=\"\" src=\"vim/js/kindeditor/plugins/emoticons/"+arr[3]+"\" border=\"0\" />";
        return [

            "<img class='emotion' src='",

            this.faceImagePath,

            (i - 1),

            ".gif'/>"

        ].join("");

    },
    //images/\emotions\/
    //<img src=\"..\/images\/emotions\/(\d+.gif)\" border=\"0\" \/> 替换成 [img:*]
    imgReplaceFace: function (str) {
        var arr;
        var src = str;
        var re = /<[i|I][m|M][g|G][ |\n|\r]+class=\"emotion\"[ |\n|\r]+src=\"[a-zA-Z0-9|:|\/|_|\.]*images\/emotions\/(\d+).gif\"[ |\/]*>/g;
        //创建正则表达式对象。
        while ((arr = re.exec(str)) != null) {
            var s = this.getReplaceFace(arr[1]);
            src = src.replace(/<[i|I][m|M][g|G][ |\n|\r]+class=\"emotion\"[ |\n|\r]+src=\"[a-zA-Z0-9|:|\/|_|\.]*images\/emotions\/(\d+).gif\"[ |\/]*>/, s);
        }
        return src;
    },
    //[img:*] 替换成 <img src=\"..\/images\/emotions\/(\d+.gif)\" border=\"0\" \/>
    faceReplaceImg: function (str) {

        var arr;
        var src = str;
        var re = /\[img:(\d+)\]/g;
        //创建正则表达式对象。
        while ((arr = re.exec(str)) != null) {
            var s = this.getFaceGIFByCode(arr[1]);
            src = src.replace(/\[img:(\d+)\]/, s);
        }
        return src;
    },
    ConnectKfStatus: '',
    KfThread: '',
    receiverTo: "49@kf95521.chat.gtja.com",
    reconnectTips: '',

    sendSearchengineTips: function () {
        //gtjawebEtUI.searchengineTips='搜索引擎：谷歌\n关键字：你好';
        if (gtjawebEtUI.ConnectKfStatus == '2') {
            if (gtjawebEtUI.searchengineTips != '') {
                var msgbody = {};
                msgbody.body = gtjawebEtUI.searchengineTips;
                msgbody.to = gtjawebEtUI.receiverTo;
                msgbody.fromname = '系统消息';
                msgbody.thread = gtjawebEtUI.KfThread;

                remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
                    if (ret == 'success') {

                    } else {

                    }
                });
            }



        }


    },

    SendKf95521Request: function ($chatMain) {
        var receiverId = $chatMain.attr("id");
        var ConnectKfStatus = $chatMain.attr('ConnectKfStatus');
        var receiver = $chatMain.attr('receiver');
        if (~receiver.indexOf("@chat.gtja.com"))
            return;

        if (ConnectKfStatus == '4') {
            var html = "当前没有客服在线,请使用留言功能！";

            gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
            ConnectKfStatus = '';
            return;
        } else if (ConnectKfStatus == '3') {
            var html = "会话已经结束,正在为您重新接入客服...";

            gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
        } else if (ConnectKfStatus == '5') {
            var html = "当前正在排队中,请耐心等待...";
            gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
            return;
        } else if (ConnectKfStatus == '6') {
            var html = "正在为您转接中,请耐心等待...";
            gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
            return;
        } else {
            var html = "正在为您转接客服...";
            gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
        }

        ConnectKfStatus = '6';
        $chatMain.attr('ConnectKfStatus', ConnectKfStatus);
        remotegtjawebet.sendMsg('kf95521', {
            kf95521type: "Visitor95521",
            to: receiver,
            brand: $chatMain.attr('cmdtypebrand')
        }, function (ret, tips, data) {
            if (ret == 'success') {
                var htmlTip = '';
                var ConnectKfStatus = '';
                var KfThread = '';
                if (data.result == 'Success') {
                    ConnectKfStatus = '2';
                    KfThread = data.thread;
                    if (data.serviceid != 'XiaoJun')
                        htmlTip = '接入客服成功,当前客服工号:' + data.serviceid + '!';

                } else if (data.result == 'NoServiceOnline') {
                    ConnectKfStatus = '4';
                    KfThread = '';
                    htmlTip = '您好,当前无客服在线,可能当前不在工作时间。';

                } else if (data.result == 'ServiceBusy') {
                    ConnectKfStatus = '5';
                    KfThread = data.thread;
                    htmlTip = '您好,当前客服忙碌,您之前还有' + data.waitCount + '人在排队,请耐心等待...';

                } else {
                    ConnectKfStatus = '';
                    KfThread = '';
                    htmlTip = '接入不成功,请重新接入。';
                }

                $chatMain.attr('ConnectKfStatus', ConnectKfStatus);
                $chatMain.attr('KfThread', KfThread);
                if (htmlTip != '')
                    gtjawebEtUI.writeReceiveMessage('sys', htmlTip, receiverId);
            } else {
                $chatMain.attr('ConnectKfStatus', '');
            }
        });

    },
    kfUserName: '',
    // 发送消息

    sendHandler: function ($chatMain) {
        var receiverId = $chatMain.attr("id");
        if (remotegtjawebet.isConnectSuccess() == false) {

            gtjawebEtUI.writeReceiveMessage('sys', '正在登录ET服务器，请稍候...', receiverId);
            gtjaWebEtLoginApi.checkLogin();
            return;

        }

        var content = $chatMain.find("#textarea").html();
        var content_tipsDiv;

        var default_text = "请输入问题内容(CTRL+V粘贴)";
        if ($chatMain.find("#textarea").text() != default_text) {

            content = $.trim(content);

            content = content.replace(new RegExp("<div>|</div>|<br>|<p>|</p>|&nbsp;", "igm"), "");
            content_tipsDiv=content;
        } else {
            content = null;
        }


        // 获取即将发送的内容

        if (content) {


            var receiver = $chatMain.attr('receiverto');

            var toname = $chatMain.attr('username');

            if (~receiver.indexOf("@kf95521.chat.gtja.com")) {
                var ConnectKfStatus = $chatMain.attr('ConnectKfStatus');
                if (ConnectKfStatus != '2') {

                    gtjawebEtUI.SendKf95521Request($chatMain);
                    return;
                }
            }
            toname = '' + "|" + toname;


            // 接收区域写消息
            var writeContent = content;


            // 判断是否是手机端会话，如果是就发送纯text，否则就发送html代码


            //转换表情
            content = gtjawebEtUI.imgReplaceFace(content);

            try {
                if (content != null && content != '') {
                    content = $(["<div>", content, "</div>"].join("")).text();

                    if (content.length > 1000) {
                        var html = "发送内容不能超过1000字符，实际长度为" + content.length + "字符，请分开发送！";

                        gtjawebEtUI.writeReceiveMessage('sys', html, receiverId);
                        return;
                    }

                }
            } catch (e) {
                //alert(e);
            }
            // 接收区域写消息
            gtjawebEtUI.writeReceiveMessage('me', writeContent, receiverId);


            var sthread = $chatMain.attr('KfThread');
            var msgbody = {};


            msgbody.body = content;
            msgbody.to = receiver;
            msgbody.fromname = gtjawebEtUI.myusername;
            msgbody.toname = gtjawebEtUI.kfUserName;
            msgbody.thread = sthread;
            var cmdtypebrand = $chatMain.attr('cmdtypebrand');
            if (cmdtypebrand != null && cmdtypebrand != '')
                msgbody.cmdtypebrand = cmdtypebrand;
            var cmdtypecmd = $chatMain.attr('cmdtypecmd');
            if (cmdtypecmd != null && cmdtypecmd != '')
                msgbody.cmdtypecmd = cmdtypecmd;

            remotegtjawebet.sendMsg('sendMsg', msgbody, function (ret, tips, data) {
                if (ret == 'success') {
                     //首次发消息时,更新查历史的起止时间,防止查出重复消息
					            var _endtime = $chatMain.attr('_endtime')|| '';
				              if(_endtime=='')
				              {
					              if(data&&data.sendTime)
					              {
					             	   $chatMain.attr("_endtime",data.sendTime);
					              }
				              	
				              }
                } else {

                }
            });
            
            
           var rosterID = "uroster" + sha256_digest(receiver);
           var stime = gtjawebEtUI.getDatetime();
           $("#et_box .list ul ." + rosterID + "  .magtime").text(stime.substr(11,5));
           $("#et_box .list ul ." + rosterID + "  .content_tips").text(content_tipsDiv);


            // 清空发送区域
            $chatMain.find("#textarea").html("")


        } else {
            gtjawebEtUI.writeReceiveMessage('sys', '请输入聊天内容!', receiverId);
        }

    },


    faceImagePath: "images/emotions/",

    faceElTpl: function (i) {

        var num = i - 1;
        if (num == 100)
            num = 17;
        else if (num >= 101 && num <= 103)
            num = num - 100;
        else if (num == 105)
            num = 4;
        else if (num == 109)
            num = 0;
        else if (num >= 112 && num <= 116)
            num = num - 106;
        else if (num >= 120 && num <= 123)
            num = num - 109;
        else if (num == 125)
            num = 15;
        else if (num == 127)
            num = 16;
        else if (num == 130)
            num = 18;
        else if (num == 134)
            num = 19;
        else if (num >= 136 && num <= 139)
            num = num - 116;
        else if (num == 153)
            num = 5;

        return [

            "<li><a href='javascript:;'><img src='",

            this.faceImagePath,

            num,

            ".gif' gif='",

            this.faceImagePath,

            num,

            ".gif'/></a></li>"

        ].join("");

    },


    myusername: '游客',

    GetChild: function (snode, sName) {

        var ret = {};
        if (snode && snode._subTagCount > 0) {
            for (var i = 0; i < snode._subNodes.length; i++) {
                var nodeitem = snode._subNodes[i];
                if (nodeitem._tagName == sName) {
                    ret = nodeitem;
                    break;
                }
            }
        }
        return ret;

    },

    GetChildCmdVal: function (snode, scmd) {

        var ret = '';
        if (snode && snode._subTagCount && snode._subTagCount > 0) {
            for (var i = 0; i < snode._subNodes.length; i++) {
                var nodeitem = snode._subNodes[i];
                if (nodeitem._tagName == 'command' && nodeitem._attrib.cmdtype == scmd) {
                    ret = nodeitem._content;
                    break;
                }
            }
        }
        return ret;

    },

    GetChildVal: function (snode, sName) {

        var ret = '';
        if (snode && snode._subTagCount && snode._subTagCount > 0) {
            for (var i = 0; i < snode._subNodes.length; i++) {
                var nodeitem = snode._subNodes[i];
                if (nodeitem._tagName == sName) {
                    ret = nodeitem._content;
                    break;
                }
            }
        }
        return ret;

    },
    GetChildOfflineTime: function (msg) {

        var ret = '';
        var offNode = gtjawebEtUI.GetChild(msg, 'offline');
        if (offNode) {
            var itemNode = gtjawebEtUI.GetChild(offNode, 'item');
            if (itemNode && itemNode._attrib && itemNode._attrib.node)
                ret = itemNode._attrib.node;
        }

        return ret;

    },

    KF95521PresenceHandler: function (presence) {
        var xnode = gtjawebEtUI.GetChild(presence, 'x');

        if (xnode._attrib) {
            var receiver = presence._attrib.from;
            receiver = gtjawebEtUI.userAddress(receiver);
            var receiverId = "u" + sha256_digest(receiver);


            var sresult = xnode._attrib.result;
            if (sresult == 'ServiceAbort') {
                $('#et_box #' + receiverId).attr('ConnectKfStatus', '');
                $('#et_box #' + receiverId).attr('KfThread', '');

                gtjawebEtUI.writeReceiveMessage("sys", '已经断开人工服务。', receiverId);

            } else if (sresult == 'NewSessionCreateSuccess') {
                $('#et_box #' + receiverId).attr('ConnectKfStatus', '2');
                $('#et_box #' + receiverId).attr('KfThread', xnode._attrib.thread);
                var servicejid = xnode._attrib.servicejid;
                if (~servicejid.indexOf("\.")) {

                    servicejid = servicejid.substr(0, servicejid.indexOf("\."));

                }
                gtjawebEtUI.writeReceiveMessage("sys", '成功为您接入人工客服', receiverId);
                gtjawebEtUI.writeReceiveMessage("friend", '您好,我是客服' + servicejid + ',请问有什么可以帮您的?', receiverId);


            } else if (sresult == 'ServiceJump') {
                $('#et_box #' + receiverId).attr('ConnectKfStatus', '2');
                $('#et_box #' + receiverId).attr('KfThread', xnode._attrib.thread);
                var servicejid = xnode._attrib.servicejid;
                if (~servicejid.indexOf("\.")) {

                    servicejid = servicejid.substr(0, servicejid.indexOf("\."));

                }
                if(xnode._attrib.isJunHongZX == 'true')
                {
                	
                   gtjawebEtUI.writeReceiveMessage("sys", '为您转接君弘在线投顾……');
                   gtjawebEtUI.writeReceiveMessage("friend", '您好,我是君弘在线投顾' + servicejid + ',请问有什么可以帮您的?', receiverId);
                }
                else
                {
                   gtjawebEtUI.writeReceiveMessage("sys", '转接到新的客服', receiverId);
                   gtjawebEtUI.writeReceiveMessage("friend", '您好,我是客服' + servicejid + ',请问有什么可以帮您的?', receiverId);
                		
                }

            }
        }

    },
    userAddress: function (user) {

        if (user) {

            if (!~user.indexOf("@")) {

                user += "@" + 'chat.gtja.com'; // + "/" + remote.jsjac.resource;

            } else if (~user.indexOf("/")) {

                user = user.substr(0, user.indexOf("/"));

            }

        }

        return user;


    },
    userAddressNoIdentity: function (user) {

        if (user) {

            if (!~user.indexOf("@")) {

                user += "@" + 'chat.gtja.com'; // + "/" + remote.jsjac.resource;

            } else if (~user.indexOf("/")) {

                user = user.substr(0, user.indexOf("/"));

            }
            if (~user.indexOf("_")) {

                user = user.substr(0, user.indexOf("_")) + "@" + 'chat.gtja.com';

            }

        }

        return user;

    },
    state: {
        "available": "在线",
        "chat": "在线", //"欢迎聊天";
        "away": "离开",
        "xa": "请勿打扰",
        "dnd": "忙碌",
        "invisible": "隐身",
        "unavailable": "离线"
    },
    handlePresence: function (presence) {

        var tempUser = presence._attrib.from;
        if (~tempUser.indexOf("@kf95521.chat.gtja.com")) {
            gtjawebEtUI.KF95521PresenceHandler(presence);
            return;
        }

    },
    handleDisconnected: function (e) {
        var tselect = '#ETUI-Start s';
        if (gtjawebEtUI.ETSelectID && gtjawebEtUI.ETSelectID != '')
            tselect = gtjawebEtUI.ETSelectID;

        $(tselect).removeClass('status_online');
        $(tselect).removeClass('status_offline');
        $(tselect).addClass('status_offline');

        remotegtjawebet.connection._presence = '';
        gtjawebEtUI.ConnectKfStatus = '';
        gtjawebEtUI.KfThread = '';
        $('#et_box .chat-main').attr('ConnectKfStatus', '');
        //$('#et_box .chat-main').attr('KfThread','');

        /*
         退出
         "errorcode":"451","errorlog":"您成注销ET助手!"
         "errorcode":"452","errorlog":"您超时退出ET助手!"
         登录
         "errorcode":"410","errorlog":"[0111]创建session失败"
         "errorcode":"411","errorlog":"[0112]token认证失败"
         "errorcode":"412","errorlog":"当前cookei已登录不能切换用户"
         交验登录
         "errorcode":"401","errorlog":"查检到该cookei未登录!"
         "errorcode":"402","errorlog":"当前cookei登录中,请稍后再试"
         本地错误
         "errorcode":"501"
         */
        if (e.errorcode == '401') {
            if (gtjawebEtUI.bstsession && gtjawebEtUI.bstsession != '') {
                var bstsession = gtjawebEtUI.bstsession;
                gtjawebEtUI.bstsession = '';
                gtjaWebEtLoginApi.login(bstsession);
                return;
            }

        } else if (e.errorcode == '402') {
            window.setTimeout(function () {

                gtjaWebEtLoginApi.checkLogin(gtjawebEtUI.ETSelectID);

            }, 700);
            return;
        } else if (e.errorcode == '415') {
            window.setTimeout(function () {

                gtjaWebEtLoginApi.checkLogin(gtjawebEtUI.ETSelectID);

            }, 700);
            return;
        } else if (e.errorcode == '411') {
            //令牌登录失败则以游客登录
            if (gtjaWebEtLoginApi.custType == '3') {
                gtjaWebEtLoginApi.custId = 'fyyk' + gtjaWebEtLoginApi.custId;
                gtjaWebEtLoginApi.ettoken = '';
                gtjaWebEtLoginApi.custType = '-1';
            }


            window.setTimeout(function () {

                gtjaWebEtLoginApi.checkLogin(gtjawebEtUI.ETSelectID);

            }, 700);
            return;
        }
        var html = e.errorlog;
        if (e.errorcode == '501') {
            if (~e.errorlog.indexOf("aborted")) {
                html = "网络异常,您离线了！";
            } else if (~e.errorlog.indexOf("disconnect")) {
                html = "您登出ET助手了！";
            }
        }
        if (gtjawebEtUI.reconnectTips == '1') {
            gtjawebEtUI.writeReceiveMessage('sys', '重新登录失败。', '');
        }
        gtjawebEtUI.reconnectTips = '';
        // 接收区域写消息
        gtjawebEtUI.writeReceiveMessage("sys", html, '');
    },
    ETImagePath: 'images/',

    //创建cookie
    SetCookie: function (sName, sValue) {
        var Days = 100;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = sName + "= " + escape(sValue) + ";expires= " + exp.toGMTString();
    },

    //获取cookie
    GetCookie: function (sName) {
        var aCookie = document.cookie.split("; ");
        for (var i = 0; i < aCookie.length; i++) {
            var aCrumb = aCookie[i].split("=");
            if (sName == aCrumb[0])
                return unescape(aCrumb[1]);
        }
    },

    //生成n位随机数
    RndNum: function (n) {
        var rnd = "";
        for (var i = 0; i < n; i++) {
            rnd += Math.floor(Math.random() * 10);
        }
        return rnd;
    },
    getVisitor: function () {
        var custId = gtjawebEtUI.GetCookie("visitorId");
        if (custId == undefined || custId == null || custId == "") {
            custId = 'ydbet' + gtjawebEtUI.RndNum(10);
            gtjawebEtUI.SetCookie("visitorId", custId);
        } else {
            custId = gtjawebEtUI.GetCookie("visitorId");
        }
        return custId
    },
    initUIXXZX:function(){
    	  var typeArray=[
				  {
					  typeID:"xtgsType", //类别唯一ID,
					  parentID:"",
					  typeName:"系统推送",//类别名称
					  typeimg:"xtts.png",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"100001", //类别唯一ID,
					  parentID:"xtgsType",
					  typeName:"资讯提醒",//类别名称
					  typeimg:"",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"100002", //类别唯一ID,
					  parentID:"xtgsType",
					  typeName:"新股提醒",//类别名称
					  typeimg:"",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"100003", //类别唯一ID,
					  parentID:"xtgsType",
					  typeName:"交易提醒",//类别名称
					  typeimg:"",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"100004", //类别唯一ID,
					  parentID:"xtgsType",
					  typeName:"账户提醒",//类别名称
					  typeimg:"",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"100005", //类别唯一ID,
					  parentID:"xtgsType",
					  typeName:"理财提醒",//类别名称
					  typeimg:"",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"100006", //类别唯一ID,
					  parentID:"xtgsType",
					  typeName:"服务提醒",//类别名称
					  typeimg:"",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"100007", //类别唯一ID,
					  parentID:"xtgsType",
					  typeName:"系统提醒",//类别名称
					  typeimg:"",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
				  {
					  typeID:"xtszType", //类别唯一ID,
					  parentID:"",
					  typeName:"收藏",//类别名称
					  typeimg:"sz.png",
					  recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
					  recentlyMsyContent:"",
					  isShow:false,
					  unreadMsgCount:""//未读消息数
				  },
                  {
                      typeID:"npsType", //类别唯一ID,
                      parentID:"",
                      typeName:"有奖问卷",//类别名称
                      typeimg:"nps.png",
                      recentlyMsgTime:"", //最近类别消息时间yyyymmdd hh:mi
                      recentlyMsyContent:"",
                      isShow:false,
                      unreadMsgCount:""//未读消息数
                  },
			  ];
			  gtjaWebEtLoginApi.addXXZXTypeList(typeArray);
    	
    },
    initUIET: function () {
        var etchathtml = [
            '<div id="faqbg"></div>',
            '<div id="et_box"  style="display:none;left:0px;top:0px;position:absolute;margin:0; box-sizing: border-box;width: 100%;height: 100%;">	',
            '<div class="title">',
            '<span class="span1">响应人</span>',
            // '<a  href="javascript:void()">',
            '<img class="etchat_small" src="', gtjawebEtUI.ETImagePath, 'xiao.png"/>',
            //  '</a>',
            '<img class="etchat_close" src="', gtjawebEtUI.ETImagePath, 'close.png"/>',
            '</div>',
            '<div class="chat_whole" id="chat_whole">',
            '<div class="list">',

        //    '<ul class="nav_menu">',
        //    '<li class="onT" id="navmessage">消息' +
        //    '<span class="msgtipcount_showtips">9</span></li>',
        //    '<li id="navcollection" style="	margin-left:2px; width: 48%;" >收藏</li>',
        //    '</ul>',
            '<ul id="change_ul" class="showXiaoXi">',
            '<li class="change_ulLingXi" style="display:none" ></li>',
            '<li class="change_ulXianYinRen" style="display:none" ></li>',
            '<li class="change_ulxxzxMsg" style="display:none" ></li>',
            '<li class="change_ulxxzxMsgEnd" style="display:none" ></li>',
            '</ul>',
            
       //       	'<div class="qrcode">',				   
						 //   		'<img src="', gtjawebEtUI.ETImagePath, 'download.png"/>',
							// 		'<p class="">扫码关注国泰君安微理财</p>',
							// 		'<p class="">免费赠送操盘通知大礼包</p>',
			    // '</div>', 
            '</div>',
            '<div class="chatLeft" id="etchats">',
            '</div>',
            //      '<div class="chatRight">',

            //      '</div>',
            '<div style="clear: both;"></div>',
            '</div>',
            //    '<div class="scan">',
            //      '<div class="scan_title"><span class="detail_title" >国泰君安服务平台</span><span class="return"><img id="return" src="', gtjawebEtUI.ETImagePath, 'fa-angle-left.png"/>返回</span></div>',
            //      '<div class="detail_content"></div>',
            //    '</div>',
            '</div>'
        ].join("");

        var $etchatmain = $(etchathtml);

        $("body").append($etchatmain);

        $etchatmain.find(".etchat_close,.etchat_small").click(function () {
            $("#faqbg").css("display", "none");
            $("#et_box").css("display", "none");
        });

        /*点击切换选项卡*/
        $(document).on("click",".nav_menu li",function(){
            var navmenu_title=$(this).attr("id");

            if(navmenu_title=="navmessage"){
                TDAPP.onEvent("消息中心", '消息tab点击');
                $(this).addClass("onT").siblings().removeClass("onT");
                $("#et_box #change_ul").removeClass('showXiaoXi');
                $("#et_box #change_ul").removeClass('showSZ');
                $("#et_box #change_ul").addClass('showXiaoXi');
                $('#et_box .chat-main').hide();         
                gtjawebEtUI.isShowXX=true;
               if(gtjawebEtUI.selectId!='')
               {
               	  gtjawebEtUI.rosteritemclick($("#et_box #change_ul ." + gtjawebEtUI.selectId), false);
               }
            }else{
                TDAPP.onEvent("消息中心", '收藏tab点击');
                //检查游客是否登录

                if (gtjaWebEtLoginApi.custType != '3') {
                    window.location.href = "http://fyadduser.com";
                    return;
                }
                $(this).addClass("onT").siblings().removeClass("onT");
                $("#et_box #change_ul").removeClass('showXiaoXi');
                $("#et_box #change_ul").removeClass('showSZ');
                $("#et_box #change_ul").addClass('showSZ');
                $('#et_box .chat-main').hide();
                gtjawebEtUI.isShowXX=false;
                if(gtjawebEtUI.selectSZId!='')
                    gtjawebEtUI.rosteritemclick($("#et_box #change_ul ." + gtjawebEtUI.selectSZId), false);




            }

        });

        //点击返回到聊天页面
        $etchatmain.find(".return").click(function () {
            $("#et_box .chat_whole").css("display", "block");
            $("#et_box .scan").css("display", "none");
        });

        try {
            if (!(window.TDXQuery)) {
                $etchatmain.removeClass("et_showTitle");
                $etchatmain.addClass("et_showTitle");
            }
        } catch (e) {
            $etchatmain.removeClass("et_showTitle");
            $etchatmain.addClass("et_showTitle");
        }
        try {
            var localurl = window.location.href;

            if (~localurl.indexOf("#/WebFy")) {
                gtjawebEtUI.openChatWin('', '', true);
            }
        } catch (e) {}
        /*


         $(document).on("click", ".ETChat_contact", function(e) {
         $etShowDiv.show();
         if (animating) return;
         animating = true;
         // $(document).off("click", closeSidebar);
         var that = this,
         name = $(this).find(".contact__name").text();
         var kfServiceNode=$(this).find(".service_node_id").text();
         if(kfServiceNode&&kfServiceNode!='')
         gtjawebEtUI.receiverTo=kfServiceNode+"@kf95521.chat.gtja.com";
         //    online = $(this).find(".contact__status").hasClass("online");
         $(".ETChat .chat__name").text(name);
         // $(".chat__online").removeClass("active");
         // if (online) $(".chat__online").addClass("active");
         ripple($(that),e);
         setTimeout(function() {
         moveImage(that);
         finalX = -80;
         setTimeout(function() {
         $(".ripple").remove();
         setTimeout(function() {
         $chat.show();
         $chat.css("top");
         $chat.addClass("active");
         // $(".ETChat_contact").hide();
         animating = false;}, sContTrans*2);
         }, sContTrans);
         }, sContTrans);
         });




         $(document).on("click", ".ETChat .chat__inputDiv .buttonSend", function() {
         var $chatMain = $(this).parents(".ETChat");
         gtjawebEtUI.sendHandler($chatMain);
         });
         */

        //默认添加灵犀窗口
        gtjawebEtUI.addChatWin('', '', false);

    },
    searchengineTips: '',
    getSearchKeyword: function () {
        try {
            var refer = document.referrer; //搜索来源页
            var searchengine = '';
            var sosuo = refer.split(".")[1];
            var grep = null;
            var str = null;
            var keyword = '';
            switch (sosuo) {
                case "baidu":
                    searchengine = '百度';
                    grep = /wd\=.*\&/i;
                    str = refer.match(grep)
                    keyword = str.toString().split("=")[1].split("&")[0];
                    break;
                case "google":
                    searchengine = '谷歌';
                    grep = /q\=.*\&/i;
                    str = refer.match(grep)
                    keyword = str.toString().split("=")[1].split("&")[0];
                    break;
                case "sogou":
                    searchengine = '搜狗搜索';
                    grep = /query\=.*\&/i;
                    str = refer.match(grep)
                    keyword = str.toString().split("=")[1].split("&")[0];
                    break;
                case "soso":
                    searchengine = '搜狗搜索';
                    grep = /query\=.*\&/i;
                    str = refer.match(grep)
                    keyword = str.toString().split("=")[1].split("&")[0];
                    break;
                case "bing":
                    searchengine = '微软必应';
                    grep = /q\=.*\&/i;
                    str = refer.match(grep)
                    keyword = str.toString().split("=")[1].split("&")[0];
                    break;
                case "yahoo":
                    searchengine = '雅虎搜索';
                    grep = /p\=.*\&/i;
                    str = refer.match(grep)
                    keyword = str.toString().split("=")[1].split("&")[0];
                    break;
                case "so":
                    searchengine = '360搜索';
                    grep = /q\=.*\&/i;
                    str = refer.match(grep)
                    keyword = str.toString().split("=")[1].split("&")[0];
                    break;
            }
            if (keyword && keyword != '') {
                keyword = decodeURI(keyword);
            }
            if (searchengine != '') {
                gtjawebEtUI.searchengineTips = '搜索引擎：' + searchengine;
                if (keyword && keyword != '') {
                    gtjawebEtUI.searchengineTips = gtjawebEtUI.searchengineTips +
                        '\n关键字：' + keyword;
                }
            }
        } catch (e) {

        }

    },
    setCustomPersonPage: function (personPage, detailTitle, detailPage) {
        if (personPage) {
            var $personPage = $(personPage);
            $('#et_box .chat_whole .chatRight').html('');
            $('#et_box .chat_whole .chatRight').append($personPage);
            //点击二维码到扫一扫页面
            //$personPage.find(".show_detail").click(function(){

            $("#et_box .show_detail").click(function () {
                $("#et_box .chat_whole").css("display", "none");
                $("#et_box .scan").css("display", "block");
            });
        }
        if (detailTitle) {
            $('#et_box .detail_title').text(detailTitle);
        }
        if (detailPage) {
            var $detailPage = $(detailPage);
            $('#et_box .detail_content').html('');
            $('#et_box .detail_content').append($detailPage);
        }
    },
    closeScreenPicBox:function()
    {
        $('#ETSendPicBox').remove();
        $('#ETSendPicBg').remove();
    },
    sendScreenPicBtn:function()
    {
        var sendurl=gtjaWebEtLoginApi.weblogicserver+"WebIM/UploadPicFY/updatepic_3321.html?currentDomain="+gtjawebEtUI.ETScreenCallBack;
        var $sendHtml=$([
            '<div id="ETSendPicBg"></div>',
            '<div id="ETSendPicBox">',
            '<div class="sendpictitle"><span>请选择图片</span><img class="etchat_colse" src="'+gtjawebEtUI.ETImagePath+'close.png" /></div>',
            '<div class="sendpicdiv">',
            '<iframe id="" src="'+sendurl+'" style="width:100%;height:100%;border: 0;"></iframe>',
            '</div>',
            '</div>',
        ].join(''));

        $("body").append($sendHtml);
        $sendHtml.find(".etchat_colse").click(function () {

            gtjawebEtUI.closeScreenPicBox();

        });


    }
};
//图片上传

$(document).on("click", "#et_box .ctb02", function() {


    // if(gtjawebEtUI.phoneSystemType!="Android")
    gtjawebEtUI.sendScreenPicBtn();
    //
});

var gtjaWebEtLoginApi = {
    httpdomain: 'http://etweb.gtja.com:7070',
    // httpdomain:'http://114.141.166.48:5222',//仿真
     // httpdomain: 'http://114.141.166.48:7070',
    //weblogicserver: 'http://et.gtja.com:7002/manage/',
    weblogicserver: 'http://etweb.gtja.com:7002/',
    nTime: 1000,
    custId: '',
    ettoken: '',
    custType: '',
    setCustomPersonPage: function (personPage, detailTitle, detailPage) {
        gtjawebEtUI.setCustomPersonPage(personPage, detailTitle, detailPage);


    },
    openChatWin: function (kfjid, kfname) {
        if (remotegtjawebet.isConnectSuccess()) {
            window.setTimeout(function () {


                gtjawebEtUI.openChatWin(kfjid, kfname, true);
                gtjawebEtUI.openParam = null;

            }, 100);
        } else {
            gtjawebEtUI.openParam = {};
            gtjawebEtUI.openParam.kfjid = kfjid;
            gtjawebEtUI.openParam.kfname = kfname;
            gtjawebEtUI.openParam.isZNKFSTATUS = true;

            //window.setTimeout(function () {

            //		gtjawebEtUI.openChatWin(kfjid,kfname,true);

            //	}, 1500);
        }


    },
    addXXZXTypeList: function (typeArray) {

        gtjawebEtUI.addXXZXTypeList(typeArray);

    },
    /*收藏*/
    addXXZXTypeListSC: function (typeArraySC) {

        gtjawebEtUI.addXXZXTypeListSC(typeArraySC);

    },


    viewType: function (typeID)
    {
        gtjawebEtUI.viewType(typeID);
    },
    /*用于收藏定位*/
    viewTypeSC: function (msgID)
    {
        gtjawebEtUI.viewTypeSC(msgID);
    },
     /*删除收藏*/
    delSCMsg: function (msgID)
    {
       gtjawebEtUI.delSCMsg(msgID);

    },
    checkLogin: function (ETSelectID) {
        if (remotegtjawebet.isConnectSuccess())
            return;
        gtjawebEtUI.ETSelectID = ETSelectID;
        // gtjaWebEtLoginApi.custId='asfsafsf';
        if (gtjaWebEtLoginApi.custId == '' || gtjaWebEtLoginApi.custType == '') {
            var custId = getParam("custId");
            var ettoken = getParam("ettoken");
            if (custId != '' && ettoken != '') {
                gtjaWebEtLoginApi.custId = custId;
                gtjaWebEtLoginApi.ettoken = ettoken;
                gtjaWebEtLoginApi.custType = '3';

            } else {

                gtjaWebEtLoginApi.custId = gtjaWebEtLoginApi.custId || gtjawebEtUI.getVisitor();
                gtjaWebEtLoginApi.custType = gtjaWebEtLoginApi.custType || '-1';
            }


        }
        var that = this;
        var connectionConfig = {};
        connectionConfig.httpdomain = that.httpdomain;
        connectionConfig.custId = gtjaWebEtLoginApi.custId;
        connectionConfig.custType = gtjaWebEtLoginApi.custType;
        connectionConfig.ettoken = gtjaWebEtLoginApi.ettoken;
        remotegtjawebet.loginXmpp(connectionConfig, that.nTime);
    }


};
$(function () {
    // 设置消息处理函数
    //设置登陆成功消息处理函数
    remotegtjawebet.handleFunc.handleConnected = gtjawebEtUI.handleConnected;
    // 掉线消息处理函数
    remotegtjawebet.handleFunc.handleDisconnected = gtjawebEtUI.handleDisconnected;

    // 接收消息处理函数
    remotegtjawebet.handleFunc.handleMessage = gtjawebEtUI.handleMessage;
    // 接收状态处理函数
    remotegtjawebet.handleFunc.handlePresence = gtjawebEtUI.handlePresence;
    // 接收错误消息
    remotegtjawebet.handleFunc.handleError = function (scode, stype, nodeName, content) {};

    var t = document.getElementsByTagName('script');
    var n = './';
    for (var r = 0; r < t.length; r++) {
        if (t.item(r).src && t.item(r).src.match(/jslib\/webet1\.0\.js$/)) {
            n = t.item(r).src.replace(/jslib\/webet1\.0\.js$/, '');
            break;
        }
    }
    gtjawebEtUI.faceImagePath = n + "images/emotions/";
    gtjawebEtUI.ETImagePath = n + "images/";
    gtjawebEtUI.ETScreenCallBack = n + "callback-up.html";
    gtjawebEtUI.initUIET();
    gtjawebEtUI.initUIXXZX();
    // gtjawebEtUI.getSearchKeyword();
    // gtjaWebEtLoginApi.checkLogin();

    $(document).keypress(function (event) {
        var e = event || window.event;

        var keyCode = e.keyCode || e.which;

        if (keyCode == 13) {
            $("#et_box .chat-main").each(function (index, element) {
                var $chatMain = $(this);
                if ($chatMain.is(":visible"))
                    gtjawebEtUI.sendHandler($chatMain);
            });


        }

    });
});