﻿
/********************************************************/
/*                    ISURI CHAT                        */
/*                    Abril 2010                        */
/*                  www.isuri.com.ar                    */   
/********************************************************/

//Notes: 
// Have to manually change the offline msg
// Have to manually modify the Admin ID  // userID ==

(function($) {

    var _userName;
    var _userID;
    var _Title;
    
    $.fn.isuriChat = function(userID) {

        if (userID != null) {
            setInterval('PopMessage(' + userID + ')', 3000);   //check if I have new messages
            setInterval('refreshContactList(' + userID + ')', 30000); //refresh contact list
            //setInterval('refreshChatBoxPosition()', 1000);   //maximize or minimize the browser
        };

        if(userID == 112)
        {
            _Title = "Online Customer";
        }
        else
        {
            _Title = "<marquee scrolldelay=200>Jordeen HP: 012-6976188 &nbsp; MSN: jordeen01@hotmail.com &nbsp; Email: jordeen@live.com</marquee>";
	    setInterval('ReloadcookieData(' + userID + ')', 3000); //Reload cookies
        }
        
        /***************************************************/
        /************  CREATE THE HTML *********************/
        /***************************************************/
        var html = "";


        html = html + "<div id='divContenedor'>";
        html = html + "<div id='divContenedor2'>";

        html = html + "<div id='chatBar' userID='" + userID + "'>";
        html = html + "<div class='btnChat' onClick='ToggleDiv(\".contactList\");refreshContactList(" + userID + ");'><span>" + _Title + "</span></div>";

        html = html + "</div>";

        /* Create the div of Contacts Online */
        html = html + "<div class='contactList'>";
        html = html + "<div class='titleContactList'>" + _Title +  "</div>";
        html = html + "<div class='contentContactList'></div>";
        html = html + "";
        html = html + "";
        html = html + "</div>";

        this.append(html);
        //Position data from cookies
        loadcookieData();
        
        //Display Chat
        refreshContactList(userID);
    }

})(jQuery);


/***********************************************/
/***************   FUNCTIONS      **************/
/***********************************************/


function ToggleDiv(div) {
    $(div).toggle();
}


function toogleChatBox(idChatBox) {
    if ($("#chatBox" + idChatBox).is(":visible")) {
        $("#chatBox" + idChatBox).hide();
        $("#pestañaBar" + idChatBox).css("background-color", "gainsboro");
        //keep in the cookie
        $.cookie("maximizedChatBox", null);
    }
    else {
        //minimize all other windows
        $.each($(".chatBox"), function() {
            $(this).hide();            
        });
        //put all the tabs in gray
        $.each($(".pestañaBar"), function() {            
            $(this).css("background-color", "gainsboro");
        });
        
        $("#chatBox" + idChatBox).show();
        $("#pestañaBar" + idChatBox).css("background-color", "white");
        //keep in the cookies
        $.cookie("maximizedChatBox",idChatBox);
    }
}

function ReloadcookieData() {
    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] != "") 
            {
                  $("#chatBox" + activeChats[i] + " .contentDiv").html($.cookie("chat" + activeChats[i]));
                  $("#chatBox" + activeChats[i] + " .contentDiv").scrollTop($("#chatBox" + activeChats[i] + " .contentDiv").attr("scrollHeight") - $("#chatBox" + activeChats[i] + " .contentDiv").height());
            }
        }
        
        
        //make the tabs Blink need
        if (blinkChats != null) {
            i = 0;
            for (i = 0; i < blinkChats.length; i++) {
                blinkPestañaBar(blinkChats[i]);
            }
        }
    }
}


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] != "") {
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/getUserName",
                    data: '{"userID":"' + 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() {
                        accion = 1;
                    },
                    async: false
                });
                
            }
        }
        //Maximizes the chatbox if necessary
        //first minimize all
        $.each($(".chatBox"), function() {
            $(this).hide();
        });
        $(".pestañaBar").css("background-color", "gainsboro");
        if (maximizedChat != null) {
            $("#chatBox" + maximizedChat).show();
            $("#pestañaBar" + maximizedChat).css("background-color", "white");
            $.cookie("maximizedChatBox", maximizedChat)
        }
        else
            $.cookie("maximizedChatBox", null);

        //make the tabs Blink need
        if (blinkChats != null) {
            i = 0;
            for (i = 0; i < blinkChats.length; i++) {
                blinkPestañaBar(blinkChats[i]);
            }
        }
    }
}

