﻿
var ChatPolling = false;
var LastChatCaller = null;
var ChatTimerIntervalID = null;


// global request and XML document objects
var reqChat;

function loadChatXMLDoc(url, func) {
    if (window.XMLHttpRequest) {
        reqChat = new XMLHttpRequest();
        reqChat.onreadystatechange = func;
        reqChat.open("GET", url, true);
        reqChat.send(null);
    } else if (window.ActiveXObject) {
        isIE = true;
        reqChat = new ActiveXObject("Microsoft.XMLHTTP");
        if (reqChat) {
            reqChat.onreadystatechange = func;
            reqChat.open("GET", url, true);
            reqChat.send();
        }
    }
}

function ChatAjaxUpdate(Caller, Message)
{ 
    if (Caller == null) return;
    if (Caller == "") return;
       
    var url = "/PageCode/Chat/Ajax.aspx?CallingControlName=" + Caller + "&Message=" + Message;
   
    loadChatXMLDoc(url, ChatAjaxCallBack);
}

function ChatAjaxCallBack()
{
    if (reqChat.readyState == 4) {
        // only if "OK"
        if (reqChat.status == 200) {
            ChatAjaxApply();
         } else {
            //alert("There was a problem retrieving the XML data:\n" + req.statusText);
         }
    }
    
    ChatPolling = false;
}

function ChatPoller()
{
    if (ChatPolling != false) return; // Don't overrun
    
    ChatPolling = true; // We're polling now
    
    ChatAjaxUpdate("poller", "");
}

function ChatStartPoller()
{
    if (ChatTimerIntervalID != null) clearInterval(ChatTimerIntervalID);
    
    setInterval("ChatPoller()", 10 * 1000); // Every 10 seconds 
}

function ChatAjaxApply()
{
    if (reqChat == null) return;
    if (reqChat.responseXML == null) return;
    
    var DocumentElement = reqChat.responseXML.documentElement;
    if (DocumentElement == null) return;
    if (DocumentElement.childNodes == null) return;
    
    for (var i = 0; i < DocumentElement.childNodes.length; i++)
    {
        var CurrentNode = DocumentElement.childNodes[i];
        if (CurrentNode.nodeName == "TargetControl")
        {
        }
    }
}

function ChatSend()
{
    var chatMessage = document.getElementById("chatMessage");
    if (chatMessage == null) return;
    
    var MessageToSend = chatMessage.value;
    if (MessageToSend == "") return;
    
    ChatAjaxUpdate("send", MessageToSend);
}

function ChatWindow(PolicyGUID)
{
      var windowtitle = 'Policy_' + PolicyGUID.replace(/-/g, '_');
      var windowurl = '/PageCode/Chat/Window.aspx?GUID=' + PolicyGUID;
      
      window.open(windowurl,windowtitle, 'width=400,height=305,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');

    return false; // Stop browser from following anchor tag 
}
