// funzioni globali
UTF8 = {
    encode: function(s){
        for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
            s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
        );
        return s.join("");
    },
    decode: function(s){
        for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
            ((a = s[i][c](0)) & 0x80) &&
            (s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
            o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
        );
        return s.join("");
    }
};

function switchVal(obj){
                if(obj.parentNode.lastChild.value==1){
                        obj.parentNode.lastChild.value = 0;
                        obj.style.fontWeight = "normal";
                        obj.style.color = "white";
                }else{
                        obj.parentNode.lastChild.value = 1;
                        obj.style.fontWeight = "bolder";
                        obj.style.color = "orange";
                }
}

function alertUtf8(str){
  alert(UTF8.decode(str));
}

function controlloTesto(maxWord,campo,countWord){
    var i=0;

    //var  campoTesto = document.getElementById('boxTestoCount');
    //alert(campoTesto.value.length);

    campoTesto = document.getElementById(campo);

    if(((maxWord - campoTesto.value.length) == 0) || ((campoTesto.value.length) > maxWord )){

            word = document.getElementById(countWord);
            word.innerHTML = 0;

    }else {
            word = document.getElementById(countWord);
            word.innerHTML = "<span style='color:darkblue'>"+(maxWord - campoTesto.value.length)+"</span>";
    }
    if(campoTesto.value.length > maxWord){
    
            wordWrite = campoTesto.value;
            //rinserisco il testo nel textarea eliminando il testo in pi cio quello che supera i 230 caratteri.
            //document.forms[0].testoFlash.value = wordWrite.substr(0,maxWord);
            campoTesto.value = wordWrite.substr(0,maxWord);
            //alert("Hai superato il numero di caratteri consentiti.")
    }
}

function addOnScroll() {

var htmlEl = document.getElementsByTagName('html')[0];
htmlEl.onscroll = function() {doSomething();}

}

function buildUri(obj){
  var strUri = "";
  for(var n=0; n<obj.elements.length; n++){
    if(obj.elements[n].name!=""){
		stri = obj.elements[n].value;
    	reg = new RegExp("\\+","g");
    	stri = stri.replace(reg,"caratzPiu");
    	reg = new RegExp("€","g");
    	stri = stri.replace(reg,"caratzEuro");
		strUri += "&"+obj.elements[n].name+"="+escape(stri);
		strUri = strUri.replace("caratzPiu","%2B","g");
		strUri = strUri.replace("caratzEuro","%26euro;","g");
	}
  }
  return strUri;
}


function normalizeCampo(obj){
  obj.style.border = "1px solid #999";
  obj.style.borderBottom = "1px solid #ccc";
  obj.style.borderRight = "1px solid #ccc";
}

function resetBorder(obj) {
	for(var n=0; n<obj.elements.length; n++){
	  if(obj.elements[n].name!=""){
    	obj.elements[n].style.border = "1px solid #999";
  		obj.elements[n].style.borderBottom = "1px solid #ccc";
  		obj.elements[n].style.borderRight = "1px solid #ccc";
	  }
	}
}

function indirizzoEmailValido(indirizzo) {
  if (window.RegExp) {
    var nonvalido = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
    var valido = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    var regnv = new RegExp(nonvalido);
    var regv = new RegExp(valido);
    if (!regnv.test(indirizzo) && regv.test(indirizzo))
      return true;
    return false;
  }else {
    if(indirizzo.indexOf("@") >= 0)
      return true;
    return false;
  }
}

function getForm(obj){
        while(obj.nodeName!="FORM"){
                obj = obj.parentNode;
                if(obj.nodeName == "BODY"){
                        alert("FORM NOT FOUND");
                        break;
                }
        }
        return obj;
}

