﻿
/********************************************************/
/*                    MRM CHAT                          */
/*                   Noviembre 2010                     */
/*                  www.isuri.com.ar                    */   
/********************************************************/

(function ($) {

    var _userName;
    var _userID;
   

    $.fn.isuriChat = function (userID, Logged) {

        if (userID != null) {
       
                setInterval('PopMessage(' + userID + ')', 3000);   //verifico si tengo nuevos mensajes
                setInterval('refreshContactList(' + userID + ')', 30000); //refresco la lista de contactos
            
            //setInterval('refreshChatBoxPosition()', 1000);   //refresco por si maximizo o minimizo el browser..  
        };






        /***************************************************/
        /************  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> CHAT </span></div>";

        html = html + "</div>";

        /* creo el div de Contactos Online */
        html = html + "<div class='contactList'>";
        html = html + "<div class='titleContactList'>Usuarios Online</div>";
        html = html + "<div class='contentContactList'></div>";
        html = html + "";
        html = html + "";
        html = html + "</div>";

        this.append(html);
        //Cargo los datos de las cookies
        loadcookieData();
    }

})(jQuery);


/***********************************************/
/***************   FUNCIONES      **************/
/***********************************************/



function ToggleDiv(div) {
    $(div).toggle();
}



function toogleChatBox(idChatBox) {
    if ($("#chatBox" + idChatBox).is(":visible")) {
        $("#chatBox" + idChatBox).hide();
        $("#pestañaBar" + idChatBox).css("background-color", "gainsboro");
        //Guardo en la cookie
        $.cookie("maximizedChatBox", null);
    }
    else {
        //minimizo todas las otras ventanas
        $.each($(".chatBox"), function() {
            $(this).hide();            
        });
        //pongo en gris todas las pestañas
        $.each($(".pestañaBar"), function() {            
            $(this).css("background-color", "gainsboro");
        });
        
        $("#chatBox" + idChatBox).show();
        $("#pestañaBar" + idChatBox).css("background-color", "white");
        //Guardo en la cookie
        $.cookie("maximizedChatBox",idChatBox);
    }
}

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: "isuriChat.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
                });
                
            }
        }
        //Maximizo el chatBox en caso de ser necesario
        //primero minimizo todo
        $.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);

        //Hago el Blink a las pestañas que lo necesitan
        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");    
    //quito el id de chat en la cookie de 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")
    //guardo el id de chat en la cookie        
    if ($.cookie("blinkChat") != null) {
        //veridico que no haya sido agregada esta 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();
    
    //quito el id de usuario en la cookie de chats activos    
    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);
    }
    //borro la cookie de conversación
    $.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) {
    //Opciones accion
    //0 - creo el html
    //1 - error
    var accion = 0;
    var html = "";
    var json;
    $.ajax({
        type: "POST",
        url: "isuriChat.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) {
        //creo el html
        if (json.onlineUsers.count == 0)
            html = html + "<table><tr><td>No hay usuarios conectados</td></tr></table>";
        else {
            var i = 0;
            //Coloco la leyeda OFFLINE  en todos los chatBox, y luego se la quito a quien este conectado
            $.each($(".chatBox span"), function() {
                $(this).html(" (Desconectado)");
            });
            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>" + json.onlineUsers.items[i].userName + "</td></tr>";
                //Saco la leyenda Desconectado a quien si esta!
                $("#chatBox" + json.onlineUsers.items[i].id + " span").html("");
                i++;
            }
            html = html + "</table>";
        }
        $(".btnChat span").html("Usuarios (" + json.onlineUsers.count + ")");
    }
    else
        html = html + "<table><tr><td>Ocurrió un error. Verifique su conexión de internet.</td></tr></table>";

    $(".contentContactList").html(html);
}




function createChatWindow(withUserID, withUserName) {    
    /*Verifico si existe la ventana*/
    var chatbox = "#chatBox" + withUserID;
    var createWindow = false;
    if ($(chatbox).length)
        createWindow = false;
    else 
        createWindow = true;        
    

    if (createWindow) {
        var html = "";
        /* Creo la solapa en la barra */
        html = html + "<div class='pestañaBar' id='pestañaBar" + withUserID + "' onClick='toogleChatBox(" + withUserID + ")'><table><tr><td class='pestañaImage'></td><td>" + withUserName + "</td></tr></table></div>";
        $("#chatBar").append(html);

        /*  Creo el ChatBox*/
        html = "";
        html = html + "<div class = 'chatBox' id='chatBox" + withUserID + "' style='display:none'>";
        //html = html + "<div class = 'titleDiv'> <a class='closeChat' title='Cerrar esta converzación.' onClick='closeChatBox(" + withUserID + ")'/> <a class='minimizeChat' title='Minimizar Ventana' onClick='toogleChatBox(" + withUserID + ")'/> ";
        html = html + "<div class = 'titleDiv'> <a class='closeChat' title='Cerrar esta converzación.' onClick='closeChatBox(" + withUserID + ")'/> <a class='minimizeChat' title='Minimizar Ventana' onClick='toogleChatBox(" + withUserID + ")'/> <a class='BlockChat' title='Sacar al usuario de la session' onClick='BlockUser(" + 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);

        //guardo el id de usuario en la cookie        
        if ($.cookie("activeChats") != null) {
            //veridico que no haya sido agregada esta 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);        //como se inicia minimizada entonces la maximizo
        refreshChatBoxPosition();         //llamo manualmente a este metodo para que arranque posicionado con la pestaña
        $("#chatBox" + withUserID).click(function() { quitarTextoParpad(withUserID) });
        $("#pestañaBar" + withUserID).click(function() { quitarTextoParpad(withUserID) });
    }

}


function BlockUser(toUserID) {
    $.ajax({
        type: "POST",
        url: "isuriChat.asmx/BlockUser",
        data: '{"userID":"' + toUserID + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msj) {
            if (msj.d != "error") {
                closeChatBox(toUserID);

            } else
                alert('No se pudo bloquear al Usuario, intente nuevamente');
        },
        error: function () {
            alert('Error al intentar bloquear al Usuario, intente nuevamnete');
        }
    });
}





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: "isuriChat.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>yo</b>: " + message + "<br />");
                    $(chatbox + " textarea").val("");
                    $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
                    //escribo en la cookie
                    $.cookie("chat" + toUserID, $(chatbox + " .contentDiv").html());                    
                }
            },
            error: function() {
                $(chatbox + " .contentDiv").append("Error al enviar el mensaje <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: "isuriChat.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;
                    var chatbox = "#chatBox" + z.mensajes.items[i].fromID;
                    $(chatbox + " .contentDiv").append("<b>" + z.mensajes.items[i].fromUserName + "</b>: " + message + "<br />");
                    $(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
                    //hago parpadear el pestañaBar para que el usuario sepa que tiene texto nuevo
                    blinkPestañaBar(z.mensajes.items[i].fromID);
                    //escribo en la cookie
                    $.cookie("chat" + z.mensajes.items[i].fromID, $(chatbox + " .contentDiv").html());
                    i++;
                }
            }
            else
                accion = 1;

        },
        error: function() {
            PopMessageError(true);
        }
    });

}


function PopMessageError(value) {
    if (value) {
        $(".contentDiv").addClass("contentDivError");
        $(".inputDivTxt").val("Se perdió la conexión con el servidor. Verifique su conexión a internet.");
        $(".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;
    }
};
