﻿var chat;
var originalTitle;

$(document).ready(function() {
    if (!chat && $.cookie.get("userID") != null && $.cookie.get("userID") != "") {
        chat = new Chat();
        chat.startChatSession();
    }
});

function openIMChat(toID, toUsername) {
    var chatBox = new ChatBox(toID, toUsername);
    var reloadAll = true;
    if ($("#chatbox_" + chatBox.userID).length > 0)
        reloadAll = false;
    chat.createChatbox(chatBox);
    chat.chatHeartbeat(reloadAll, false);
}

//
// ChatBox Class
//
function ChatBox(_userID, _username) {
    this.userID = _userID;
    this.username = _username;
}

//
// Chat Class
//
var Chat = function() {
    this._userID;
    this._username;
    this._chatHeartbeatTime = 5000;
    this._chatBoxes = new Array();
    this._cookieList = new CookieList("chatBoxes");
}

Chat.prototype.getCookieList = function() {
    return this._cookieList;
}

Chat.prototype.setDefaultName = function() {
    this._userID = $.cookie.get("userID");
    this._username = $.cookie.get("username");
}

Chat.prototype.startChatSession = function() {
    this.setDefaultName();
    var items = $.JSON.decode(this._cookieList.items());

    if (items.length > 0) {
        for (x in items) {
            if ($("#chatbox_" + items[x].userID).length <= 0) {
                this.createChatbox(items[x]);
            }
        }
    }

    chat.chatHeartbeat(true, true);
}

Chat.prototype.createInvitationBox = function(chatBox) {
    var obj = this;

    $.ajax({
        type: "POST",
        url: urlRoot + "WebServices/IMChat.asmx/GetUser",
        data: "{'userID':'" + chatBox.userID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            $(" <div />").attr("id", "chatbox_" + chatBox.userID)
	            .addClass("chatbox")
	            .html('<div class="chatboxhead"><div class="chatboxtitle"></div>' +
	                '<div class="chatboxoptions">' +
	                    '<a style="display:none;" class="minimize" href="javascript:void(0)">-</a> ' +
	                    '<a class="close" href="javascript:void(0)">X</a>' +
	                '</div><br clear="all"/></div>' +
	                '<div class="chatboxcontent"><div class="floatcontainer">' +
	                '<div class="chatphoto">' + response.d.photo + '</div>' +
	                '<div class="chatuser">' + response.d.name + '<br />' + response.d.city + '</div></div><br />' +
	                '<div><a class="title" href="javascript:void(0)">' + chatBox.username + '</a> ' + chatInvitation + '</div>' +
	                '<br /><br />' +
	                '<a class="yes" href="javascript:void(0)">' + yes + '</a> &nbsp; ' +
	                '<a class="no" href="javascript:void(0)">' + no + '</a>' +
	                '</div>')
	            .appendTo($("body"));

            $("#chatbox_" + chatBox.userID).css('bottom', '0px');
            chatBoxeslength = 0;
            for (x in this._chatBoxes) {
                if ($("#chatbox_" + this._chatBoxes[x].userID).css('display') != 'none') {
                    chatBoxeslength++;
                }
            }
            if (chatBoxeslength == 0) {
                $("#chatbox_" + chatBox.userID).css('right', '20px');
            } else {
                width = (chatBoxeslength) * (225 + 7) + 20;
                $("#chatbox_" + chatBox.userID).css('right', width + 'px');
            }

            $("#chatbox_" + chatBox.userID + " .yes").click(function() {
                obj.closeChatBox(chatBox.userID);
                obj.createChatbox(chatBox);
                chat.chatHeartbeat(true, false); //Reload all, poll just once
            });

            $("#chatbox_" + chatBox.userID + " .no").click(function() {
                obj.closeChatBox(chatBox.userID);
                var message = " " + declinedChat;
                $.post(urlRoot + "WebServices/IMChat.asmx/SaveChatMessage", { loginKey: $.cookie.get("loginKey"), fromID: obj._userID, toID: chatBox.userID, message: message, type: 'System' });
            });

            $("#chatbox_" + chatBox.userID).show();
            obj._chatBoxes.push(chatBox);
            obj.restructureChatBoxes();    
        }
    });
}