function controlField(nome,id,id2,tipo){
	var colore = "#ff6600";
  switch(tipo){
    case "_":       // controlla se il campo ��? vuoto
    if(document.getElementById(id).value == false){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+colore;
    	return false;
    }else{
    	return true;
    }
    break;
    case "__":      // controlla se il campo ��? vuoto con ""
    if(document.getElementById(id).value == ""){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+colore;
    	return false;
    }else{
      return true;
    }
    break;
    case "@":       // controlla la validit��? del campo mail
    if(!indirizzoEmailValido(document.getElementById(id).value)){
      alert(nome+": campo non valido");
      document.getElementById(id).style.border = "1px solid "+colore;
      document.getElementById(id).focus();
      return false;
    }else{
      return true;
    }
    break;
    case "=":       // confronta  due campi
    if(document.getElementById(id).value != document.getElementById(id2).value){
      alert("Le Password non Coincidono");
      document.getElementById(id).focus();
      document.getElementById(id).style.border = "1px solid "+colore;
      document.getElementById(id2).value = "";
      return false;
    }else{
      return true;
    }
    break;
    case "h":       // controlla se il campo hidden ��? vuoto
    if(document.getElementById(id2).value == false){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+colore;
    	return false;
    }else{
    	return true;
    }
    break;
    case "hS":       // controlla se il campo autoSuggest ��? vuoto
    if(document.getElementById(id2).value == false){
    	if(document.getElementById(id).value == false){
    		alert(nome+": campo mancante");
    	}else{
    		alert(nome+": non presente tra i dati disponibili");
    	}
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+colore;
    	return false;
    }else{
    	return true;
    }
    break;
    case "c":       // controlla se il campo e' piu' lungo di un tot
    if(document.getElementById(id).value.length > id2){
        alert(nome+": il campo deve contenere un massimo di "+id2+" caratteri");
        document.getElementById(id).focus();
        document.getElementById(id).style.border = "1px solid "+colore;
        return false;
    }else{
        return true;
    }
    break;
    case "c-":       // controlla se il campo e' piu' lungo di un tot
    if(document.getElementById(id).value.length < id2){
        alert(nome+": il campo deve contenere almeno "+id2+" caratteri");
        document.getElementById(id).focus();
        document.getElementById(id).style.border = "1px solid "+colore;
        return false;
    }else{
        return true;
    }
    break;
    case "n":       // controlla se il campo e' un numero
    if(isNaN(document.getElementById(id).value)){
        alert(nome+": il campo deve contenere solo numeri");
        document.getElementById(id).focus();
        document.getElementById(id).style.border = "1px solid "+colore;
        return false;
    }else{
        return true;
    }
    break;
    case "img": // controllo se il file ̬ una img
	    obj = document.getElementById(id);
	    var extensions = new Array();  
		 	extensions[1] = "jpg";  
			extensions[0] = "jpeg";  
			extensions[2] = "gif";  
			/*extensions[3] = "png";  
			extensions[4] = "bmp";*/   
			var image_file = obj.value;
			var image_length = image_file.length;
			var pos = image_file.lastIndexOf('.') + 1;   
			var ext = image_file.substring(pos, image_length);   
			var final_ext = ext.toLowerCase();   
			  
			for (i = 0; i < extensions.length; i++){   
			    if(extensions[i] == final_ext){
					return true;   
			    }   
			}
			alert("Seleziona un'immagine con una delle seguenti estensioni:\n\n gif, jpeg, jpg");
			return false;
		break;
	  default:
	  alert("tipo non riconosciuto");
	  return false;
  }
}

function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}

function viewMex(mex){
	dTop = document.body.scrollTop+200;
	document.getElementById('loader').innerHTML = "<img src=\"img/loading.gif\" style=\"vertical-align: -10px\">&nbsp;&nbsp;"+mex;
	document.getElementById('loader').style.top = dTop+"px";
	document.getElementById('loader').style.display = "block";
}

function hideMex(cont,dbg){
	if(dbg){
		document.getElementById('loader').innerHTML = cont;
	}else{
		document.getElementById('loader').style.display = "none";
		document.getElementById('loader').innerHTML = "";
	}	
}

function ctrlKey(e,o){
	if(e.keyCode==13) document.getElementById(o).click();
}

function getPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	curleft += obj.x;
	return curleft;
}

function getPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	curtop += obj.y;
	return curtop;
}

