/* 

  (C) 2009 Andrea Pezzino - www.andreapezzino.com - www.jyingo.com
  Tutti i diritti riservati.
  
  Parte del codice è derivante da Jyingo */

/*
 * Copyright 2008-2009 by SiberianSTAR aka Andrea Pezzino
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
  
  var ADDON_IM_DELAY = false;

function global_replace(cosa, con, dove) { return dove.split(cosa).join(con); }
function canceldefault(evt) { jyingo.cancelEvent(evt, false); }
Function.createDelegate=function(a,b){return function(){return b.apply(a,arguments)}};

var _SKIP_GET = true;
if (jyingo) _SKIP_GET=false;

function $get(what) {  for (var i = 0; i < jyingo.arrCustomObjects.length; i++) {if (!_SKIP_GET) if (jyingo.arrCustomObjects[i].get_name() == what) return jyingo.arrCustomObjects[i];}  if ( document.getElementById(what) ) return document.getElementById(what); if (document.forms.form1) if (document.forms.form1[what]) return document.forms.form1[what]; return null}


if (!jyingo)
{

var jyingo = {
 arrCustomObjects : new Array(),
 active_timers_array : new Array(),
 is_postback : false,
 loadingHandler : null,
 endLoadingHandler : null,
 currentEvents : new Array(),
 is_under_msgbox : null,

 init : function()
 {
 	 this.addEvent._i = 1;
 },
 
 cancelEvent : function(e, c)
 {
   e.returnValue = false;
   if (e.preventDefault) e.preventDefault();
   if (c)
   {
     e.cancelBubble = true;
     if (e.stopPropagation) e.stopPropagation();
   }
  },
   
 addEvent : function(o, t, f, l)
 {
 	
 	if (!o) return;

 	for (var i = 0; i < this.currentEvents.length; i++)
 	{
 	
 		 var p = this.currentEvents[i];
 		 if (p[0] == o && p[1] == t && p[2] == f && p[3] == l)
 		 {
 		 	 jyingo.removeEvent(o, t, f, l);
 		 	 this.currentEvents.splice(i, 1);
 		 	 break;
 		 }
 	}
 	
 	this.currentEvents.push(new Array(o, t, f, l));
 	
  var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
  if (o[d] && !l) return o[d](t, f, false);
  if (!o._evts) o._evts = {};
  if (!o._evts[t])
  {
   o._evts[t] = o[n] ? { b: o[n] } : {};
   o[n] = new Function('e',
    'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
     'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
     '} return r');
   if (t != 'unload') this.addEvent(window, 'unload', function() {
    jyingo.removeEvent(rO, rT, rF, rL);
   });
  }
  if (!f._i) f._i = this.addEvent._i++;
  o._evts[t][f._i] = f;
 },
 
 removeEvent : function(o, t, f, l)
 {
 	
 	for (var i = 0; i < this.currentEvents.length; i++)
 	{
 		 var p = this.currentEvents[i];
 		 if (p[0] == o && p[1] == t && p[2] == f && p[3] == l)
 		 {
 		 	 this.currentEvents.splice(i, 1);
 		 	 break;
 		 }
 	} 	
 	
  var d = 'removeEventListener';
  if (o[d] && !l) return o[d](t, f, false);
  if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
 }
}
}
addon_im = function()
{
	 this.sKey = null;
	 this.stateElement = null;
	 this.menuDiv = null;
};

addon_im.prototype = {
	
	
	init : function(sKey, nickname, icona, suoni, emoticons)
	{
		 // STATI
		 this.STATO_VISIBLE = 1;
		 this.STATO_INVISIBLE = 2;
		 this.icona = icona;
		 this.nickname = nickname;
		 
		 if (suoni == 's')
		 {
		  this.suoni = true;

			
		 }
		 else
		 	this.suoni = false;
		 
		 if (emoticons == 's')
		  this.emoticons = true;
		 else
		 	this.emoticons = false;
		 
		 this.stateElement = $get('chatstate');
		 this.sKey = sKey;
		 this.stateElement.title = 'Connessione in corso ...';
		 this.stateElement.innerHTML = '<img src="http://www.fuoriditesta.it/addon/im/connecting.gif" />';
		 
		 this.menuvisible = false;
		 this.hidemenutimer = 0;
		 
		 var el = document.createElement('div');
		 el.innerHTML = '<div class="chaticon"><img src="'+icona+'" width="50" height="50" /></div><div class="chatstatus"><img src="http://www.fuoriditesta.it/images/loader.gif" /> Connessione in corso ...</div><div class="clearleft" />';
		 
		 this.connected = false;
		 
		 this.menuDiv = el;
		 this.menuDiv.className = 'chatmenu';
		 this.status = 0;
		 
		 jyingo.addEvent(window, 'load', Function.createDelegate(this, this.loaded));
		 jyingo.addEvent(window, 'resize', Function.createDelegate(this, this.resize));
		 jyingo.addEvent(document, 'mousemove', Function.createDelegate(this, this.mousemove));
		 this.aggancia();
		 
		 this.operating = false;
		 
		 this.stateElement.onclick = Function("return false");
		 this.stateElement.onmousemove = Function.createDelegate(this, this.showmenu);
		 
		 this.hidemenuhandler = Function.createDelegate(this, this.hidemenu);
		 
		 this.datareceivehandler = Function.createDelegate(this, this.datareceive);
		 this.pushhandler = Function.createDelegate(this, this.pushdata);
		 
		 this.commandStack = new Array();
		 this.opdata = 0;
		 
		 this.pushtimer  = setInterval(this.pushhandler, 3000);
		 this.friendlist=new Array();
		 
		 this.arrwnds = new Array();
		 
		 this.resptime = 0;
		 this.frienddata = new Array();
		 
		 this.emoticonsArr = new Array();
		 this.push_emo(':)', 'smile.gif');
		 this.push_emo(':-)', 'smile.gif');
		 this.push_emo(':(', 'infelice.gif');
		 this.push_emo(':-(', 'infelice.gif');
		 this.push_emo(':@', 'arrabbiato.gif');
		 this.push_emo(':x', 'arrabbiato.gif');
		 this.push_emo(':X', 'arrabbiato.gif');
		 this.push_emo(':@', 'arrabbiato.gif');
		 this.push_emo('(h)', 'figo.gif');
		 this.push_emo('(H)', 'figo.gif');
		 this.push_emo('8-)', 'figo.gif');
		 this.push_emo(':p', 'lingua.gif');
		 this.push_emo(':-p', 'lingua.gif');
		 this.push_emo(':P', 'lingua.gif');
		 this.push_emo(':-P', 'lingua.gif');
		 this.push_emo(':$', 'shiny.gif');
		 this.push_emo(':oops:', 'shiny.gif');
		 this.push_emo(':d', 'happy.gif');
		 this.push_emo(':-d', 'happy.gif');
		 this.push_emo(':D', 'happy.gif');
		 this.push_emo(':-D', 'happy.gif');
		 this.push_emo(';)', 'occhiolino.gif');
		 this.push_emo(';-)', 'occhiolino.gif');
		 this.push_emo(':|', 'sbarrati.gif');
		 this.push_emo(':-|', 'sbarrati.gif');
		 this.push_emo(':s', 'strano.gif');
		 this.push_emo(':-s', 'strano.gif');
		 this.push_emo(':S', 'strano.gif');
		 this.push_emo(':-S', 'strano.gif');
		 this.push_emo(':evil:', 'dito.gif');
		 this.push_emo(':nice:', 'wink.gif');
		 this.push_emo(':roll:', 'rolleyes.gif');
		 this.push_emo(':o', 'sorpreso.gif');
		 this.push_emo(':O', 'sorpreso.gif');
		 this.push_emo(':lol:', 'lol.gif');
		 this.push_emo(':kiss:', 'kiss.gif');
		 this.push_emo(':*', 'kiss.gif');
		 this.push_emo(':-*', 'kiss.gif');
		 this.push_emo(':shock:', 'eek.gif');
		 this.push_emo(':cry:', 'cry.gif');
		 this.push_emo('(K)', 'bacio.gif');
		 this.push_emo('(k)', 'bacio.gif');
		 this.push_emo(':rosa:', 'rosa.gif');
		
	},
	
	destroy : function()
	{

		this.commandStack = new Array();
		smartCallQueue=new Array();
		clearInterval(this.pushtimer);
		
	},
	
	push_emo : function(name, path)
	{
		 this.emoticonsArr.push(new Array(name, path));
	},
	
	pushdata : function()
	{
		
		if (ADDON_IM_DELAY == true) return;
		
		var dati = JSON.stringify(this.commandStack);
		this.commandStack = new Array();
		
		if (navigator.userAgent.indexOf('MSIE') == -1)
		 eseguiPost('/interface.php?key='+this.sKey, 'time='+this.resptime+'&opdata='+this.opdata+'&cmds='+escape(dati), this.datareceivehandler) ;
		else
		{
	   var bObj = new JSONscriptRequest('http://www.fuoriditesta.it/interface.php?IE=1&key='+this.sKey+'&time='+this.resptime+'&opdata='+this.opdata+'&cmds='+escape(dati));
     bObj.buildScriptTag(); 
     bObj.addScriptTag();
	  }
	 
	},
	
	goOnline : function()
	{

		 if (this.connected != true || this.status == this.STATO_VISIBLE) return;
		 
		 this.setoperating();
		 this.command('go','online');
		 this.setloader();
		 
	},
	
	setoperating : function()
	{
		 this.opdata = Math.random();
		 this.operating = true;
	},
	
	push_wnd : function(w)
	{
		 this.arrwnds.push(w);
	},
	
	search_wnd : function(id)
	{
		 for (var i = 0; i < this.arrwnds.length; i++)
		  if (this.arrwnds[i].user_id == id) return this.arrwnds[i];
		 
		 return undefined;
	},
	
	goInvisible : function()
	{
		 if (this.connected != true || this.status == this.STATO_INVISIBLE) return;
		 
		 this.setoperating();
		 this.command('go','invisible');
		 this.setloader();		
		 
		 for ( var i = 0; i < this.friendlist.length; i++)
		 { 
		 	 
		 	 var uid = this.friendlist[i][0];
		 	 if (this.frienddata[uid][0] == true)
		 	  this.frienddata[uid][2].destroy();
		 	
		 }
		 
		 
		 
	},
	
	setloader : function()
	{
		 this.menuDiv.innerHTML = '';
		 this.addloader();
	},
	
	addloader : function()
	{
		
		this.menuDiv.innerHTML += '<div class="chatstatus"><img src="http://www.fuoriditesta.it/images/loader.gif" /></div>';
		
		
	},
	
	datareceive : function(data)
	{
		if (data.length == 0) return;
		
	
		var resp = eval('(' + data + ')');

		if (resp['opdata'] == this.opdata)
		{
		 this.operating = false;
		 this.opdata = 0;
		}
		
		this.resptime = resp['resptime'];
		
		if (resp['error'] != undefined)
		{
			 
			 switch(resp['error'])
			 {
			 	 case 'invalidkey':
			 	  clearInterval(this.pushtimer);
		      this.stateElement.title = 'Errore di connessione';
		      this.stateElement.innerHTML = '<img src="http://www.fuoriditesta.it/addon/im/error.png" />';
		      
		      this.menuDiv.innerHTML = '<div class="chatstatus">Connessione non riuscita</div>';
		      return;
			 	 break;
 
			 }
			 
		}
		

		if (resp['connected'] == 'true')
		{
			this.connected = true;
		}

		if (resp['invisible'] == 'true')
		{
		   
		   this.status = this.STATO_INVISIBLE;
		   this.stateElement.title = 'Invisibile';
		   this.stateElement.innerHTML = '<img src="http://www.fuoriditesta.it/addon/im/invisible.png" />';
		      
		   this.menuDiv.innerHTML = '<div class="chaticon"><img src="'+this.icona+'" width="50" height="50" /></div><div class="chatstatus"><img src="http://www.fuoriditesta.it/addon/im/invisible_small.png" width="10" height="10"> Il tuo stato è: <strong>Invisibile</strong><a href="#" onclick="aIM.goOnline(); return false;"><font color="#336699">Clicca qui per tornare In Linea</font></a></div><div class="clearleft"></div>';			
			 
			
			
		}		
		
		if (resp['visible'] == 'true')
		{
		    this.status = this.STATO_VISIBLE;
		   this.stateElement.title = 'Connesso';
		   this.stateElement.innerHTML = '<img src="http://www.fuoriditesta.it/addon/im/online.png" />';
		      
		   this.menuDiv.innerHTML = '<div class="chaticon"><img src="'+this.icona+'" width="50" height="50" /></div><div class="chatstatus"><img src="http://www.fuoriditesta.it/addon/im/online_small.png" width="10" height="10" /> Il tuo stato è: <strong>In Linea</strong><a href="#" onclick="aIM.goInvisible(); return false"><font color="#336699">Clicca qui per diventare Invisibile</font></a></div><div class="clearleft"></div><div id="chatlist"></div><div id="userlist"></div>';			
			 
			
			
		}
		

		
		if (resp['initlist'] != undefined)
		{
			
			 var s = resp['initlist'];
			 if (s.length == 0)
			 {
			 	  this.friendlist = new Array();
			 }
			 else
			 {
			 	  this.friendlist = s;
			 	  this.frienddata = new Array();
			 	  for (var i= 0; i < s.length; i++)
			 	  this.frienddata[s[i][0]] = new Array(false, s[i]);
			 }
			 this.render_friendlist();
			
		}
		
		var newrender = false;
		var olddata = new Array();
		if (resp['dellist'] != undefined)
		{
			
			var s = resp['dellist'];
			if (s.length) {
			var newfriend = new Array();
			for (var i = 0; i < this.friendlist.length; i++)
			{
				var found = false;
				for (var t = 0; t < s.length; t++)
				 if ( s[t] == this.friendlist[i][0] ) found = true;
			 
			  if (!found) newfriend.push(this.friendlist[i]);
				else {  olddata[this.friendlist[i][0]] = this.frienddata[this.friendlist[i][0]]; this.frienddata[this.friendlist[i][0]] = undefined; }
			}
			
			this.friendlist = newfriend;
			newrender=true;
		 }
		}
		

		if (resp['addlist'] != undefined)
		{
			
			 var s = resp['addlist'];
			 if (s.length) { 
	
			 for (var i = 0; i < s.length; i++)
			 {
			 	if (s[i][3]== false)
			   this.friendlist.splice(0,0,s[i]);
			  else
			   this.friendlist.push(s[i]);
			  
			  if (olddata[s[i][0]] == undefined)
			  this.frienddata[s[i][0]] = new Array(false, s[i], undefined);
			  else
			  {
			  	olddata[s[i][0]][1] = s[i];
			  	this.frienddata[s[i][0]] = olddata[s[i][0]];
		
			  	var k= this.search_wnd(s[i][0]);
			  	if (k != undefined)
			  	{
	
			  		 if (this.frienddata[s[i][0]][0] == true)
			  		 {

			  		 	if (this.frienddata[s[i][0]][1][3] == true)
			  		 	  k.addtxt(2, this.frienddata[s[i][0]][1][1] + ' è away.', 1, this.resptime);
			  		 	else
			  		 		k.addtxt(2, this.frienddata[s[i][0]][1][1] + ' non è più away.', 1, this.resptime);
			  		 		
			  		 		
			  		 	k.show();
			  		 }
			  	}
			  }
			 }
			newrender=true;
		}
		}
   if (newrender) this.render_friendlist();				

    

		if (resp['alert'] != undefined)
		{
			
			 for ( var i = 0; i < resp['alert'].length; i++)
			 {

			 	 alert(resp['alert'][i]);
			 }			
		}
		
		if (resp['wnddata'] != undefined)
		{
			
			 for ( var i = 0; i < resp['wnddata'].length; i++)
			 {

			 	 this.open_chat(resp['wnddata'][i]);
			 }
		}		

		
		if (resp['msgs'] != undefined)
		{
			 
			 var msgs = resp['msgs'];
       var pv = 0;
			 for (var i = 0; i < msgs.length; i++)
			 {
			 	 
			 	 if (this.frienddata[msgs[i][0]] != undefined)
			 	 {
			 	 	 
			 	 	 if (this.lastmsg == msgs[i][2] && this.lastmsgid == msgs[i][0]) continue;
			 	 	 this.lastmsg = msgs[i][2];
			 	 	 this.lastmsgid = msgs[i][0];
			 	 	 
			 	 	 if (this.frienddata[msgs[i][0]][0] == false)
			 	 	 {
			 	 	 	var p =new Array();
			 	 	 	p[0] = msgs[i][0];
			 	 	 	p[1] = true;
			 	 	  this.open_chat(p);
			 	 	 }
			 	 	 var tipo = 1;
			 	 	 if (msgs[i][1] == msgs[i][0])
			 	 	  tipo = 2;
			 	 	  
			 	 	
			 	 	 this.frienddata[msgs[i][0]][2].addtxt(tipo, (unescape(msgs[i][2])), 0, msgs[i][3]);
			 	 	 pv++;
			 	 }
			 	 
			 	 
			 }
			 if (pv)
			   this.playsound();
			 
			
		}
		
		if (resp['msgc'] != undefined)
		{
			 
			 var msgs = resp['msgc'];
	     var skip = false;
			 
			 for (var i = 0; i < msgs.length; i++)
			 {
			 	 
			 	 if (this.frienddata[msgs[i][0]] != undefined && (this.frienddata[msgs[i][0]][2].vuoto == true || skip == true))
			 	 {
			 	 	 
			 	 	 var tipo = 1;
			 	 	 if (msgs[i][1] == msgs[i][0])
			 	 	  tipo = 2;
			 	 	  
			 	 	 skip = true;
			 	 	 this.frienddata[msgs[i][0]][2].addtxt(tipo, (unescape(msgs[i][2])), 0, msgs[i][3]);
			 	 	 
			 	 }
			 	 
			 	 
			 }
			
		}
		
		 //var arr = eval(data);
	},
	
	
  parse_emo : function(t)
  {
  	
  	 if (this.emoticons == false) return t;
  	 var s = t;
  	 for ( var i = 0; i < this.emoticonsArr.length; i++)
  	  s = global_replace(this.emoticonsArr[i][0], '<img src="http://www.fuoriditesta.it/addon/im/emos/'+this.emoticonsArr[i][1]+'" />', s);
  	 return s;
  	 
  },
	
	render_friendlist : function()
	{
		 
		 var code = '';
		 for ( var i = 0; i < this.friendlist.length; i++)
		 {
		 	 
		 	 var ico;
		 	 if (this.friendlist[i][3] == true)
		 	   code += '<a onselectstart="return false" href="#" onclick="aIM.start_chat('+this.friendlist[i][0]+'); return false;" class="idle"/><img src="http://www.fuoriditesta.it/addon/im/idle.gif?2" height="16" width="16" /><span>'+this.friendlist[i][1]+' (inattivo)</span></a>';
		 	 else
		 	   code += '<a onselectstart="return false"  href="#" onclick="aIM.start_chat('+this.friendlist[i][0]+'); return false;" /><img src="'+ this.friendlist[i][2]+'" height="18" width="18" /><span>'+this.friendlist[i][1]+'</span></a>';

		 }
		 
		 if (!$get('chatlist'))
		  return;
		  
		 $get('chatlist').innerHTML = '(<strong>'+this.friendlist.length+'</strong>) amici online <img id="btn_audio_im_switch" onclick="aIM.toggleAudio(this);" />';
		 $get('userlist').innerHTML = code;
		 
		 var chatBtn = $get('btn_audio_im_switch');
		  
		 if (this.suoni == true)
		 {
		 	chatBtn.title = 'Disabilita i suoni'; 
		 	chatBtn.src='http://www.fuoriditesta.it/images/audio_on.gif';
		 } 
     else
     {
     	  chatBtn.title = 'Abilita i suoni';
     		chatBtn.src='http://www.fuoriditesta.it/images/audio_off.gif';
		 }
		 
	},
	
	toggleAudio : function(chatBtn)
	{
		
		 if (this.suoni == true)
		 {
		   chatBtn.src='http://www.fuoriditesta.it/images/audio_off.gif';
		   this.suoni=false;
		   this.command('sound','n');
		   chatBtn.title = 'Abilita i suoni';
		 }
     else
     {
     	 chatBtn.src='http://www.fuoriditesta.it/images/audio_on.gif';		
     	 this.suoni=true;
     	 this.command('sound','s');
     	 chatBtn.title = 'Disabilita i suoni';
		 }
	},


	open_chat : function(data)
	{
     var user_id = data[0];
     

     
		 if( this.frienddata[user_id] == undefined) return; 
		 if (this.frienddata[user_id][0] != false) return;
		 
		 if (this.frienddata[user_id][2] == undefined)
		 {
      var s = this.search_wnd(user_id);
      if (s == undefined)
		  this.frienddata[user_id][2] = new whisper_window(user_id);
		  else
		  this.frienddata[user_id][2] = s;
		 
		 }
		 

     if (data[1].length == 2)
     {
      var x = data[1][0];
      var y = data[1][1];
      this.frienddata[user_id][2].move(x,y);
     } else {
     	 this.frienddata[user_id][2].setpos();
     }
     this.frienddata[user_id][2].show();		 
		 
		 this.frienddata[user_id][0] = true;
		
		 // apriamo sta finestrella
		 
	},
	
	start_chat : function(user_id)
	{
		 if( this.frienddata[user_id] == undefined) return;
		 if (this.frienddata[user_id][0] != false) return;
		 
		 
		 if (this.frienddata[user_id][2] == undefined)
		 {
      var s = this.search_wnd(user_id);
      if (s == undefined)
		  this.frienddata[user_id][2] = new whisper_window(user_id);
		  else
		  this.frienddata[user_id][2] = s;
		 
		 }
		 
		 this.frienddata[user_id][2].setpos();
		 this.frienddata[user_id][2].show();
		 this.frienddata[user_id][0] = true;
		 
		 this.command('open', user_id);
		 this.hidemenu();
		 // apriamo sta finestrella
		 
	},
	
	hidemenu : function()
	{
     if (this.hidemenutimer)
     {
     	 clearInterval(this.hidemenutimer);
     	 this.hidemenutimer = 0;
     }
   
     
     this.menuvisible == false;
     this.menuDiv.style.display='none';
     
     		 
	},
	
	command : function(param, value)
	{
		 this.commandStack.push(new Array(param, value));
	},
	
	connect : function()
	{
		if (this.connected == true) return;
		
		this.command('connect', 'true');
		setTimeout(Function.createDelegate(this, this.connect), 5000);
		
	},
	
	
	
	
	
	mousemove : function()
	{
		
		if (this.menuvisible == true && this.operating == false)
		{
		
			if (mouse_in_element(this.menuDiv) || mouse_in_element(this.stateElement))
			{
				
     		if (this.hidemenutimer)
     		{
     	 		clearInterval(this.hidemenutimer);
     	 		this.hidemenutimer = 0;
     		}
				
			}
			else
			{
					
				if (this.hidemenutimer == 0)
				 this.hidemenutimer = setInterval(this.hidemenuhandler, 500);
				
			}
			
			
		}

	},
	
	showmenu : function()
	{

     this.menuvisible = true;
     
     if (this.hidemenutimer)
     {
     	 clearInterval(this.hidemenutimer);
     	 this.hidemenutimer = 0;
     }
     
		 this.menuDiv.style.display='block';
	
		 	
		 return false;
	},
	
	resize : function()
	{
		 this.aggancia();
	},
	
	loaded : function()
	{
		
		if (this.suoni == true)
		{
	
			if (browser.isIE)
			 this.soundObj = $get('suoni');
			else
			 this.soundObj = document['suoni'];
			
		 } 
		 
		 document.body.appendChild(this.menuDiv);
		 this.aggancia();
		 
		 this.connect();
	},
	
	playsound : function()
	{
		 if (this.suoni == true && this.soundObj)
		 {
		 	try {
		 	 if(this.soundObj.suona)
		 	  this.soundObj.suona();
		 	}
		 	catch(e)
		 	{
		 		return;
		 	}
		 }
	},
	
	aggancia : function()
	{
			var el = this.menuDiv;
			var agg = $get('chatstate');
			var x = getX(agg);
			var y = getY(agg);

 			el.style.top=(y+35)+'px';	
 			el.style.left=(x)+'px';

	}
	
	
	
};

function getX( oElement )
{
    var iReturnValue = 0;
    
    while( oElement != null ) {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}
function getY( oElement  )
{
    var iReturnValue = 0;    
    while( oElement != null ) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
}
return iReturnValue;
}

function mouse_in_element(el)
{
	var x= getX(el);
	var y = getY(el);
	var w = el.offsetWidth;
	var h = el.offsetHeight;
	
	if (tempX > x && tempX < x+w && tempY > y && tempY < y+h) return true;
	return false;
}
	 var tempX = 0;
	 var tempY = 0;
	 function getMouseXY(e) {
  	if (IE) {
  		if (event && document.body) { 
    	 tempX = event.clientX + document.documentElement.scrollLeft;
    	 tempY = event.clientY + document.documentElement.scrollTop;
      }
  	} else {
    	tempX = e.pageX;
    	tempY = e.pageY;
  	}  

  	if (tempX < 0){tempX = 0}
  	if (tempY < 0){tempY = 0}  

  
  	return true;
	 }
	 
	 var IE = document.all?true:false
	 if (!IE) document.captureEvents(Event.MOUSEMOVE)
	 document.onmousemove = getMouseXY;
whisper_window_scroll_manager = function()
{
	 this.windows = new Array();
	 this.scroll_delegate = Function.createDelegate(this, this.scroll);
	 jyingo.addEvent(window,'scroll',this.scroll_delegate);
}
whisper_window_scroll_manager.prototype = {
	
	scroll : function(wnd)
	{
		 
		 for (var i =0; i < this.windows.length; i++)
		  this.windows[i].scroll();
		
	},
	
	add_window : function(wnd)
	{
		 this.windows.push(wnd);
	},
	
	remove : function(wnd)
	{ 
		
		for (var i = 0; i < this.windows.length;i++)
		{
			 if (this.windows[i].user_id == wnd.user_id)
			 {
			   this.windows[i].splice(i, 1);
			   return;	
			 }
		}
		
	}
	
}

wmgr= new whisper_window_scroll_manager();

whisper_window = function(user_id)
{
	this.user_id = user_id;
	var el = document.createElement('div');
	
	this.divId = 'chatuser'+user_id;
	el.id = this.divId;
	
	var up = document.createElement('div');
	var down = document.createElement('div');
	var textbox = document.createElement('div');
	
	el.appendChild(up);
	el.appendChild(down);
	el.appendChild(textbox);
	el.onselectstart = Function("return false");
	up.onselectstart = Function("return false");
	
	this.delegate_scroll = Function.createDelegate(this, this.scroll);
	
	wmgr.add_window(this);
	
	el.style.left = '200px';
	el.style.top = '200px';
	
	el.onmousemove = Function("aIM.hidemenu();");
	
	el.className = 'whisper_window';
	up.className = 'my_info';
	up.onmousedown = function(event)
	{
		dragStart(event, 'chatuser'+user_id, user_id);
	}
	down.className = 'chat';
	
	//up.innerHTML = '<img onselectstar="return false" src="'+aIM.frienddata[user_id][1][2]+'" width="40" height="40" /><span onselectstar="return false" >'+aIM.frienddata[user_id][1][1];
	if (aIM.frienddata[user_id][1][3] == true)
	  up.innerHTML = '<img onselectstar="return false" src="'+aIM.frienddata[user_id][1][2]+'" width="40" height="40" /><span onselectstar="return false" id="user_span_'+user_id+'">'+aIM.frienddata[user_id][1][1]+' <i style="font-weight:normal">(inattivo)</i></span>';
	else
		up.innerHTML = '<img onselectstar="return false" src="'+aIM.frienddata[user_id][1][2]+'" width="40" height="40" /><span onselectstar="return false" id="user_span_'+user_id+'">'+aIM.frienddata[user_id][1][1]+'</span>';

	textbox.className = 'textbox';
	textbox.innerHTML = '<input type="text" id="txt_send_'+user_id+'" class="txt"  /> <input type="button" id="btn_send_'+user_id+'" value="Invia" class="btnpiccolo" />';
	
	
	
	var closer = document.createElement('a');
	closer.className = 'closer';
	closer.onmousemove = Function.createDelegate(this, this.mousemove);
	closer.onmousedown = Function.createDelegate(this, this.mousedown);
	closer.onmouseout = Function.createDelegate(this, this.mouseout);
	closer.onclick = Function.createDelegate(this, this.close);
	closer.href = '#';

  this.oldScrollTop = document.documentElement.scrollTop;
  var p = document.createElement('div');
  p.style.clear='right';
	
	up.appendChild(closer);
	
	aIM.push_wnd(this);
	
  up.appendChild(p);
	
	document.body.appendChild(el);
	
	this.mainEl = el;
	this.boxEl = down;
	this.textEl = textbox;
	this.closerEl = closer;
	
	$get('txt_send_'+user_id).onkeypress = Function.createDelegate(this, this.keyp);
	$get('btn_send_'+user_id).onclick = Function.createDelegate(this, this.send);
	
	this.tipotxt = -1;
	this.contcont = 0;
	this.vuoto = true;
	this.last_time=-1;
	

	
}

whisper_window.prototype = {
	
	show : function()
	{
		 
	if (aIM.frienddata[this.user_id][1][3] == true)
	  $get('user_span_'+this.user_id).innerHTML = aIM.frienddata[this.user_id][1][1]+' <i style="font-weight:normal">(inattivo)</i>';
	else
		$get('user_span_'+this.user_id).innerHTML = aIM.frienddata[this.user_id][1][1];
		 
		 this.mainEl.style.display='block';
		// 	$get('txt_send_'+this.user_id).focus();
	},
	
	setpos : function()
	{
		
		var maxW = getX($get('chatbutton'));
		var y = getY($get('chatbutton'))+35;
		
		for ( var i = 0; i < aIM.arrwnds.length; i++)
		{
			
			 var k = aIM.arrwnds[i];
			 if (k.user_id<1) continue;

			 if ( parseInt(k.mainEl.style.left) == parseInt(maxW) )
			  maxW += 301;
			
		}
		
		this.mainEl.style.left = maxW+'px';
		this.mainEl.style.top=(y+document.documentElement.scrollTop)+'px';
		
	},
	
	keyp : function(evt)
	{
		 
		 if (!evt)
		  evt = window.event;
		 
		 if (evt.keyCode == 13)
		  this.send();
		 
	},
	
	addcode : function(code)
	{
		 this.boxEl.innerHTML += code;
		 this.boxEl.scrollTop = this.boxEl.scrollHeight;
		 
	},
	
	vv : function(x)
	{ 
		
		 if (x < 10) return '0'+x;
		 return x;
		
	},
	
	get_time : function(tm)
	{
		if (tm == undefined)
		 var p = new Date();
		else
		 var p = new Date(tm*1000);
		 
		 return this.vv(p.getHours())+':'+this.vv(p.getMinutes())+':'+this.vv(p.getSeconds());
	},
	
	addtxt : function(tipo, txt, col, tempo)
	{
		 this.vuoto = false;
		 
		 if (this.tipotxt != tipo || (this.contcont++)==6 || (tempo-this.last_time > 3600) )
		 {
		 	if (this.tipotxt != -1)
		 	 this.addcode('<div class="sep"></div>');
		 	 this.contcont = 0;
		 	  tt = this.get_time(tempo);
		 	 
		 	 if (tipo == 1)
		 	 {
		 	 	 this.addcode('<div class="nck"><span class="gr">'+unescape(aIM.nickname)+' scrive:</span></div><div class="time">'+tt+'</div><div style="clear:left; clear:right"></div>');
		 	 }
		 	 else if (tipo == 2)
		 	 {
		 	 	 this.addcode('<div class="nck">'+unescape(aIM.frienddata[this.user_id][1][1])+' scrive:</div><div class="time">'+tt+'</div><div style="clear:left; clear:right"></div>');	
		 	 }
		 	 
		 	 this.tipotxt = tipo;
		   this.last_time = tempo;
		 }
		 
		 if (col == 0)
		 {
		 	 this.addcode('<div class="msg">'+aIM.parse_emo(special_chars(txt))+'</div>');
		 }
		 if (col == 1)
		 {
		 	 this.addcode('<div class="info">'+special_chars(txt)+'</div>');
		 }		 
	},
	
	send : function()
	{
		
		if (aIM.frienddata[this.user_id] == undefined)
		{
			this.addtxt(3, 'Utente offline',1, aIM.resptime);
			return;
		}
		 var t = trim($get('txt_send_'+this.user_id).value);
		 if (t.length == 0) return;
		
		 aIM.playsound();
		 this.addtxt(1, (t) , 0, aIM.resptime);
		 $get('txt_send_'+this.user_id).value = '';
		 
		 aIM.command('msg', new Array(this.user_id, escape(t)));
	},
	
	hide : function()
	{
		this.mainEl.style.display = 'none';
	},
	
	mousemove : function()
	{
		 this.closerEl.style.backgroundImage = 'url(http://www.fuoriditesta.it/addon/im/close_on.png)';
	},
	
	mouseout : function()
	{
		this.closerEl.style.backgroundImage = 'url(http://www.fuoriditesta.it/addon/im/close_off.png)';
	},
	
	move : function(x,y)
	{
		 this.mainEl.style.left=x+'px';
		 this.mainEl.style.top=(y+document.documentElement.scrollTop)+'px';
	},
	
	scroll : function()
	{
		
		var curY = parseInt(this.mainEl.style.top);
		curY+= (document.documentElement.scrollTop-this.oldScrollTop);
		this.mainEl.style.top=curY+'px';
		
		
		this.oldScrollTop = document.documentElement.scrollTop;
	},
	
	mousedown : function()
	{
		this.closerEl.style.backgroundImage = 'url(http://www.fuoriditesta.it/addon/im/close_on.png)';
  },
  	
	destroy : function()
	{ 
		this.mainEl.innerHTML = '';
		this.mainEl.id = '';
		this.user_id=-11111;
		document.body.removeChild(this.mainEl);
		wmgr.remove(this);
 	
	},
	
	close : function()
	{
		if (aIM.frienddata[this.user_id] != undefined)
		 aIM.frienddata[this.user_id][0] = false;
		 aIM.command('close', this.user_id);
		 this.mainEl.style.display='none';
		 return false;
	}
	
	
	
};

var aIM = new addon_im();


var dragObj = new Object();
dragObj.zIndex = 22222;
var msEvent;

function dragStart(event, id, ww) {

  var el;
  var x, y;
  
  dragObj.ww = ww;


  dragObj.elNode = document.getElementById(id);

  if (browser.isIE) {
  	
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

 

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;


  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
  	
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;


  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }
  
  if (approx((dragObj.elStartLeft + x - dragObj.cursorStartX),15) > -200)
  dragObj.elNode.style.left = approx((dragObj.elStartLeft + x - dragObj.cursorStartX),15) + "px";
  
  if ( approx((dragObj.elStartTop  + y - dragObj.cursorStartY - document.documentElement.scrollTop),15) > -15)
  dragObj.elNode.style.top  = approx((dragObj.elStartTop  + y - dragObj.cursorStartY),15) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function approx(val, to) { return Math.floor(val/to)*to; }

function dragStop(event) {

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
  
  aIM.command('move', new Array(dragObj.ww, parseInt(dragObj.elNode.style.left), parseInt(dragObj.elNode.style.top)-document.documentElement.scrollTop));
}

window.onbeforeunload = Function.createDelegate(aIM,aIM.destroy);



 function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}
var browser = new Browser();
 
 var smartCallQueue = new Array();
  
 function eseguiPost(szurl, parametri, callback)
 {
   
   
   if (smartCallQueue.length != 0)
   {
    smartCallQueue.push(new Array(1, szurl, parametri, callback ));
    return;
   }
   
   var obj = inizializzaRichiesta();

   obj.onreadystatechange = function() {
    
    if (obj.readyState == 4) {
       if (obj.status == 200) {
          callback(obj.responseText);
          setTimeout(processNextSmartCall, 0);
       }
    }
   };
   
   obj.open('POST', szurl, true);
   obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   obj.setRequestHeader("Content-length", parametri.length);
   obj.setRequestHeader("Connection", "close");
   obj.send(parametri);

 }


function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime() + Math.random();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}



 function processNextSmartCall()
 { 
 	  if (smartCallQueue.length == 0)
 	   return;
 	  
 	  var el = smartCallQueue.shift();
 	  if (el[0] == 0)
 	   eseguiGet(el[1], el[2]);
 	  else
 	   eseguiPost(el[1], el[2], el[3]);
 } 
 
 
 function inizializzaRichiesta()
 {
 
  var http_request = false;
 
  if (window.XMLHttpRequest) {
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
  } else if (window.ActiveXObject) {
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
  }
  if (!http_request) {
         alert('Impossibile inizializzare correttamente il sito web. Aggiornare il proprio browser.');
         return false;
  }
  return http_request;
 }
 
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function remove_ands(txt)
{
    return global_replace('&', '&#038;', txt);
}
function special_chars(txt)
{
    var process = txt;
    process = remove_ands(process);
    process = global_replace('<', "&lt;",process);
    process = global_replace('>', "&gt;",process);
    process = global_replace('"', "&quot;",process);
    process = global_replace("'", "&#039;",process);
    return process;
}
