/**
 * Object JAS_chat
 * 	Simple JS front-end application, based on LoadVars JS Object.
 *
 * @author               Andrea Giammarchi
 * @date                 2005/08/12
 * @lastmod              2005/10/11 19:30 (resolved NS_ERROR_XPC_JS_THREW_STRING problem)
 * @version              0.3 - tested with IE 6.0 and FireFox 1.0.6
 * @dependencies	 Elapsed.js, JAS_CodeLighter.js, LoadVars.js [www.devpro.it]
 */
function JAS_chat(
	PHP_JAS_chat_Class, 	// :String => where is JAS_chat.config.php file
	ChatInterval,		// :Integer => milliseconds for each chat refresh
	JASid,			// :String => div id where Jas should be and JAS var NAME
	JASsmileFolder,		// :String => folder where are smiles
	JASisDraggable,		// :Boolean => do you want to drag your JAS_chat ? 
	JASisMinimizable	// :Boolean => do you want to minimize your JAS_chat ?
) {
	
	/**
	 * Public method
         * 	initialize thisobject and load content for fist time
	 */
	function init() {
		if(Rheight > 0)
			document.getElementById(JASid).style.height = Rheight + 'px';
		else
			Rtitle = document.title;
		if(create()) {
			dragInit();
			channel = document.getElementById(JASid + 'Channel');
			message = document.getElementById(JASid + 'Message');
			sender = document.getElementById(JASid + 'Sender');
			pbar = document.getElementById(JASid + 'Pbar');
			chat.onLoad = function(s) {
				var channeltext = '';
				if(s) {
					if(sender.onclick == null && IsHelp == false) {
						delete this.message;
						enableMessages();
					}
					if(typeof(this['users']) != 'undefined') {
						document.title = '[online: ' + this['users'] + '] ' + Rtitle;
						delete this['users'];
					}
					document.title = document.title + ' :: ' + getElapsed.info() + ' secs.';
					if(typeof(this['service']) != 'undefined') {
						message.value = this['service'];
						delete this['service'];
					}
					if(typeof(this['help']) != 'undefined') {
						disableMessages('online help');
						IsHelp = true;
						channeltext = this['help'];
						delete this['help'];
					}
					else {
						var a = 0;
						while(chat['n' + a]) {
							channeltext += '<strong>' + this['n' + a] + ' :</strong>';
							channeltext += ' <span class="' + JASid + 'Text">' + CodeLighter.parse(this['t' + a]) + '</span><br />';
							channeltext += '<span class="' + JASid + 'Date">[' + this['d' + a] + ']</span><br />';
							delete this['n' + a];
							a++;
						}
					}
					if(IsHelp) {
						ChatInterval = (ChatInterval * 2);
						IsHelp = false;
					}
					else if(ChatInterval != RChatInterval) {
						ChatInterval = RChatInterval;
						enableMessages();
					}
					if(typeof(this['active']) == 'undefined' || this['active'] != 'false')
						Linterval = setInterval(setLinterval, ChatInterval);
					else
						delete this['active'];
					IsLoading = false;
				}
				else {
					channeltext = '<strong>Server problems.</strong><br />Please try later or wait some seconds.';
					Linterval = setInterval(setLinterval, (ChatInterval * 4));
				}
				channel.innerHTML = channeltext;
			}
			message.value = '';
			message.onkeyup = checkInput;
			message.focus();
			setPinterval();
			setLinterval();
		}
	}
	
	/**
	 * Public method
         * 	send a message and load new contents
	 */
	function checkInput(e) {
		try {
			if(!e && window.event)
				var e = window.event.keyCode;
			else if(e && e.keyCode)
				e = e.keyCode;
			if(e == 13)
				sendMessage();
		}
		catch(evt) { /** do nothing **/ }
	}
	function sendMessage() {
		if(IsLoading == false) {
			var txt = message.value;
			if(txt.split(' ').join('').length > 0) {
				disableMessages('sending ...');
				clearInterval(Linterval);
				Linterval = 0;
				chat.message = txt;
				getElapsed = new Elapsed(3);
				chat.sendAndLoad(PHP_JAS_chat_Class, chat, 'POST');
			}
		}
	}
	
	/** LIST OF ALL PRIVATE METHODS [ uncommented ] */
	function minimize() {
		if(JASisMinimizable && !IsLoading) {
			dragKiller();
			var lnk = document.getElementById(JASid + 'A_Drag');
			if(IsMInimized)
				pause(false);
			else
				pause(true);
			IsMInimized = IsMInimized == true ? false : true;
			this.minimized = IsMInimized;
			dragInit();
		}
	}
	
	function pause(leave) {
		var jas = document.getElementById(JASid);
		if(Rheight == 0)
			Rheight = jas.clientHeight - 2;
		if(leave) {
			clearInterval(Linterval);
			clearInterval(Pinterval);
			Linterval = 0;
			Pinterval = 0;
			chat.remOnLoad = chat.onLoad;
			delete chat.onLoad;
			var htmlchat = '<div id="' + JASid + 'Dragger" style="text-align: right;">'
			+ '<a id="' + JASid + 'A_Drag" class="' + JASid + 'Link" title="maximize">[_]</a> &nbsp; </div>';
			jas.innerHTML = htmlchat;
			jas.style.height = (document.getElementById(JASid + 'Dragger').clientHeight + 2) + 'px';
		}
		else
			init();
	}
	
	function create() {
		var result = true;
		var htmlchat = '<div id="' + JASid + 'Dragger" style="text-align: right;">';
		if(JASisMinimizable)
			htmlchat += '<a id="' + JASid + 'A_Drag" class="' + JASid + 'Link" title="minimize">[_] &nbsp; </a>';
		htmlchat += '</div><div id="' + JASid + 'Channel"></div>'
		+ '<input id="' + JASid + 'Message" type="text" autocomplete="off" name="message" value="" size="16" maxlength="250" />'
		+ '<input id="' + JASid + 'Sender" type="button" name="sender" value="send" onclick="' + JASid + '.sendMessage();" />'
		+'<div id="' + JASid + 'Pbar">&nbsp;</div>';
		try {
			document.getElementById(JASid).innerHTML = htmlchat;
			if(JASisDraggable) {
				if(!document.all)
					document.captureEvents(Event.MOUSEMOVE);
				document.onmousemove = getMousePosition;
			}
		}
		catch(evt) {
			result = false;
		}
		return result;
	}
	
	function getMousePosition(evt) {
		var x = 0;
		var y = 0;
		if(document.all) {
			x = event.clientX + document.body.scrollLeft;
			y = event.clientY + document.body.scrollTop;
		}
		else {
			x = evt.pageX;
			y = evt.pageY;
		}
		x = x < 0 ? 0 : x;
		y = y < 0 ? 0 : y;
		MousePosition['x'] = x;
		MousePosition['y'] = y;
	}
	
	function windowSize( minW, minH ) {
		var objSize = Array( minW, minH );
		if( typeof( window.innerWidth ) == 'number' ) {
			objSize[0] = window.innerWidth;
			objSize[1] = window.innerHeight;
		}
		else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			objSize[0] = document.documentElement.clientWidth;
			objSize[1] = document.documentElement.clientHeight;
		}
		else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			objSize[0] = document.body.clientWidth;
			objSize[1] = document.body.clientHeight;
		}
		return objSize;
	}
	
	function onDrag() {
		var y = (MousePosition['y'] - MousePosition['ydif']);
		var x = (MousePosition['x'] - MousePosition['xdif']);
		if(y <= 10)
			y = 0;
		else if(y >= MousePosition['ymax'] - 10)
			y = MousePosition['ymax'] - 2;
		if(x <= 10)
			x = 0;
		else if(x >= MousePosition['xmax'] - 10)
			x = MousePosition['xmax'] - 2;
		MousePosition['referer'].style.top = y + 'px';
		MousePosition['referer'].style.left = x + 'px';
	}
	
	function startDrag() {
		var wsize = windowSize(100, 100);
		if(MousePosition['interval'] && MousePosition['interval'] > 0)
			clearInterval(MousePosition['interval']);
		var jas = document.getElementById(JASid);
		var tmp = document.getElementById(JASid + 'Dragger');
		MousePosition['referer'] = document.getElementById(JASid);
		MousePosition['ydif'] = tmp.clientHeight;
		MousePosition['xdif'] = tmp.clientWidth / 2;
		MousePosition['ymax'] = wsize[1] - jas.clientHeight;
		MousePosition['xmax'] = wsize[0] - jas.clientWidth;
		if(MousePosition['referer'].style.position != 'absolute')
			MousePosition['referer'].style.position = 'absolute';
		MousePosition['interval'] = setInterval(onDrag, 10);
	}
	
	function stopDrag() {
		clearInterval(MousePosition['interval']);
		MousePosition['interval'] = 0;
	}
	
	function dragInit() {
		if(JASisDraggable) {
			var drag = document.getElementById(JASid + 'Dragger');
			drag.style.cursor = 'pointer';
			drag.onmousedown = startDrag;
			drag.onmouseup = stopDrag;
		}
		if(JASisMinimizable) {
			var lnk = document.getElementById(JASid + 'A_Drag');
			lnk.onmousedown = minimize;
			lnk.style.cursor = 'pointer';
		}
	}
	
	function dragKiller() {
		if(JASisDraggable) {
			var drag = document.getElementById(JASid + 'Dragger');
			drag.onmousedown = null;
			drag.onmouseup = null;
		}
	}
	
	function setLinterval() {
		IsLoading = true;
		if(Linterval != 0) {
			clearInterval(Linterval);
			Linterval = 0;
		}
		getElapsed = new Elapsed(3);
		chat.load(PHP_JAS_chat_Class);
	}
	
	function setPinterval() {
		if(Pinterval == 0) {
			Rwidth = pbar.clientWidth;
			Pinterval = setInterval(setPinterval, 10);
		}
		if(Linterval == 0) {
			Rtimer = 0;
			pbar.style.width = Rwidth + 'px';
		}
		else {
			var dt = new Date();
			Ltimer = dt.getTime();
			if(Ltimer > Rtimer)
				Rtimer = Ltimer + ChatInterval;
			var nwidth = Math.ceil((Rwidth * (ChatInterval - (Rtimer - Ltimer))) / ChatInterval);
			pbar.style.width = nwidth + 'px';
		}
	}
	
	function disableMessages(info) {
		message.onkeyup = null;
		sender.onclick = null;
		message.value = info;
	}
	
	function enableMessages() {
		message.value = '';
		message.focus();
		sender.onclick = sendMessage;
		message.onkeyup = checkInput;
	}
	
	/** DECLARATION OF ALL PUBLIC METHODS */
	this.minimized = false;
	this.init = init;
	this.checkInput = checkInput;
	this.sendMessage = sendMessage;
	
	/** PRIVATE VARIABLES */
	var channel = null;
	var message = null;
	var sender = null;
	var pbar = null;
	var Rtitle = null;
	var IsHelp = false;
	var IsLoading = false;
	var IsMInimized = false;
	var Linterval = 0;
	var Pinterval = 0;
	var Ltimer = 0;
	var Rtimer = 0;
	var Rwidth = 0;
	var Rheight = 0;
	var getElapsed = Object();
	var MousePosition = Object();
	var RChatInterval = ChatInterval;
	var CodeLighter = new JAS_CodeLighter(JASid + 'Link', JASsmileFolder);
	var chat = new LoadVars();
}