//***************VARIABILI GLOBALI**************************//

// per la chat
var mousePosx; // posixione x del mouse
var mousePosy; // posixione y del mouse
var CurrentChat=0; // è l'id della chat corrente ovvero l'ultima selezionata
var CurrentUser='null'; // è la variabile che mappa su js l'id dell'utente loggato
var new_message_chat = new Array(); // è un array di chat che setta per ogni chat su cui ci sono messaggi non letti il valore on, altrimenti off

// variabile per la url corretta alle pagine php via ajax
/*var GlobalConfigUrl='http://37.232.28.131/';*/
var GlobalConfigUrl='http://www.studentoffice.it/';

//***************AZIONI GLOBALI**************************//
// occorre per recuperare la posizione del mouse
document.onmousemove=getMouse;

//***************FUNZIONI**************************//

// apre il form nascosto delle mail
function apriFormMail(to,subject,message){
	if(CurrentUser=='null') {
	alert('Occorre effettuare il LogIn per inviare una mail!'); }
	else {
	document.getElementById('mailSfondo').style.visibility='visible';
	document.getElementById('mailForm').style.visibility='visible';
	document.getElementById('ToUserMail').value=to;
	document.getElementById('IdFromUserMail').value=CurrentUser;
	document.getElementById('oggettoUserMail').value=subject;
	document.getElementById('testoUserMail').value=message;
	}
}
// chiude il form nascosto delle mail
function chiudiFromMail(){
	document.getElementById('mailSfondo').style.visibility='hidden';
	document.getElementById('mailForm').style.visibility='hidden';
	document.getElementById('ToUserMail').value="";
	document.getElementById('IdFromUserMail').value="";
	document.getElementById('oggettoUserMail').value="";
	document.getElementById('testoUserMail').value="";
}

// aggiunge le mail degli id delle mailing list passati in una stringa sepatati dal punto
function aggiungiMailingListToDestinatari(stringa){
	var xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{	alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=gestoreEmail/recuperaMailDaMailingList.php&stringa='+stringa;
	url=url+'&sid='+Math.random();

	xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4)
			{
			var destinatari=document.getElementById('MailDestinatari');
			if(destinatari.value==''||destinatari.value==' ') destinatari.value=xmlHttp.responseText;
			else if(xmlHttp.responseText!=''||xmlHttp.responseText!=' ')destinatari.value=destinatari.value+xmlHttp.responseText;
			}
		};
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
}

function aggiungiUtentiListToDestinatari(stringa){
	var xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{	alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=gestoreEmail/recuperaMailDaUtenti.php&stringa='+stringa;
	url=url+'&sid='+Math.random();

	xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4)
			{
			var destinatari=document.getElementById('MailDestinatari');
			if(destinatari.value==''||destinatari.value==' ') destinatari.value=xmlHttp.responseText;
			else if(xmlHttp.responseText!=''||xmlHttp.responseText!=' ')destinatari.value=destinatari.value+xmlHttp.responseText;
			}
		};
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
}

// dati from to oggetto e testo-messaggio manda una mail

function inviaMail(from, to, subject, message){
    var xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{	alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=mail/inviaMail.php&from='+from+'&to='+to+'&subject='+subject+'&message='+message;
	url=url+'&sid='+Math.random();

	xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4)
			{
			alert("mail inviata correttamente");
			}
		};
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
}



//recupera la posizione del mouse
function getMouse(e){
	mousePosx=0;mousePosy=0;
	var ev=(!e)?window.event:e;//IE:Moz
	if (ev.pageX){//Moz
		mousePosx=ev.pageX+window.pageXOffset;
		mousePosy=ev.pageY+window.pageYOffset;
	}
	else if(ev.clientX){//IE e chrome
		mousePosx=ev.clientX+document.body.scrollLeft;
		mousePosy=ev.clientY+document.body.scrollTop;
	}
	else{return false}// vecchiume
}

// ogni secondo aggiorna i messaggi della sezione corrente se una chat è in corso ed è visibile
function aggiorna_messaggi(htmlId,id_user){
    var doc=document.getElementById('chatInterface');
	if(doc.style.display=='block'){
	setTimeout("aggiorna_messaggi('"+htmlId+"','"+id_user+"')", 1000);
	var xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{	alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=chat/aggiornaChatMessaggi.php&id_chat='+CurrentChat+'&id_user='+id_user;
	url=url+'&sid='+Math.random();

	xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4)
			{
			    document.getElementById(htmlId).innerHTML=xmlHttp.responseText;
			    var objDiv = document.getElementById("chatInterfaceMessaggi");
				objDiv.scrollTop = objDiv.scrollHeight;
			}
		};
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
	}
}

//l'insieme delle azioni che devono essere compiute sul div di una chat quando sono arrivati nuovi messaggi
function segnalaNuoviMessaggi(){
	for(var chat in new_message_chat){
	  if(new_message_chat[chat]=='on') {
		var chatIn=document.getElementById('chatInterface');
		    var doc=document.getElementById('chat'+chat);
		    if (doc!=null){ doc.style.fontWeight='bold';
  				   doc.style.height='30px';
				   doc.style.color='#fff';
   				   doc.style.background='#f00';
             }
          }
	}
}


// è la funzione che viene invocata cliccando sualla barra delle chat
function onClickInChat(id_conv,id_user, nomeConv){
	var doc=document.getElementById('chatInterface');
	doc.style.display='block';
	doc.style.left=mousePosx+'px';
	CurrentChat=id_conv;
	aggiorna_messaggi('chatInterfaceMessaggi',id_user);
	var nom=document.getElementById('chatInterfaceNome');
	nom.innerHTML=nomeConv;
	var input=document.getElementById('chText');
	input.focus();
	new_message_chat[id_conv]='off';
}