Chat.prototype.createChatbox = function(chatBox) {
    var obj = this;

    //If allready exist
    if ($("#chatbox_" + chatBox.userID).length > 0) {
        if ($("#chatbox_" + chatBox.userID).css('display') == 'none') {
            $("#chatbox_" + chatBox.userID).css('display', 'block');
            this.restructureChatBoxes();
        }
        $("#chatbox_" + chatBox.userID + " .chatboxtextarea").focus();
        return;
    }
    else {
        chat.getCookieList().addJson({ "userID": chatBox.userID, "username": chatBox.username });
    }

    $(" <div />").attr("id", "chatbox_" + chatBox.userID)
	    .addClass("chatbox")
	    .html('<div class="chatboxhead"><div class="chatboxtitle"><a class="title" href="javascript:void(0)">' + chatBox.username + '</a></div>' +
	        '<div class="chatboxoptions">' +
	            '<a style="display:none;" class="minimize" href="javascript:void(0)">-</a> ' +
	            '<a class="close" href="javascript:void(0)">X</a>' +
	        '</div><br clear="all"/></div>' +
	        '<div class="chatboxcontent"></div>' +
	        '<div class="chatboxinput"><textarea class="chatboxtextarea"></textarea></div>')
	    .appendTo($("body"));

    $("#chatbox_" + chatBox.userID).css('bottom', '0px');

    chatBoxeslength = 0;

    for (x in this._chatBoxes) {
        if ($("#chatbox_" + this._chatBoxes[x].userID).css('display') != 'none') {
            chatBoxeslength++;
        }
    }

    if (chatBoxeslength == 0) {
        $("#chatbox_" + chatBox.userID).css('right', '20px');
    } else {
        width = (chatBoxeslength) * (225 + 7) + 20;
        $("#chatbox_" + chatBox.userID).css('right', width + 'px');
    }

    $("#chatbox_" + chatBox.userID + " .chatboxtextarea").blur(function() {
        $("#chatbox_" + chatBox.userID + " .chatboxtextarea").removeClass('chatboxtextareaselected');
    }).focus(function() {
        $('#chatbox_' + chatBox.userID + ' .chatboxhead').removeClass('chatboxblink');
        $("#chatbox_" + chatBox.userID + " .chatboxtextarea").addClass('chatboxtextareaselected');
    });

    $("#chatbox_" + chatBox.userID).click(function() {
        if ($('#chatbox_' + chatBox.userID + ' .chatboxcontent').css('display') != 'none') {
            $("#chatbox_" + chatBox.userID + " .chatboxtextarea").focus();
        }
    });

    $("#chatbox_" + chatBox.userID + " .title").click(function() {
        openUser(chatBox.userID);
    });

    $("#chatbox_" + chatBox.userID + " .minimize").click(function() {
        obj.toggleChatBoxGrowth(chatBox.userID);
    });

    $("#chatbox_" + chatBox.userID + " .close").click(function() {
        obj.closeChatBox(chatBox.userID);
    });

    $("#chatbox_" + chatBox.userID + " .chatboxtextarea").keydown(function(event) {
        return obj.checkChatBoxInputKey(event, this, chatBox.userID);
    });

    $("#chatbox_" + chatBox.userID).show();
    $("#chatbox_" + chatBox.userID + " .chatboxtextarea").focus();

    this._chatBoxes.push(chatBox);
}


Chat.prototype.toggleChatBoxGrowth = function(toID) {
    if ($('#chatbox_' + toID + ' .chatboxcontent').css('display') == 'none') {
        $('#chatbox_' + toID + ' .chatboxcontent').css('display', 'block');
        $('#chatbox_' + toID + ' .chatboxinput').css('display', 'block');
        $("#chatbox_" + toID + " .chatboxcontent").scrollTop($("#chatbox_" + toID + " .chatboxcontent")[0].scrollHeight);
    } else {
        $('#chatbox_' + toID + ' .chatboxcontent').css('display', 'none');
        $('#chatbox_' + toID + ' .chatboxinput').css('display', 'none');
    }
}

Chat.prototype.closeChatBox = function(toID) {
    $('#chatbox_' + toID).remove();
    this.restructureChatBoxes();
    this._cookieList.remove(toID);
    for (x in this._chatBoxes) {
        if (this._chatBoxes[x].userID == toID)
            this._chatBoxes.splice(x, 1);
    }
}

