﻿var srvpath = './';

(function ($) {
    var _userName;
    var _userID;

    $.fn.syrostodayChat = function (userID, path) {
        if (userID != null) {
            setInterval('PopMessage("' + userID + '")', 5000);
            setInterval('refreshContactList("' + userID + '")', 30000);
            //setInterval('refreshChatBoxPosition()', 1000);
        };
        srvpath = path;
        var html = "";

        html = html + "<div id=\"ChatContent\">";
        html = html + "<div id=\"ChatContentInner\">";

        html = html + "<div class=\"contactList\">";
        html = html + "<div class=\"titleContactList\">Μέλη Online</div>";
        html = html + "<div class=\"contentContactList\"></div>";
        html = html + "";
        html = html + "";
        html = html + "</div>";

        html = html + "<div class=\"btnOnOff\" onClick=\"GoOnOff('" + userID + "')\">Go Online</div>";

        html = html + "</div>";
        html = html + "</div>";
        
        this.append(html);

        $("#chatUsers").append("<div id=\"chatBar\" userID=\"" + userID + "\"></div>");

        GetStatus(userID);        
        loadcookieData();
        refreshContactList(userID);
    };
})(jQuery);


function GetStatus(userId) {
    var status;
    $.ajax({
        type: "POST",
        url: srvpath + "ChatEngine.asmx/GetStatus",
        data: '{"MemberId":"' + userId + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msj) {
            if (msj.d != "error") {
                if (msj.d == "True") {
                    $(".btnOnOff").html("Go Offline");
                }
                else {
                    $(".btnOnOff").html("Go Online");
                }
            }
        },
        error: function () {
            $(chatbox + " .contentDiv").append("Σφάλμα επικοινωνίας!<br />");
        }
    });

    return status;
}

function GoOnOff(userID) {
    if ($(".btnOnOff").html() == "Go Offline") {

        $.ajax({
            type: "POST",
            url: srvpath + "ChatEngine.asmx/GoOffline",
            data: '{"MemberId":"' + userID + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msj) {
                if (msj.d != "error") {
                    $(".btnOnOff").html('Go Online');
                }
            },
            error: function () {
                $(chatbox + " .contentDiv").append("Σφάλμα επικοινωνίας!<br />");
            }
        });
    }
    else {
        $.ajax({
            type: "POST",
            url: srvpath + "ChatEngine.asmx/GoOnline",
            data: '{"MemberId":"' + userID + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msj) {
                if (msj.d != "error") {
                    $(".btnOnOff").html('Go Offline');
                }
            },
            error: function () {
                $(chatbox + " .contentDiv").append("Σφάλμα επικοινωνίας!<br />");
            }
        });
    }

    refreshContactList(userID);
}

function toogleChatBox(chatBoxId) {
    if ($("#chatBox" + chatBoxId).is(":visible")) {
        $("#chatBox" + chatBoxId).hide();
        $("#userChatBar" + chatBoxId).css("background-color", "gainsboro");
        
        $.cookie("maximizedChatBox", null);
    }
    else {
        
        $.each($(".chatBox"), function() {
            $(this).hide();            
        });
        
        $.each($(".userChatBar"), function() {            
            $(this).css("background-color", "gainsboro");
        });

        $("#chatBox" + chatBoxId).show();
        $("#userChatBar" + chatBoxId).css("background-color", "#CCC");
        
        $.cookie("maximizedChatBox", chatBoxId);
    }
}

