﻿var _userIdChat;
var _event;

var _aviso;
var _userId;
var _roomId;
var _lastmessageId;
var _chatvisible;
var _sendmail;

var _posx = 0;
var _posy = 0;


function sendMessageCallBack(res) {
    var Msgs;
    var newMsg;
    var i;

    Msgs = res.value;

    if (Msgs == null) return false;

    var pnl = document.getElementById("ctl00_dlgChat_PnlMessages");

    for (i = 0; i < Msgs.length; i++) {
        newMsg = Msgs[i];

        pnl.innerHTML +=
                        "<TABLE width='100%'> <TBODY>" +
                        "<TR style='WIDTH: 100%; HEIGHT: auto'> " +
                        "<TD style='WIDTH: 5%; COLOR: navy; TEXT-ALIGN: left' valign='top'><INPUT type=hidden><img style='BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px' alt='' src='images/icon.gif'> </TD>" +
                        "<TD style='WIDTH: 15%; COLOR: navy; TEXT-ALIGN: left' valign='top'>" + newMsg.UserName + "</TD>" +
                        "<TD style='WIDTH: 55%; HEIGHT: auto'>" + newMsg.Text + "</TD>" +
                        "<TD style='FONT-SIZE: smaller; WIDTH: 20%' valign='top'> [" + newMsg.TimeStamp + "]</TD></TR></TBODY></TABLE>"

        _lastmessageId = newMsg.Id;
    }

    scrollContentDown();

};

function sendMessage(e) {
    var evento = "Tienes un mensaje de {0}";
    var msg = ASPxTxtMessage.GetText();

    if (msg == '') return false;

    ASPxTxtMessage.SetText("");
    ASPxTxtMessage.Focus();

    msg = FormatMsg(msg);

    clsChatRoom.AddMessages(_roomId, _userId, msg, 'Verdana', 10, "Black", evento, _lastmessageId, _sendmail, sendMessageCallBack);

};

function keyDownMessage(e) {
    if (e.htmlEvent.keyCode == 13) {
        sendMessage(e);
    }
};

function disableEnterKey(e) {
    if (e.htmlEvent.keyCode == 13) {
        e.htmlEvent.returnValue = false;
        e.htmlEvent.cancel = true;
        if (navigator.appName == "Netscape") {
            e.htmlEvent.stopPropagation();
            e.htmlEvent.preventDefault();
        }
        return false;
    }
};

function scrollContentDown() {
    var panel = document.getElementById("ctl00_dlgChat_PnlMessages");
    panel.scrollTop = panel.scrollHeight + 1000000;
};

function ShowStatus() {
    var dlg = document.getElementById('ctl00_dlgStatus').control;
    var txt = document.getElementById("ctl00_dlgStatus_txtOtro");
    if (!ASPxrdbtnOtro.GetChecked()) txt.disabled = true;
    dlg.move(_posx, _posy);
    dlg.showModal();
};

function ShowAvatar() {
    var dlg = document.getElementById('ctl00_dlgAvatar').control;
    dlg.move(_posx, _posy); // .event.clientX, window.event.clientY);
    dlg.showModal();
};

function ShowEmoticon() {
    var dlg = document.getElementById('ctl00_dlgEmoticonos').control;
    dlg.move(_posx , _posy);
    dlg.showModal();
};

function AddTexto(emoticono) {
    var temp;
    var dlg = document.getElementById('ctl00_dlgEmoticonos').control;
    var tbr = document.getElementById("ctl00_dlgChat_C1ToolBar1").control;

    temp = ASPxTxtMessage.GetText();
    temp = temp + emoticono + '';

    ASPxTxtMessage.SetText(temp);
    ASPxTxtMessage.SetCaretPosition(temp.length);
    ASPxTxtMessage.Focus();

    for (i = 0; i < tbr._propertiesState.Items.length; i++) {
        if (tbr._propertiesState.Items[i].Selected == true) tbr._propertiesState.Items[i].Selected = false;
    }

    dlg.hide();
};

function SetAvatarCallBack(res) {
    //        ASPxPopupAvatar.Hide();
    var dlg = document.getElementById('ctl00_dlgAvatar').control;
    dlg.hide();
};

function SetAvatar(s) {

    var str = s.mainElement.src;
    var tbr = document.getElementById("ctl00_dlgChat_C1ToolBar1").control;

    str = str.substr(str.search('images/'));

    var btn2 = tbr.get_items().get_item(0)

    btn2.set_imageUrl(str);

    //ASPxImgMiAvatar.mainElement.src = s.mainElement.src.substr(0, s.mainElement.src.search('images/')) + str;

    clsUserChat.UpdateAvatar(_roomId, _userId, str, SetAvatarCallBack);

};

