
//Funzioni base javascript
//Principe Orazio

//Generali
var ns4 = (navigator.appName=="Netscape");


function logout(){
	var risp;
	risp = confirm("Chiudere la propria sessione di lavoro?");
	if(risp){
		top.location.href = "../logout.jsp";
	}
}



function convalidaNumero(campo)
{
  if(campo.value == "") return true;
  if(!isNumeric(campo.value)) {
    var ValidChars = "0123456789.-";
    var msg = "Il valore "+campo.value+" nel campo "+campo.name+" non � numerico.\nI valori ammessi sono: "+ValidChars+"\n(Attenzione: i valori decimali devono essere inseriti con il punto. Es: 15.43)";
    if(ns4) msg += "\n\nCliccare con il MOUSE su 'ok'\nper chiudere questo messaggio";
    alert(msg);
    if(!ns4) campo.focus();
    campo.select();
    return false;
  }
  return true;
}


function isNumeric(sText)
{

  var ValidChars = "-0123456789.";
  var IsNumber=true;
  var Char;
  for (i = 0; i < sText.length && IsNumber == true; i++)
    {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
	{
	  IsNumber = false;
	}
    }
  return IsNumber;

}


function mostraNascondi(idOggetto)
{
	var obj = document.getElementById(idOggetto);
	if(obj.style.visibility == "visible"){ obj.style.visibility = "hidden"; }
	else { obj.style.visibility = "visible"; }
}




