2011年6月29日星期三

  基于pushlet 的开发代码,现正在使用的。

 

      http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      http://www.w3.org/1999/xhtml">


      指路网 IM

      < language="javascript" src="lib/jquery.js">
      < language="javascript" src="lib/util.js">
      < language="javascript" src="lib/ajax-pushlet-client.js">
      < language="javascript" >
      var contents =new Array();//内容数组,二维。
      var senders_array=new Array();
      var currentAccountID=null;
      var interval=new Array(); //定时闪烁用
      var goodsID=new Array();
      var fromID=null;
      var msg_loaded=new Array(); //ajax的消息是否读取到
      var msg_load_times=50;//加载次数限制。一次是100毫秒
      var msg_load_timeout=null;//读取消息的settimeout

      var goodsUrlPrefix="http://192.168.3.242:8080/c2cweb/shop/";//实际上线后需要手动更改

      $(function(){
      var p1=getPageParameter('senders', '');
      var    p2=getPageParameter('user','');
      var en=getPageParameter('en','');
      if(unicode(p1+'_'+p2)==en){
      init(p1,p2);

      }
      else
      {
          alert('参数错误,请返回原地址重新请求!');
      }

      });
      function init(senders,user)
      {
          currentAccountID=user;
          goodsID[0]=getPageParameter('goodsID','');
          fromID=goodsID[0];
          if(senders && senders!='')
          {
               senders_array=senders.split(',');
               create_chattab();        
              for(var i=0;i         {
                  contents[i]=new Array();
                  //读取session 获取未读信息放入array。   
                  msg_loaded[i]=false;
                  fill_contentsArray(i);
              }
          }
          //启动聊天
          enterChat(currentAccountID);
          //绑定快捷键
          bind_quick_key();
          //关闭窗口时出发事件
          $(window).unload(function(){leaveChat();});
          //window.attachEvent('onunload',function(){leaveChat();});
          //执行ajax_loaded后的事件。
          do_loaded();
      }

      function do_loaded()
      {
          if(msg_loaded&&msg_loaded[0]==true)
          {
              fill_contentsHTML(0);
              display_goods_info(0);
          }
          else if(msg_load_times>0)
          {
              msg_load_times--;
              if(msg_load_timeout!=null)
              clearTimeout(msg_load_timeout);
              msg_load_timeout=setTimeout(function(){do_loaded();},50);
          }
      }

      //创建各个聊天窗口
      function create_chattab(senders)
      {
          var sa=senders_array;
          var chatwin_tab=$('#chatwin_tab');
          for(var i=0;i     {
              var maimai="买家";
              if(goodsID[0]!='')
              maimai="卖家";
              var tabhtml="

      • "+maimai+":"+sa[i]+"
      • ";
                chatwin_tab.append(tabhtml);
            }
            //设置第一个为默认。
            chatwin_tab.children().first().addClass("now");
        }

        function fill_contentsArray(contentsindex)
        {
        var sender=senders_array[contentsindex];
        //$.get("msg?type=put&key="+sender+"&content=aaaaaaaa&sender=s&receiver=r&fromID=1&seller=s");

            $.ajax({
               type: "GET",
               url: "msg",
               data: "type=get&key="+sender,
               success: function(msg){   
                        msg_loaded[contentsindex]=true;//设置已经读取成功
                       if(msg&&msg!=null&&msg!=''){           
                       var lists=jQuery.parseJSON(msg);
                       for(var i=0;i                {                      
                               lists[i].content=decodeURI(lists[i].content);
                            contents[contentsindex][i]=lists[i];
                            //有的情况下才赋值。
                            if(lists[i].fromID)
                            goodsID[contentsindex]=lists[i].fromID;
                       }
                   }
               },
               error: function(msg){ msg_loaded[contentsindex]=true;}
            });

            /*    var msgs=eval("[{'content':'aa"+contentsindex+"','fromID':'1','receiver':'1','sender':'1','time':'2011 06 20 17 57 46'},{'content':'aa','fromID':'1','receiver':'1','sender':'1','time':'2011 06 20 17 58 32'},{'content':'aa','fromID':'1','receiver':'1','sender':'1','time':'2011 06 20 17 58 33'}]");
            for(var i=0;i     {
                contents[contentsindex][i]=msgs[i];       
            }
            */
        }
        //根据array填充div html
        function fill_contentsHTML(contentsindex)
        {
                clear_chatcontent();
                if(contents.length>0&&contents[contentsindex] && contents[contentsindex].length>0){
                    for(var j=0;j                 append_chatcontent(contents[contentsindex][j]);
                    }
                }
        }

        //给内容div添加聊天内容
        function append_chatcontent(msgobj)
        {
            var className='buyer-c';
            if(msgobj &&msgobj.seller==currentAccountID)
            className='seller-c';
            var content=decodeURI(msgobj.content);
            var ptn=/http:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/g;
            var result=ptn.exec(content);
            if(result && result[0])
            content=content.replace(result[0],''+result[0]+'');
            var contenthtml="

      • "+msgobj.sender+":("+msgobj.time+")
      •  
      • "+content+"
      • ";
            var chat_content=$('#chat_content');
            chat_content.append(contenthtml);   
        }
        function clear_chatcontent()
        {
            var chat_content=$('#chat_content');
            chat_content.html("");   
        }
        function change_sender(index)
        {
            var chatwin_tab=$('#chatwin_tab');
            chatwin_tab.find("li").removeClass();
            $("#tab_"+index).addClass("now");
            //create_chatcontent(sender);
            fill_contentsHTML(index);
            for(var i=0;i     {
                if(interval[i]!=null){
                    clearInterval(interval[i]);
                    interval[i]=null;
                }
            }
            document.title='';
            display_goods_info(index);
        }
        function display_goods_info(index)
        {
            if(goodsID[index])
            {
                //这里执行调用右侧商品和订单显示。
                //$('#txtgoodsname').html("传入商品ID为:"+goodsID[index]);
                if(!fromID)
                $("#iframe").attr("src",goodsUrlPrefix+"getSellerWebIm.action?goodsID="+goodsID[index]);
                else
                $("#iframe").attr("src",goodsUrlPrefix+"getBuyerWebIm.action?goodsID="+goodsID[index]);
            }
        }
        function senders_exists(sender)
        {
            for(var i=0;i     {
                if(senders_array[i]!=null && senders_array[i]==sender)
                return true;
            }
            return false;
        }
        function senders_index(sender)
        {
            for(var i=0;i     {
                if(senders_array[i]!=null && senders_array[i]==sender)
                return i;
            }
            return -1;
        }
        function close_sender(index,sender)
        {   
            //var chatwin_tab=$('#chatwin_tab');
            //chatwin_tab.remove('#tab_'+index);
            $('#tab_'+index).remove();
            contents[index]=null;
            senders_array[index]=null;
            goodsID[index]=null;
            if(contents.length>0)
            {
                fill_contentsHTML(0);
                $("#tab_0").addClass("now");
            }
        }

        function enterChat(currentAccountID){     p_join_listen(currentAccountID);}
        function onJoinAck(event) {}

        function onData(event) {         
        var action = event.get('action');
        var receiver=event.get('receiver');

        if (action == 'send' && receiver==currentAccountID)
            {
                var msg=event.get('msg');
                var sender=event.get('sender');
                var fromID=event.get('fromID');
                if(msg!=null && msg!="" && sender!=null && sender!="")   
                {
                    var index=senders_index(sender);   
                    if(index==-1)
                    {
                        var chatwin_tab=$('#chatwin_tab');
                        var i=chatwin_tab.find("li").length;
                        chatwin_tab.find("li").attr('class','');
                        var tabhtml="

      • 卖家:"+sender+"
      • ";
                        chatwin_tab.append(tabhtml);
                        contents[i]=new Array();
                        senders_array[i]=sender;
                        var msgobj=new Object();
                        msgobj.sender=sender;
                        msgobj.receiver=receiver;
                        msgobj.content=decodeURI(msg).replace(/\&/g,'&');
                        msgobj.time=getdate();
                        msgobj.fromID=fromID;
                        contents[i][0]=msgobj;               
                        goodsID[i]=fromID;
                        //没有其他任何窗口的情况下直接显示内容。
                        if(i==0){
                        append_chatcontent(msgobj);
                        $("#tab_0").attr('class',"now");
                        }
                    }       
                    else if(index>-1){
                        //fill_contentsArray(index);
                        var i=contents[index].length;
                        var msgobj=new Object();
                        msgobj.sender=sender;
                        msgobj.receiver=receiver;
                        msgobj.content=decodeURI(msg).replace(/\&/g,'&');
                        msgobj.time=getdate();   
                        msgobj.fromID=fromID;
                        contents[index][i]=msgobj;
                        goodsID[index]=fromID;
                        //fill_contentsHTML(index);
                        if($("#tab_"+index).attr('class')=='now')
                        {
                            append_chatcontent(msgobj);
                        }
                        else
                        {
                            if(interval[index])
                            clearInterval(interval[index]);
                            interval[index]=window.setInterval(function(){flashtab(index);}, 600);
                        }
                    }
                }
            }
        else if(action == 'exit')
                {
                    var index= jQuery.inArray(event.get('sender'), senders_array);
                    if(index>-1)
                    {
                        var i=contents[index].length;
                        var msgobj=new Object();
                        msgobj.sender=event.get('sender');
                        msgobj.receiver=currentAccountID;
                        msgobj.content=' 系统消息:'+msgobj.sender+'关闭了聊天窗口!';
                        msgobj.time=getdate();           
                        contents[index][i]=msgobj;
                        if($("#tab_"+index).attr('class')=='now')
                        {
                            append_chatcontent(msgobj);
                        }
                        else
                        {
                            if(interval[index])
                            clearInterval(interval[index]);
                             interval[index]=window.setInterval(function(){flashtab(index);}, 600);
                        }
                    }
                }
        scrolldown();
        }
        function flashtab(index)
        {
            if($("#tab_"+index).attr('class')=='')
            $("#tab_"+index).attr('class','flash');
            else
            $("#tab_"+index).attr('class','');
            if(document.title=='')
            document.title='您有新消息未读取!';
            else
            document.title='';
        }

          function leaveChat(){
              try{
                for(var i=0;i             if(senders_array[i])
                    p_publish(senders_array[i], 'action', 'exit', 'sender', currentAccountID);
                }
                   p_leave();
            }
            catch(e){}
          }

        function onNack(event) {
        alert('negative response from server: ' + event.getEvent() + ' reason: ' + event.get('p_reason'));
        }

        function sendmsg(obj)
        {
            var sender=find_current_sender();
            if(sender==null)
            alert('请选择需要发送的对象!');
            else{
                //.replace(/<\/?[^>]*>/g,'')
                var s=encodeURI(DBC2SBC(obj.val().replace(/<\/?[^>]*>/g,'').replace(/\n/g,'
        '),0));
                 if(s&&obj.val().length<200){
                    p_publish(sender, 'action', 'send', 'sender', currentAccountID, 'msg',s,'receiver',sender);
                     obj.val("");
                         var msgobj=new Object();
                    msgobj.sender=currentAccountID;
                    msgobj.receiver=sender;
                    msgobj.content=s;
                    msgobj.time=getdate();
                    if(fromID)
                    msgobj.fromID=fromID;
                    var current_content=contents[senders_index(sender)];   
                    current_content[current_content.length]=msgobj;
                    append_chatcontent(msgobj);               
                    obj.focus();
                    scrolldown();
                }
                else
                {alert('字符不能为空或者超过200字!');}   
             }
        }
        function DBC2SBC(str,flag) {
             var i;
             var result='';
             if (str.length<=0) {return "";}
             var strs=str.split("");
              for(i=0;i       {
                  if(/[\^\'\,\;\$\x22\!\(\)\[\]\"\|\#\&\%\+]+/.test(strs[i])){
                    str1=str.charCodeAt(i);
                    if(str1<125&&!flag)
                     result+=String.fromCharCode(str.charCodeAt(i)+65248);
                     else
                     result+=String.fromCharCode(str.charCodeAt(i)-65248);
                 }
                 else
                 result+=strs[i];
              }
             return result;
        }
        function find_current_sender()
        {
            var current_sender=null;
            var chatwin_tab=$('#chatwin_tab');
            var lis=chatwin_tab.find("li");
            for(var i=0;i     {
                if(    lis.eq(i).attr('class')=='now')
                {
                    var index=lis.eq(i).attr('id').replace('tab_','');
                    return senders_array[index];
                }
            }
            return current_sender;
        }

        function bind_quick_key(){
            jQuery(document).keypress(function(e){
            if(e.ctrlKey && e.which == 13 || e.which == 10) {
                sendmsg($('#txtmsg'))
            } else if (e.shiftKey && e.which==13 || e.which == 10) {
                sendmsg($('#txtmsg'))
            }
            });
        }
        function scrolldown()
        {
                     //移动滚动条到底部            
                     var h=document.getElementById("chatDiv");
                     h.scrollTop=h.scrollHeight;
        }


      没有评论:

      发表评论