function $(element) { return document.getElementById(element); }
function $C(element){ return document.createElement(element); } 
function $T(element){ return document.createTextNode(element); }
function $A(element,node) { return node.appendChild(element); }
function $S(element,attr,val) { return element.setAttribute(attr,val); }
function $R(filename,type) {
		if (type == 'js') {
			var fl = $C('SCRIPT');
			$S(fl,'src',filename);
			$S(fl,'defer','true');
			$S(fl,'type','text/javascript');
			$S(fl,'charset','UTF-8');	
		} else if (type == 'css') {
			var fl = $C('LINK');
			$S(fl,'href',filename);			
			$S(fl,'rel','stylesheet');
			$S(fl,'type','text/css');
		}
		$A(fl,document.getElementsByTagName('head').item(0));
};

function $A(element,node) { return node.appendChild(element); };

function Chat(o) {

	this.Icon = [ 
		 Array('images/chat/icons/smile.gif', 'images/chat/icons/laughing.png', 'images/chat/icons/sad.png', 'images/chat/icons/wink.png', 'images/chat/icons/sad.png', 'images/chat/icons/pinch.png', 'images/chat/icons/shocked.png', 'images/chat/icons/tongue.png', 'images/chat/icons/smile.gif')
		,Array(/:-?\)/g, /(:-D|:d|:D)\b/g, /(:-\(|:\()/g, /;-?\)/gi, /:'\(/g, /%\)/g, /(:-O|:o|:O)\b/gi, /(:-P|:p|:P)\b/g, /o\/\//gi)
	];
	
	if (!window._chat) window._chat = new Array();
	window._chat[o.div] = this;
	this.configuration = o;
	this.rTime = 5; /* secondi */
	this.dCE = $(o.div);
	
	this.dCS = $C('DIV');
	this.dCS.className = 'shadow';
	this.dCS.setAttribute('id',o.div + '_shadow');
	
		
	this.dCM = $C('DIV');
	this.dCM.className = 'main';
	this.dCM.setAttribute('id',o.div + '_main');
	
	this.channel = ((o.channel) ? o.channel:'default');
	this.useCookie = ((o.useCookie) ? o.useCookie:false);
	this.userContainerHeight = ((o.userContainerHeight) ? o.userContainerHeight:50);
	this.userContainerVisible = true;
	if (o.css)  { $R(o.css,'css')};
	if (o.titleBar === true)
	{
		this.dCT = $C('DIV');
		this.dCT.setAttribute('id',o.div + '_title');
		this.dCT.style.width = o.width  + 'px';
		this.dCT.className = 'title';

		var m = $C('A');
		$S(m,'href','javascript:void(0)');	
		m.className = 'chat_minbutton'; 
		m.onclick = function() { window._chat[o.div]._minmax(); };

		$A(m,this.dCT);	

		$A($T(o.title),this.dCT);
		$A(this.dCT,this.dCM);
	}
	
	this.dBD = $C('DIV'); /* user container */
	this.dBD.setAttribute('id',o.div + '_bdcontainer');
	this.dBD.style.overflow = 'auto';
	this.dBD.className = 'chat_bdcontainer';
	this.dBD.style.height = this.userContainerHeight + 'px';
	this.dBD.style.display = 'none';
	$A(this.dBD,this.dCM);
		
	this.dCC = $C('DIV'); /* Chat container */
	this.dCC.setAttribute('id',o.div + '_container');
	this.dCC.style.overflow = 'auto';
	
	this.dCC.style.height = o.height + 'px';
	this.dCC.className = 'chat_container';
	$A(this.dCC,this.dCM);
	
	this.dCI = $C('DIV');
	this.dCI.className = 'chat_inputbar';
	
	
	this.dCB = $C('INPUT');
	$S(this.dCB,'id',o.div + '_input');
	$S(this.dCB,'type','text');
	var uid = this.configuration.div;
	this.dCB.onkeypress = function(e) {
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		if(keycode == 13){
			var m = $(window._chat[uid].configuration.div + '_input');
			var mess = m.value;
			for (var i = 0; i < window._chat[uid].Icon[1].length; i++) {
  			mess = mess.replace(window._chat[uid].Icon[1][i],'<img src="'+ window._chat[uid].Icon[0][i] +'"  />');
 			}
			window._chat[uid].wget({ type : 'chat', reqtime : window._chat[uid].rTime ,lastreq : window._chat[uid].user.lastreq ,userid : window._chat[uid].user.id,channel : window._chat[uid].configuration.channel,message : mess });	
			m.value = '';
		}	
		
	};
	this.dCB.className = 'chat_inputbox';
	$A(this.dCB,this.dCI);	
	$A(this.dCI,this.dCM);
	$A(this.dCM,this.dCS);
	
}

Chat.prototype.setCookie = function(vname,vvalue,vday)
{
	var dt = new Date();
	var de = new Date();
	de.setTime(dt.getTime() + 24 * vday * 3600000);
	document.cookie = vname + "=" + escape(vvalue) + "; expires=" + de.toGMTString();
};

Chat.prototype.getCookie = function(vname)
{
	var arCook = document.cookie.split("; ");
  for (var i = 0; i < arCook.length; i++)
  {
    var cook = arCook[i].split("=");
    if (vname == cook[0]) { 
      return (unescape(cook[1]));
    }
  }

  return("");	
	
};


Chat.prototype.delCookie = function(vname) {
  this.setCookie(vname, "");
};

Chat.prototype._minmax = function () {
	this.dCC.style.display = ((this.minimize === true) ? 'block':'none');
	this.minimize = !this.minimize;
};

Chat.prototype.loginForm = function() {
		var frc = $C('DIV');
		frc.align = 'center';
		var frm = $C('DIV');
		frm.className = 'chat_login';
		var ust = $T('Username');
		var usi = $C('INPUT');
		$S(usi,'id',this.configuration.div + '_luser');
		$S(usi,'type','text');		
		usi.className = 'chat_inputbox';
		
		var pit = $T('Password');
		var pin = $C('INPUT');	
		$S(pin,'id',this.configuration.div + '_lpass');
		$S(pin,'type','password');		
		pin.className = 'chat_inputbox';		
			
		var btn = $C('BUTTON');
		btn.className = 'chat_btnlogin';
		var uid = this.configuration.div;
		btn.onclick = function() { window._chat[uid]._login(); };
		var btl = $T('Login');
		$A(btl,btn);

		$A(ust,frm);
		$A(usi,frm);
		$A(pit,frm);
		$A(pin,frm);
		$A(btn,frm);		
		$A(frm,frc);
		return frc;		
};


Chat.prototype._login = function() {
	var u = $(this.configuration.div + '_luser');
	var p = $(this.configuration.div + '_lpass');	

	this.wget({ type : 'login',user : u.value, pass : p.value});

};


Chat.prototype.wget = function(s) {
	var div = this.configuration.div;	
	var URL = '';
			URL += this.configuration.server;
			for ( el in s) {
				URL+=((URL.indexOf('?')==-1)?'?':'&') ;
				URL +=  encodeURIComponent(el) + '=' + encodeURIComponent(s[el]); 
			}
	CCom.asyncRequest('GET',URL,{ 
		success : function (o) {
				var p = window._chat[div];
				p.parseResponse(o.responseXML);			
		}
	});	
	
};

Chat.prototype.Create = function() {
	var div = this.configuration.div;	
	this.dCS.style.width = this.configuration.width  + 'px';
	$A(this.dCS,this.dCE);
	this.minimize = false;
	
	var uid = this.getCookie('mChat_' + this.configuration.div + '_id');
	var uni = this.getCookie('mChat_' + this.configuration.div + '_nick');
	
	if (uid != '' && this.useCookie)
	{
		this.user = { id:uid,nick : uni,lastreq : ''};
		this.autoRefresh(this.rTime,true);
	} else {
		this.user = { id:null,nick : '',lastreq : ''};
		$A(this.loginForm(),$(this.configuration.div + '_container'));
	}
};

Chat.prototype.autoRefresh = function(interval,refreshNow) {
			if(refreshNow)	{ this.Update() }
		    if(this._autoRefreshProcId){
		        clearInterval(this.autoRefreshProcId);
		    }	
			this._autoRefreshProcId = setInterval("window._chat['" + this.configuration.div + "'].Update()", interval*1000);
			return null;		       
};

Chat.prototype.Update = function() {
	this.wget({ type : 'chat',reqtime : this.rTime ,lastreq : this.user.lastreq ,userid : this.user.id,channel : this.configuration.channel });	
};


Chat.prototype.parseResponse = function(o) {
	var r = o.getElementsByTagName('response');
	if (r)
	{
		
			 switch(o.getElementsByTagName('request')[0].firstChild.nodeValue)
			 {
			 		case 'login' :
			 				if (o.getElementsByTagName('autenticate')[0].firstChild.nodeValue == 'true')
			 				{
			 					var c = $(this.configuration.div + '_container');
			 					c.innerHTML = '';
			 					this.user = { id: o.getElementsByTagName('userid')[0].firstChild.nodeValue,nick : o.getElementsByTagName('nick')[0].firstChild.nodeValue,lastreq : ''};		
			 					this.setCookie('mChat_' + this.configuration.div + '_id',this.user.id,2);
			 					this.setCookie('mChat_' + this.configuration.div + '_nick',this.user.nick,2);
			 					this.autoRefresh(this.rTime,true);
			 				} else {
			 					alert('Login non valida');
			 				}
			 				
			 	
			 		break;
			 		
			 		case 'chat' : 
			 		
						var el = o.getElementsByTagName('item');
						for (var i = 0; i < el.length;i++)
						{
							
							var msg = $C('DIV');
							msg.className='chat_element_container r' + (el[i].getAttribute('id'))%2;
							
							var it = $C('DIV');
							it.className='chat_element_title';
							var ct = $T(el[i].getElementsByTagName("nick")[0].firstChild.nodeValue + " : ");
							
							$A(ct,it);
							$A(it,msg);
							
							var tt = $C('DIV');
							tt.className='chat_element_text';
							tt.innerHTML = el[i].getElementsByTagName("text")[0].firstChild.nodeValue;
							
							$A(tt,msg);
							$A(msg,$(this.configuration.div + '_container'));
							($(this.configuration.div + '_container')).scrollTop = 	($(this.configuration.div + '_container')).scrollHeight;			
						}		
						if (el.length > 0) this.user.lastreq = el[(el.length-1)].getAttribute('id');
						
						var us = o.getElementsByTagName('user');
						($(this.configuration.div + '_bdcontainer')).innerHTML = '';
						for (var i = 0; i < us.length;i++)
						{
							var u = $C('DIV');
							u.className='chat_user_container';
							var t = $T(us[i].getElementsByTagName("nick")[0].firstChild.nodeValue);
							$A(t,u);
							$A(u,$(this.configuration.div + '_bdcontainer'));
							
						}						



			 		break;
			 		
			 		default : 
			 		
			 		break;
			 }
			 

	}
}



CCom = {
	_poll:{},
	_timeOut:{},
	_polling_interval:50,
	_transaction_id:0, 
	_msxml:['Microsoft.XMLHTTP','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP'],	
	asyncRequest:function(method, uri, callback)
	{
		var o = this.getConnectionObject();
		var args = (callback && callback.argument)?callback.argument:null;	
		o.conn.open(method, uri, true);
		this.handleReadyState(o, callback);
		o.conn.send(null);
		return o;					
	},
	getConnectionObject:function()
	{
		var o;
		var tId = this._transaction_id;

		try
		{
			o = this.createXhrObject(tId);
			if(o) this._transaction_id++;
		}
		catch(e){}
		finally
		{
			return o;
		}
	},	
	createXhrObject:function(transactionId)
	{
		var obj,http;
		try
		{
			http = new XMLHttpRequest();
			obj = { conn:http, tId:transactionId };
		} catch(e) {
			for(var i=0; i< this._msxml.length; ++i){
				try
				{
					http = new ActiveXObject(this._msxml[i]);
					obj = { conn:http, tId:transactionId };
					break;
				}
				catch(e){}
			}
		}
		finally
		{
			return obj;
		}
	},
  handleReadyState:function(o, callback)
  {
		var oConn = this;
		var args = (callback && callback.argument)?callback.argument:null;

		if(callback && callback.timeout){
			this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
		}

		this._poll[o.tId] = window.setInterval(
			function(){
				if(o.conn && o.conn.readyState === 4){
					window.clearInterval(oConn._poll[o.tId]);
					delete oConn._poll[o.tId];

					if(callback && callback.timeout){
						window.clearTimeout(oConn._timeOut[o.tId]);
						delete oConn._timeOut[o.tId];
					}
					if (o.conn.status == '200') { callback.success(o.conn); }
				}
			}
		,this._polling_interval);
    }	
			
}
