/* VARIABILI */
var quickrepsize = 95; //85
var speed = 12; //12
//var lista = new Array("utenti", "amici", "ricerca", "compleanni", "stats", "utente", "forum");
var lista = new Array("utenti", "amici", "ricerca", "compleanni", "stats");


function setVisibility(id, way){
	//way stabilisce se display va su inline, block o none
	var el=document.getElementById(id);
	if(setVisibility.arguments[1]){
		el.style.display = way;
		
	}else{
		el.style.display = (el.style.display=="none") ? "inline" : "none";	
	}
}

function display(){

	for(var i = 0;arguments[i];i++){
	var id = arguments[i];
		switch( typeof(id) ){
			case 'string':
			//alert('stringa'+document.getElementById(id));
				var el = document.getElementById(id);
				el.style.display = (el.style.display=="none") ? "inline" : "none";
			break;
			
			case 'object':
			//alert('oggetto'+id);
				id.style.display = (id.style.display=="none") ? "inline" : "none";
			break;
		}
	}

}

//display( document.getElementById('firedout') );

function show(id){
//imposta quale barra mostrare, evidenzia in grassetto quella selezionata e salva in un cookie quella attiva.
	for(var i = 0;lista[i];i++){

	var text=document.getElementById("testo_"+lista[i]);
	var trigger=document.getElementById("trg_"+lista[i]);

	trigger.style.fontWeight = (lista[i]==id) ? "bold" : "normal";
	text.style.display = (lista[i]==id) ? "inline" : "none";
	
	}
	var showBar = new fx.Opacity('testo_'+id , {duration: 1000, transition: fx.sinoidal});
	showBar.hide();
	showBar.custom(0.3,1);
	//fadeIn("testo_"+id, 2);	
	setCookie("frdt_bar", id, 2);
}

function setbar(){
//se non c'è il cookie con la barra salvata imposta quella di default
var par = getCookie("frdt_bar");
var check = false;
for(var i = 0;lista[i];i++){
	if(par==lista[i]){
		check = true;
		break;	
	}
}
if(!check) par = "utenti";
show(par);
}

/*COOKIE*/

function setCookie(name,value,expire){
//salva un cookie "name", con valore "value", "expire" sono i giorni di vita del cookie.
var expdate=new Date()
expdate.setTime(expdate.getTime()+(expire*24*3600*1000))

document.cookie=name+"="+escape(value)+((expire==null) ? "" : "; expires="+expdate)
}

function getCookie(name){
//legge il contenuto del cookie "name"
if (document.cookie.length==0) return false;
c_start=document.cookie.indexOf(name + "=")
if (c_start==-1) return false;
  
c_start=c_start + 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))
}


function smile(obj,text) {
document.getElementById(obj).value+=text;
document.getElementById(obj).focus();
} 

/*QUOTE*/
function getQuote(post,thread){
var el = document.getElementById('forumrep');
xmlhttpreq("xmlhttpreq/quote.php", "quote="+post+"&3d="+thread, "GET", "quote", el);
}

/*QUICK REPLY*/
function showQuickrep(node,toid){

	el = document.getElementById('cid' + node);
	//se il div è già aperto, lo nascondo
	if(el.style.display == "block"){
		el.style.display = "none";
		return false;
	}
	//altrimenti creo il form per rispondere
	el.innerHTML = '<br><form method="post" onSubmit="sendQuickRep(this, '+node+'); return false;"><textarea id="textarea" name="textrep" cols="60" rows="3"></textarea><br>	<input style="border: none;" type="checkbox" name="privato" value="1">&nbsp;Privato&nbsp;&nbsp;	<input type="hidden" value="' + toid + '" name="toid">	<input type="hidden" value="' + node + '" name="cid"><input type="submit" name="subquickrep" value="Rispondi" accesskey="s"> <span id="quickreperror'+node+'" class="error"></span></form>';
	el.style.display = "block";
	
	var showQuickrep = new fx.Height('cid' + node , {duration: 500, transition: fx.circ, onComplete: function(){document.getElementById('textarea').focus();} });
	showQuickrep.hide();
	showQuickrep.toggle();
	return false;
}

function sendQuickRep(form, node){
	el = document.getElementById('cid' + node);
	if(form.textrep.value == ""){
		document.getElementById("quickreperror"+node).innerHTML = 'Non puoi inviare un messaggio vuoto';
		return false;
	}
	
	xmlhttpreq("xmlhttpreq/inviacommento.php", formatHttpvars(form), "POST", "quickrep", el);

}


