//  //

/*
 * GLOBAL TRY-CATCH
 */
try {
/*
 * GLOBAL TRY-CATCH
 */

//  //

//  //
document.write('<link rel="stylesheet" type="text/css" href="/saleschat/chat.css.php">');

var Chat = {
	// CONFIG BEGIN
	'pollInterval'  : 1, // in seconds
	'cookieName'    : 'sInteractiveChat',
	'cookieExp'     : 365, // in days
	'debug'         : 0,
	'divTopOffset'  : 150,
	// CONFIG END

	'lastSeq'       : 0,
	'token'         : '',
	'textBox'       : null,
	'textContainer' : null,
	'mainWindow'    : null,
	'typeCnt'       : 0,
	'loopPoll'      : 1,
	'sendQueue'     : [],
	'eventQueue'    : [],
	'divObj'        : null,
	'divUpdateTimer': null,

	/* COOKIE HANDLING FUNCTIONS */

	'setCookie' : function(c_name, value, expiredays) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie = c_name + '=' + escape(value) +
			((expiredays == null) ? '' : ';expires=' + exdate.toGMTString());
	},

	'getCookie' : function(c_name) {
		if (document.cookie.length > 0) {
			c_start = document.cookie.indexOf(c_name + '=');
			if (c_start != -1) { 
				c_start = c_start + c_name.length + 1; 
				c_end = document.cookie.indexOf(';', c_start);
				if (c_end == -1) c_end = document.cookie.length;
				return unescape(document.cookie.substring(c_start, c_end));
			}
		}
		return '';
	},

	'getToken' : function() {
		var req_done = 0;

		Chat.token = Chat.getCookie(Chat.cookieName);
		if (Chat.token == '') { // we have no token, request one
			new Ajax.Request(
				'/saleschat/rpc_token.php',
				{
					method: 'post',
					evalJSON: 'true',
					onSuccess: function(transport) {
						if (!transport.responseJSON || !transport.responseJSON['token']) {
							if (Chat.debug) alert('rpc_token.php: success but no JSON obj');
						} else {
							Chat.setCookie(Chat.cookieName, transport.responseJSON['token'], Chat.cookieExp);
							// now user needs to visit another page or refresh this page, so that the
							// new cookie takes effect;
							// the user cannot use the chat from the very first page visit
							Chat.token = transport.responseJSON['token'];
							Chat.initiate();
						}
					},
					onFailure: function(transport) {
						if (Chat.debug) alert('rpc_token.php: AJAX request failed.');
					}
				}
			); // new Ajax.Request
		} else {
			Chat.initiate();
		}
	},

	/* MAIN CHAT FUNCTIONS */

	'createDiv' : function(id, html, visible, width, height) {
		var newdiv = document.createElement('div');
		Element.extend(newdiv);
		newdiv.setAttribute('id', id);
	
		if (width) {
			newdiv.setStyle({
				width: width
			});
		}
		if (height) {
			newdiv.setStyle({
				height: height
			});
		}
		if (!html) {
			html = 'empty';
		}

		if (visible) {
			visible = 'block';
		} else {
			visible = 'none';
		}

		var divHorizOffset = -10;

		newdiv.setStyle({
			display: visible,
			border: "0px",
			position: 'absolute',
//				'z-index': 100,
			top: Chat.divTopOffset + 'px'
		});		

		if (divHorizOffset > 0) { // from left
			newdiv.setStyle({
				left: divHorizOffset + 'px'
			});
		} else { // from right
			newdiv.setStyle({
				right: -divHorizOffset + 'px'
			});
		}

		newdiv.update(html);

		document.body.appendChild(newdiv);
		Chat.divObj = newdiv;
	},

	'updateDivPos' : function() {
		var newtop = Chat.divTopOffset + document.viewport.getScrollOffsets().top;
		Chat.divObj.setStyle({
			top: newtop + "px"
		});
	},

	'getWindowSize' : function() {
		var myWidth = 0, myHeight = 0;
		if (typeof(window.innerWidth) == 'number') {
			// Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
			// IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
			// IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		return myWidth + " x " + myHeight;
	},

	'handleWindowChange' : function() {
		if (!Chat.divObj) return;
		if (Chat.divUpdateTimer) clearTimeout(Chat.divUpdateTimer); // so that they do not overlap
		Chat.divUpdateTimer = setTimeout('Chat.updateDivPos()', 500);
	},

	'newDataEntry' : function(type, data) {
		var a = [];
		a[0] = type;
		a[1] = data;
		return a;
	},

	'formSubmit' : function() {
		var e = document.getElementById("chat_input");
		if (!e) {
			if (Chat.debug) {
				alert('Unable to get the text from the input box');
			}
			return;
		}
		Chat.eventQueue.push(Chat.newDataEntry('msg', e.value));
		Chat.addChatText(Chat.compose_html_chatmsg('Visitor', e.value), 'msg_client');
		e.value = '';
		e.focus();
	},

	'formTyping' : function() {
		++Chat.typeCnt;
	},

	'compose_html_chatmsg' : function(nickname, text) { 		return "<strong>" + nickname.escapeHTML() + ":</strong> " + text.escapeHTML().replace(/\n/g, "<br>\n");
	},

	'addChatText' : function(text, type) {
		var css;
		if (type == 'msg_oper') {
			css = 'sInteractiveChatoper';
		} else {
			css = 'sInteractiveChatme';
		}
		text = '<tr><td class="' + css + '">' + text + '</td></tr>' + "\n";
		Chat.textBox.insert(text);
		Chat.scrollTextBottom();
	},

	'scrollTextBottom' : function() {
		if (!Chat.mainWindow.visible) return; // we do not know the height if we are not visible
		Chat.textContainer.scrollTop = Chat.textContainer.scrollHeight;
	},

	'processIncomingData' : function(data_obj) {
		var type;
		var seq;
		var data;
		data_obj.each(function(item) {
			type = item[0];
			seq = item[1];
			data = item[2];
			if (type == 'msg_client' || type == 'msg_oper') {
				Chat.addChatText(data, type);
			} else if (type == 'close_chat') {
				Chat.mainWindow.hide(); // hide chat window
			} else if (type == 'open_chat') {
				Chat.mainWindow.show(); // open chat window
				Chat.scrollTextBottom();
				Chat.updateDivPos();

				// Correct <textarea> width for strict and non-strict DOCTYPE's
				var e = document.getElementById("chat_input");
				if (!e) {
					if (Chat.debug) {
						alert('Unable to get the text from the input box');
					}
					return;
				} else {
					Element.extend(e);
					var currWidth = e.getWidth()
					var expectedWidth = 192;
					if (currWidth > expectedWidth)
					{
						var newWidth = expectedWidth - (currWidth - expectedWidth);
						e.setStyle({
							width: newWidth + "px"
						});
					}
				}
			} else if (type == 'skipped_echo_msg_client') {
				// noop, we already visualized this message
			} else {
				if (Chat.debug)	{
					if (!confirm('processIncomingData: Got unknown type ' + type + '(' + seq + '): ' + data + '". Continue?')) {
						Chat.loopPoll = 0;
						last;
					}
				}
			}
			Chat.lastSeq = seq;
		});
	},

	'schedulePollChat' : function(t) {
		if (!Chat.loopPoll) return;
		setTimeout("Chat.pollChat()", t*1000);
	},

	'pollChat' : function() {
		if (Chat.typeCnt) {
			Chat.eventQueue.push(Chat.newDataEntry('typing', Chat.typeCnt));
			Chat.typeCnt = 0;
		}

		if (Chat.sendQueue.length == 0) {
			while (Chat.eventQueue.length) {
				Chat.sendQueue.push(Chat.eventQueue.shift());
			}
		}

		new Ajax.Request(
			'/saleschat/rpc_client.php',
			{
				method: 'post',
				evalJSON: 'true',
				parameters: {
					token: Chat.token,
					seq: Chat.lastSeq,
					data_json: Chat.sendQueue.toJSON(),
					url: window.location.href,
					wsize: Chat.getWindowSize()
				},
				onSuccess: function(transport) {
					if (!transport.responseJSON || !transport.responseJSON instanceof Array) {
						if (Chat.debug) {
							if (!confirm('rpc_client.php: success but no JSON obj. Continue?')) {
								Chat.loopPoll = 0;
							}
						}
					} else {
						Chat.sendQueue = [];
						Chat.processIncomingData(transport.responseJSON);
					}
				},
				onFailure: function(transport) {
					if (Chat.debug) {
						if (!confirm('rpc_client.php: AJAX request failed. Continue?')) {
							Chat.loopPoll = 0;
						}
					}
				},
				onComplete: function() {
					Chat.schedulePollChat(Chat.pollInterval);
				}
			}
		);
	},

	'processFormChange' : function(form, value){
		var chinfo = [];
		chinfo[0] = form.name;
		chinfo[1] = form.action;
		chinfo[2] = value;
		Chat.eventQueue.push(Chat.newDataEntry('form_change', chinfo.toJSON()));
	},

	'initiate' : function() {
		Chat.createDiv('testID', '		<form id="sInteractiveChat_form" action="#" onSubmit="Chat.formSubmit(); return false;">' + 
'		<table class="sInteractiveChatbg" border="0" cellpadding="0" cellspacing="0" width="218">' + 
'			<tr>' + 
'				<td colspan="5"><img src="/saleschat/images/en/top.gif" usemap="#sInteractiveChatMap" border="0" height="27" width="218"></td>' + 
'			</tr>' + 
'			<tr>' + 
'				<td colspan="5" class="sInteractiveChattabg" align="center">' + 
'					<div id="chat_text_container" class="sInteractiveChatchatdiv">' + 
'						<table id="chat_text" width="100%" cellpadding="0" cellspacing="0">' + 
'						</table>' + 
'					</div>' + 
'				</td>' + 
'			</tr>' + 
'			<tr>' + 
'				<td colspan="5"><img src="/saleschat/images/en/ym.gif" height="35" width="218"></td>' + 
'			</tr>' + 
'			<tr>' + 
'				<td colspan="5" align="center">' + 
'					<textarea id="chat_input" onkeypress="Chat.formTyping(); return true;" class="sInteractiveChattam"></textarea>' + 
'				</td>' + 
'			</tr>' + 
'			<tr>' + 
'				<td colspan="5"><img src="/saleschat/images/en/h.gif" height="9" width="1"></td>' + 
'			</tr>' + 
'			<tr>' + 
'				<td><img src="/saleschat/images/en/h.gif" height="1" width="12"></td>' + 
'				<td><img src="/saleschat/images/en/h.gif" height="1" width="73"></td>' + 
'				<td><img src="/saleschat/images/en/h.gif" height="1" width="46"></td>' + 
'				<td><input src="/saleschat/images/en/send.gif" accesskey="s" title="Send your message" border="0" height="17" type="image" width="73"></td>' + 
'				<td><img src="/saleschat/images/en/h.gif" height="1" width="14"></td>' + 
'			</tr>' + 
'			<tr>' + 
'				<td colspan="5"><img src="/saleschat/images/en/bot.gif" height="13" width="218"></td>' + 
'			</tr>' + 
'		</table>' + 
'		</form>' + 
'' + 
'		<map name="sInteractiveChatMap">' + 
'			<area shape="rect" coords="195,6,208,21" href="#" onclick="Chat.endChat(); return false;" alt="Close chat" title="Close chat">' + 
'		</map>', 0);
		Chat.textBox = document.getElementById('chat_text');
		Chat.textContainer = document.getElementById('chat_text_container');
		Chat.mainWindow = Chat.divObj;
		if (!Chat.textBox || !Chat.mainWindow || !Chat.textContainer) {
			if (Chat.debug) alert('Init error, unable to get elements references');
		} else {
			if (Chat.token != '') {
				for (var index = 0; index < document.forms.length; ++index) {
					var form_obj = document.forms[index];
					if (!form_obj) if (Chat.debug) alert('Init error, unable to get the form element object');
					var form_id = form_obj.id;
					if (form_id == 'sInteractiveChat_form') {
						continue;
					}
					new Form.Observer(form_obj, 1.0, Chat.processFormChange);
				};

				Element.extend(Chat.textBox);
				Element.extend(Chat.mainWindow);
				Element.extend(window);

				Event.observe(window, 'scroll', Chat.handleWindowChange);
				Event.observe(window, 'resize', Chat.handleWindowChange);

				Chat.eventQueue.push(Chat.newDataEntry('page_load', document.referrer));
				Chat.schedulePollChat(Chat.pollInterval);
			}
		}
	},

	'endChat' : function() {
		if (confirm('Please confirm that you want to close the chat window.')) {
			Chat.mainWindow.hide(); // hide window ASAP
			Chat.eventQueue.push(Chat.newDataEntry('close_chat', ''));
		}
	}
}

Event.observe(window, 'load', function() {
	// you have to initiate all the chat power _after_ DOM has been fully created or you will have IE problems
	Chat.getToken();
});

/*
 * GLOBAL TRY-CATCH
 */
} catch(e) {
	if (0) {
		alert("A JavaScript exception occurred. Error name: " + e.name + ". Error message: " + e.message);
	}
}
