﻿//// v 1.0

// ------------------------------------------------------------ UpdateChat

/*
 * action: "read", "add", "clear" - default value is "read"
 */
function UpdateChat(action)
{
    if (updateChatIntervalID != null)
        clearTimeout(updateChatIntervalID);

    actionInProgress = action;

    if (actionInProgress == null)
        actionInProgress = "read";

    var queryParameters;

    if (actionInProgress == "add")
    {
        $("#ChatSubmitButton").attr("disabled","disabled");   

        var name = $("#ChatNameInput").val();
        var msg = $("#ChatMsgTextArea").val();

        name = VisioTec.Utilities.Strings.htmlEncode(name);
        name = escape(name);
        msg = VisioTec.Utilities.Strings.htmlEncode(msg);
        msg = escape(msg);
        if ((msg == null) || (msg == ""))
        {
            alert("Inserisci un messaggio");
            queryParameters = "action=read";
        }
        else
        {
            queryParameters = "action=add&name=" + name + "&msg=" + msg;
        }
    }
    else if (actionInProgress == "read")
        queryParameters = "action=read";        
    else // if (actionInProgress == "clear")
        queryParameters = "action=clear";        

    $.ajax({
       type: "GET",
       url: "ChatService.aspx?" + queryParameters,
       dataType : "text",
       cache: false,
       success: function (data) 
            {
                $("#ChatBody").html(unescape(data));
                if (actionInProgress == "add") 
                {
                    $("#ChatMsgTextArea").val("")
                    $("#ChatSubmitButton").removeAttr("disabled");
                }

                updateChatIntervalID = setTimeout('UpdateChat()', 2000);
            },
       error: function (xmlHttpRequest, textStatus, errorThrown)
            {
                if (actionInProgress == "add")
                    $("#ChatSubmitButton").removeAttr("disabled");
                updateChatIntervalID = setTimeout('UpdateChat()', 2000);
            }
    });
}

var updateChatIntervalID = null;
var actionInProgressInProgress;

// ------------------------------------------------------------ Document Ready

$(document).ready(function()
{
    if ($("#ChatWrapper").length != 0)
        UpdateChat();
});
