// contains all methods to handle webchats.
function lvsysChat() 
{
    this.wsHeartbeatInterval = null;
    this.wsQueue = "";
    this.wsChat = "";
    this.bChatDeniedOffer = false;
    this.bChatOffered = false;

    this.formChatDialog = null;
    this.formChatDialogId = "";         // dialog to show.
    this.formChatDialogTableId = "";    // table output
    this.formChatDialogInputId = "";    // text input
    this.formChatDialogScrollId = "";

    this.formOfferDialog = null;   
    this.formOfferDialogId = "";

    // init the chat
    this.init = function(options) {
        if (this.wsQueue != '' ) {
            // don't initiate the chat when the queue has not been set by the engine
            this.wsHeartbeatInterval = setInterval("lvsysChat.wsHeartbeat()", 10 * 1000); // hearbeat every 10 seconds

            this.formChatDialogId = options['chatFormId'];          // dialog to show.
            this.formChatDialogTableId = options['chatTableId'];    // table output
            this.formChatDialogScrollId = options['chatScrollId'];  // html element to scroll
            this.formChatDialogInputId = options['chatInputId'];    // text input
            this.formOfferDialogId = options['offerFormId'];          // dialog to show.
        }
    }

    this.requestChat = function() {
        this.hangUp();  // close current chat if any
        this.bChatDeniedOffer = true;    // don't allow automatic web chats.
        // request & approve a chat, and pop chat form
        this.wsRequestChat();
    }

    this.accept = function() {
        if (this.formOfferDialog != null) {
            this.formOfferDialog.hide();
        }
        this.formOfferDialog = null;
        // approve chat, and pop chat form
        this.wsApproveChat();
        this.showChatDialog();
    }
    
    this.showChatDialog = function() {
        $("#" + this.formChatDialogTableId + ' > *').remove();
        $("#" + this.formChatDialogTableId).append("<tr><td colspan=\"2\" style=\"color: #ccc;\">An Agent will be with you shortly</td></tr>");
        this.formChatDialog = this.showForm(this.formChatDialogId);

        // reset interval to 5 seconds (faster refresh)
        clearInterval(this.wsHeartbeatInterval);
        this.wsHeartbeatInterval = setInterval("lvsysChat.wsHeartbeat()", 5 * 1000);
    }

    this.deny = function() {
        if (this.formOfferDialog != null) {
            this.formOfferDialog.hide();
        }
        this.formOfferDialog = null;
        this.bChatDeniedOffer = true;
        this.wsHangUpChat();
        // reset interval to 10 seconds.
        clearInterval(this.wsHeartbeatInterval);
        this.wsHeartbeatInterval = setInterval("lvsysChat.wsHeartbeat()", 10 * 1000); 
    }

    this.hangUp = function() {
        if (this.formChatDialog != null) {
            this.formChatDialog.hide();
        }
        this.formChatDialog = null;
        this.bChatDeniedOffer = true; // no more chats for this current page.
        this.wsHangUpChat();
        // reset interval to 10 seconds.
        clearInterval(this.wsHeartbeatInterval);
        this.wsHeartbeatInterval = setInterval("lvsysChat.wsHeartbeat()", 10 * 1000);
    }

    this.showForm = function(formId) {
        var dialog = new Boxy("#" + formId, { title: 'Online Web Chat', modal: true });
        var pos = dialog.getPosition();
        if (pos[1] < 50) {
            pos[1] = 50;
            dialog.moveTo(pos[0], pos[1]);
        }
        return dialog;
    }

    // send message to server
    this.postMessage = function() {
        var text = $("#" + this.formChatDialogInputId).val();
        $("#" + this.formChatDialogInputId).val("");
        this.printMessage("You", text);
        this.wsPostMessage(text);
    }

    this.recvMessage = function(from, text) {
        this.printMessage(from, text);
    }

    this.printMessage = function(from, text) {
        var style = "color: #ccc;";
        if (from != "You") {
            style = "color: #55F;";
        }
        var html = "<tr class='msg'><td valign='top' style='"+style+" width: 100px;'>" + from + ":</td><td valign='top'>" + text + "</td></tr>";
        $("#" + this.formChatDialogTableId).append(html);

        var objDiv = document.getElementById(this.formChatDialogScrollId);
        objDiv.scrollTop = objDiv.scrollHeight;
    }
       
    // maintain heartbeat with server
    this.wsHeartbeat = function() {
        $.post(
				'index.php',
 				{
 				    ws: '1',
 				    P1: 'Heartbeat',
 				    P2: lvsys.wsCS,
 				    P3: lvsysChat.wsChat,
 				    P4: lvsysChat.wsQueue,
 				    P5: ((lvsysChat.bChatDeniedOffer) ? '0' : '1')   // whether to allow chat offers
 				},
 				function(data, textStatus) {
 				    if (textStatus == 'success') {
 				        var xml = LoadXml(data);
 				        if (!lvsysChat.bChatDeniedOffer) {
 				            if (!lvsysChat.bChatOffered) {
 				                // get the chat session, if provided
 				                $(xml).find("chat").each(function() {
 				                    var text = $(this).text();
 				                    if (lvsysChat.wsChat == "" && lvsysChat.formOfferDialog == null) {
 				                        lvsysChat.formOfferDialog = lvsysChat.showForm(lvsysChat.formOfferDialogId);
 				                        lvsysChat.wsChat = $(this).text();
 				                        lvsysChat.bChatOffered = true;
 				                    }
 				                });
 				            }
 				         }
			            $(xml).find("message").each(function() {
			                var from = $(this).find("from").text();
			                var body = $(this).find("body").text();
			                lvsysChat.recvMessage(from, body);
			            });
 				    }
 				},
 				'text'
 			);

    }

    this.wsRequestChat = function() {
        $.post(
				'index.php',
 				{
 				    ws: '1',
 				    P1: 'RequestChat',
 				    P2: lvsys.wsCS,
 				    P3: lvsysChat.wsQueue
 				},
 				function(data, textStatus) {
 				    if (textStatus != 'success') {
 				        alert('your message could not be delivered. Please check your connection');
 				    } else {
 				        var xml = LoadXml(data);
 				        $(xml).find("error").each(function() {
 				            alert('Could not start a webchat, please try again later');
 				            return;
 				        });
 				        // store the chat session id
 				        lvsysChat.wsChat = '';
 				        $(xml).find("chat").each(function() {
 				            var text = $(this).text();
 				            lvsysChat.wsChat = $(this).text();
 				        });
 				        if (lvsysChat.wsChat == '') {
 				            alert('Could not start a webchat because chat center is closed, please try again later');
 				            return;
 				        }
 				        // chat accepted => wait for agent, unless we're already on
 				        lvsysChat.showChatDialog();
 				    }
 				},
 				'text'
 			);
    }

    
    // accept a webchat
    this.wsApproveChat = function() {
        $.post(
				'index.php',
 				{
 				    ws: '1',
 				    P1: 'ApproveChat',
 				    P2: lvsys.wsCS,
 				    P3: this.wsChat
 				},
 				function(data, textStatus) {
 				    if (textStatus != 'success') {
 				        alert('your message could not be delivered. Please check your connection');
 				    }
 				},
 				'text'
 			);
     }
     // accept a webchat
     this.wsHangUpChat = function() {
         if (this.wsChat != null && this.wsChat != '') {
             $.post(
			        'index.php',
			        {
			            ws: '1',
			            P1: 'HangUpChat',
			            P2: lvsys.wsCS,
			            P3: this.wsChat
			        },
			        function(data, textStatus) {
			            if (textStatus != 'success') {
			                alert('your message could not be delivered. Please check your connection');
			            }
			        },
			        'text'
		        );
         }
     }

    // post a chat message
    this.wsPostMessage = function(text) {
        $.post(
				'index.php',
 				{
 				    ws: '1',
 				    P1: 'PostMessage',
 				    P2: lvsys.wsCS,
 				    P3: this.wsChat,
 				    P4: text
 				},
 				function(data, textStatus) {
 				    if (textStatus != 'success') {
 				        alert('your message could not be delivered. Please check your connection');
 				    }
 				},
 				'text'
 			);
 	}

}

