// constants
var SLEEP_TIME = 4000;  // every four seconds
var STILL_ON_PAGE = '/stillOnPage.do';
var SEND_MESSAGE = '/sendMessage.do';
var LIVE_HELP_CHAT_URL = '/liveHelpChat.do';
var PARAM_P3_URL = 'url';
var PARAM_SESSION_ID = 'si';
var PARAM_URL = 'ur';
var PARAM_LIVE_HELP_REQUEST = 'lh';
var PARAM_LIVE_HELP_VISITOR_NAME = 'vn';
var PARAM_LIVE_HELP_CHAT_ID = 'ci';
var PARAM_LIVE_HELP_MESSAGE = 'ms';
var PARAM_TIME = 'da';
var AMPERSAND_SUBSTITUTE = '::'
var POUND_SUBSTITUTE = ':num:'

// page variables
var recorderSite;
var protocol;
var sessionId;
var p3;
var liveHelpImage;
var liveHelpAnchor;
var communicationImage;
var unavailableImage;
var availableImage;
var chatId;
var email;

// chat window
var chatPopup = new PopupWindow();
chatPopup.offsetX = 20;
chatPopup.offsetY = 20;
chatPopup.setSize(550, 400);

// invite window variables
var documentWidth;
var documentHeight;
if(document.body && document.body.clientWidth)
{
	documentWidth = document.body.clientWidth;
	documentHeight = document.body.clientHeight;
}
else if(window.outerWidth)
{
	documentWidth = window.outerWidth;
	documentHeight = window.outerHeight;
}
else
{
	documentWidth = 800;
	documentHeight = 600;
}
var inviteXPos = 0;
var inviteYPos = 200;
var inviteXPosIncrement = 1;
var inviteXPosIncrementBackup;
var moveInviteWindowEvery = 50;
var inviteWidth = 200;
var inviteHeight = 100;
var inviteDivName = 'inviteDiv';

/**
 * Displays live help button.
 *
 * @param recorderSiteParam the Extensive Web Stats recorder site (e.g. a.recorder.extensivewebstats.com)
 * @param sessionIdParam a unique string identifying the current user's session
 * @param unavailableImageSrc the path to the image you wish to use to show that live help is unavailable
 * @param availableImageSrc the path to the image you wish to use to show that live help is available
 * @param p3Param true if called by a p3 site
 */
function displayLiveHelp(recorderSiteParam, sessionIdParam, unavailableImageSrc, availableImageSrc, emailParam, p3Param)
{
	// initialize page scope variables
	recorderSite = recorderSiteParam;
	sessionId = sessionIdParam;
	p3 = p3Param;
	email = emailParam;
	if(document.URL.indexOf('https') >= 0 && false) // todo: remove false when recorder gets cert
		protocol = 'https://';
	else
		protocol = 'http://';
	unavailableImage = new Image();
	unavailableImage.src = unavailableImageSrc;
	availableImage = new Image();
	availableImage.src = availableImageSrc;
	document.write('<a href="#" id="liveHelpAnchor"><img id="availability" src="" border="0" alt="Checking live help..."/></a>');
	document.write('<div id="'+inviteDivName+'" style="position: absolute;left: '+inviteXPos+';top: '+inviteYPos+';visibility: hidden;z-index: 999">&nbsp;('+inviteXPos+','+inviteYPos+')</div>');
	liveHelpImage = document.getElementById('availability');
	liveHelpAnchor = document.getElementById('liveHelpAnchor');
	communicationImage = new Image();
	communicationImage.onload = responseReceived;
	communicationImage.onerror = responseReceived;

	// send first live help request
	sendRequest();
}

function responseReceived()
{
	if(typeof communicationImage != 'undefined' && communicationImage != null && communicationImage.height != null)
	{
		if(communicationImage.height == 2)
		{
			setAvailable();
		}
		else if(communicationImage.height == 3)
		{
			setAvailable();
			adminInitiatedChat();
		}
		else
		{
			setUnavailable();
		}
		// schedule another request
		window.setTimeout('sendRequest()', SLEEP_TIME);
	}
	else
	{
		setUnavailable();
	}
}

function visitorInitiatedChat()
{
	openChatWindow();
}

function adminInitiatedChat()
{
	openInviteWindow();
}