function openDivEvent(w,idOpen,urlAj,corrX,corrY,doEvent){
	this.win = document.getElementById('win');
	xx = corrX;//getPosX(document.getElementById(idOpen))+corrX;
	yy = corrY+document.body.scrollTop;//getPosY(document.getElementById(idOpen))+corrY+document.body.scrollTop;;
    if(idOpen!=""){
      xx = getPosX(document.getElementById(idOpen))+corrX;
      yy = getPosY(document.getElementById(idOpen))+corrY+document.body.scrollTop;;
    }
	win.style.width = w+"px";
	//win.style.overflow = "visible";
	viewMex("Caricamento in corso...");

	myajax.post(urlAj,"");
  	myajax.echoFunction=function(response){
		hideMex(response,0);
		if(win.style.display !="block"){
    		win.style.top=yy+"px";
    		win.style.left=xx+"px";
    	}
	    win.innerHTML = response;
	    win.style.display="block";
	    Drag.init(document.getElementById("handle"),document.getElementById('win'));
		doEvent();
  }
}

function openDiv(w,idOpen,urlAj,corrX,corrY){
	this.win = document.getElementById('win');
    xx = getPosX(document.getElementById(idOpen))+corrX;
    yy = getPosY(document.getElementById(idOpen))+corrY+document.body.scrollTop;;
	win.style.width = w+"px";
	//win.style.overflow = "visible";
	viewMex("Caricamento in corso...");
	myajax.post(urlAj,"");
  	myajax.echoFunction=function(response){
		hideMex(response,0);	
        win.style.top=yy+"px";
        win.style.left=xx+"px";
	    win.innerHTML = response;
	    win.style.display="block";
  }
}

function openSelect(w,h,idName,idValue,urlAj,corrX,corrY,multi,any){
	this.win = document.getElementById('select');
	selIds = "";
	if(!multi){
		document.onmouseup=function(e){
			e = e || window.event;
			trg = e.srcElement || e.target;
			if(trg.id!="select"){
				document.getElementById('select').style.display='none';
				document.onmouseup='';
			}
		}
	}else {
		selIds = document.getElementById(idValue).value;
	}

	xx = getPosX(document.getElementById(idName))+corrX;
	yy = getPosY(document.getElementById(idName))+corrY;
	win.style.width = w+"px";
	win.style.height = h+"px";
	win.style.overflow = "auto";
	viewMex("Caricamento in corso...");
	myajax.post(urlAj,'idName='+idName+'&idValue='+escape(idValue)+'&multi='+multi+'&any='+any+'&selIds='+selIds);
	myajax.echoFunction=function(response){
		hideMex(response,0);
	    win.style.top=yy+"px";
	    win.style.left=xx+"px";
	    win.style.textAlign = "left";
	    win.innerHTML = response;
	    win.style.display="block";
	}
}

function setControl(val, obj){
  var parentObj = obj.parentNode.childNodes;
    for(i=0; i<parentObj.length; i++){
    	if(parentObj[i].nodeName == "A") parentObj[i].style.fontWeight = "normal";
    	if(parentObj[i].nodeName == "A") parentObj[i].style.color = "#014294";
	    if(parentObj[i].nodeName == "INPUT") parentObj[i].value = val;
    }
    obj.style.fontWeight = "bolder";
    //obj.style.color = "orange";
}

function multiSel(idInput,idHidden,valueInput,valueHidden,obj){
	var i=0;
	valsAr = document.getElementById(idHidden).value;
	valsAr = valsAr.split(";");
	flag = false;
	for(var i=0;i<valsAr.length;i++){
		if(valueHidden == valsAr[i]) flag = true;		
	}
	inPut = document.getElementById(idInput);
	hiPut = document.getElementById(idHidden);
	if(flag){
		// toglie item
		obj.style.fontWeight='normal';
		arText = inPut.value;
		dummy = arText.split(" - ");
		arText = dummy;
		newText = new Array();
		for(var i=0; i<arText.length; i++){
			if(arText[i] != valueInput) newText.push(arText[i]);
		}
		inPut.value = newText.join(" - ");
		// hidden
		arText = hiPut.value;
		dummy = arText.split(";");
		arText = dummy;
		newText = new Array();
		for(var i=0; i<arText.length; i++){
			if(arText[i] != valueHidden) newText.push(arText[i]);
		}
		hiPut.value = newText.join(";");
	}else {
		// aggiunge item
		obj.style.fontWeight='bolder';
		if(inPut.value != "") inPut.value += " - ";
		inPut.value += valueInput;
		// hidden
		if(hiPut.value != "") hiPut.value += ";";
		hiPut.value += valueHidden;
	}
}

