/**
 * @package JLive! Chat
 * @version 3.8.0
 * @copyright (C) Copyright 2008-2010 CMS Fruit, CMSFruit.com. All rights reserved.
 * @license GNU/LGPL http://www.gnu.org/licenses/lgpl-3.0.txt

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU Lesser General Public License as published by
 the Free Software Foundation; either version 3 of the License, or (at your
 option) any later version.

 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 License for more details.

 You should have received a copy of the GNU Lesser General Public License
 along with this program.  If not, see http://www.gnu.org/licenses/.
 */

var liveChatUri = 'index.php?option=com_livechat&view=popup&do_not_log=true&format=raw';
var liveChatWindow = null;

var processingSomething = false;
var chatIsOffline = false;

var chatSessionActive = 0;
var chatSessionMdate = 0;
var chatClientName = null;

var messageSentTxt = 'Message sent successfully!';

var refreshTimerDelay = 1.5; // in seconds

var operatorIsTyping = false;
var clientIsTyping = 0;
var typingTimeoutTimer = null;

var popupMode = false;
var closedPermanently = false;
var isMinimized = false;

function setPopupMode(newMode)
{
    popupMode = newMode;
}

function windowAlwaysOnTop()
{
    var body = $$('body');

    if(body)
    {
	body.setProperty('onblur', 'this.focus()');
    }
}

function attachCloseEvent()
{
    if(popupMode != 'iframe') {
	window.addListener('beforeunload', function(){
	    window.addListener('unload', endSession);
	    if (window.ie) window.addListener('unload', endSession);
	});
    }
}

function initName()
{
    var nameInput = $('name');

    nameInput.setStyle('width', '340px');
    nameInput.setStyle('padding', '5px 0 5px 3px');
    nameInput.setStyle('border', '1px solid #383C3F');
    nameInput.setStyle('float', 'left');
}

function initMessageName()
{
    var nameInput = $('message_name');

    nameInput.setStyle('width', '95%');
    nameInput.setStyle('padding', '3px 0 3px 4px');
    nameInput.setStyle('border', '1px solid #383C3F');
}

function initMessageEmail()
{
    var inputBox = $('message_email');

    inputBox.setStyle('width', '95%');
    inputBox.setStyle('padding', '3px 0 3px 4px');
    inputBox.setStyle('border', '1px solid #383C3F');
}

function initMessageTxt()
{
    var inputBox = $('message_text');

    inputBox.setStyle('width', '95%');
    inputBox.setStyle('height', '55px');
    inputBox.setStyle('padding', '3px 0 3px 4px');
    inputBox.setStyle('border', '1px solid #383C3F');
}

function initTxtInput()
{
    var inputBox = $('msg-input');

    inputBox.setStyle('width', '345px');
    inputBox.setStyle('height', '73px');
    inputBox.setStyle('padding', '0');
    inputBox.setStyle('border', '1px solid #383C3F');
    inputBox.setStyle('float', 'left');
    inputBox.setStyle('font-size', '13px');

    inputBox.addEvent('keydown', function (event) {	
	if(event.keyCode == 13)
	{
	    //	user pressed enter on the keyboard
	    sendMsg();
	}
	else
	{
	    clientIsTyping = 1;

	    if(typingTimeoutTimer)
	    {
		typingTimeoutTimer = $clear(typingTimeoutTimer);
	    }

	    var typingTimeoutFunc = function() {
		clientIsTyping = 0;
	    };

	    typingTimeoutTimer = typingTimeoutFunc.delay(1100);
	}
    });
}

function requestLiveChat(popupUri, mode)
{
    var livechatFrame = document.getElementById('livechat_iframe');
    
    if(!mode) {
	if(livechatFrame) {
	    livechatFrame.parentNode.removeChild(livechatFrame);
	    window.parent.closedPermanently = true;
	}

	var w = 480, h = 340;

	if(screen.availWidth && screen.availHeight) {
	    w = screen.availWidth;
	    h = screen.availHeight;
	}

	var popW = 480;
	var popH = 400;

	if(window.webkit) {
	    // Safari popup window should be about 10px more
	    popW = 490;
	    popH = 410;
	}

	var leftPos = (w-popW)/2, topPos = (h-popH)/2;

	liveChatWindow = window.open(popupUri,'LiveChatWindow','menubar=0,scrollbars=0,status=1,resizable=0,location=0,toolbar=0,height='+popH+',width='+popW+',left='+leftPos+',top='+topPos);

	if (window.focus && liveChatWindow) {
	    liveChatWindow.focus();
	}
    } else if(mode=='iframe' && !livechatFrame && !closedPermanently) {
	var popW = 484;
	var popH = 404;

	var body = document.getElementsByTagName('body').item(0);

	var iframeObj = null;
	iframeObj = document.createElement('iframe');
	iframeObj.src = popupUri;
	iframeObj.id = 'livechat_iframe';
	iframeObj.width=popW;
	iframeObj.height=popH;
	iframeObj.frameborder=0;
	iframeObj.scrolling='no';
	iframeObj.allowautotransparency=true;
	iframeObj.style.overflow='hidden';
	iframeObj.style.display='block';
	iframeObj.style.zIndex=10000;
	iframeObj.style.bottom=0;
	iframeObj.style.right=0;
	iframeObj.style.border='none';

	body.appendChild(iframeObj);
    }
    
    return false;
}