function ShowChat(roomId, userId, sendmail, event) {
    var res;
    var dlg;

    try {

        if (_chatvisible) {
            dlg = document.getElementById('ctl00_dlgChat').control;
            dlg.hide();
            //ASPxPopupChat.Hide();
        }

        if (roomId == -1) return false;

        _roomId = roomId;
        _userId = userId;
        _chatvisible = true;
        _sendmail = sendmail;

        dlg = document.getElementById('ctl00_dlgChat').control;

        dlg.move(_posx, _posy);
//        if (event != null) {
//            dlg.move(event.clientX, event.clientY);
//            //ASPxPopupChat.ShowAtPos(event.clientX, event.clientY);
//        } // else {
//        //    ASPxPopupChat.Show();
        //}
        dlg.showModal();

        Load_Messages(roomId, _userId);
        Start_Timer();
    }
    catch (sError) {

    }
};

function Load_MessagesCallBack(res) {

    var pnl;
    var Msgs;
    var Msg;
    var i;

    try {

        Msgs = res.value;

        _lastmessageId = null;

        pnl = document.getElementById("ctl00_dlgChat_PnlMessages");

        if (pnl.childNodes.length > 0) {
            for (i = pnl.childNodes.length - 1; i >= 0; i--) {
                pnl.removeChild(pnl.childNodes[i]);
            }
        }

        if (Msgs == null) return false;

        for (i = 0; i < Msgs.length; i++) {
            Msg = Msgs[i];

            pnl.innerHTML +=
                            "<TABLE width='100%'> <TBODY>" +
                            "<TR style='WIDTH: 100%; HEIGHT: auto'> " +
                            "<TD style='WIDTH: 5%; COLOR: navy; TEXT-ALIGN: left' valign='top'><INPUT type=hidden><img style='BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px' alt='' src='images/icon.gif'> </TD>" +
                            "<TD style='WIDTH: 15%; COLOR: navy; TEXT-ALIGN: left' valign='top'>" + Msg.UserName + "</TD>" +
                            "<TD style='WIDTH: 55%; HEIGHT: auto'>" + Msg.Text + "</TD>" +
                            "<TD style='FONT-SIZE: smaller; WIDTH: 20%' valign='top'> [" + Msg.TimeStamp + "]</TD></TR></TBODY></TABLE>"

            _lastmessageId = Msg.Id;
        }

        scrollContentDown();
    }
    catch (sError) {

    }

};

function Load_Messages(roomId, userId) {
    clsChatRoom.GetLastMessages(roomId, 20, userId, Load_MessagesCallBack);
};