// è la funzione che, quando si clicca su di un utente on line salva su db una nuova conversazione
function avvia_conversazione_chat(id_user,id_ricevente,nome_ricevente){
	var xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{	alert ('Browser does not support HTTP Request');
  		return;
  	}
	if(id_user!='null'){
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=chat/avviaConversazioneChat.php&id_user='+id_user+'&id_ricevente='+id_ricevente;
	url=url+'&sid='+Math.random();

	xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4)
			{
			   CurrentChat=xmlHttp.responseText;
			   var objDiv = document.getElementById("chatInterface");
				if(objDiv!=null) {
				objDiv.style.left='80%';
				objDiv.style.display='block';
			   }
				var nom=document.getElementById('chatInterfaceNome');
				if(nom!=null) {	nom.innerHTML=nome_ricevente;}
			  aggiorna_messaggi('chatInterfaceMessaggi',id_user);
			}
		};
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
	}
	else {
	alert("Occorre effettuare il LogIn per accedere alla Chat");
	}
}
// invia un messaggio specificando il mittente e la conversazione
function invia_messaggio_chat(id_conv,testo,id_mittente){
	var xmlhttp3=GetXmlHttpObject();
	if (xmlhttp3==null)
  	{
		alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=chat/inviaMessaggioChat.php&id_conv='+id_conv+'&testo='+testo+'&id_mittente='+id_mittente;
	url=url+'&sid='+Math.random();
	xmlhttp3.onreadystatechange=function(){};
	xmlhttp3.open('GET',url,true);
	xmlhttp3.send(null);
}

//ogni due secondi verifica se ci sono nuovi messaggi ancora non letti su una chat non attiva e se ci sono colora di rosso la chat fino
// a che l'utente non clicca sulla barra
function evidenzia_chat_messaggi(id){
	setTimeout("evidenzia_chat_messaggi("+id+")",2000);
	var xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{
		alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=chat/ListaNuoviMessaggiChat.php&id='+id;
	url=url+'&sid='+Math.random();

	xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4)
			{   // la stringa che ricevo è l'elenco degli id delle chat separati da punto e virgola
			    //parso la stringa
			       var tempArray= new Array();
				if (xmlHttp.responseText!=""){
				 tempArray=xmlHttp.responseText.split(";");
				  for(var index in tempArray){
			    	 //se non è la chat corrente e contemporaneamente non è visibile la chatInterface
				     if(CurrentChat!=tempArray[index] || document.getElementById('chatInterface').style.display=='none') {
				        new_message_chat[tempArray[index]]='on';
                                        //document.getElementById("sound").Play();                     
				     }
				  }

				}
			segnalaNuoviMessaggi();
			}
		};
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
}

// aggiorna le chat attive, ovvero la barra delle chat in basso al sito si attiva ogni 2 secondi
function aggiorna_chat(id,htmlId){
	setTimeout("aggiorna_chat("+id+",\'"+htmlId+"\')",2000);
	var xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
  	{
		alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=chat/aggiornaChat.php&id='+id+'&htmlId='+htmlId;
	url=url+'&sid='+Math.random();

	xmlHttp.onreadystatechange=function(){
				if (xmlHttp.readyState==4)
			{
			    document.getElementById(htmlId).innerHTML=xmlHttp.responseText;
					segnalaNuoviMessaggi();
			}
		};
	xmlHttp.open('GET',url,true);
	xmlHttp.send(null);
}

// ogni 5 secondi verifica se ci sono rappresentanti on line,
// viene invocata da tutti gli utenti anche non loggati se è presente uno smart view di chat
function rappresentanti_on_line(htmlId,id_fac){
	setTimeout("rappresentanti_on_line('"+htmlId+"',"+id_fac+")",5000);
	var id2=htmlId;
	var xmlhttp3=GetXmlHttpObject();
	if (xmlhttp3==null)
  	{
		alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url=utenti/rappresentantiOnLine.php&id_fac='+id_fac+'&id='+CurrentUser;
	url=url+'&sid='+Math.random();

	xmlhttp3.onreadystatechange=function(){
			    if (xmlhttp3.readyState==4)
			{
				document.getElementById(id2).innerHTML=xmlhttp3.responseText;
			}
		};
	xmlhttp3.open('GET',url,true);
	xmlhttp3.send(null);
}
// una funzione che 5 secondi notifica che un utente  LOGGATO è on-line
function im_on_line(idUser,htmlId){
setTimeout('im_on_line('+idUser+', "usersOnline")',5000);
url=GlobalConfigUrl+'/xmlhttpRequest.php?url=utenti/utentiOnLine.php&id='+idUser+'&sid='+Math.random();
var xmlhttp2=GetXmlHttpObject();
if (xmlhttp2==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
xmlhttp2.onreadystatechange=function(){};
xmlhttp2.open("GET",url,true);
xmlhttp2.send(null);
}


function call_a_page(url, str, html)
{
	var xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
  	{
		alert ('Browser does not support HTTP Request');
  		return;
  	}
	url=GlobalConfigUrl+'/xmlhttpRequest.php?url='+url+'&'+str;
	url=url+'&sid='+Math.random();
	xmlhttp.onreadystatechange=function stateChanged()
		{
			if (xmlhttp.readyState==4) {
		 	    document.getElementById(html).innerHTML=xmlhttp.responseText;
			}
		};

	xmlhttp.open('GET',url,true);
	xmlhttp.send(null);
}


function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}						