function switchOnOff(idInput,idImg){
	idInputOld = document.getElementById(idInput).value;
	idInputNew = idInputOld=='0'?"1":"0";
	document.getElementById(idInput).value = idInputNew;
	img = idInputOld=='0'?"gre.gif":"red.gif";
	document.getElementById(idImg).src = "img/"+img;
}

function selCal(anno,mese,campo){
	this.win = document.getElementById("select");
	myajax.post('?cmd=selCal&mese='+mese+'&anno='+anno+'&campo='+campo,'');
	myajax.echoFunction=function(aa){
  	xx = getPosX(document.getElementById(campo));
		yy = getPosY(document.getElementById(campo))+21;
		win.style.width = "";
		win.style.height = "";
		win.style.left = xx+"px";
		win.style.top = yy+"px";
		win.innerHTML = aa;
		win.style.display = "block";
	}
}

function calcolaSelCal(id,id2,yCorr,mCorr){
  data1 = document.getElementById(id).value;
  data2 = document.getElementById(id2).value;
  if(data1!=""){
    dummy = data1.split("-");
    y = dummy[2];
    m = dummy[1];
  }else  if(data2!=""){
    dummy = data2.split("-");
    y = dummy[2];
    m = dummy[1];
  }else{
    y = yCorr;
    m = mCorr;
  }
  selCal(y,m,id);
}

function opacity(id, opacStart, opacEnd, millisec) {
    var speed = Math.round(millisec / 100);
    var timer = 0;
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}


function addCampi(tmpl,idContainer,nCampi){
	/*if(nCampi>9){
		alert("Troppi Campi");
		return false;
	}*/
	//nCampi++;
	//alert(nCampi);
	tmpl = tmpl.replace(/\$/g, nCampi+"");
	div = document.createElement('DIV');
	div.innerHTML = tmpl;
	document.getElementById(idContainer).appendChild(div);
}

function showTab(a,b){
  for(var i=1; i<=b; i++){
    document.getElementById("tab"+i).style.background="#ffffff";
    document.getElementById("box"+i).style.display="none";
  }
  document.getElementById("tab"+a).style.background="#DEE7EC";
  document.getElementById("box"+a).style.display="block";
}

// fine globali

function controllaLogin(obj){
	resetBorder(obj); 
	flag = true;
    flag = flag && controlField('USERNAME','user','','_');
	flag = flag && controlField('PASSWORD','pass','','_');
	if(flag){
  	strUri = "?cmd=validation"+buildUri(obj);
    viewMex("Autenticazione in corso...");
    myajax.post("?cmd=validation",strUri);
  }
  myajax.echoFunction=function(aa){
    hideMex(aa,0);
    if(aa=="no"){
       //document.getElementById('password').value = "";
       alert("Account non valido");
    }else if(aa=="oki"){
      if(document.getElementById('cat').value!=""){
        cat = document.getElementById('cat').value;
        ii = document.getElementById('ii').value;
        location.href="?cmd="+cat+"&id="+ii;
      }else{
        location.href="./";
      }
    }
  }
}

function inviaContact(obj){
  resetBorder(obj);
  flag = true;
  flag = flag && controlField('NOME','nome','','_');
  flag = flag && controlField('E-MAIL','blabla','','_');
  flag = flag && controlField('E-MAIL','blabla','','@');

  if(flag){
  	strUri = buildUri(obj);
  	//alert(strUri);
    viewMex("Invio in corso...");
    myajax.post("?cmd=inviaContact",buildUri(obj));
  }
  myajax.echoFunction=function(response){
    hideMex(response,0);
    if(response=="ok") alert("Invio effettuato");
  }
}

