var GB_ROOT_DIR="./js/greyBox/";
// funzioni globali
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 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!=""){
			strUri += "&"+obj.elements[n].name+"="+escape(obj.elements[n].value);
    }
  }
  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){
	color = "darkorange";
  switch(tipo){
    case "_":       // controlla se il campo e' vuoto
    if(document.getElementById(id).value == false){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+color;
    	return false;
    }else{
    	return true;
    }
    break;
    case "__":      // controlla se il campo e' vuoto con ""
    if(document.getElementById(id).value == ""){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+color;
    	return false;
    }else{
      return true;
    }
    break;
    case "@":       // controlla la validita' del campo mail
    if(!indirizzoEmailValido(document.getElementById(id).value)){
      alert(nome+": campo non valido");
      document.getElementById(id).style.border = "1px solid "+color;
      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 "+color;
      document.getElementById(id2).value = "";
      return false;
    }else{
      return true;
    }
    break;
    case "h":       // controlla se il campo e' vuoto
    if(document.getElementById(id2).value == false){
    	alert(nome+": campo mancante");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+color;
    	return false;
    }else{
    	return true;
    }
    break;
    case "c":       // controlla se il campo pi lungo di un tot
    if(document.getElementById(id).value.length > id2){
    	alert(nome+": il campo deve contenere massimo "+id2+" caratteri");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+color;
    	return false;
    }else{
    	return true;
    }
    break;
    case "c-":       // controlla se il campo pi corto di un tot
    if(document.getElementById(id).value.length < id2){
    	alert(nome+": il campo deve contenere minimo "+id2+" caratteri");
    	document.getElementById(id).focus();
    	document.getElementById(id).style.border = "1px solid "+color;
    	return false;
    }else{
    	return true;
    }
    break;
    case "n":       // controlla se il campo  e' numerico
	   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 "+color;
	       return false;
	   }else{
	       return true;
	   }
	   break;
    default:
    alert("tipo non riconosciuto");
    return false;
  }
}