function initChatSession()
{
    if(processingSomething == false)
    {
        processingSomething = true;

	var connectingLayer = $('connecting-wrapper');
	var errorLayer = $('connecting-error-wrapper');

	connectingLayer.setStyle('display', 'block');
	errorLayer.setStyle('display', 'none');

        var options = {
            method: 'post',
            onSuccess: function(response) {
                var data = Json.evaluate(response);
		
		processingSomething = false;

                if(data.success == 0)
                {
		    var errorTxtContainer = errorLayer.getElement('span');
		    
		    connectingLayer.setStyle('display', 'none');
		    errorLayer.setStyle('display', 'block');

                    $each(data.errors, function (item, index) {
                        errorTxtContainer.setText(item);
                    });
                }
                else
                {
                    //	Waiting for Operator Response
                    chatClientName = $('name').getProperty('value');

                    connectingLayer.setStyle('display', 'block');
		    errorLayer.setStyle('display', 'none');
		    
                    checkIfChatAccepted();
                }
            },
            headers: {
                'X-Request': 'JSON'
            }
        };

	var handlerUri = liveChatUri+'&task=start_session&t='+$time();

	var uriVars = 'name='+URLEncode($('name').getProperty('value'));

	var specificRoute = $('specific-route');
	var specificOperator = $('specific-operators');

	if(specificOperator)
	{
	    if(specificOperator.getProperty('value'))
	    {
		uriVars += '&operator='+URLEncode(specificOperator.getProperty('value'));
	    }
	}

	if(specificRoute)
	{
	    if(specificRoute.getProperty('value'))
	    {
		uriVars += '&routeid='+URLEncode(specificRoute.getProperty('value'));
	    }
	}
	
        var myXhr = new XHR(options).send(handlerUri, uriVars);
    }

    return false;
}

function chatAccepted()
{
    attachCloseEvent();

    $('pre-chat-window').setStyle('display', 'none');
    $('in-chat-window').setStyle('display', 'block');

    refreshSession();
}

function checkIfChatAccepted()
{
    var options = {
        method: 'post',
        onSuccess: function(response) {
            var data = Json.evaluate(response);
	    
            chatSessionActive = data.is_active;
	    
            if(chatSessionActive == 1)
            {
                // Chat Accepted
                chatAccepted();
            }
            else if(data.is_offline == 1)
            {
                // Chat is offline
		chatOffline();
            }
	    else
	    {
		setTimeout('checkIfChatAccepted()', 2000);
	    }
        },
        headers: {
            'X-Request': 'JSON'
        }
    };
    
    var uriVars = 'task=check_session_active&t='+$time();

    var specificRoute = $('specific-route');
    var specificOperator = $('specific-operators');

    if(specificOperator)
    {
	if(specificOperator.getProperty('value'))
	{
	    uriVars += '&operator='+URLEncode(specificOperator.getProperty('value'));
	}
    }

    if(specificRoute)
    {
	if(specificRoute.getProperty('value'))
	{
	    uriVars += '&routeid='+URLEncode(specificRoute.getProperty('value'));
	}
    }

    var myXhr = new XHR(options).send(liveChatUri, uriVars);
}

function refreshSession()
{
    var options = {
        method: 'get',
        onSuccess: function(response) {
            var data = Json.evaluate(response);

	    chatSessionActive = data.is_active;

            if(chatSessionMdate != data.mdate)
            {
		if(popupMode == 'iframe') {
		    // Check if minimized, if so, restore
		    if(isMinimized) {
			restoreWindowSize();
		    }
		} else {
		    // Popup mode, ensure iframe is not open at the same time
		    var parentWnd = window.opener;

		    if(parentWnd) {
			try {
			    var popupIframe = parentWnd.document.getElementById('livechat_iframe');

			    if(popupIframe) {
				popupIframe.parentNode.removeChild(popupIframe);
			    }
			} catch(err) {
			    // We must be using in Ultimate Live Chat mode
			    
			}
		    }
		}

		if(parseInt(data.session_data.is_operator_typing) == 0)
		{
		    //	Operator is not typing
		    $('status-display').setStyle('display', 'none');
		}
		else
		{
		    //	Operator is typing
		    $('status-display').setStyle('display', 'block');
		}

                var sessionTxt = '';
                var lineColor = null;
                var a = 0;

		var reExcludePattern = new RegExp('(^[^:]+[\.]{3}$)');

                $each(data.session_lines, function (item, index) {
		    if(!reExcludePattern.test(item)) {
			sessionTxt += item+"\n";
		    }

                    a += 1;
                });

                $('session-content-display').setHTML(sessionTxt);

                chatSessionMdate = data.mdate;

		// Make popup window flash in the task bar
		if(clientIsTyping == 0)
		{
		    window.focus();
		    
		    $('msg-input').focus();
		}
		
                // Keep scroll position at the bottom
                $('session-content-display').scrollTop = $('session-content-display').scrollHeight - $('session-content-display').clientHeight;
            }
	    
	    if(chatSessionActive == 1)
            {
		var refreshDelay = 1000*refreshTimerDelay;
		
                setTimeout('refreshSession()', refreshDelay);
            }
	    else
	    {
		var inputBox = $('msg-input');

		inputBox.setProperty('disabled', true);
	    }
        },
        headers: {
            'X-Request': 'JSON',
	    'Connection': 'Keep-Alive'
        }
    };

    var handlerUri = liveChatUri+'&task=refresh_session&t='+$time();

    var uriVars = 'client_is_typing='+clientIsTyping;

    if(popupMode) {
	uriVars += '&mode='+popupMode;
    }
    
    var myXhr = new XHR(options).send(handlerUri, uriVars);
}