function registraUt(obj){
  flag = true;
  flag = flag && controlField("NOME",'nome','','_');
  flag = flag && controlField("NOME UTENTE",'username','','_');
  flag = flag && controlField("E-MAIL",'blabla','','_');
  flag = flag && controlField("E-MAIL",'blabla','','@');
  if(flag){
    strUri = buildUri(obj);
    viewMex("Registrazione in corso");
    myajax.post("?cmd=exRegistrazione", strUri);
  }
  myajax.echoFunction=function(aa){
    hideMex(aa,0);
    if(aa=="user"){
      //document.getElementById('password').value = "";
      alert("Username presente nel nostro database, utilizzarne una nuova per proseguire con la registrazione.");
    }else if(aa=="ok"){
      alert("Abbiamo spedito un'email al tuo indirizzo che contiene le credenziali di accesso. Grazie per la collborazione.");
    }
  }
}

function modificaPref(obj){
  flag = true;
  flag = flag && controlField("NOME",'nome','','_');
  flag = flag && controlField("NOME UTENTE",'username','','_');
  flag = flag && controlField("E-MAIL",'email','','_');
  flag = flag && controlField("E-MAIL",'email','','@');
  if(document.getElementById('pass').value!=""){
    flag = flag && controlField("PASSWORD",'pass','8','c-');
  }
  flag = flag && controlField("PASSWORD",'pass','pass2','=');
  if(flag){
    strUri = buildUri(obj);
    viewMex("Modifica preferenze in corso");
    myajax.post("?cmd=exModificaPref", strUri);
  }
  myajax.echoFunction=function(aa){
    hideMex(aa,0);
    if(aa=="ok"){
      //document.getElementById('password').value = "";
      alert("Modifica effettuata corretamente");
    }
  }
}

function apriComm(){
  if(document.getElementById('addComm').style.display=="none"){
    document.getElementById('addComm').style.display="block";
  }else{
    document.getElementById('addComm').style.display="none";
  }
}

function inviaCommento(obj){
  flag = true;
  flag = flag && controlField("OGGETTO",'subject','','_');
  flag = flag && controlField("TESTO",'mex','','_');
  if(flag){
    strUri = buildUri(obj);
    viewMex("Invio in corso");
    myajax.post("?cmd=inviaCommento", strUri);
  }
  myajax.echoFunction=function(aa){
    hideMex(aa,0);
    if(aa=="ok"){
      //document.getElementById('password').value = "";
      alert("Commento inserito corretamente");
      window.location.reload(false);
    }
  }
}

function modificaCommento(obj,ii){
  flag = true;
  flag = flag && controlField("OGGETTO",'titolo'+ii,'','_');
  flag = flag && controlField("TESTO",'mex'+ii,'','_');
  if(flag){
    strUri = buildUri(obj);
    viewMex("Modifica in corso");
    myajax.post("?cmd=modificaCommento", strUri);
  }
  myajax.echoFunction=function(aa){
    hideMex(aa,0);
    if(aa=="ok"){
      //document.getElementById('password').value = "";
      alert("Commento modificato corretamente");
      window.location.reload(false);
    }
  }
}

function eliminaComm(id){
  if(confirm("Conferma Eliminazione")){
    viewMex("Eliminazione in corso...");
    myajax.post("?cmd=eliminaComm&id="+id,"");
  }
  myajax.echoFunction=function(aa){
    hideMex(aa,0);
    if(aa=="ok"){
      alert("Eliminazione effettuata");
      window.location.reload(false);
    }else{
      alertUtf8("Si è verificato un errore durante l'eliminazione!")
    }
  }
}

function cercaTutto(key){
  parola = document.getElementById(key).value;
  if(parola==""){
    alert("CAMPO DI RICERCA VUOTO");
  }else{
    location.href='?cmd=cercaTutto&key='+escape(parola);
  }
}