/*XMLHTTPREQUEST*/

/*tramite xhr carica l'url inviando le variabili contenute nella stringa string col metodo method.
display ed element personalizzano il messaggio di successo\insuccesso.*/
function xmlhttpreq(url, string, method, display, element){

		var xmlHttpReq = new XMLHttpRequest();

		//xmlHttpReq.open((method == "GET") ? method : "POST", url + ( (method == "GET") ? "?" + string : "" ));
		xmlHttpReq.open((method == "GET") ? method : "POST", url + ( (method == "GET") ? ( (string == '') ? '' : "?" + string ) : "" ));
		xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		
		//aggiungo un listener sullo stato
		xmlHttpReq.onreadystatechange = function(){
			//1: loading
			if (xmlHttpReq.readyState == 1) {
				switch(display){
				case "quickrep":
					element.innerHTML = '<br><br><i>Invio messaggio in corso...</i>';
				break;
				case "cronologia":
					element.innerHTML = '\n<i>Caricamento in corso...</i>';
				break;
				case "inviavoto":
					//alert(element.innerHTML);
					element.innerHTML = '<i>Salvataggio voto...</i>';
				break;

				}

       		}
			//4: completed
			if (xmlHttpReq.readyState == 4) {
        		//controllo eventuali errori
				if (xmlHttpReq.status == 200) {
					switch(display){
					case "quickrep":
						element.innerHTML = '<br><br>'+xmlHttpReq.responseText;
					break;
					case "quote":
						//alert(string);
						//alert(xmlHttpReq.responseXML);
						element.value = element.value+"\n"+xmlHttpReq.responseText;
						element.focus();
					break;
					case "cronologia":
						//alert(element);
						element.innerHTML = xmlHttpReq.responseText;
					break;
					case "nuovicommenti":
						var string = xmlHttpReq.responseText;

						var bar = string.substr(0, string.indexOf('|sep|'));
						var grow = string.substr(string.indexOf('|sep|')+5);
						
						if(bar != 'false') document.getElementById('ncbar').innerHTML = bar; 

						if(grow != 'false'){
							
							growList.push(grow);
							Growler();
							//riproduce un suono
							//document.getElementById('sound').Play();
						}
						//alert("grow vale:"+grow+";");
						//alert("bar vale:"+bar+";");
						//element.innerHTML = xmlHttpReq.responseText;
					break;
					case "inviavoto":
						eval(xmlHttpReq.responseText);
						//alert(xmlHttpReq.responseText);
						element.innerHTML = unescape(captionText);
						if(nuovaMedia){
							var testo = '';
							
							for(i=1;i<=Math.round(nuovaMedia);i++) testo += '<img src="immagini/vote.gif">';
							testo += ' '+nuovaMedia+'/10';
							document.getElementById('divMedia').innerHTML = testo;
							
							var hideForm = new fx.Height('formVoto', {duration: 1500, transition: fx.sinoidal});
							hideForm.toggle();
							//showBar.custom(0.3,1);
							//document.getElementById('formVoto').style.display = 'none';
							//setCookie(userId+"->"+userProfileId,timeStamp,2);
							//alert(toUser);
							
						}
					break;
					}
				} else {
					alert("There was a problem retrieving the XML data:\n" + xmlHttpReq.statusText);
				}
				//interrompe il submit del form
				return false;
       		}
		}
		
		xmlHttpReq.send((method == "GET") ? null : string);

}


function formatHttpvars(docForm) {
//by Matthew Eernisse
  var submitContent = '';
  var formElem;
  var lastElemName = '';
  
  for (i = 0; i < docForm.elements.length; i++) {
    
    formElem = docForm.elements[i];
    switch (formElem.type) {
      // Text fields, hidden form elements
      case 'text':
      case 'hidden':
      case 'password':
      case 'textarea':
      case 'select-one':
        submitContent += formElem.name + '=' + escape(formElem.value) + '&'
        break;
        
      // Radio buttons
      case 'radio':
        if (formElem.checked) {
          submitContent += formElem.name + '=' + escape(formElem.value) + '&'
        }
        break;
        
      // Checkboxes
      case 'checkbox':
        if (formElem.checked) {
          // Continuing multiple, same-name checkboxes
          if (formElem.name == lastElemName) {
            // Strip of end ampersand if there is one
            if (submitContent.lastIndexOf('&') == submitContent.length-1) {
              submitContent = submitContent.substr(0, submitContent.length - 1);
            }
            // Append value as comma-delimited string
            submitContent += ',' + escape(formElem.value);
          }
          else {
            submitContent += formElem.name + '=' + escape(formElem.value);
          }
          submitContent += '&';
          lastElemName = formElem.name;
        }
        break;
        
    }
  }
  // Remove trailing separator
  submitContent = submitContent.substr(0, submitContent.length - 1);
  return submitContent;
}


