﻿
function validateText(e)
{
    var arr = [16, 13, 8, 39, 37, 38, 40, 36, 35, 186, 188, 189, 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)
{
    $.get(server_location, { "SID": SID, "WIN_STATE": isMinimized });
}

function UpdateWritingStatus(status)
{
    $.get(server_location, { "SID": SID, "STATUS": status });
}

function SendMessage()
{
    var msg = (arguments.length == 0 ? document.getElementById("tar").value : arguments[0]);
    //AppendMessage(msg, yourName, 0, true);
    //AdjustLastMessage();
    if (msg != "")
    {
        $.getJSON(server_location, { "RT": 1, "SID": SID, "LCMID": lcmid, "MSG": msg }, function (json) { AppendROFromServer(json); });
        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>");
    $.getJSON(server_location, { "VRC": 1, "SID": SID, "SPID": pSalesPersonID }, function (json) { AppendROFromServer(json); SetCookie("WinMin", "0"); });
}

function AppendMessage(msg, from, sender, isBlank)
{
    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 isBlank='" + (isBlank ? 1 : 0) + "' style='color:" + (sender == 1 ? "#0005C6" : "#000") + ";'><td valign='top'><img style='margin-right:4px;' src='/NewChatModule/img/guy" + (sender == 0 ? "side" : "") + ".jpg'></td><td>" + (sender == 1 ? from.bold() : "<b style='color:#C90200;'>You</b>") + " : " + msg + "<td></tr>");
    if (!isBlank)
        $("#tbl_messages tr[isBlank=1]").remove();
}

function AdjustLastMessage()
{
    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)
    {
        $("#div_chat_messages table").empty();
        for (var i = 0; i < ro.MSGS.length; i++)
        {
            if (ro.MSGS[i] != null && ro.MSGS[i].MSG && ro.MSGS[i].S)
                AppendMessage(ro.MSGS[i].MSG, (ro.CSRName ? ro.CSRName : "CSR"), ro.MSGS[i].S, false);
        }

        lcmid = ro.LCMID;

        try {
            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].S == 1 ? ro.CSRName : "You"));
            //ToggleRequestInfoForm(ro.CIR, WinMin);
        } catch (exp) { }

        if ($("#dv_chat_win").css("display") == "none")
        {
            $("#dv_chat_win").show();
            PositionChatWin(0);
        }
    }

    if (ro.CIR != "undefined" && ro.CIR != null && ro.SPID != "undefined" && ro.SPID != null && ro.SPID > 0) {
        try {
            ToggleRequestInfoForm(ro.CIR, WinMin);
        } catch (exp) { }
    }

    AdjustLastMessage();
}

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", "130px");
            $("#tr_ri_form").hide();
        }
        else
            ChangeWindowState(1);
    }
}

function ToggleMinimizedHeader(pWinMin, isNewMessageFromCSR, message, from)
{
    if (pWinMin != null && pWinMin == "1")
    {
        if (isNewMessageFromCSR)
        {
            ChangeWindowState(5);
            var msg_trimmed = (message.length > 60 ? message.substr(0, 60) + " ..." : message);
            $("#span_csr_message").html("<span style='font-weight:bold;color:White'>" + from + "</span> : " + msg_trimmed);
            $("#span_csr_message").parent().attr("title", message);
        }
        else
            ChangeWindowState(4);
    }
}

function PollServer()
{
    try 
    {
        $.getJSON(server_location, { "RT": 3, "SID": SID, "LCMID": lcmid }, function (json) { AppendROFromServer(json); });
    }
    catch (exp) { }
}

function GetAvailableSalesPersons()
{
    $.getJSON(server_location, { "GASPL": "1", "SID" : SID },
        function (json) 
        {
            if (json.RO && json.RO.length && json.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 < json.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_" + json.RO[i].Name + ".jpg' style='width:30px;height:35px;padding:2px;' /><a style='color:blue;padding-left:2px;' onclick='RequestChatWithSalesPerson(" + json.RO[i].ID + ");' href='javascript:void(0);'>" + json.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 (json.IN_CONV != null) {
                ChangeWindowState((json.IN_CONV == "1") ? 1 : 3);
            }
        }
    );
}

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", "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;
}

function ClientShowChatWindow() {
    ChangeWindowState(6);
    $("#dv_chat_win").show();
}