Chat.prototype.checkChatBoxInputKey = function(event, chatboxtextarea, toID) {
    var obj = this;

    if (event.keyCode == 13 && event.shiftKey == 0) {
        var message = $(chatboxtextarea).val();
        message = message.replace(/^\s+|\s+$/g, "");

        $(chatboxtextarea).val('');
        $(chatboxtextarea).focus();
        $(chatboxtextarea).css('height', '44px');
        if (message != '') {
            $.post(urlRoot + "WebServices/IMChat.asmx/SaveChatMessage", { loginKey: $.cookie.get("loginKey"), fromID: this._userID, toID: toID, message: message, type: 'User' }, function(data) {
                message = message.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
                $("#chatbox_" + toID + " .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">' + obj._username + ':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">' + message + '</span></div>');
                $("#chatbox_" + toID + " .chatboxcontent").scrollTop($("#chatbox_" + toID + " .chatboxcontent")[0].scrollHeight);
            });
        }

        return false;
    }
    else
        return true;
}


Chat.prototype.restructureChatBoxes = function() {
    var align = 0;
    for (x in this._chatBoxes) {
        chatBox = this._chatBoxes[x];

        if ($("#chatbox_" + chatBox.userID).css('display') != 'none') {
            if (align == 0) {
                $("#chatbox_" + chatBox.userID).css('right', '20px');
            } else {
                width = (align) * (225 + 7) + 20;
                $("#chatbox_" + chatBox.userID).css('right', width + 'px');
            }
            align++;
        }
    }
}

Chat.prototype.chatHeartbeat = function(reloadAll, continuePolling) {

    var obj = this;
    var msgTime = "";
    if (!reloadAll && $.cookie.get("msgTime") != null)
        msgTime = $.cookie.get("msgTime");

    for (x in obj._chatBoxes) {
        if (reloadAll)
            $("#chatbox_" + obj._chatBoxes[x].userID + " .chatboxcontent").empty();
    }

    var msgTimeObj = parseDate(msgTime);
    var parameters = "{'userID':'" + this._userID + "','msgTime':'" + msgTime + "','reloadAll':'" + reloadAll + "'}";

    if ($.cookie.get("userID") != "" && $.cookie.get("userID") != null) {
        $.ajax({
            type: "POST",
            url: urlRoot + "WebServices/IMChat.asmx/Heartbeat",
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {

                $.each(response.d, function(i, data) {
                    var exists = false;

                    //Check for present chatbox
                    for (x in obj._chatBoxes) {
                        if (obj._chatBoxes[x].userID == data.frID || obj._chatBoxes[x].userID == data.toID) {
                            if (data.t == "u" || (data.t == "s" && data.frID != obj._userID && !reloadAll)) {
                                var name = (data.frID == this._userID) ? this._username : data.name;
                                var systemCssClass = (data.t == "s") ? "red" : "";
                                var kolon = (data.t == "u") ? ":&nbsp;&nbsp;" : "&nbsp";
                                $("#chatbox_" + obj._chatBoxes[x].userID + " .chatboxcontent").append('<div class="chatboxmessage ' + systemCssClass + '">' +
                                '<span title="' + data.sent + '" class="chatboxmessagefrom">' + name + kolon + '</span><span class="chatboxmessagecontent">' + data.msg + '</span></div>');
                                $("#chatbox_" + obj._chatBoxes[x].userID + " .chatboxcontent").scrollTop($("#chatbox_" + obj._chatBoxes[x].userID + " .chatboxcontent")[0].scrollHeight);

                                if (msgTimeObj != null && parseDate(data.sent) > msgTimeObj)
                                    $.cookie.set("msgTime", data.sent, { path: '/' });
                                exists = true;
                            }
                        }
                    }

                    //Is it a new chat message?
                    if (reloadAll == false && exists == false) {
                        var chatBox = new ChatBox(data.frID, data.name);
                        obj.createInvitationBox(chatBox);
                        if (parseDate(data.sent) > msgTimeObj)
                            $.cookie.set("msgTime", data.sent, { path: '/' });
                    }
                });
            }
        });
    }

    if (continuePolling)
        setTimeout(function() { obj.chatHeartbeat(false, continuePolling); }, this._chatHeartbeatTime);
}

function parseDate(str) {
    if (str != "") {
        var tmp = str.split(" ");
        var date = tmp[0].split("-");
        var time = tmp[1].split(":");
        return new Date(date[0], date[1], date[2], time[0], time[1], time[2]);
    }
    return null;
}


///
/// CookieList static Class
///
var CookieList = function(cookieName) {
    var cookie = $.cookie.get(cookieName);
    var array = (cookie) ? $.JSON.decode(cookie) : new Array();
    return {
        "addJson": function(val) {
            var exists = false;
            for (x in array) {
                if (array[x].userID == val.userID)
                    exists = true;
            }
            if (!exists) {
                array.push(val);
                $.cookie.set(cookieName, array, { path: '/', json: true });
            }
        },
        "clear": function() {
            $.cookie.unset(cookieName);
        },
        "remove": function(val) {
            for (x in array) {
                if (array[x].userID == val)
                    array.splice(x, 1);
            }
            $.cookie.set(cookieName, array, { path: '/', json: true });
        },
        "items": function() {
            return $.JSON.encode(array);
        }
    }
}