function quitarTextoParpad(idPestaña) {
    $("#pestañaBar" + idPestaña).css("color", "black");
    //take my chat id cookie chats Blinks
    if ($.cookie("blinkChat") != null) {
        idsConvers = $.cookie('blinkChat').split("*");
        var i = 0;
        var idConversNew = "";
        for (i = 0; i < idsConvers.length; i++) {
            if (idsConvers[i] != idPestaña) {
                if (idConversNew == "")
                    idConversNew = idsConvers[i];
                else
                    idConversNew = idConversNew + "*" + idsConvers[i];
            }
        }
        $.cookie("blinkChat", idConversNew);
    }
}

function blinkPestañaBar(idPestaña) {
    $("#pestañaBar" + idPestaña).css("color", "red")
    //keep my chat id in the cookie
    if ($.cookie("blinkChat") != null) {
        //that has not been truthful added this ID
        idsConvers = $.cookie('blinkChat').split("*");
        var i = 0;
        var existe = false;
        for (i = 0; i < idsConvers.length; i++) {
            if (idsConvers[i] == idPestaña) {
                existe = true
            }
        }
        if (!existe)
            if ($.cookie("blinkChat") != "")
                $.cookie("blinkChat", $.cookie("blinkChat") + "*" + idPestaña)
        else
            $.cookie("blinkChat", idPestaña)
    }
    else
        $.cookie("blinkChat", idPestaña);
}

function closeChatBox(idChatBox) {
    $("#chatBox" + idChatBox).remove();
    $("#pestañaBar" + idChatBox).remove();
    refreshChatBoxPosition();

    //remove the user id in the cookie of active chats
    if ($.cookie("activeChats") != null) {        
        idsConvers = $.cookie('activeChats').split("*");
        var i = 0;        
        var idConversNew = "";
        for (i = 0; i < idsConvers.length; i++) {
            if (idsConvers[i] != idChatBox) {
                if (idConversNew == "")
                    idConversNew = idsConvers[i];
                else
                    idConversNew = idConversNew + "*" + idsConvers[i];
            }
        }
        $.cookie("activeChats", idConversNew);
    }
    //delete the cookies and conversation
    $.cookie("chat" + idChatBox, null);
}



function refreshChatBoxPosition() {
    $.each($(".pestañaBar"), function() {
        id = $(this).attr('id');
        res = id.substring(10, id.length);
        var offset = $("#pestañaBar" + res).offset().left - 85;
        if (offset != $("#chatBox" + res).offset().left)
            $("#chatBox" + res).offset({ left: offset });
    });
}