function setAvailable()
{
	liveHelpImage.src = availableImage.src;
	liveHelpImage.alt = 'Live Help Available';
	liveHelpImage.title = 'Live Help Available';
	liveHelpAnchor.href = 'javascript:visitorInitiatedChat()';
}

function setUnavailable()
{
	liveHelpImage.src = unavailableImage.src;
	liveHelpImage.alt = 'Live Help Unavailable';
	liveHelpImage.title = 'Live Help Unavailable';
	liveHelpAnchor.href = 'mailto:' + email;
}

function sendRequest(request)
{
	var params = getParams();
	if(request != null)
		params = params + '&' + PARAM_LIVE_HELP_REQUEST + '=' + request;
	if(p3)
	{
		params = params + '&' + PARAM_P3_URL + '=' + recorderSite ;
		communicationImage.src = STILL_ON_PAGE + '?' + params;
	}
	else
		communicationImage.src = protocol + recorderSite + STILL_ON_PAGE + '?' + params;
}

function getParams()
{
	var params = PARAM_URL + '=' + runSubstitutions(document.URL);
	params = params + '&' + PARAM_TIME + '=' + new Date().getTime();
	if(sessionId != null)
		params = params + '&' + PARAM_SESSION_ID + '=' + sessionId;
	return params;
}

function runSubstitutions(string)
{
	while(string.indexOf('&') >= 0)
		string = string.replace('&', AMPERSAND_SUBSTITUTE);
	while(string.indexOf('#') >= 0)
		string = string.replace('#', POUND_SUBSTITUTE);
	return string;
}

function getChatUrl(init)
{
	var params = getParams();
	var message = getMessageText();
	if(init)
		params = params + '&' + PARAM_LIVE_HELP_CHAT_ID + '=-1';
	else if(chatId != null)
		params = params + '&' + PARAM_LIVE_HELP_CHAT_ID + '=' + chatId;
	if(message != null)
		params = params + '&' + PARAM_LIVE_HELP_MESSAGE + '=' + escape(message);
	if(p3)
	{
		params = params + '&' + PARAM_P3_URL + '=' + recorderSite ;
		chatUrl = LIVE_HELP_CHAT_URL;
	}
	else
		chatUrl = protocol + recorderSite + LIVE_HELP_CHAT_URL;
	return chatUrl + '?' + params + '#bottom';
}

function openChatWindow()
{
	var chatHtml = '<html><head><title>Live Help';
	chatHtml = chatHtml + '</title><link rel="stylesheet" type="text/css" href="/liveHelp.css"/>';
	chatHtml = chatHtml + '<base target="_parent"/></head>';
	chatHtml = chatHtml + '<body class="live-help-bg" onload="document.getElementById(\'messageText\').focus();">';
	chatHtml = chatHtml + '<table width="100%">';
	chatHtml = chatHtml + '	<tr>';
	chatHtml = chatHtml + '		<td>';
	chatHtml = chatHtml + '			Your Name: <input type="text" id="visitorName" style="width:350px" value="Visitor"></textarea>';
	chatHtml = chatHtml + '		</td>';
	chatHtml = chatHtml + '	</tr>';
	chatHtml = chatHtml + '	<tr>';
	chatHtml = chatHtml + '		<td>';
	chatHtml = chatHtml + '			<iframe style="display:inline;width:450px;height:250px;" name="chatFrame" id="chatFrame" onload="window.opener.chatFrameLoaded()" src="'+getChatUrl(true)+'"></iframe>';
	chatHtml = chatHtml + '		</td>';
	chatHtml = chatHtml + '	</tr>';
	chatHtml = chatHtml + '	<tr>';
	chatHtml = chatHtml + '		<td>';
	chatHtml = chatHtml + '			<textarea id="messageText" onkeyup="window.opener.messageKeyUp()" disabled="true" style="height:50px; width:450px"></textarea>';
	chatHtml = chatHtml + '		</td>';
	chatHtml = chatHtml + '	</tr>';
	chatHtml = chatHtml + '	<tr>';
	chatHtml = chatHtml + '		<td class="powered-by-extensive">';
	chatHtml = chatHtml + '		Powered By <a href="http://www.extensivewebstats.com" target="_blank">Extensive Live Help</a>';
	chatHtml = chatHtml + '		</td>';
	chatHtml = chatHtml + '	</tr>';
	chatHtml = chatHtml + '</table>';
	chatHtml = chatHtml + '<div class="center"><a href="javascript:window.opener.closeChatWindow()">Close Chat Window</a></div>';
	chatHtml = chatHtml + '</body></html>';

	chatId = null;
	chatPopup.populate(chatHtml);
	chatPopup.showPopup('liveHelpAnchor');
}

