﻿
function validateText(e)
{
    var arr = [16, 13, 8, 39, 37, 38, 40, 36, 35, 186, 188, 222, 190, 191, 46];
    for (var i = 0; i < arr.length; i++)
    {
        if (arr[i] == e.keyCode)
            return true;
    }
    var re = /[a-z]|\d|\s|\r|\n|\f/i;
    return re.test(String.fromCharCode(e.keyCode));
}

function tar_keyup(e)
{
    if (e.keyCode == 13)
        SendMessage();
}

function UpdateChatWindowMinimizeState(isMinimized)
{
    var xhr = new XHRRequester(
                        server_location,
                        [["SID", SID], ["WIN_STATE", isMinimized]],
                        function() { /* in progress */ },
                        function(ro) { }
                      );
    xhr.MakeRequest();
}

function UpdateWritingStatus(status)
{
    var xhr = new XHRRequester(
                server_location,
                [['SID', SID], ['STATUS', status]],
                function() { /* in progress */ },
                function(ro) { }
                );
    xhr.MakeRequest();
}

function SendMessage()
{
    var msg = (arguments.length == 0 ? document.getElementById("tar").value : arguments[0]);
    AppendMessage(msg, yourName, 2);
    AdjustLastMessage();
    if (msg != "")
    {
        xhr = new XHRRequester(
                                server_location,
                                [["RT", 1], ["SID", SID], ["LT", last_request_time], ["MSG", msg]],
                                function() { /* in progress */ },
                                function(ro)
                                {
                                    AppendROFromServer(ro);
                                }
                              );
        xhr.MakeRequest(1);
        document.getElementById("tar").value = "";
    }
}

function SubmitRIForm()
{
    ChangeWindowState(1);
    $("#frmRI").submit();
    return false;
}

function RequestChatWithSalesPerson(pSalesPersonID)
{
    $("#div_csr_list").empty();
    $("#div_csr_list").append("<br /><i style='text-align:center;color:blue;'>Loading chat with the selected CSR<br />please wait ...</i>");
    delete xhr; xhr = null;
    xhr = new XHRRequester(
                server_location,
                [["VRC", 1], ["SID", SID], ["SPID", pSalesPersonID]],
                function() { /* in progress */ },
                function(ro)
                {
                    if (ro && ro.CRT)
                    {
                        last_request_time = ro.CRT;
                        SetCookie("WinMin", "0");
                    }
                }
              );
    xhr.MakeRequest();
    SendMessage("Hi");
}

function AppendMessage(msg, from, sender)
{
    if ($("#div_chat_messages table").size() == 0)
        $("#div_chat_messages").append("<table id='tbl_messages' celpadding='2' cellspacing='0' style='font-family:Verdana;font-size:11px;'></table>");
        
    $("#tbl_messages").append("<tr style='color:" + (sender == 1 ? "royalblue" : "gray") + ";'><td nowrap='nowrap' valign='top'>" + (sender == 1 ? from.bold() : "You".bold()) + " : <td><td>" + msg + "<td></tr>");
}

function AdjustLastMessage()
{
    //$("#tbl_messages").append("<tr><td colspan='2' nowrap='nowrap' valign='top'><a href=''>view complete chat</a><td></tr>");
    document.getElementById("div_chat_messages").scrollTop = document.getElementById("div_chat_messages").scrollHeight - document.getElementById("div_chat_messages").clientHeight;
}