//OPERAZIONI SU STRINGHE
function htmlEncodeString (inputString)
{
	var encodedHtml = escape(inputString);
	encodedHtml = encodedHtml.replace(/\//g,"%2F");
	encodedHtml = encodedHtml.replace(/\?/g,"%3F");
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");

	return encodedHtml;
}


function htmlUnencodeString (inputString)
{
  return unescape(inputString);
}


function addSlashes(inputString)
{
	var str = inputString.replace("'","\\'");
	alert("add: " + str);
	return str;
}

function stripSlashes(inputString)
{
	alert("strip: " + inputString.replace("\\",""));

	return inputString.replace("\\","");

}



function ltrim(str)
{
	while(""+str.charAt(0)==" "){
		str=str.substring(1,str.length);
	}
	return str;
}

function reverse(str)
{
	var reversedstr = "";
	var strArray;
	strArray = str.split("");

	for(var i = str.length -1 ; i >= 0 ; i--){
		reversedstr += strArray[i];
	}
	return reversedstr;
}

function trim(str)
{
	str = ltrim(str);
	str = reverse(str);
	str = ltrim(str);
	str = reverse(str);
	return str;
}

function addslashes(str)
{
	return str.replace("\'","'");
}


function lcase(str){
	var inizio = str.substring(0,1);
	var fine = str.substring(1,str.length);
	return inizio.toLowerCase()+fine;
}


function ucase(str){
	var inizio = str.substring(0,1);
	var fine = str.substring(1,str.length);
	return inizio.toUpperCase()+fine;
}


function replaceCharacters(conversionString,inChar,outChar)
{
  var convertedString = conversionString.split(inChar);
  convertedString = convertedString.join(outChar);
  return convertedString;
}




//OPERAZIONI SU OGGETTI DEL FORM

/**
* Restituisce un elemento della pagina con un deleterminato id
*/
function getId(idObject)
{
	var obj = document.getElementById(idObject);
	return obj;
}

/**
* Restituisce un array degli elementi specificati in una pagina html
*/
function getElements(elementName)
{
		return document.getElementsByTagName(elementName);
}



/**
* Apre un popup unico per l'applicazione
*/
var popUpWin=0;
var mainWindow = 0;
function popUpWindow(URLStr, left, top, width, height)
{
  if(popUpWin)
  {
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = window.open(URLStr, 'popUpWin', 'modal=yes,directories=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}



//FUNZIONI PER MODULI

/**
* Disattiva un array di input utente
*/
function disattivaElementi(arrElementsType)
{
	for(var i = 0; i < arrElementsType.length; i++)
	{
		var els = document.getElementsByTagName(arrElementsType[i]);
		for(var elIndex = 0; elIndex < els.length; elIndex++)
		{
				els[elIndex].disabled = true;
		}
	}
}


/**
* Attiva un array di input utente
*/
function attivaElementi(arrElementsType)
{
	for(var i = 0; i < arrElementsType.length; i++)
	{
		var els = document.getElementsByTagName(arrElementsType[i]);
		for(var elIndex = 0; elIndex < els.length; elIndex++)
		{
				els[elIndex].disabled = false;
		}
	}
}




/**
* Imposta un valore ad un array di input utente
*/
function setFieldsValue(arrFieldsId, value)
{
    //Questa funzione imposta il valore di ogni id passato
    //come parametro
    for(var i = 0; i < arrFieldsId.length; i++){
		document.getElementById(arrFieldsId[i]).value = value;
    }


}






/**
* Imposta un valore ad un array di input utente
*/
function setInputsValue(arrIdInput, value)
{
    //Questa funzione imposta il valore di ogni campi imput passato
    //come parametro

    var arr;
    var msgDebug = "";
    for(var x = 0; x < 2; x++)
	{

	//Sia per gli input che per i textarea
	 if(x==0) { arr = document.getElementsByTagName("input"); }
	 else { arr = document.getElementsByTagName("textarea"); }

	 for(var i=0; i < arr.length; i++)
	     {

		 for(var el = 0; el < arrIdInput.length; el ++)
		     {

			 msgDebug += "Trovato elemento: " + arr[i].type + "    ";
			 if(arr[i].type == arrIdInput[el].type)
			     {

				 var el = document.getElementById(arr[i].id)
				     if(el != undefined) { el.value = value; }
			     }
		     }
	     }

	    //alert(msgDebug);

	}

}





/**
* Azzera tutte le caselle di input utente con la possibilit�
* di indicare un array di elementi da escludere
*/
function azzeraInputUtente(arrIgnoredFields)
{
    //Questa funzione imposta il valore di ogni campi imput passato
    //come parametro


    var arr;
    var msgDebug = "";
    var disattiva = true;
    for(var x = 0; x < 2; x++)
	{

	//Sia per gli input che per i textarea
	    if(x==0) { arr = document.getElementsByTagName("input"); }
	    else { arr = document.getElementsByTagName("textarea"); }


	    for(var i=0; i < arr.length; i++)
		{
			disattiva = true;
			for(var y = 0; y < arrIgnoredFields.length; y++)
				if(arr[i].id == arrIgnoredFields[y]) disattiva = false;

			if(disattiva) arr[i].value = "";
		}

	    //alert(msgDebug);

	}

}


/**
* Imposta il valore di un campo hidden con id=action
*/
function setAction(value)
{
  document.getElementById('action').value = value;
}

/**
* Restituisce il valore di un campo hidden con id=action
*/
function getAction(){
	return document.getElementById('action').value;
}




//FUNZIONI PER COMBO
/**
* Seleziona tutti i valori in una select html
*/
function selectAll(idCombo){
   var combo = document.getElementById(idCombo);
   for (var i = 0; i < combo.length; i++) {
	combo.options[i].selected = true;
   }
}

/**
* Toglie le selezioni da una select hmtl
*/
function clearSelection(idCombo){
   var combo = document.getElementById(idCombo);
   for (var i = 0; i < combo.length; i++) {
	combo.options[i].selected = false;
   }
}

/**
* Aggiunge dei valori in una select html
*/
function addToList(idCombo, newText, newValue) {

   var combo = document.getElementById(idCombo);

   if ( ( newValue == "" ) || ( newText == "" ) ) {
      alert("Non si pu aggiungere un valore vuoto!");
   } else {
      var len = combo.length++;
      combo.options[len].value = newValue;
      combo.options[len].text = newText;
      combo.selectedIndex = len;
   }
}


/**
* Cancella i valori selezionati da una select html
*/
function removeFromList(idCombo) {

   var combo = document.getElementById(idCombo);

   if ( combo.length == -1) {
      //alert("Non ci sono voci da eliminare!");
   } else {

      var selected = combo.selectedIndex;
      if (selected == -1) {

         //alert("Selezionare una voce da eliminare!");

      } else {  // Costruisco l'arrai ed i testi da riposizionare nella combo


	 //Conto i valori non selezionati
	 var els = 0; //Elementi presenti nell'array
	 for (var i = 0; i < combo.length; i++) {
		if(!combo.options[i].selected){ els++; }
	 }

	 if(els == 0) { els = 1; } //Se  presente solo un elemento imposto ad 1 il valore per non
				   //causare l'errore di javascript per l'indice negativo di array



	 var replaceTextArray = new Array(els - 1);
         var replaceValueArray = new Array(els -1);

	 els = 0; //Azzero l'indice dell'array nuovo
         for (var i = 0; i < combo.length; i++) {
            // Inserisco tutti valori, tranne i selezionati nell'array
            if(!combo.options[i].selected){
		replaceTextArray[els] = combo.options[i].text;
		replaceValueArray[els] = combo.options[i].value;
		els ++;
            }
         }
         combo.length = replaceTextArray.length;  // Diminuisco la lunghezza della combo originale
						  // impostandola a quella nuova

         for (i = 0; i < replaceTextArray.length; i++) { // Inserisco i valori
            combo.options[i].value = replaceValueArray[i];
       	    combo.options[i].text = replaceTextArray[i];
         }
      }
   }
}



/**
* Restituisce true o false a seconda se il valore �presente o meno
* in un campo select html
*/
function valorePresenteInCombo(valore, idCombo) {

	var combo = document.getElementById(idCombo);

	for (var i = 0; i < combo.length; i++) {
		if(combo.options[i].value == valore){
			return true;
		}
	}
	return false;
}



/**
* date format: ddmmyyyy - ddmmyy
*/
function check_date(dateValue)
{

	var checkstr = "0123456789";
	var DateTemp = "";
	var seperator = ".";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	/* Delete all chars except 0..9 */
	for (i = 0; i < dateValue.length; i++) {
	if (checkstr.indexOf(dateValue.substr(i,1)) >= 0) {
	DateTemp = DateTemp + dateValue.substr(i,1);
	}
	}
	/* Always change date to 8 digits - string*/
	/* if year is entered as 2-digit / always assume 20xx */
	if (dateValue.length == 6) {
	   dateValue = dateValue.substr(0,4) + '20' + dateValue.substr(4,2); }
	if (dateValue.length != 8) {
	   err = 19;
	}
	/* year is wrong if year = 0000 */
	year = dateValue.substr(4,4);
	if (year == 0) {
	   err = 20;
	}
	/* Validation of month*/
	month = dateValue.substr(2,2);
	if ((month < 1) || (month > 12)) {
	   err = 21;
	}
	/* Validation of day*/
	day = dateValue.substr(0,2);
	if (day < 1) {
	  err = 22;
	}
	/* Validation leap-year / february / day */
	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
	   leap = 1;
	}
	if ((month == 2) && (leap == 1) && (day > 29)) {
	   err = 23;
	}
	if ((month == 2) && (leap != 1) && (day > 28)) {
	   err = 24;
	}
	/* Validation of other months */
	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
	   err = 25;
	}
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
	   err = 26;
	}
	/* if 00 ist entered, no error, deleting the entry */
	if ((day == 0) && (month == 0) && (year == 00)) {
	   err = 0; day = ""; month = ""; year = ""; seperator = "";
	}
	/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
	if (err == 0) {
	   //DateField.value = day + seperator + month + seperator + year;
	   return true;
	}
	/* Error-message if err != 0 */
	else {	
		return false;
	}
}


	function InsertTag(obj,tag_open,tag_close) { 
		/* Questa funzione inserisce i tag indicati
		*  come parametri nel testo selezionato.
		*  Se il testo selezionato �0 verr�domandato
		*  all'utente il testo da inserire nell'oggetto
		*  indicato		
		*
		*  This function inserts the tag indicates to you 
		*  like parameters in the selected text. 
		*  If the selected text ... asked 
		*  to the customer the text to insert in the object 
		*  indicated
		*/
		var sel = document.selection.createRange(); 
		

		var to = sel.text; 
		//var ta = document.obj.value; 
		var ta = obj.value; 
		
		//Se non c'�selezione non inserisco il tag
		if(sel.text != ""){
			sel.text = ""; 
		}
		
		//var parti = document.obj.value.split(""); 
		var parti = obj.value.split(""); 
		var fine = new Array(parti[0],to,parti[1]); 

		//document.obj.value = ta; 
		obj.value = ta; 
		
		if(fine[1]=="")
		{
			fine[1] = prompt("Digitare il testo qui sotto","");
			if(fine[1]!=null)
			{
			fine[1] = tag_open+fine[1]+tag_close;			
			obj.value = "";	
			obj.value = fine[0]+fine[1];
			}
		
		}
		else
		{
			fine[1] = tag_open+fine[1]+tag_close;
			obj.value = "";
			obj.value = fine[0]+fine[1]+fine[2];
		}
		
		document.selection.empty;
		sel.empty;
	} 






function ReloadReferer(){
	window.opener.top.location.reload(true);
}


function Print(){ 
	var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>'; 
	document.body.insertAdjacentHTML('beforeEnd', WebBrowser); 
	WebBrowser1.ExecWB(6, 2); 
	WebBrowser1.outerHTML = ""; 
} 


function salva_modifiche(){
	document.forms['Dettagli'].submit();
}



function conferma_caricamento()
{
	if(confirm("ATTENZIONE:\nIl messaggio verra' salvato automaticamente prima del caricamento degli allegati, confermi?")) {
		document.getElementById('id_goto_contenuti').value = 'false';
		document.getElementById('Dettagli').submit();
	}
	else {
		alert("operazione annullata");
	}
}



	
function hyperlink(obj) {
	/* Questa funzione �uguale alla funzione InsertTag ma
	*  chiede all'utente anche l'indirizzo del link relativo alla pagina
	*/
	var sel = document.selection.createRange(); 
	var link = prompt("Digitare l\'url del link da inserire","http://");

	var to = sel.text; 
	var ta = obj.value; 
	
	//Se non c'�selezione non inserisco il tag
	if(sel.text != ""){
		sel.text = ""; 
	}
	
	//var parti = document.obj.value.split(""); 
	var parti = obj.value.split(""); 
	var fine = new Array(parti[0],to,parti[1]); 
	//document.obj.value = ta; 
	obj.value = ta; 
	
	if(fine[1]=="")
	{
		fine[1] = prompt("Digitare il testo qui sotto il titolo del link",link);
		
		if(fine[1]!=null && link != null)
		{
			fine[1] = "[URL='"+link+"']"+fine[1]+"[/URL]";
			obj.value = "";	
			obj.value = fine[0]+fine[1];
		}
	
	}
	else
	{
		if(link != null){
			fine[1] = "[URL='"+link+"']"+fine[1]+"[/URL]";
			obj.value = "";
			obj.value = fine[0]+fine[1]+fine[2];
		}
	}
	
	document.selection.empty;
	sel.empty;


}

function getTableHeightSetDivHeight(idTable,idDiv){
	var table = document.getElementById(idTable);
	var div = document.getElementById (idDiv);
	
	if (div.offsetHeight > table.offsetHeight) {
		
		div.style.height = table.offsetHeight+"px";
	}
}