//array per gli effetti
var showGrow = new Array();	
//lista dei vari messaggi
var growList = new Array();

function Growler(){

	if(showGrow.length>0){
		//alert('sto ancora mostrando i growler');
		setTimeout('Growler();',showGrow.length*300+7500+100);
		return false;
	}
		
	for(i=0;growList[i];i++){
		//alert(growList[i]);
		var oNewNode = document.createElement("div");
   		document.getElementById('growlerHook').appendChild(oNewNode);
		//document.body.appendChild(oNewNode);
		oNewNode.id = "growl"+i;
		oNewNode.className = "growler";
		oNewNode.innerHTML= growList[i];

		//array di tutti gli effetti	
		showGrow[i] = new fx.Opacity('growl'+i , {duration: 2500, transition: fx.sinoidal});
		//nasconde il div preparandolo ad essere mostrato
		showGrow[i].hide();
		//posizione i div in fila verticalmente.
		document.getElementById('growl'+i).style.top = i*100+"px";


	} 
	//per ogni elemento della lista imposta un timeout e mostra l'effetto.
	//alert(showGrow);
	for(var i = 0;showGrow[i];i++){
		setTimeout('showGrow['+i+'].custom(0,0.6);',i * 300);	
		setTimeout('showGrow['+i+'].custom(0.6,0);',i * 300 + 5000);
	}
	//400ms di delay prima di azzerare 
	setTimeout('showGrow = new Array(); document.getElementById(\'growlerHook\').innerHTML = \'\';', showGrow.length*300+7500+100);
	//alert(showGrow);
	//azzera le varie liste
	growList = new Array();
	//alert(growList.length);


}

/*Grafica intercambiabile*/
function switchBackground(file,cssdec){

setCookie("frdt_bg",file,365*3);
document.getElementsByTagName('body')[0].style.background = cssdec;
}

/*MODULI*/
function enableEsterno(){
document.getElementById('sezione').disabled = (document.getElementById('sezione').disabled) ? false : true;
document.getElementById('anno').disabled = (document.getElementById('anno').disabled) ? false : true;
}

/*CRONOLOGIA*/
function cronologia(uid, cid){
	var el = document.getElementById('cron'+cid);
	if(el.style.display == "block"){
		el.style.display = "none";
		return false;
	}
	el.style.display = "block";
	xmlhttpreq("xmlhttpreq/cronologia.php", "partner="+uid, "GET", "cronologia", el);
	return false;
}
/*NUOVI COMMENTI*/
var countCommenti = 0;
function nuoviCommenti(){
	var delay;
	countCommenti++;
	
		if(countCommenti<=2) delay = 10000; 
		else if(countCommenti>2 && countCommenti<=4) delay = 15000;
		else if(countCommenti>4 && countCommenti<=6) delay = 20000;
		else if(countCommenti>6 && countCommenti<=8) delay = 25000;
		else if(countCommenti>8 && countCommenti<=10) delay = 30000;
		else delay = false;
	
	//alert("refresh:"+countCommenti+"; delay:"+delay);
	
	xmlhttpreq("xmlhttpreq/nuovicommenti.php", '', "GET", "nuovicommenti", '');
	if(delay != false) setTimeout('nuoviCommenti()',delay);
}

function inviaVoto(form){

el = document.getElementById('voteText');
if(el.className != "gray") el.className = "gray";

if(form.voto_utente.value == "false"){
	//el.className = "error";
	el.innerHTML = 'Seleziona un voto da assegnare';
	return false;
}
	var showText = new fx.Opacity('voteText', {duration: 300, transition: fx.sinoidal});
	showText.hide();
	showText.toggle();
	xmlhttpreq("xmlhttpreq/inviavoto.php", formatHttpvars(form), "POST", "inviavoto", el);
}
