 		 var wst, objs = {}, lockReconnect = false;
       
        function CreateWebSockets() {
            try {
//              $("#conn").attr("disabled", "disabled");

                //Connects();
            } catch (e) {
                ReConnect();
            }
        }
           //连接
        function Connects() {
//            ws = new WebSocket("ws://192.168.4.18:4006");
//            ws = new WebSocket("ws://192.168.1.21:2021");
            wst = new WebSocket("ws://121.196.219.217:8007");
            wst.onopen = function () {
                console.log(new Date() + "    " + "建立连接");
//              $("#conn").removeAttr("disabled");
				var userCode=$.cookie("zx_user");
				Conn(userCode); //注册
                lockReconnect = false;
            };
            //接收到消息的回调方法
            wst.onmessage = function (evt) {
                console.log(new Date() + "  receive  " + evt.data);
                var data = JSON.parse(evt.data);
                if (data) {
                    var ele = $("#" + data.code).find(".chatlist_con")[0];
                    var type = data.action; 
                    switch (type.toLowerCase()) {
                        case "serconn":
                            if (!data.state) {
                                $(".error").text(data.msg);
                            }
                            else {

                                $(".sidebar_list").empty();//sidebar
                                $(".chat_main").empty();
                            }
                            break;
                        case "sersend":
                            if (data.state) {
                                append(ele, "self", data.msg,data.code,data.time);
                                $("#" + data.code).find(".send_content").val("");
                            }
                            else {
                                notice(ele,"notice", data.msg);
                            }
                            break
                            //case "sersenderror":
                            //    append("notice", data.msg);
                            //    break
                        case "serreceive":

                            if (!ele) {
                            	$('.before').show();
                                var first = '';
                                if (!$(".sidebar_list li").length) {
                                    first = 'activess';
                                }
//                              var userhtml = '<span class="user ' + first + '" code="' + data.code + '">' + data.name + '</span>';
                                var userhtml = '<li class="user '+ first +' li' + data.code + '" code="' + data.code + '">'+
									 				'<img class="ver_middle"  src="img/youkeTx.png" alt="" width="30" height="30"/>'+
									 				'<p class="chat_name">' + data.name + '</p>'+
									 				'<i class="fa fa-circle pie" style="color:red;"></i>'+
									 				'<i class="fa fa-remove closeds" onclick="removed(this)"></i>'+
								 				'</li>';
                                $(userhtml).appendTo(".sidebar_list").click(function(){
                                    $(".user").removeClass("activess");
//                                  $(this).siblings('li').removeClass("actives");
                                    $(this).addClass("activess");
                                    $(this).find('.pie').removeClass('pieShow').addClass('pieHide');
                                    $('.open_chat').find('.before').removeClass('show').addClass('hide');
                                    $(".tabMain").removeClass("activess");
                                    $("#" + $(this).attr("code")).addClass("activess");
                                    var conul = $("#" + $(this).attr("code")).find(".chatlist_con");
                                    $(conul).scrollTop($(conul)[0].scrollHeight);
                                });
                                var tabhtml = '<div class="tabMain ' + first + '" id="' + data.code + '">'+
													'<div class="main_message">'+
														'<ul class="chatlist_con">'+
															'<a href="javascript:void(0)" class="more" onclick="getmore(\'' + data.code + '\')"><i class="fa fa-clock-o" style="margin-right: 5px;"></i>查看更多信息</a>'+
															'<input type="hidden" class="hidnum" />' +
														'</ul>'+
													'</div>'+
													'<div class="main_sendMessage ">'+
														'<textarea name=" " rows=" " cols=" " onkeypress="keySend(event)" placeholder="按Enter 发送 " class="send_content "></textarea>'+
													    '<input type="hidden" class="hidcid" value="' + data.code + '" />'+
													    '<div class="send_btn ">'+
													    	'<button class="sendTo " onclick="sendinfo(\'' + data.code + '\') ">发送(S)</button>'+
													    	 '<span style="color:red; " class="senderror"></span>'+
													    '</div>'+
													'</div>'+
												'</div>' ;
                                $(".chat_main").append($(tabhtml));
                                ele = $("#" + data.code).find(".chatlist_con")[0];
                                objs.action = "loglist";
                                objs.code = data.code;
                                Sends();
                            }
                            if (!data.state) {
                                notice(ele, "notice", data.msg);
                            }
                            else {
                                append(ele, "left", data.msg ,data.code,data.time);
                            }
                            
                            break; //收到消息
                        case "loglist":
                            var list = data.data.rows;
                            $(list).each(function (i, n) {
                                var classname = "self";
                                if (n.F_FromUser == data.code) {
                                    classname = "left";
                                }
                                insert(ele, classname, n.F_Message, $("#" + data.code).find(".hidnum").val());
                            })
                            if (!data.data.isfirst) {
                                $(ele).find(".more").css("display", "block");
                                $("#" + data.code).find(".hidnum").val(data.data.num);
                            }
                            else {
                                $(ele).find(".more").css("display", "none");
                            }

                            break;//聊天记录
                    }
                }
            };

            //连接关闭的回调方法
            wst.onclose = function (evt) {
                console.log(new Date() + "    " + "连接关闭");
                console.log(new Date() + "    " + "开始重连");
                ReConnect();
            };
            //连接发生错误的回调方法
            wst.onerror = function (evt) {
                console.log(new Date() + "    " + "连接异常");
                console.log(new Date() + "    " + "开始重连");
                ReConnect();
            };
        }
		 //重连
        function ReConnect() {
            if (!lockReconnect) {
                lockReconnect = true;
                //没连接上会一直重连，设置延迟避免请求过多
                setTimeout(function () {
                    console.log(new Date() + "    " + "重连中……");
                    lockReconnect = false;
                    CreateWebSockets();
                }, 2000);
            }
        }
        //发送
        function Sends() {
            if (wst.readyState != wst.OPEN) {
                ReConnect();
            }
            if (wst.readyState == wst.OPEN) {
                console.log(new Date() + "  send  " + JSON.stringify(objs));
                wst.send(JSON.stringify(objs));
            }
        }
         //注册
        function Conn(userCode) {
        	console.log(userCode);
            objs.action = "serconn";
            objs.code = userCode;
            Sends();
        }
		//查看更多
	    function getmore(ele) {
	            objs.action = "loglist";
	            objs.code = $("#" + ele).find(".hidcid").val();
	            objs.msg = $("#" + ele).find(".hidnum").val();
	            Sends();
	    }
        //发送消息
         function sendinfo(ele) {
            var msg = $("#" + ele).find(".send_content").val();
            console.log(msg)
            if ($.trim(msg)) {
                objs.action = "sersend";
                objs.code = $("#" + ele).find(".hidcid").val();
                objs.msg = msg;
                Sends();
                $("#" + ele).find(".senderror").text("");
            }
            else {
            	$("#" + ele).find(".send_content").val('');
                $("#" + ele).find(".senderror").text("请输入内容");
            }
        } 
        
        function append(ele, cname, msg,codes,dates) {
			var html='<li>' +
						'<p class="message_time"><span>' + dates + '</span></p>' +
  						'<div class="message_mincon ' + cname + '">' 
  						if(cname=='self'){
  							html +='<img class="ver_middle" src="img/kefuTx.png" alt="" width="30" height="30"/>' 
  						}else{
  							html +='<img class="ver_middle" src="img/youkeTx.png" alt="" width="30" height="30"/>' 
  						}
  						
  						html +='<div class="message_text">' + msg + '</div>' +
  						'</div>' +
  					'</li>'
            $(html).appendTo(ele);
            $(ele).scrollTop($(ele)[0].scrollHeight);
            $('.li'+codes).find('.pie').removeClass('pieHide').addClass('pieShow');
            $('.open_chat').find('.before').removeClass('hide').addClass('show');
        }
		 
		 function insert(ele, cname, msg, nodown) {
  			var html='<li>' +
//						'<p class="message_time"><span>' + n.CreateDate + '</span></p>' +
  						'<div class="message_mincon ' + cname + '">' 
  						if(cname=='self'){
  							html +='<img class="ver_middle chat_yhtx" src="img/kefuTx.png" alt="" width="30" height="30" />' 
  						}else{
  							html +='<img class="ver_middle" src="img/youkeTx.png" alt="" width="30" height="30"/>' 
  						}
  						
  						html +='<div class="message_text">' + msg + '</div>' +
  						'</div>' +
  					'</li>'
            var list = $(ele).find("li");
            if (list.length) {
                $(html).insertBefore(list[0]);
            }
            else {
                $(html).appendTo(ele);
            }
            if (!nodown) {
                $(ele).scrollTop($(ele)[0].scrollHeight);
            }
        }
		   function notice(ele,cname, msg){
            var html = '<li><span class="' + cname + '">' + msg + '</span></li>';
            $(html).appendTo(ele);
            $(ele).scrollTop($(ele)[0].scrollHeight);
        } 
// 		  //键盘发送事件
			function keySend(event){
				event = event || window.event;
	   		  	if(event.keyCode == 13) {
	   		  		$(".sendTo").click();
	   		  		event.returnValue = false;    
					return false
	   		  	}
			}
        function removed(ele){
        	var code=$(ele).parent().attr('code');
        	$(".user").removeClass("activess");
        	$("#" + code).remove();
        	$(ele).parent().remove();
        	$(ele).parent().parent();
			showChat();
        }
        function showChat(){
        	$('.sidebar_list').children("li:first-child").addClass("activess");
        	$('.chat_main').children(".tabMain:first-child").addClass("activess");
        }
        $('.open_chat').click(function(){
        	if($('#chat').css('display')=='block'){
        		$('#chat').hide();
        	}else{
        			$('#chat').show();
        	}
        		
        })