function viewMex(mex){
	dTop = document.body.scrollTop+200;
	document.getElementById('loader').innerHTML = "<img src=\"img/loading.gif\" style=\"vertical-align: -18px\">&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){
	e = e || window.event;
	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 openDiv(w,idOpen,urlAj,corrX,corrY){
	this.win = document.getElementById('win');
	xx = getPosX(document.getElementById(idOpen))+corrX;
	yy = getPosY(document.getElementById(idOpen))+corrY+document.documentElement.scrollTop;;
	win.style.width = w+"px";
	win.style.overflow = "visible";
	viewMex("Caricamento in corso...");
	//ajaxGetRand(urlAj,myHandler);
	myajax.post(urlAj,"");
  myajax.echoFunction=function(aa){
  	hideMex(aa,0);
    //if(win.style.display !="block"){
    	win.style.top=yy+"px";
    	win.style.left=xx+"px";
    //}
    win.innerHTML = aa;
    if(win.style.display!="block"){
    	changeOpac(0, "win");
    	win.style.display="block";
    	opacity("win", 0, 100, 500);
    }
    //Drag.init(document.getElementById("handle"),document.getElementById('win'));
    //tinyMCE.execCommand("mceAddControl",true,"bio");
  }
  /*
  function myHandler(aa){
    hideMex(aa,0);
    //if(win.style.display !="block"){
    	win.style.top=yy+"px";
    	win.style.left=xx+"px";
    //}
    win.innerHTML = aa;
    win.style.display="block";
    Drag.init(document.getElementById("handle"),document.getElementById('win'));
    tinyMCE.execCommand("mceAddControl",true,"bio");
    tinyMCE.execCommand("mceReplaceContent",false,"bio");
  }*/
}

function openDiv2(w,idOpen,urlAj,corrX,corrY){
	this.win = document.getElementById('win');
	win.style.display = "none";
	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...");
	//ajaxGetRand(urlAj,myHandler);
	myajax.post(urlAj,"");
	myajax.echoFunction=function(aa){
	aa = aa.replace("’","'");	
    hideMex(aa,0);
    //if(win.style.display !="block"){
    	win.style.top=yy+"px";
    	win.style.left=xx+"px";
    //}
    win.innerHTML = aa;
    if(win.style.display!="block"){
    	document.getElementById('op').style.display = "block";
    	
    	hB = document.getElementById('page').offsetHeight;
    	
    	document.getElementById('op').style.height = hB+"px";
    	changeOpac(0, "win");
    	win.style.display="block";
    	opacity("win", 0, 100, 500);
    }
    //Drag.init(document.getElementById("handle"),document.getElementById('win'));
    //tinyMCE.execCommand("mceAddControl",true,"bio");
    //tinyMCE.execCommand("mceReplaceContent",false,"bio");
  }
}

function openSelect(w,h,idName,idValue,urlAj,corrX,corrY,multi,any){
	this.win = document.getElementById('select');
	selIds = "";
	if(!multi){
		document.onmouseup=function(){
			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...");
	//ajaxGetRand(urlAj+'&idName='+idName+'&idValue='+escape(idValue)+'&multi='+multi+'&any='+any+'&selIds='+selIds,myHandler);
	
	myajax.post(urlAj,'&idName='+idName+'&idValue='+escape(idValue)+'&multi='+multi+'&any='+any+'&selIds='+selIds);
  myajax.echoFunction=function(aa){
		hideMex(aa,0);
    win.style.top=yy+"px";
    win.style.left=xx+"px";
    win.innerHTML = aa;
    win.style.display="block";
    //Drag.init(document.getElementById("handle"),document.getElementById('win'));
  }
  /*   
  function myHandler(aa){
    hideMex(aa,0);
    win.style.top=yy+"px";
    win.style.left=xx+"px";
    win.innerHTML = aa;
    win.style.display="block";
     //Drag.init(document.getElementById("handle"),document.getElementById('win'));
  }*/
}

function setControl(val, obj){
  var parentObj = obj.parentNode.childNodes;
    for(i=0; i<parentObj.length; i++){
    	if(parentObj[i].nodeName == "DIV") {
    		parentObj[i].style.fontWeight = "normal";	
    		parentObj[i].firstChild.src = "img/off.gif";
    	}
    	if(parentObj[i].nodeName == "DIV") parentObj[i].style.color = "#555555";
	    if(parentObj[i].nodeName == "INPUT") parentObj[i].value = val;
    }
    //obj.style.fontWeight = "bolder";
    obj.firstChild.src = "img/on.gif";
    //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 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 getOpac(id){
	var object = document.getElementById(id).style;
    if(object.opacity){
    	op=object.opacity;
    }else if(object.MozOpacity){
    	op=object.MozOpacity;
    }else if(object.KhtmlOpacity){
    	op=object.KhtmlOpacity;
    }else if(object.filters){
    	op=filters.alpha.opacity;
    }
    return op;
}

function mostraMenu(obj,n){
	if(obj){
		x = getPosX(obj);
		y = getPosY(obj) + 15;
		document.getElementById('subMenu').style.top = y+"px";
		document.getElementById('subMenu').style.left = x+"px";
	}
	if(n){
		 div = document.getElementById('subMenu');
		 switch(n){
		 	case 1:
		 		div.innerHTML = "<a href='?cmd=regInnovatore'>Innovatore</a><br>";
		 		div.innerHTML += "<a href='?cmd=regIstituzione'>Istituzione</a><br>";
		 		div.innerHTML += "<a href='?cmd=regRicercatore'>Ricercatore</a><br>";
		 		div.innerHTML += "<a href='?cmd=regImprenditore'>Imprenditore</a><br>";
		 	break;
		 	case 2:
		 		div.innerHTML = "<a href='?cmd=profilo'>Profilo</a><br>";
		 		div.innerHTML += "<a href='?cmd=viewInnovatori'>Innovatori</a><br>";
		 		div.innerHTML += "<a href='?cmd=viewIstituzioni'>Istituzioni</a><br>";
		 		div.innerHTML += "<a href='?cmd=viewRicercatori'>Ricercatori</a><br>";
		 		div.innerHTML += "<a href='?cmd=viewImprenditori'>Imprenditori</a><br>";
		 	break;
		}
		/*
		poststr = "&n="+n;
		myajax.post("?cmd=subMenu",poststr);
	  myajax.echoFunction=function(response){
	  	document.getElementById('subMenu').innerHTML = response;
	  }
	  */
  }
	document.getElementById('subMenu').style.display = "block";
}

function nascondiMenu(){
	document.getElementById('subMenu').style.display = "none";
}

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);
}

// fine globali

function controllaLogin(obj){
	resetBorder(obj); 
	flag = true;
	flag = flag && controlField('USER','username','','_');
	flag = flag && controlField('PASSWORD','password','','_');
	if(flag){
  	strUri = buildUri(obj);
    viewMex("Autenticazione in corso...");
    //alert(strUri);
    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"){
    	//location.href="./?cmd=home";
    	window.location.reload(false);
    }
  }
}

function openSWF(filez){
		var s2 = new SWFObject("mp3player.swf", "video", "500", "400", "9");
		s2.addVariable("file",filez);
		//s2.addVariable("backcolor","0x000000");
		//s2.addVariable("frontcolor","0xffffff");
		//s2.addVariable("lightcolor","0xf1a543");
		//s2.addVariable("displayheight","150");
		//s2.addVariable("showicons","true");
		//s2.addVariable("showdigits","true");
		s2.addVariable("autostart","true");
		s2.addParam('allowfullscreen','true');
		//s2.addParam('allowscriptaccess','true');
		s2.addParam('allowscriptaccess','sameDomain');
		//s2.addVariable('height','180');
		//s2.addVariable('width','400');
		//s2.addVariable('displayheight','400');
		//s2.addVariable('displaywidth','500');
		//s2.addParam('scale','exactfit');
		//s2.addParam('align','middle');
		s2.write("flashcontent");
}