function loadcookieData() {
    if ($.cookie("activeChats") != null) {
        var activeChats = $.cookie("activeChats").split("*");
        var maximizedChat = $.cookie("maximizedChatBox");
        var blinkChats = null;
        if ($.cookie("blinkChat") != null)
             blinkChats = $.cookie("blinkChat").split("*");
        var i = 0;

        for (i = 0; i < activeChats.length; i++) {
            if (activeChats[i] != "") {
                if (activeChats[i] == "all") {
                    createChatWindow(activeChats[i], '[ΔΗΜΟΣΙΑ ΣΥΖΗΤΗΣΗ]');
                    $("#chatBox" + activeChats[i] + " .contentDiv").append($.cookie("chat" + activeChats[i]));
                    $("#chatBox" + activeChats[i] + " .contentDiv").scrollTop($("#chatBox" + activeChats[i] + " .contentDiv").attr("scrollHeight") - $("#chatBox" + activeChats[i] + " .contentDiv").height());
                }
                else
                {
                    $.ajax({
                        type: "POST",
                        url: srvpath + "ChatEngine.asmx/getUserName",
                        data: '{"MemberId":"' + activeChats[i] + '"}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msj) {
                            if (msj.d != "error") {
                                createChatWindow(activeChats[i], msj.d);
                                $("#chatBox" + activeChats[i] + " .contentDiv").append($.cookie("chat" + activeChats[i]));
                                $("#chatBox" + activeChats[i] + " .contentDiv").scrollTop($("#chatBox" + activeChats[i] + " .contentDiv").attr("scrollHeight") - $("#chatBox" + activeChats[i] + " .contentDiv").height());
                            }
                        },
                        error: function () {
                            action = 1;
                        },
                        async: false
                    });
                }
            }
        }
        
        $.each($(".chatBox"), function() {
            $(this).hide();
        });
        $(".userChatBar").css("background-color", "gainsboro");
        if (maximizedChat != null) {
            $("#chatBox" + maximizedChat).show();
            $("#userChatBar" + maximizedChat).css("background-color", "#CCC");
            $.cookie("maximizedChatBox", maximizedChat);
        }
        else
            $.cookie("maximizedChatBox", null);
        
        if (blinkChats != null) {
            i = 0;
            for (i = 0; i < blinkChats.length; i++) {
                blinkChatBar(blinkChats[i]);
            }
        }
    }
}

function removeTextBlink(userChatBarId) {
    $("#userChatBar" + userChatBarId).css("color", "black");    
    
    if ($.cookie("blinkChat") != null) {
        idsConvers = $.cookie('blinkChat').split("*");
        var i = 0;
        var idConversNew = "";
        for (i = 0; i < idsConvers.length; i++) {
            if (idsConvers[i] != userChatBarId) {
                if (idConversNew == "")
                    idConversNew = idsConvers[i];
                else
                    idConversNew = idConversNew + "*" + idsConvers[i];
            }
        }
        $.cookie("blinkChat", idConversNew);
    }
}

function blinkChatBar(userChatBarId) {
    $("#userChatBar" + userChatBarId).css("color", "red");
    if ($.cookie("blinkChat") != null) {       
        idsConvers = $.cookie('blinkChat').split("*");
        var i = 0;
        var existe = false;
        for (i = 0; i < idsConvers.length; i++) {
            if (idsConvers[i] == userChatBarId) {
                existe = true;
            }
        }
        if (!existe)
            if ($.cookie("blinkChat") != "")
                $.cookie("blinkChat", $.cookie("blinkChat") + "*" + userChatBarId);
            else
            $.cookie("blinkChat", userChatBarId);
    }
    else
        $.cookie("blinkChat", userChatBarId);
}

function closeChatBox(chatBoxId) {
    $("#chatBox" + chatBoxId).remove();
    $("#userChatBar" + chatBoxId).remove();
    refreshChatBoxPosition();
        
    if ($.cookie("activeChats") != null) {        
        idsConvers = $.cookie("activeChats").split("*");
        var i = 0;        
        var idConversNew = "";
        for (i = 0; i < idsConvers.length; i++) {
            if (idsConvers[i] != chatBoxId) {
                if (idConversNew == "")
                    idConversNew = idsConvers[i];
                else
                    idConversNew = idConversNew + "*" + idsConvers[i];
            }
        }
        $.cookie("activeChats", idConversNew);
    }    
    $.cookie("chat" + chatBoxId, null);
}



function refreshChatBoxPosition() {
    $.each($(".userChatBar"), function () {
        id = $(this).attr('id');
        res = id.substring(11, id.length);
        var offset = $("#userChatBar" + res).offset().left - 85;
        if (offset != $("#chatBox" + res).offset().left)
            $("#chatBox" + res).offset({ left: offset });
    });
}

