var ws;
var SocketCreated = false;
var isUserloggedout = false;

//保存对每个用户的聊天内容
var onlineChat = new Array();
var onlineId = "";


//连接webSocket
function ToggleConnectionClicked() {
    if (SocketCreated && (ws.readyState == 0 || ws.readyState == 1)) {
        SocketCreated = false;
        isUserloggedout = true;
        ws.close();
    } else {
        try {
            if ("WebSocket" in window) {
                ws = new WebSocket("ws://192.168.0.102:4141/chat");
            }
            else if ("MozWebSocket" in window) {
                ws = new MozWebSocket("ws://192.168.0.102:4141/chat");
            }

            SocketCreated = true;
            isUserloggedout = false;
        } catch (ex) {
            Log(ex);
            return;
        }
        ws.onopen = WSonOpen;               //连接成功回调    
        ws.onmessage = WSonMessage;         //接收到消息回调
        ws.onclose = WSonClose;             //连接关闭回调
        ws.onerror = WSonError;             //连接出错回调
    }
};

//连接成功回调    
function WSonOpen() {
    ws.send("login:" + $("#hiddenid").val() + "," + $("#hiddenname").val());
};
//接收到消息回调
function WSonMessage(event) {
    var message = event.data;
    if (message.indexOf("onLineList:") == 0) {
        oL(message.split(':')[1]);
    } else {
        msgRec(message);
    }
};
//连接关闭回调
function WSonClose() {
    if (isUserloggedout)
        Log("离开聊天室！");
};
//连接出错回调
function WSonError() {
    Log("远程连接中断...");
};

//输出错误, 并禁止操作
function Log(Text) {
    $("#waiting").html(Text);
    $("#waiting").show();
};


$(document).ready(function () {
    
    //判断是否支持html5 websocket
    var WebSocketsExist = true;
    try {
        var dummy = new WebSocket("ws://localhost:8989/test");
    } catch (ex) {
        try {
            webSocket = new MozWebSocket("ws://localhost:8989/test");
        }
        catch (ex) {
            WebSocketsExist = false;
        }
    }
    //不支持html5 ,这显示不支持
    if (!WebSocketsExist) {
        $("#LockOn").show();
        $("#waiting").hide();
    } else {
        //否则 连接websocket
        ToggleConnectionClicked();
    }
    
    //关闭和发送按钮绑定
    close();
    sendMsg();

    //绑定输入框 回车事件
    $("#msg").keypress(function(evt) {
        if (evt.keyCode == 13) {
            $("#send").click();
            evt.preventDefault();
        }
    });
});


//构造在线列表
function oL(data) {
    //好友列表格式为 id|name,id|name,id|name,
    var now = "";
    var html = "<table class=\"oL\">";
    var oList = data.split(',');
    for (var i = 0; i < oList.length; i++) {
        var temp = oList[i].split('|');
        if (temp[0] == $("#hiddenid").val()) {
            //好友ID为自己 则不作操作
            continue;
        }
        
        //初始化用户聊天内容
        if (onlineId.indexOf(temp[0]) == -1) {
            onlineChat[temp[0]] = "";
            onlineId += temp[0] + ",";
        }
        now += temp[0] + ",";
        //每一个用户
        html += "<tr><td><table class=\"contactTable\" id=\"" + temp[0] + "\"><tr><td class=\"username\">" + temp[1] + "</td><td class=\"newMsg\">★</td></tr></table></td></tr>";
    }
    html += "</table>";
    $("#contactList").html(html);
    if ($(".oL").html() == "") {
        //如果在线列表没有用户, 则现在等待用户
        $("#waiting").fadeIn("slow");
        $("#contactList").fadeOut("slow");
    } else {
        //显示聊天框绑定
        showChatBox();
        $("#waiting").fadeOut("slow");
        //如果用户正在聊天 ,判断是否断线
        if ($("#chatBox").attr("isopen") == "f") {
            $("#contactList").fadeIn("slow");
        } else {
            if (now.indexOf($("#chatBox").attr("uid")) == -1) {
                $("#title").append("(断线...)");
            }
        }
    }
}

//显示聊天框
function showChatBox() {
    $(".contactTable").unbind();
    $(".contactTable").bind("click", function () {
        $("#contactList").hide("slow");
        $("#chatBox").show("slow");
        $("#chatBox").attr("uid", this.id);
        $("#chatBox").attr("isopen", "t");
        $("#title").text($(this).find(".username").text());
        $("#content").height($("#MsgDiv").offset().top - 20);
        $("#content").html(onlineChat[this.id]);
        $("#content").scrollTop($("#content").height());
        $(this).find(".newMsg").fadeOut("slow");
    });

}
//聊天框关闭
function close() {
    $(".Box_Close").unbind();
    $(".Box_Close").bind("click", function () {
        $("#contactList").show("slow");
        $("#chatBox").hide("slow");
        $("#content").html("");
        $("#chatBox").attr("isopen", "f");
        $(".Box_info").find(".temp").remove();
    });
}

//发送点击事件
function sendMsg() {
    $("#send").unbind();
    $("#send").bind("click", function () {

        var receiver = $("#chatBox").attr("uid");   //接收人
        var text = $("#msg").val();                //发送的文本
        var sender = $("#hiddenid").val();          //发送人

        if (text == "") {
            return;
        }

        var msg = receiver + "|" + sender + "|" + text;
        ws.send(msg);       //socket发送

        //将发送的消息保存到聊天内容
        onlineChat[receiver] = onlineChat[receiver] + showMsg(text, $("#hiddenname").val());

        //聊天框增加信息
        $("#content").append(showMsg(text, $("#hiddenname").val()));
        $("#content").scrollTop($("#content").height());        //滚动条到聊天框底部
        $("#msg").val("");
    });
}

//打包发送 和接收的消息 
function showMsg(text,who) {
    var html = "<div><table  style=\"width:100%; color:orange;\"><tr><td>" + who + "</td><td>" + NowTime() + "</td></tr></table>";
    html += "<div class=\"detail\">" + text + "</div></div>";
    return html;
}

//接收到新消息
function msgRec(msg) {
    //消息格式 id|msg
    var info = msg.split('|');
    var tid = "#" + info[0];
    //保存到聊天内容
    onlineChat[info[0]] = onlineChat[info[0]] + showMsg(info[1], $(tid).find(".username").text());
    
    //判断是否需要显示有新消息
    if ($("#chatBox").attr("isopen")=="t") {
        if ($("#chatBox").attr("uid") == info[0]) {
            //正在当前聊天框,直接显示消息
            $("#content").append(showMsg(info[1], $(tid).find(".username").text()));
        } else {
            //在和其他用户聊天 , 显示有新消息
            $(".Box_info").append("<span class=\"temp\" style=\"color: red;float: right;\">★</span>");
            $(tid).find(".newMsg").fadeIn("slow");
        }
    } else {
        //不在聊天框 ,显示有新消息
        $(tid).find(".newMsg").fadeIn("slow");
    }
}