function FormatMsg(Msg) {
    Msg = Msg.replace(":D", "<IMG ALIGN=top SRC='images/Emoticons/openmouth.gif'>");
    Msg = Msg.replace(":B", "<IMG ALIGN=top SRC='images/Emoticons/buck.gif'>");
    Msg = Msg.replace("=|", "<IMG ALIGN=top SRC='images/Emoticons/bored.gif'>");
    Msg = Msg.replace(":C", "<IMG ALIGN=top SRC='images/Emoticons/shy.gif'>");
    Msg = Msg.replace(":|", "<IMG ALIGN=top SRC='images/Emoticons/stunned.gif'>");

    Msg = Msg.replace(":S", "<IMG ALIGN=top SRC='images/Emoticons/crazy.gif'>");
    Msg = Msg.replace(":(", "<IMG ALIGN=top SRC='images/Emoticons/sad.gif'>");
    Msg = Msg.replace(":O", "<IMG ALIGN=top SRC='images/Emoticons/shocked.gif'>");
    Msg = Msg.replace(":)", "<IMG ALIGN=top SRC='images/Emoticons/smiley.gif'>");
    Msg = Msg.replace(")|", "<IMG ALIGN=top SRC='images/Emoticons/suss.gif'>");

    Msg = Msg.replace(";)", "<IMG ALIGN=top SRC='images/Emoticons/wink.gif'>");
    Msg = Msg.replace(":P", "<IMG ALIGN=top SRC='images/Emoticons/tounge.gif'>");
    Msg = Msg.replace(":M", "<IMG ALIGN=top SRC='images/Emoticons/smoke.gif'>");
    Msg = Msg.replace("=M", "<IMG ALIGN=top SRC='images/Emoticons/stoned.gif'>");
    Msg = Msg.replace("(MT)", "<IMG ALIGN=top SRC='images/Emoticons/biker.gif'>");

    Msg = Msg.replace("(P)", "<IMG ALIGN=top SRC='images/Emoticons/pirate.gif'>");
    Msg = Msg.replace("(B)", "<IMG ALIGN=top SRC='images/Emoticons/mask.gif'>");
    Msg = Msg.replace("(N)", "<IMG ALIGN=top SRC='images/Emoticons/ninja.gif'>");
    Msg = Msg.replace("(M)", "<IMG ALIGN=top SRC='images/Emoticons/alien.gif'>");
    Msg = Msg.replace("(R)", "<IMG ALIGN=top SRC='images/Emoticons/angry.gif'>");

    Msg = Msg.replace("(L)", "<IMG ALIGN=top SRC='images/Emoticons/heart.gif'>");
    Msg = Msg.replace("(T)", "<IMG ALIGN=top SRC='images/Emoticons/phone.gif'>");
    Msg = Msg.replace("(K)", "<IMG ALIGN=top SRC='images/Emoticons/lips.gif'>");
    Msg = Msg.replace("(G)", "<IMG ALIGN=top SRC='images/Emoticons/present.gif'>");
    Msg = Msg.replace("(A)", "<IMG ALIGN=top SRC='images/Emoticons/rainbow.gif'>");

    Msg = Msg.replace("(F)", "<IMG ALIGN=top SRC='images/Emoticons/reach.gif'>");
    Msg = Msg.replace("(@)", "<IMG ALIGN=top SRC='images/Emoticons/rose.gif'>");
    Msg = Msg.replace("(WL)", "<IMG ALIGN=top SRC='images/Emoticons/broken.gif'>");
    Msg = Msg.replace("(W@)", "<IMG ALIGN=top SRC='images/Emoticons/wilt.gif'>");
    Msg = Msg.replace("(MN)", "<IMG ALIGN=top SRC='images/Emoticons/moon.gif'>");

    Msg = Msg.replace("(LH)", "<IMG ALIGN=top SRC='images/Emoticons/bright.gif'>");
    Msg = Msg.replace("(TIC)", "<IMG ALIGN=top SRC='images/Emoticons/clock.gif'>");
    Msg = Msg.replace("(SR)", "<IMG ALIGN=top SRC='images/Emoticons/star.gif'>");
    Msg = Msg.replace("(DV)", "<IMG ALIGN=top SRC='images/Emoticons/devil.gif'>");
    Msg = Msg.replace("(C)", "<IMG ALIGN=top SRC='images/Emoticons/cake.gif'>");

    Msg = Msg.replace("(SU)", "<IMG ALIGN=top SRC='images/Emoticons/sun.gif'>");
    Msg = Msg.replace("(PH)", "<IMG ALIGN=top SRC='images/Emoticons/camera.gif'>");
    Msg = Msg.replace("(NO)", "<IMG ALIGN=top SRC='images/Emoticons/thumbdown.gif'>");
    Msg = Msg.replace("(Y)", "<IMG ALIGN=top SRC='images/Emoticons/thumbup.gif'>");
    Msg = Msg.replace("(GO)", "<IMG ALIGN=top SRC='images/Emoticons/goat.gif'>");

    Msg = Msg.replace("(BE)", "<IMG ALIGN=top SRC='images/Emoticons/beer.gif'>");
    Msg = Msg.replace("(W)", "<IMG ALIGN=top SRC='images/Emoticons/wine.gif'>");
    Msg = Msg.replace("(CF)", "<IMG ALIGN=top SRC='images/Emoticons/coffee.gif'>");

    return Msg;

};

function GetLastMessagesCallBack(res) {
    try {

        var pnl;
        var Msgs;
        var Msg;

        Msgs = res.value;

        if (Msgs == null) return false;
        if (!ASPxTimerChat.GetEnabled()) return false;

        //pnl = document.getElementById("ctl00_ASPxPopupChat_PnlMessages")
        pnl = document.getElementById("ctl00_dlgChat_PnlMessages");

        for (i = 0; i < Msgs.length; i++) {
            Msg = Msgs[i];

            pnl.innerHTML +=
                            "<TABLE width='100%'> <TBODY>" +
                            "<TR style='WIDTH: 100%; HEIGHT: auto'> " +
                            "<TD style='WIDTH: 5%; COLOR: navy; TEXT-ALIGN: left' valign='top'><INPUT type=hidden><img style='BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px' alt='' src='images/icon.gif'> </TD>" +
                            "<TD style='WIDTH: 15%; COLOR: navy; TEXT-ALIGN: left' valign='top'>" + Msg.UserName + "</TD>" +
                            "<TD style='WIDTH: 55%; HEIGHT: auto'>" + Msg.Text + "</TD>" +
                            "<TD style='FONT-SIZE: smaller; WIDTH: 20%' valign='top'> [" + Msg.TimeStamp + "]</TD></TR></TBODY></TABLE>"

            _lastmessageId = Msg.Id;
        }

        scrollContentDown();
    }
    catch (sError) {

    }
};