function closeChatWindow()
{
	chatPopup.hidePopup();
	chatId = null;
}

function openInviteWindow()
{
	if(!isInviteShowing())
	{
		var inviteHtml = '<div class="invite" onmouseover="pauseInviteWindow()" onmouseout="resumeInviteWindow()">';
		inviteHtml = inviteHtml + '<table>';
		inviteHtml = inviteHtml + '	<tr>';
		inviteHtml = inviteHtml + '		<td colspan="2">';
		inviteHtml = inviteHtml + '			A customer service agent would like to chat<br/>';
		inviteHtml = inviteHtml + '			with you.  Will you accept the invitation?';
		inviteHtml = inviteHtml + '		</td>';
		inviteHtml = inviteHtml + '	</tr>';
		inviteHtml = inviteHtml + '	<tr>';
		inviteHtml = inviteHtml + '		<td class="center">';
		inviteHtml = inviteHtml + '			<a href="javascript:acceptInvitation()">Accept</a>';
		inviteHtml = inviteHtml + '		</td>';
		inviteHtml = inviteHtml + '		<td class="center">';
		inviteHtml = inviteHtml + '			<a href="javascript:declineInvitation()">Decline</a>';
		inviteHtml = inviteHtml + '		</td>';
		inviteHtml = inviteHtml + '	</tr>';
		inviteHtml = inviteHtml + '</table>';
		inviteHtml = inviteHtml + '</div>';

		var inviteDiv = document.getElementById(inviteDivName);
		inviteDiv.innerHTML = inviteHtml;

		getInviteWindowStyle().visibility = 'visible';
		positionInviteWindow();
		moveInviteWindow(true);
	}
}

function getInviteWindowStyle()
{
	return getStyleObject(inviteDivName);
}


function getStyleObject(objectId)
{
	// cross-browser function to get an object's style object given its id
	if(document.getElementById && document.getElementById(objectId))
	{
		// W3C DOM
		return document.getElementById(objectId).style;
	}
	else if (document.all && document.all(objectId))
	{
		// MSIE 4 DOM
		return document.all(objectId).style;
	}
	else if (document.layers && document.layers[objectId])
	{
		// NN 4 DOM.. note: this won't find nested layers
		return document.layers[objectId];
	}
	else
	{
		return false;
	}
}

function closeInviteWindow()
{
	getInviteWindowStyle().visibility = 'hidden';
}

function isInviteShowing()
{
	return getInviteWindowStyle().visibility == 'visible';
}

function positionInviteWindow()
{
	if(isInviteShowing())
	{
		var topOfPage;
		if(document.body.scrollTop)
			topOfPage = document.body.scrollTop;
		else if(window.pageYOffset)
			topOfPage = window.pageYOffset;
		else
			topOfPage = 0;

		var inviteStyle = getInviteWindowStyle();
	  if (document.layers)
	  {
			inviteStyle.left = inviteXPos;
			inviteStyle.top = topOfPage + inviteYPos;
		}
		else
		{
			inviteStyle.left = inviteXPos + 'px';
			inviteStyle.top = (topOfPage + inviteYPos) + 'px';
		}
	}
}

function pauseInviteWindow()
{
	inviteXPosIncrementBackup = inviteXPosIncrement;
	inviteXPosIncrement = 0;
}

function resumeInviteWindow()
{
	inviteXPosIncrement = inviteXPosIncrementBackup;
}