function refreshContactList(userID) {    
    //0 - html
    //1 - error
    var action = 0;
    var html = "";
    var json;
    $.ajax({
        type: "POST",
        url: srvpath + "ChatEngine.asmx/getContactList",
        data: '{"MemberId":"' + userID + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msj) {
            if (msj.d != "error") {
                action = 0;
                eval('var z=' + msj.d);
                json = z;
            }
            else
                action = 1;

        },
        error: function() {
            action = 1;
        },
        async: false
    });

    if (action == 0) {
        var usronline = 0;
        if (json.onlineUsers.count == 0) {
            html = html + "<table id=\"tblContactLst\">";
            html = html + "<tr onclick=\"createChatWindow('all', '[ΔΗΜΟΣΙΑ ΣΥΖΗΤΗΣΗ]')\"><td class=\"allUsersImg\"></td><td>[ΔΗΜΟΣΙΑ ΣΥΖΗΤΗΣΗ]</td></tr>";
            html = html + "<tr><td colspan=\"2\">Δεν υπάρχουν μέλη online</td></tr>";
            html = html + "</table>";
            usronline = 0;
        }
        else {
            var i = 0;

            $.each($(".chatBox .titleDiv span"), function () {
                $(this).html(" <span class=\"red\">(Offline)</span>");
            });
            html = html + "<table id=\"tblContactLst\">";
            html = html + "<tr onclick=\"createChatWindow('all', '[ΔΗΜΟΣΙΑ ΣΥΖΗΤΗΣΗ]')\"><td class=\"allUsersImg\"></td><td>[ΔΗΜΟΣΙΑ ΣΥΖΗΤΗΣΗ]</td></tr>";
            while (i < json.onlineUsers.count) {                
                if (json.onlineUsers.items[i].MemberStatus) {
                    html = html + "<tr onclick=\"createChatWindow('" + json.onlineUsers.items[i].MemberId + "', '" + json.onlineUsers.items[i].DisplayName + "')\"><td class=\"stateImg\"></td><td>" + json.onlineUsers.items[i].DisplayName + "</td></tr>";

                    $("#chatBox" + json.onlineUsers.items[i].MemberId + " .titleDiv span").html("");
                    usronline++;
                }
                i++;
            }
            $("#chatBoxall .titleDiv span").html("");
            html = html + "</table>";
        }
        $("#chat-pop-out-trigger span").html("Chat - Μέλη online (" + usronline + ")");
    }
    else
        html = html + "<table><tr><td>Σφάλμα! Πιθανή απώλεια σύνδεσης.</td></tr></table>";

    $(".contentContactList").html(html);
}

function createChatWindow(withUserID, withUserName) {        
    var chatbox = "#chatBox" + withUserID;
    var createWindow = false;
    if ($(chatbox).length)
        createWindow = false;
    else 
        createWindow = true;        
    
    if (createWindow) {
        var html = "";
        
        html = html + "<div class=\"userChatBar\" id=\"userChatBar" + withUserID + "\" onClick=\"toogleChatBox('" + withUserID + "')\"><table><tr><td class=\"chatImage\"></td><td>" + withUserName + "</td></tr></table></div>";
        $("#chatBar").append(html);
        
        html = "";
        html = html + "<div class = \"chatBox\" id=\"chatBox" + withUserID + "\" style=\"display:none\">";
        html = html + "<div class = \"titleDiv\"> <a class=\"closeChat\" title=\"Κλείσιμο συνομιλίας\" onClick=\"closeChatBox('" + withUserID + "')\"/> <a class=\"minimizeChat\" title=\"Ελαχιστοποίηση\" onClick=\"toogleChatBox('" + withUserID + "')\"/> ";
        html = html + withUserName;
        html = html + "<span></span>";
        html = html + "</div>";
        html = html + "<div class=\"contentDiv\">";
        html = html + "</div>";
        html = html + "<div class=\"inputDiv\">";
        html = html + "<textarea class=\"inputDivTxt\" cols=\"30\" onkeydown=\"javascript:PushMessage(event,'" + withUserID + "');\"/>";
        html = html + "</div>";
        html = html + "</div>";
        $("#chatBar").append(html);
       
        if ($.cookie("activeChats") != null) {            
            idsConvers = $.cookie("activeChats").split("*");
            var i = 0;
            var existe = false;
            for (i = 0; i < idsConvers.length; i++) {
                if (idsConvers[i] == withUserID) {
                    existe = true;
                }
            }
            if (!existe)
                if ($.cookie("activeChats") != "")
                    $.cookie("activeChats", $.cookie("activeChats") + "*" + withUserID);
                else
                    $.cookie("activeChats",  withUserID);
        }
        else
            $.cookie("activeChats", withUserID);
        

        toogleChatBox(withUserID);
        refreshChatBoxPosition();        
        $("#chatBox" + withUserID).click(function () { removeTextBlink(withUserID); });
        $("#userChatBar" + withUserID).click(function () { removeTextBlink(withUserID); });
    }

}

function PushMessage(event, toUserID) {
    if (event.keyCode == 13) {
        var chatbox = "#chatBox" + toUserID ;
        var message = $(chatbox + " textarea").val();
        var fromUserID = $("#chatBar").attr("userID");
        if ((message == "") | (message == "\n")) { $(chatbox + " textarea").val(""); return;
        };
        $.ajax({
            type: "POST",
            url: srvpath + "ChatEngine.asmx/PushMessage",
            data: '{"FromId":"' + fromUserID + '", "ToId":"' + toUserID + '", "Message":"' + message + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msj) {
                if (msj.d != "error") {
                    $(chatbox + " .contentDiv").append("<span class=\"msg\">Εγώ</span>:<br/>" + message + "<br />");
                    $(chatbox + " textarea").val("");
                    $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
                    
                    $.cookie("chat" + toUserID, $(chatbox + " .contentDiv").html());                    
                }
            },
            error: function() {
                $(chatbox + " .contentDiv").append("Σφάλμα επικοινωνίας!<br />");
            }
        });
        event.returnValue = false; //this is for chrome,, :(
    }
}