function GetLastMessages() {
    clsChatRoom.GetLastMessage(_roomId, _lastmessageId, GetLastMessagesCallBack);
};

function Start_Timer() {
    ASPxTimerChat.SetEnabled(true);
};

function Stop_Timer() {
    ASPxTimerChat.SetEnabled(false);
    _chatvisible = false;
};

function ShowPopupCallBack(res) {
    try {
        _aviso = res.value;
        if (_aviso != null) {
            LblMsg.SetText(_aviso.Message)
            ImgMsg.SetImageUrl(_aviso.Photo);
            ImgMsg.SetSize(61, 65);
            //ASPxPopupMsg.SetFooterText(_aviso.Fecha);
            //ASPxPopupMsg.Show();
            var dlg = document.getElementById('ctl00_dlgMsg').control;
            lblMsgStatus.SetText(_aviso.Fecha.tostring());
            dlg.move(screen.width - 275, screen.height - 350);
            dlg.show();
        }
    }
    catch (sError) {

    }
};

function ShowPopup() {
    clsUserMessages.ExistsPending(ShowPopupCallBack);
};

function OpenChatCallBack(res) {
    var dlg = document.getElementById('ctl00_dlgMsg').control;

    if (res.value) {
        dlg.hide();
        _roomId = _aviso.RoomId;
        _userId = _aviso.UserId;
        _event = event;
        clsChatRooms.MustSendMsgByMail(_aviso.RoomId, _aviso.UserId, MustSendMsgByMailCallBack);
        //            ShowChat(_aviso.RoomId, _aviso.UserId, event)
    }
};

function OpenChat() {
    if (_aviso != null) {
        clsUserMessages.SetVisited(_aviso.Id, OpenChatCallBack);
    }
};

function SetStatusCallBack(res) {
    //ASPxPopupStatus.Hide();
    var dlg = document.getElementById('ctl00_dlgStatus').control;
    dlg.hide();
};

function SetStatus(s) {

    var tbr = document.getElementById("ctl00_dlgChat_C1ToolBar1").control;

    if (!s.GetChecked()) return false;

    var str = s.GetMainElement().innerText;

    var btn2 = tbr.get_items().get_item(0)

    btn2.set_text(str);
    clsUserChat.UpdateStatus(_roomId, str, SetStatusCallBack);

};

function TxtEnabled(s) {
    if (s.GetChecked()) {
        var txt = document.getElementById("ctl00_dlgStatus_txtOtro");
        txt.disabled = false;
        txt.focus();
    }
};

function Status_Hide() {

    var txt = document.getElementById("ctl00_dlgStatus_txtOtro");
    var tbr = document.getElementById("ctl00_dlgChat_C1ToolBar1").control;
    var str;

    if (ASPxrdbtnOtro.GetChecked()) {
        str = txt.value;
        if (str != "") {
            var btn2 = tbr.get_items().get_item(0)

            btn2.set_text(str);
            clsUserChat.UpdateStatus(_roomId, str, SetStatusCallBack);
        }
    }

};

function Status_OtroKeyPress(event) {
    var dlg = document.getElementById('ctl00_dlgStatus').control;
    if (event.keyCode == 13) {
        dlg.hide();
        event.returnValue = false;
        event.cancel = true;
        if (navigator.appName == "Netscape") {
            event.stopPropagation();
            event.preventDefault();
        }
        return false;
    }
};

function Chat_Resizing() {

    var dialog = document.getElementById("ctl00_dlgChat").control;
    var tbr = document.getElementById("ctl00_dlgChat_C1ToolBar1").control;

    tbr.set_width(dialog.get_width());

    return false;

};

function Chat_ToolBarClick(sender, eventargs) {

    var btn;
    var btnName;

    btn = eventargs.get_item();
    btnName = eventargs.get_item().get_id();

    if (btnName == "ctl00_dlgChat_C1ToolBar1_tcr_C1ToolBarButton1") ShowStatus();
    if (btnName == "ctl00_dlgChat_C1ToolBar1_tcr_C1ToolBarButton2") ShowEmoticon();
    if (btnName == "ctl00_dlgChat_C1ToolBar1_tcr_C1ToolBarButton3") ShowAvatar();

    btn.set_selected(false)

};