function openSWFAudio(filez){
		var s2 = new SWFObject("mp3player.swf", "playlist", "400", "180", "9");
		s2.addVariable("file",filez);
		s2.addVariable("backcolor","0x000000");
		s2.addVariable("frontcolor","0xffffff");
		s2.addVariable("lightcolor","0xf1a543");
		s2.addVariable("displayheight","150");
		s2.addVariable("showicons","true");
		s2.addVariable("showdigits","true");
		s2.addVariable("autostart","true");
		s2.addParam('allowfullscreen','true');
		s2.addParam('allowscriptaccess','sameDomain');
		s2.addVariable('height','180');
		s2.addVariable('width','400');
		s2.addVariable('displaywidth','140');
		s2.write("flashcontent");
}

function regUtente(obj){
	flag = true;
	flag = flag && controlField("NOME",'nome','','_');
	flag = flag && controlField("COGNOME",'cognome','','_');
	flag = flag && controlField("E-MAIL",'blabla','','_');
	flag = flag && controlField("E-MAIL",'blabla','','@');
	flag = flag && controlField("USER",'user','','_');
	flag = flag && controlField("PASSWORD",'pass','','_');
	flag = flag && controlField("PASSWORD",'pass','7','c-');
	flag = flag && controlField("PASSWORD",'pass','pass2','=');
	flag = flag && controlField("TIPOLOGIA UTENTE",'docente','','__');
	flag = flag && controlField("AUTORIZZAZIONE AL TRATTAMENTO DEI DATI PERSONALI",'concedo','','_');
	if(flag){
		strUri = buildUri(obj);
		viewMex("Registrazione in Corso");
    myajax.post("?cmd=exRegUtente", strUri);
	}
	 myajax.echoFunction=function(aa){
    hideMex(aa,0);
    if(aa=="user"){
      //document.getElementById('password').value = "";
   		alert("User gia' presente. Modificarlo prima di continuare!");
    }else if(aa=="codice"){
      alert("Il codice del libro inserito e' errato!");
    }else if(aa=="ok"){
      alert("Il sistema ha inviato una email all'indirizzo inserito. Cliccare sul link presente nell'email ricevuta per confermare l'avvenuta registrazione. Grazie per la collaborazione.");
    }
  }
}

function inviaCodice(obj,i){
	resetBorder(obj); 
	flag = true;
	flag = flag && controlField('CODICE','codice'+i,'','_');
	flag = flag && controlField('CODICE','codice'+i,'5','c-');
	if(flag){
  	strUri = buildUri(obj);
    viewMex("Attivazione in corso...");
    //alert(strUri);
    myajax.post("?cmd=attivaVolume",strUri);
  }
  myajax.echoFunction=function(aa){
  	hideMex(aa,0);
    if(aa=="no"){
       //document.getElementById('password').value = "";
       alert("Codice di Attivazione non Valido");
    }else if(aa=="ok"){
      //location.href="./?cmd=home";
    	alert("Volume Attivato");
    	window.location.reload(false);
    }
  }
}

/*
function GB_showCenter(title,url,w,h){
	w = w+20;
	openDiv2(w,'anelli','extra.php?url='+url,30,30);
	return false;
}
*/

function adminCont(obj){
	nextz = obj.parentNode;
	while(nextz.nextSibling.nodeName!="DIV"){
        nextz = nextz.nextSibling;
	}
	if(nextz.nextSibling.style.display=="none"){
		nextz.nextSibling.style.display = "block";
		obj.title = "nascondi contenuti";
		obj.innerHTML = "&nbsp;<img src=\"img/dw.gif\" style=\"vertical-align: -3px\">";
	}else{
		nextz.nextSibling.style.display = "none";
		obj.title = "mostra contenuti";
		obj.innerHTML = "&nbsp;<img src=\"img/dx.gif\" style=\"vertical-align: -3px\">";
	}
}

function dissolvi(obj){
	//changeOpac(0, obj);
	//win.style.display="block";
	/*
	if(!isNaN(getOpac(obj))){
		if(getOpac(obj)<100) opacity(obj, 0, 100, 500);
	}else{
		opacity(obj, 0, 100, 500);
	}*/
	document.getElementById(obj).style.visibility="hidden";
}

function sdissolvi(obj){
	//changeOpac(100, obj);
	//win.style.display="block";
	//opacity(obj, 100, 0, 500);
	/*
	if(!isNaN(getOpac(obj))){
		if(getOpac(obj)>0) opacity(obj, 100, 0, 500);
	}else{
		opacity(obj, 100, 0, 500);
	}*/
	document.getElementById(obj).style.visibility="visible";
}

function appari(){
	
	document.getElementById("aa").style.background="url('../img/left.gif')";
}