function refreshContactList(userID) {
    //0 - create the html
    //1 - error
    var accion = 0;
    var html = "";
    var json;
    $.ajax({
        type: "POST", url: "WebService.asmx/getContactList", data: '{"userID":"' + userID + '"}',
        contentType: "application/json; charset=utf-8", dataType: "json",
        success: function(msj) {
            if (msj.d != "error") {
                accion = 0;
                eval('var z=' + msj.d);
                json = z;
            }
            else
                accion = 1;

        },
        error: function() {
            accion = 1;
        },
        async: false
    });

    if (accion == 0) {
        //create html
        var offline = "";
        var _Title = "";
        var tips = "";

        if(userID == 112)
        {
            _Title = "Online Customer";
            offline = 'No customer found. Work out something to get customer !!!';
        }
        else
        {
            _Title = "Customer Service";
            offline = 'Kindly <a style="color:#2B60DE;" href="http://www.jordeen.com/message.aspx" target="_blank">leave us message</a> or call us 012-6976188.<br /><br />MSN: <br />jordeen01@hotmail.com<br /><br />Email: <br />jordeen@live.com' +
                    '<br /><br />Tips: <br /><a rel="nofollow" href="http://www.jordeen.com/shoppingguide.aspx" target="_blank" style="color:#2B60DE;" >How to place order?</a>';
	    tips = 'Chat with us now or call us 012-6976188.<br /><br />MSN: <br />jordeen01@hotmail.com<br /><br />Email: <br />jordeen@live.com' +
                    '<br /><br />Tips: <br /><a rel="nofollow" href="http://www.jordeen.com/shoppingguide.aspx" target="_blank" style="color:#2B60DE;" >How to place order?</a>';
        }
        
        if (json.onlineUsers.count == 0)
            html = html + "<table><tr><td>" + offline + "</td></tr></table>";
        else {
            var i = 0;
            //take it off to whoever is logged
            $.each($(".chatBox span"), function() {
                $(this).html(" (Offline)");
            });
            html = html + "<table id='tblContactLst'>";
            while (i < json.onlineUsers.count) {
                html = html + "<tr onclick='createChatWindow(" + json.onlineUsers.items[i].id + ", \"" + json.onlineUsers.items[i].userName + "\")'><td class='stateImg'></td><td style='color:#2B60DE;'>" + json.onlineUsers.items[i].userName + "</td></tr>";
                //Offline Saco legend who, if this!
                $("#chatBox" + json.onlineUsers.items[i].id + " span").html("");
                i++;
            }
            html = html + "</table><table><tr><td >" + tips + "</td></tr></table>";
        }
        $(".btnChat span").html(_Title + " (" + json.onlineUsers.count + ")");
    }
    else
        html = html + "<table><tr><td>Lost connection to server. Please refresh.</td></tr></table>";

    $(".contentContactList").html(html);
}

function createChatWindow(withUserID, withUserName) {
    //Check if there is a window
    var chatbox = "#chatBox" + withUserID;
    var createWindow = false;
    if ($(chatbox).length)
        createWindow = false;
    else 
        createWindow = true;        
    

    if (createWindow) {
        var html = "";
        /* Create the tab at the bar */
        if(withUserID == 112)
        {
            html = html + "<div class='pestañaBar' id='pestañaBar" +  withUserID + "' onClick='toogleChatBox(" + withUserID + ")'><table><tr><td class='pestañaImage'></td><td>Chat</td></tr></table></div>";
        }
        else
        {
            html = html + "<div class='pestañaBar' id='pestañaBar" +  withUserID + "' onClick='toogleChatBox(" + withUserID + ")'><table><tr><td class='pestañaImage'></td><td>" + withUserName.substring(0,4) + "</td></tr></table></div>";
        }
        $("#chatBar").append(html);

        /* Create the ChatBox */
        html = "";
        html = html + "<div class = 'chatBox' id='chatBox" + withUserID + "' style='display:none'>";
        html = html + "<div class = 'titleDiv'> <a class='closeChat' title='Close' onClick='closeChatBox(" + withUserID + ")'/> <a class='minimizeChat' title='Minimize' 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>";
        $("#divContenedor2").append(html);

        //store the user id in the cookie
        if ($.cookie("activeChats") != null) {
            //that has not been truthful added this ID
            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);        //as you start minimized then maximized
        refreshChatBoxPosition();         //manually call this method to start with the tab positioned
        $("#chatBox" + withUserID).click(function() { quitarTextoParpad(withUserID) });
        $("#pestañaBar" + withUserID).click(function() { quitarTextoParpad(withUserID) });
    }

}