function AppendROFromServer(ro)
{
    if (ro.CMD && ro.CMD != '')
        window.location = ro.CMD;

    if (ro.CW && ro.CW == 1)
        $("#div_writing_status").html("Status: CSR Writing ...");
    else
        $("#div_writing_status").html("");

    var WinMin = GetCookie("WinMin");

    if (ro.CSRName)
    {
        $("#span_csr_name").html(ro.CSRName);
        if ($("#img_csr").attr("src") == "")
            $("#img_csr").attr("src", "/NewChatModule/img/csr_thumb/" + ro.CSRName + ".jpg");
    }

    if (ro.MSGS && ro.MSGS.length && ro.MSGS.length > 0)
    {
        if (ro.CRT)
            last_request_time = ro.CRT;

        $("#div_chat_messages").empty();

        for (var i = 0; i < ro.MSGS.length; i++)
        {
            if (ro.MSGS[i].MF && ro.MSGS[i].MSG)
                AppendMessage(ro.MSGS[i].MSG, ro.MSGS[i].MF, ro.MSGS[i].S);
        }
        AdjustLastMessage();

        ToggleMinimizedHeader(WinMin, ro.MSGS[ro.MSGS.length - 1].S && ro.MSGS[ro.MSGS.length - 1].S == 1, ro.MSGS[ro.MSGS.length - 1].MSG, ro.MSGS[ro.MSGS.length - 1].MF);
        ToggleRequestInfoForm(ro.CIR, WinMin);

        if ($("#dv_chat_win").css("display") == "none")
        {
            $("#dv_chat_win").show();
            PositionChatWin(0);
        }
    }
}

function ToggleMinimizedHeader(pWinMin, isNewMessageFromCSR, message, from)
{
    if (pWinMin != null && pWinMin == "1")
    {
        if (isNewMessageFromCSR)
        {
            ChangeWindowState(5);
            var msg_trimmed = (message.length > 65 ? message.substr(0, 65) + " ..." : message);
            $("#span_csr_message").html("<span style='font-weight:bold;color:Maroon'>" + from + "</span> : " + msg_trimmed);
            $("#span_csr_message").parent().attr("title", message);
        }
        else
            ChangeWindowState(4);
    }
}

function ToggleRequestInfoForm(pCIR, pWinMin)
{
    if (pCIR && pCIR != '' && pCIR == '1')
    {
        if (pWinMin != null && pWinMin == "1")
        {
            $("#div_chat_messages").css("height", ($.browser.msie ? 132 : 145) + "px");
            $("#tr_ri_form").show();
        }
        else
            ChangeWindowState(2);
    }
    else
    {
        if (pWinMin != null && pWinMin == "1")
        {
            //$("#div_chat_messages").css("height", "300px");
            $("#div_chat_messages").css("height", "130px");
            $("#tr_ri_form").hide();
        }
        else
            ChangeWindowState(1);
    }
}

function PollServer()
{
    try{
        var xhr_0 = new XHRRequester
                (
                    server_location,
                    [["RT", 3], ["SID", SID], ["LT", last_request_time]],
                    function() { /* in progress */ },
                    function(ro)
                    {
                        AppendROFromServer(ro);
                    }
                );
        xhr_0.MakeRequest();
    }
    catch (exp) { }

    if (prev)
        clearTimeout(prev);
    prev = setTimeout(PollServer, 3000);
}

function GetAvailableSalesPersons()
{
    var xhr = new XHRRequester(
            server_location,
            [["SID", SID], ['GASPL', '1']],
            function() { /* in progress */ },
            function(ro) {
                if (ro.RO != null && ro.RO.length && ro.RO.length > 0) {
                    var str = "";
                    str += "<table id='tbl_csr_list' style='font-size:10pt;font-family:Arial;' cellpadding='0' cellspacing='0' width='100%'><tr><th colspan='4' style='color:white;background-color:RoyalBlue;padding:5px;font-size:10pt;'>Click below to chat with one of our sales reps.</th></tr><tr>";

                    //for (var i = 0; i < 100; i++)
                    for (var i = 0; i < ro.RO.length; i++) {
                        if (i != 0 && i % 4 == 0)
                            str += "</tr><tr>";

                        //str += "<td style='padding:3px;'><img src='/NewChatModule/img/csr/t_'" + i + ".jpg' style='width:30px;height:35px;padding:2px;' /><a style='color:blue;padding-left:2px;' onclick='RequestChatWithSalesPerson(" + 1 + ");' href='javascript:void(0);'>" + "Mikee" + "</a></td>";
                        str += "<td style='padding:3px;'><img src='/NewChatModule/img/csr/t_" + ro.RO[i].Name + ".jpg' style='width:30px;height:35px;padding:2px;' /><a style='color:blue;padding-left:2px;' onclick='RequestChatWithSalesPerson(" + ro.RO[i].ID + ");' href='javascript:void(0);'>" + ro.RO[i].Name + "</a></td>";
                    }
                    str += "</tr></table>";
                    $("#div_csr_list").append(str);
                }
                else
                    $("#div_csr_list").append("<div style='padding:10px;text-align:center;font-weight:bold;font-family:Verdana;font-size:10pt;'>No sales person are available at the moment.<br />Please try again.</div>");

                if (ro.IN_CONV) {
                    ChangeWindowState((ro.IN_CONV == "1") ? 1 : 3);
                }
            }
          );
    xhr.MakeRequest();
}