function HideAlert(result) {

    var dlg = document.getElementById('ctl00_dlgAlert').control;
    var tipo = ASPxlblTipo.GetText();

    if (tipo == 1) {
        dlg.hide();
    }
    else {
        if (result == 'ok') dlg.hide();
        else {
            alert('Cancel');
            dlg.hide();
        }
    }

};

function SendMsgByMailCallBack(res) {

    if (res.value != '') alert(res.value);

};

function Chat_Hide() {

    Stop_Timer();
    if (_sendmail == true) {
        clsChatRooms.SendMsgByMail(_roomId, _userId, SendMsgByMailCallBack);
    }

};
function AddFriendCallBack(res) {

    if (res.value.Res > 0) {
        alert(res.value.Msg);
        try {
            ASPxPnlFriend.SetClientVisible(false);
            if (res.value.Res = 1) ASPxPnlNoFriend.SetClientVisible(false);
            else ASPxPnlNoFriend.SetClientVisible(true);
        }
        catch (er) {
            window.location.reload();
        }
    }
};

function AddFriend(friendid, userid) {
    return clsUserFriends.AddFriend(friendid, userid, AddFriendCallBack);
};

function DeleteFriendCallBack(res) {

    if (res.value.Res > 0) {
        alert(res.value.Msg);
        try {
            ASPxPnlFriend.SetClientVisible(false);
            ASPxPnlNoFriend.SetClientVisible(true);
        }
        catch (er) {
            window.location.reload();
        }
    }

};

function DeleteFriend(friendid, userid, msg, event) {
    
    if (msg == null) {
        var obj = document.getElementById("ctl00_ContentPlaceHolder1_lblSeguro");
        if (obj != null) msg = obj.innerText;
        else msg = "";
    }
    
    if (confirm(msg)) {
        return clsUserFriends.DeleteFriend(friendid, userid, DeleteFriendCallBack)
    }
    else {
        event.cancel = true;
        event.returnValue = false;
    }
};

function MustSendMsgByMailCallBack(res) {

    if (res.value.Value == true) {
        ShowChat(_roomId, _userIdChat, true, _event);
//        if (confirm(res.value.Msg)) {
//            ShowChat(_roomId, _userIdChat, true, _event);
//        }
//        else {
//            ShowChat(_roomId, _userIdChat, false, _event);
//        }
    }
    else {
        ShowChat(_roomId, _userIdChat, false, _event);
    }
};

function GetRoomIdCallBack(res) {
    if (res.value != -1) {
        _roomId = res.value;
        clsChatRooms.MustSendMsgByMail(res.value, _userIdChat, MustSendMsgByMailCallBack);
    }
}

function GetRoomId(roomId, userId, userIdChat, event) {
    _userIdChat = userId;
    _event = event;

    var timer = $find("ctl00_ContentPlaceHolder1_Timer1");
    if (timer != null) timer._stopTimer();    

    if (roomId == -1) {
        clsChatRooms.Add("Sala", userIdChat, GetRoomIdCallBack);
    }
    else {
        _roomId = roomId;
        _event = event;
        clsChatRooms.MustSendMsgByMail(_roomId, _userIdChat, MustSendMsgByMailCallBack);
    }
};

function ValorationChanged() {

    var val = ASPxrdBtnListValoracion.GetValue();

    if (val == "0") ASPximValoracion.SetImageUrl("images/Ratio0.png");
    if (val == "1") ASPximValoracion.SetImageUrl("images/Ratio1.png");
    if (val == "2") ASPximValoracion.SetImageUrl("images/Ratio2.png");
    if (val == "3") ASPximValoracion.SetImageUrl("images/Ratio3.png");
    if (val == "4") ASPximValoracion.SetImageUrl("images/Ratio4.png");
    if (val == "5") ASPximValoracion.SetImageUrl("images/Ratio5.png");

};

function watchMouse() {
    document.onmousemove = showValues;
}

function showValues(e) {

    try {
        if (!e) { e = window.event; }
        if (!e) { return; }
        if (typeof (e.pageX) == 'number') {
            _posx = e.pageX;
            _posy = e.pageY;
        } else if (typeof (e.clientX) == 'number') {
            _posx = e.clientX;
            _posy = e.clientY;
            if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
                _posx += document.body.scrollLeft;
                _posy += document.body.scrollTop;
            } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                _posx += document.documentElement.scrollLeft;
                _posy += document.documentElement.scrollTop;
            }
        } else { return; }
    }
    catch (sError) {
        alert(sError);
    }     
};