function PopMessage(UserID) {
    //var chatbox = "#chatBox" + toUserID + " input";
    //var message = $(chatbox).val();
    //var UserID = $('#chatBar').attr('userID');

    $.ajax({
        type: "POST",
        url: srvpath + "ChatEngine.asmx/PopMessage",
        data: '{"MemberId":"' + UserID + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msj) {
            if (msj.d != "error") {
                PopMessageError(false);
                eval('var z=' + msj.d);
                
                var i = 0;
                while (i < z.messages.count) {
                    if (z.messages.items[i].ChatToId == "all")
                    {
                        createChatWindow(z.messages.items[i].ChatToId, '[ΔΗΜΟΣΙΑ ΣΥΖΗΤΗΣΗ]');
                        var message = z.messages.items[i].ChatMessage;
                        var chatbox = "#chatBox" + z.messages.items[i].ChatToId;
                        
                        
                        $(chatbox + " .contentDiv").append("<span class=\"msg\">" + z.messages.items[i].ChatFromName + "</span>:<br/>" + message + "<br />");
                        $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());

                        blinkChatBar(z.messages.items[i].ChatToId);

                        $.cookie("chat" + z.messages.items[i].ChatToId, $(chatbox + " .contentDiv").html());
                    }
                    else
                    {
                        createChatWindow(z.messages.items[i].ChatFromId, z.messages.items[i].ChatFromName);
                        var message = z.messages.items[i].ChatMessage;
                        var chatbox = "#chatBox" + z.messages.items[i].ChatFromId;
                    
                        $(chatbox + " .contentDiv").append("<span class=\"msg\">" + z.messages.items[i].ChatFromName + "</span>:<br/>" + message + "<br />");
                        $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());

                        blinkChatBar(z.messages.items[i].ChatFromId);

                        $.cookie("chat" + z.messages.items[i].ChatFromId, $(chatbox + " .contentDiv").html());
                    }
                    i++;
                }
            }
            else {
                action = 1;
            }

        },
        error: function () {
            PopMessageError(true);
        }
    });

}

function PopMessageError(value) {
    if (value) {
        $(".contentDiv").addClass("contentDivError");
        $(".inputDivTxt").val("Σφάλμα σύνδεσης - επικοινωνίας.");
        $(".inputDivTxt").attr("disabled", true);
    }
    else {
        if ($(".contentDiv").hasClass("contentDivError")) {
            $(".contentDiv").removeClass("contentDivError");
            $(".inputDivTxt").val("");
            $(".inputDivTxt").removeAttr("disabled");
        }
    }
}


/**************************      PLUGINS    **************************************************/

(function($) {
    $.fn.extend({
        /**
        * Stores the original version of offset(), so that we don't lose it
        */
        _offset: $.fn.offset,

        /**
        * Set or get the specific left and top position of the matched
        * elements, relative the the browser window by calling setXY
        * @param {Object} newOffset
        */
        offset: function(newOffset) {
            return !newOffset ? this._offset() : this.each(function() {
                var el = this;

                var hide = false;

                if ($(el).css('display') == 'none') {
                    hide = true;
                    $(el).show();
                };

                var style_pos = $(el).css('position');

                // default to relative
                if (style_pos == 'static') {
                    $(el).css('position', 'relative');
                    style_pos = 'relative';
                };

                var offset = $(el).offset();

                if (offset) {
                    var delta = {
                        left: parseInt($(el).css('left'), 10),
                        top: parseInt($(el).css('top'), 10)
                    };

                    // in case of 'auto'
                    if (isNaN(delta.left))
                        delta.left = (style_pos == 'relative') ? 0 : el.offsetLeft;
                    if (isNaN(delta.top))
                        delta.top = (style_pos == 'relative') ? 0 : el.offsetTop;

                    if (newOffset.left || newOffset.left === 0)
                        $(el).css('left', newOffset.left - offset.left + delta.left + 'px');

                    if (newOffset.top || newOffset.top === 0)
                        $(el).css('top', newOffset.top - offset.top + delta.top + 'px');
                };
                if (hide) $(el).hide();
            });
        }

    });

})(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