function ClientShowChatWindow()
{
    ChangeWindowState(6);
    $("#dv_chat_win").show();
}

/*
    Window States
    1 = In Chat With CSR
    2 = In Chat With CSR and Request Information form displayed
    3 = Active CSR Display List
    4 = Minimize in blue mode
    5 = Minimize in yellow mode
    6 = Maximize
*/
function ChangeWindowState(pState)
{
    if (pState == 1)
    {
        $("#tr_csr_list").hide();
        $("#tr_chat_messages").show();
        $("#tbl_blue_min, #tbl_yellow_min").hide();
        $("#tbl_chat_win").show();
        //$("#div_chat_messages").css("height", "150px");
        $("#div_chat_messages").css("height", "130px");
        $("#tr_ri_form").hide();
        $("#tr_send_bar").show();
    }
    else if (pState == 2)
    {
        $("#tr_csr_list").hide();
        $("#tr_chat_messages").show();
        $("#tbl_blue_min, #tbl_yellow_min").hide();
        $("#tbl_chat_win").show();
        $("#div_chat_messages").css("height", ($.browser.msie ? 132 : 145) + "px");
        $("#tr_ri_form").show();
        $("#tr_send_bar").show();
    }
    else if (pState == 3)
    {
        $("#tr_csr_list").show();
        $("#tr_chat_messages").hide();
        $("#tr_ri_form").hide();
        $("#tr_send_bar").hide();
    }
    else if (pState == 4)
    {
        $("#tbl_blue_min").show();
        $("#tbl_yellow_min").hide();
        $("#tbl_chat_win").hide();
    }
    else if (pState == 5)
    {
        $("#tbl_blue_min").hide();
        $("#tbl_yellow_min").show();
        $("#tbl_chat_win").hide();
    }
    else if (pState == 6)
    {
        $("#tbl_blue_min").hide();
        $("#tbl_yellow_min").hide();
        $("#tbl_chat_win").show();

        SetCookie("WinMin", "0");
        UpdateChatWindowMinimizeState(0);
    }

    if (pState == 4 || pState == 5)
    {
        SetCookie("WinMin", "1");
        UpdateChatWindowMinimizeState(1);
    }
    
    PositionChatWin();
}

function PositionChatWin()
{
    var win = $(window);

    var chat_win_height = $("#dv_chat_win").height();
    var chat_win_width = $("#dv_chat_win").width();

    var top = (win.height() + win.scrollTop()) - chat_win_height - 4;
    var left = (win.width() + win.scrollLeft()) - chat_win_width - 4;

    top -= 170;

    setTimeout(function() { $("#dv_chat_win").css({ "top": top + "px", "left": left + "px" }); }, (arguments.length == 0 ? 100 : arguments[0]));
    //$("#dv_chat_win").animate({ "top": top + "px", "left": left + "px" }, "fast", "swing" );
}

function SetCookie(sName, sValue)
{
    document.cookie = sName + "=" + escape(sValue);
    var date = new Date();
    date.setMonth(date.getMonth() + 1);
    document.cookie += ("; expires=" + date.toUTCString());
}

function GetCookie(sName)
{
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++)
    {
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }
    return null;
}