function chatOffline()
{
    if(chatIsOffline == false)
    {
	chatIsOffline = true;

	$('pre-chat-window').setStyle('display', 'none');
	$('in-chat-window').setStyle('display', 'none');
	$('offline-window').setStyle('display', 'block');
    }
}

function closeWindow()
{
    if(popupMode != 'iframe') {
	if(chatSessionActive == 1) {
	    endSession();
	    window.close();
	} else {
	    window.close();
	}
    } else if(popupMode == 'iframe') {
	window.parent.closedPermanently = true;
	
	var popupIframe = window.parent.document.getElementById('livechat_iframe');

	if(popupIframe) {
	    popupIframe.parentNode.removeChild(popupIframe);
	}
    }
}

function restoreWindowSize()
{
    if(popupMode == 'iframe') {
	var popupIframe = $(window.parent.document.getElementById('livechat_iframe'));

	if(popupIframe) {
	    $('restore-window-button').addClass('hide');
	    
	    $('minimize-window-button').setStyle('display', 'inline-block');

	    popupIframe.removeClass('minimized');

	    isMinimized = false;
	}
    }
}

function minimizeWindowSize()
{
    if(popupMode == 'iframe') {
	var popupIframe = $(window.parent.document.getElementById('livechat_iframe'));

	if(popupIframe) {
	    $('restore-window-button').removeClass('hide');
	    
	    $('restore-window-button').setStyle('display', 'inline-block');
	    $('minimize-window-button').setStyle('display', 'none');
	    
	    popupIframe.addClass('minimized');

	    isMinimized = true;
	}
    }
}

function endSession()
{
    var options = {
	method: 'get',
	async: false
    };

    var uriVars = 'task=end_session&t='+$time();

    var myXhr = new XHR(options).send(liveChatUri, uriVars);
}

function sendMsg(msg)
{
    var resetInput = false;
    
    if(!msg) {
	resetInput = true;
	
	var sendTxt = $('msg-input').getValue();
    }

    var options = {
        method: 'post',
        onSuccess: function(response) {
            //	Clear Box
            clientIsTyping = 0;

	    if(resetInput) {
		$('msg-input').setProperty('value', '');
	    }
        }
    };

    var handlerUri = liveChatUri+'&task=send_message&t='+$time();

    var uriVars = 'm='+URLEncode(sendTxt);

    if(chatClientName) {
	if(chatClientName.length > 0) {
	    // There is a chat client name
	    uriVars += '&n='+URLEncode(chatClientName);
	} else {
	    uriVars += '&n=Guest';
	}
    } else {
	uriVars += '&n=Guest';
    }

    var myXhr = new XHR(options).send(handlerUri, uriVars);
}

function leaveMessage()
{
    if(processingSomething == false)
    {
        processingSomething = true;

	var messageName = $('message_name');
	var messageEmail = $('message_email');
	var messageTxt = $('message_text');
	var specificOperators = $('specific-operators');
	
	var options = {
	    method: 'post',
	    onSuccess: function(response) {
		processingSomething = false;

		var data = Json.evaluate(response);

		if(parseInt(data['success']) == 0)
		{
		    //  Request Failed
		    var errorMsg = '';

		    $each(data['msg'], function(msg, index) {
			errorMsg += msg+"\n";
		    });

		    alert(errorMsg);
		}
		else
		{
		    //  Message left successfully
		    alert(messageSentTxt);

		    closeWindow();
		}
	    },
	    headers: {
		'X-Request': 'JSON'
	    }
	};

	var handlerUri = liveChatUri+'&task=leave_message&t='+$time();

	var uriVars = 'name='+URLEncode(messageName.getValue())+'&email='+URLEncode(messageEmail.getValue())+'&msg='+URLEncode(messageTxt.getValue());

	if(specificOperators)
	{
	    if(specificOperators.getValue().length > 0)
	    {
		uriVars += '&operator='+URLEncode(specificOperators.getValue());
	    }
	}

	var myXhr = new XHR(options).send(handlerUri, uriVars);
    }

    return false;
}

function URLEncode( str ) {       
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