function PushMessage(event, toUserID) {

    if (event.keyCode == 13) {
        var chatbox = "#chatBox" + toUserID ;
        var message = $(chatbox + " textarea").val().replace("\"", "''").replace("/", "&#47;");
        var fromUserID = $('#chatBar').attr('userID');
        if ((message == "") | (message == "\n")) { $(chatbox + " textarea").val(""); return };
        $.ajax({
            type: "POST",
            url: "WebService.asmx/PushMessage",
            data: '{"from":"' + fromUserID + '", "to":"' + toUserID + '", "message":"' + message + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msj) {
                if (msj.d != "error") {
                    $(chatbox + " .contentDiv").append("<b>Me</b>: " + message + "<br />");
                    $(chatbox + " textarea").val("");
                    $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
                    
		    var chathistory = $(chatbox + " .contentDiv").html()  
                    var chatlength = chathistory.length;
                    var chatstart = 0;
                    var chatlimit = 3000;
                    
                    if(chatlength > chatlimit)
                    {
                        chatstart = chatlength - chatlimit;
                        chathistory = "..." + chathistory.substring(chatstart);
                    }
                                         
                    //write in the cookie
                    $.cookie("chat" + toUserID, chathistory);             
                }
            },
            error: function() {
                $(chatbox + " .contentDiv").append("Error. Please try again. <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: "WebService.asmx/PopMessage",
        data: '{"userID":"' + UserID + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msj) {
            if (msj.d != "error") {
                PopMessageError(false);
                eval('var z=' + msj.d);
                //createChatWindow(z.mensajes.);                    
                var i = 0;
                while (i < z.mensajes.count) {
                    createChatWindow(z.mensajes.items[i].fromID, z.mensajes.items[i].fromUserName);

                    var message = z.mensajes.items[i].mensaje;
                    if(UserID == 112)
                    {
                         playSound("http://www.isois2u.com/files/type.wma");
                    }
                    
                    var chatbox = "#chatBox" + z.mensajes.items[i].fromID;
                    if(UserID == 112)
                    {
                        $(chatbox + " .contentDiv").append("<b>" + z.mensajes.items[i].fromUserName.substring(0,4) + "</b>: " + message + "<br />");
                    }
                    else
                    {
                        $(chatbox + " .contentDiv").append("<b>" + z.mensajes.items[i].fromUserName + "</b>: " + message + "<br />");
                    }
                    $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
                    //blink for the user tab Bar know you have new text
                    blinkPestañaBar(z.mensajes.items[i].fromID);

                    var chathistory = $(chatbox + " .contentDiv").html()  
                    var chatlength = chathistory.length;
                    var chatstart = 0;
                    var chatlimit = 3000;
                    
                    if(chatlength > chatlimit)
                    {
                        chatstart = chatlength - chatlimit;
                        chathistory = "..." + chathistory.substring(chatstart);
                    }
                                         
                    //write in the cookie
                    $.cookie("chat" + z.mensajes.items[i].fromID, chathistory);
                    i++;
                }
            }
            else
                accion = 1;

        },
        error: function() {
            PopMessageError(true);
        }
    });

}


function PopMessageError(value) {
    if (value) {
        $(".contentDiv").addClass("contentDivError");
        $(".inputDivTxt").val("Lost connection to server. Please refresh.");
        $(".inputDivTxt").attr("disabled", true);
    }
    else {
        if ($(".contentDiv").hasClass("contentDivError")) {
            $(".contentDiv").removeClass("contentDivError");
            $(".inputDivTxt").val("");
            $(".inputDivTxt").removeAttr("disabled");
        }
    }
}



/*********************************************************************************************/
/**************************      PLUGINS    **************************************************/
/*********************************************************************************************/
/*********************************************************************************************/

//2009-03-20  Plugin SETOFFSET
(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);

/*********************  Cookie Plugin ***************************/


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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;
    }
};