function moveInviteWindow(firstTime)
{
	if(firstTime)
	{
		if(inviteXPosIncrement < 0)
			inviteXPosIncrement = inviteXPosIncrement * -1;
		inviteXPos = 0;
	}
	if(isInviteShowing())
	{
		if((inviteXPos + inviteWidth > documentWidth && inviteXPosIncrement > 0) ||
		   (inviteXPos == 0 && inviteXPosIncrement < 0))
	  {
			inviteXPosIncrement = inviteXPosIncrement * -1;
		}
		inviteXPos = inviteXPos + inviteXPosIncrement;

		positionInviteWindow();
		window.setTimeout('moveInviteWindow()', moveInviteWindowEvery);
	}
}

function acceptInvitation()
{
	closeInviteWindow();
	visitorInitiatedChat();
}

function declineInvitation()
{
	closeInviteWindow();
	submitMessage(null);  // sending a null message declines a chat invitation
}

function messageKeyUp()
{
	var message = getMessageText();
	if(message != null && message.length > 0)
	{
		var indexOfCr = -1;
		indexOfCr = message.indexOf('\r\n'); // Windows encodes CR's as \r\n hex
		if(indexOfCr < 0)
			indexOfCr = message.indexOf('\n'); // Unix encodes CR's as \n hex
		if(indexOfCr < 0)
			indexOfCr = message.indexOf('\r'); // Macintosh encodes CR's as \r hex

		if(indexOfCr >= 0)
		{
			var messageToSend = message.substring(0, indexOfCr);
			if(messageToSend.length > 0)
				submitMessage(messageToSend, getVisitorName());
			clearMessage();
		}
	}
}

function submitMessage(message, visitorName)
{
	var params = getParams();
	if(message != null)
	{
		params = params + '&' + PARAM_LIVE_HELP_MESSAGE + '=' + escape(message);
		if(visitorName != null)
			params = params + '&' + PARAM_LIVE_HELP_VISITOR_NAME + '=' + escape(visitorName);
		if(chatId != null)
			params = params + '&' + PARAM_LIVE_HELP_CHAT_ID + '=' + chatId;
	}
	var url;
	if(p3)
	{
		params = params + '&' + PARAM_P3_URL + '=' + recorderSite ;
		url = SEND_MESSAGE;
	}
	else
		url = protocol + recorderSite + SEND_MESSAGE;
	var tempImage = new Image();
	tempImage.src = url + '?' + params;
}

function getMessageTextArea()
{
	if(chatPopup != null && chatPopup.popupWindow != null && chatPopup.popupWindow.document != null)
		return chatPopup.popupWindow.document.getElementById('messageText');
	else
		return null;
}

function getVisitorName()
{
	if(chatPopup != null && chatPopup.popupWindow != null && chatPopup.popupWindow.document != null)
	{
		var visitorNameField = chatPopup.popupWindow.document.getElementById('visitorName');
		if(visitorNameField != null)
			return visitorNameField.value;
	}
	return null;
}

function getChatFrame()
{
	if(chatPopup != null && chatPopup.popupWindow != null && chatPopup.popupWindow.document != null)
		return chatPopup.popupWindow.document.getElementById('chatFrame');
	else
		return null;
}

function clearMessage()
{
	var textArea = getMessageTextArea();
	if(textArea != null)
		return textArea.value = '';
}

function getMessageText()
{
	var textArea = getMessageTextArea();
	if(textArea != null)
		return textArea.value;
	else
		return null;
}

function chatFrameLoaded()
{
	var chatFrameDocument = getFrameDocument(getChatFrame());
	var chatIdInput = chatFrameDocument.getElementById('chatId');
	if(chatIdInput != null)
	{
		chatId = chatIdInput.value;
		getMessageTextArea().disabled = false;
	}
	var endOfChat = chatFrameDocument.getElementById('endOfChat');
	if(endOfChat == null)
	{
		// schedule another load
		window.setTimeout('refreshChatFrame()', SLEEP_TIME);
	}
	else
	{
		getMessageTextArea().disabled = true;
	}
}

function getFrameDocument(frame)
{
	if (typeof frame != 'undefined' && frame != null)
	{
		if (frame.contentDocument)
			return frame.contentDocument;
		else if (frame.contentWindow)
			return frame.contentWindow.document;
		else if (frame.document)
			return frame.document;
		else
			return null;
	}
}

function refreshChatFrame()
{
	var chatFrame = getChatFrame();
	if(chatFrame != null)
		chatFrame.src = getChatUrl();
	chatFrame.scrollTop = 99999;
}