

// FUNZIONE PER CAMBIO TITOLO E SOTOTITOLO

function changeTitle(tit, subtit){

	var IE = navigator.appName.indexOf("Microsoft") != -1;

	htmTit=tit;
	htmSubTit=subtit;

	if(IE )
	{
		if( parent.midFrame.document.all.mid_titolo){
		  parent.midFrame.document.all.mid_titolo.innerText="";
		  parent.midFrame.document.all.mid_titolo.insertAdjacentHTML("beforeEnd",htmTit);
		}
		if( parent.midFrame.document.all.mid_sottotitolo){
		  parent.midFrame.document.all.mid_sottotitolo.innerText="";
		  parent.midFrame.document.all.mid_sottotitolo.insertAdjacentHTML("beforeEnd",htmSubTit);
		}
	}
	else
	{

	  var range = "";
	  var docFrag = "";
	  parent.midFrame.document.getElementById('mid_titolo').innerText="";
	  parent.midFrame.document.getElementById('mid_titolo').innerHTML="";
	  //document.getElementById('mid_titolo').style.visibility="visible";
	  range = parent.midFrame.document.createRange();
	  range.setStartBefore(parent.midFrame.document.getElementById('mid_titolo'));
	  docFrag = range.createContextualFragment(htmTit);
	  parent.midFrame.document.getElementById('mid_titolo').appendChild(docFrag)

	  var range = "";
	  var docFrag = "";
	  parent.midFrame.document.getElementById('mid_sottotitolo').innerText="";
	  parent.midFrame.document.getElementById('mid_sottotitolo').innerHTML="";
	  //document.getElementById('mid_titolo').style.visibility="visible";
	  range = parent.midFrame.document.createRange();
	  range.setStartBefore(parent.midFrame.document.getElementById('mid_sottotitolo'));
	  docFrag = range.createContextualFragment(htmSubTit);
	  parent.midFrame.document.getElementById('mid_sottotitolo').appendChild(docFrag)
	}







}





function autoComplete (field, select, property, forcematch) {

	date = new Date();

	var found = false;

	var len = field.value.length;

	for (var i = 0; i < select.options.length; i++) {

		if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
			found=true; 
			break;
			}
	
		if((select.options[i][property].toUpperCase().substr(len-1,1).charCodeAt()) < (field.value.toUpperCase().substr(-1).charCodeAt()))
			break;

	}


	if (found) { select.selectedIndex = i; }
	//else { select.selectedIndex = -1; }
	

	if (field.createTextRange) {
		if (forcematch && !found) {
			field.value=field.value.substring(0,field.value.length-1); 
			return;
			}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) {
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) {
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
				}
			}
		}

}





// -----------------------------------------------------------
// FUZIONE CHE CONVALIDA CARATTERI AMMESSI IN UN CAMPO TESTO
// -----------------------------------------------------------
// da utilizzare come segue:    onkeypress="return ValidateChar(event, this, 'int', true);"

function ValidateChar(evt, field, type, valid)
{
	// valid true or false per indicare se i caratteri nella stinga sono validi o no
	var str = field.value;

	var charCode = (evt.charCode)?evt.charCode:((evt.which)?evt.which:evt.keyCode);
	key = String.fromCharCode(charCode);


	// tasto delete - freccia sx - freccia dx
	if(charCode == 8 || charCode == 37 || charCode == 39)
		return true;

	if(type=='num')
	{
		if(field.value.length>0)
			key = str+key;

		if(isNaN(key))
			return false;
		else 
			return true;
	}
	else
	{
		switch(type)
		{
			case 'int': // valori ammessi
				var strChar ='1234567890';
				break;
	
			case 'tel': // valori ammessi
				var strChar ='1234567890./+';
				break;
	
			case 'catenasconti': // valori ammessi
				var strChar ='1234567890.+';
				break;
		
		}
	
		if(strChar.indexOf(key.toUpperCase()) >= 0)
			return true;
		else
			return false;

	}

}










//	FUNZIONA CHE CONTROLLA SE UN CAMPO E' UN NUMERO
function isNumeric(field)
{

	if(isNaN(field.value))
		field.value=field.value.substr(0,(field.value.length-1));

}








function select(a, changeTo)
{
	//alert(a.id+'  '+lineSel);
	//if(a.id!=('tr'+lineSel))
	  a.style.backgroundColor = changeTo;
}








function selectNorm(a, changeTo)
{
	  a.style.backgroundColor = changeTo;
}



function NetscapeEventHandler_KeyDown(e) {
alert(e.which);
/*
	if (e.which == 13 && e.target.type != 'textarea' && e.target.type != 'submit') {
		e.returnValue = false;
		e.cancel = true;
		e.preventDefault();
		return false;
	}
	return true;
*/
}


// funzione per formattare un campo come data
// Parametri : campo input
// Utilizzo: onkeypress="return MaskDataddmmyyyy (this, event);"
function MaskDataddmmyyyy (field, evt) {

  var charCode = (evt.charCode)?evt.charCode:((evt.which)?evt.which:evt.keyCode);
  //key = event.keyCode;
  key = charCode;

  if(key==8) // tasto cancella
  {
	 field.value = field.value.substr(0,field.value.length-1);
	 return false;
  }
  
  // freccia sx - freccia dx
  if(key == 37 || key == 39)
  {
	//field.value = field.value;
	return true;
  }
  
  else
  {
	  switch (field.value.length) {
		case 0: 
		  return String.fromCharCode(key)>='0' && String.fromCharCode(key)<'4';
		  break;
		case 1:
		  //secondo numero maggiore di 0. NO a giorno 00, se però primo numero > 0 allora ok a 0 come secondo numero, es: 10, 20, 30gg
		  if (field.value.substring(0,1)>=1){
			var valOk=0;
		  }else{
			var valOk=1;
		  }
		  if (field.value.substring(0,1)==3){
			var valOk1=1;
		  }else{
			var valOk1=9;
		  }
		  if (/\d/.test(String.fromCharCode(key)) && String.fromCharCode(key)>=valOk && String.fromCharCode(key)<=valOk1)
		  field.value=field.value+String.fromCharCode(key)+"/";
		  return false;
		  break;
		case 2:
		  key = '/'.charCodeAt();
		  return true;
		  break;
		case 3:
		  return String.fromCharCode(key)>='0' && String.fromCharCode(key)<'2';
		  break;
		case 4:
		  //Se il primo numero del mese è 1 possibilità di 10-11-12 (mesi) altrimenti 01-02-03 ecc. NO a mese 00
		  if (field.value.substring(4,3)=='1'){
			 if (/\d/.test(String.fromCharCode(key)) && String.fromCharCode(key)<='2')
				if (field.value.substring(0,2)=='31')
				{
					 if (/\d/.test(String.fromCharCode(key)) && (String.fromCharCode(key)=='0' || String.fromCharCode(key)=='2'))
						 field.value=field.value+String.fromCharCode(key)+"/";
				}
				else if (field.value.substring(0,2)<'31')
					 field.value=field.value+String.fromCharCode(key)+"/";
			 return false;
		 }else{
			 if (/\d/.test(String.fromCharCode(key)) && String.fromCharCode(key)>='1')
				if (field.value.substring(0,2)=='31')
				{
					 if (/\d/.test(String.fromCharCode(key)) && (String.fromCharCode(key)=='1' || String.fromCharCode(key)=='3' || String.fromCharCode(key)=='5' || String.fromCharCode(key)=='7' || String.fromCharCode(key)=='8'))
						 field.value=field.value+String.fromCharCode(key)+"/";
				}
				else if (field.value.substring(0,2)<'31' && field.value.substring(0,2)>'29')
				{
					 if (/\d/.test(String.fromCharCode(key)) && String.fromCharCode(key)!='2')
						 field.value=field.value+String.fromCharCode(key)+"/";
				}
				else if (field.value.substring(0,2)<='29')
				{
					 field.value=field.value+String.fromCharCode(key)+"/";
				}
	//		 field.value=field.value+String.fromCharCode(key)+"/";
			 return false;
		 }
		  break;
		case 5:
		  key = '/'.charCodeAt();
		  return true;
		  break;
		case 6:
			return String.fromCharCode(key)>='1' && String.fromCharCode(key)<'3';
			break;
		case 7:
			break;
		case 8:
			break;
		case 9:
			year = Number(Number(field.value.substring(6,9))+String.fromCharCode(key));
			var bisestile = true;
			if (Number((year/4)) != Number(Math.floor(year/4)))   bisestile = false;
			else if ((year/100) != Math.floor(year/100)) bisestile = true;
			else if ((year/400) != Math.floor(year/400)) bisestile = false;
	
			if (field.value.substring(0,2)=='29' && field.value.substring(4,5)=='2') // se febbraio e gg 29 solo anni bisestili
			{
				if (!bisestile)
				  return false;
			}
			return true;
		  //return /\d/.test(String.fromCharCode(event.keyCode));
		  break;
		default:
		  return false;
		  break;
	  }
   }
}





function openWin(nome, nomeFin, width, height, scrol)
{

var winWidth = screen.availWidth;
var winHeight = screen.availHeight;
var popupWidth = width;
var popupHeight = height;

if ( popupWidth == '')
	popupWidth = winWidth;

if ( popupHeight == '')
	popupHeight = winHeight;

var xCoord = ((winWidth-popupWidth)/2);
var yCoord = ((winHeight-popupHeight)/2);

if ( nomeFin == '')
{
	nomeFin = 'NuovaFinestra';
}
else
{
	nomeFin=nomeFin.replace('&','and');
}

if ( scrol == '')
	scrol = 'yes';

/*
window.open(nome, nomeFin,'toolbar=no, scrollbars='+scrol+', width='+popupWidth+',height='+popupHeight+',left='+xCoord+',top='+yCoord+'screenX='+xCoord+',screenY='+yCoord+'');
*/

window.open(nome, '','toolbar=no, scrollbars='+scrol+', width='+popupWidth+', height='+popupHeight+', left='+xCoord+', top='+yCoord+', screenX='+xCoord+', screenY='+yCoord+'');

}







_ONEORMORE = 1;
_JUSTONE =2;
InvioOk=false;

// controlla se sono selezionate delle voci in un elenco a discesa
// Parametri : elenco : elenco da controllare, how : indica il tipo di controllo (_ONEORMORE : 1 o più, _JUSTONE : 1 e solo 1)

function checkSelected(elenco, how) 
  {
  if (how==_JUSTONE)
    {
	tot=0;
	for(t=0;t<elenco.length;t++)
	  if (elenco.options[t].selected) tot++;
	if (tot==0)
	  alert('Selezionare un valore');
	else
	  if (tot>1)
		alert('Selezionare un solo valore');
	return tot==1;
	}
  else
    if (how==_ONEORMORE)
	  {
	  tot=0;
	  for(t=0;t<elenco.length;t++)
  	    if (elenco.options[t].selected) tot++;
  	  if (tot==0)
  	    alert('Selezionare almeno un valore');
	  return tot>=1;
	  }
  }
  
  
_MOVE = 1;
_COPY =2;
InvioOk=false;

// Sposta le voci selezionate da un elenco ad un altro
// Parametri : elencosorg : elenco sorgente, elencodest : elenco destinazione, how : (se _MOVE sposta la selezione, con _COPY la copia)

function moveSelection(elencosorg, elencodest, how) 
  {
//  var option0 = new Option("Red", "color_red")   var option1 = new Option("Blue", "color_blue")   var option2 = new Option("Yellow", "color_yellow")   var option3 = new Option("Green", "color_green")
//   for (var i=0; i < 4; i++) {      eval("inForm.selectTest.options[i]=option" + i)
	for(t=0;t<elencodest.length;t++)
		elencodest.options[t].selected = false;
	for(t=0;t<elencosorg.length;t++)
		if (elencosorg.options[t].selected) 
			elencodest.options[elencodest.length]=new Option(elencosorg.options[t].text,elencosorg.options[t].value,false,true);
	if (how==_MOVE)
		for(t=elencosorg.length-1;t>=0;t--)
			if (elencosorg.options[t].selected)
				elencosorg.options[t]=null;
	// history.go(0);
    return true;
  }
  
  
// Seleziona tutte le voci di un elenco
// Parametri : elenco : elenco da selezionare

function selectAll(elenco)
{
	for(t=0;t<elenco.length;t++) elenco.options[t].selected = true;
	return true;
}
  
// Elimina le voci selezionate da un elenco 
// Parametri : elenco : elenco da cui eliminare le voci
function deleteSelection(elenco) 
  {
	for(t=elenco.length-1;t>=0;t--)
		if (elenco.options[t].selected)
			elenco.options[t]=null;
    return true;
  }

_TOP=1;
_BOTTOM=2;
// Aggiunge una voce ad un elenco
// Parametri : elenco : elenco a cui aggiungere la voce, Unique : se true impedisce l'inserimento di valori duplicati, Testo : testo dell'opzione, Valore: Value per l'opzione, DefaultSelected : true se la voce è selezionata di default, Selected : true se la voce è selezionata
//             ResetSelection : reimposta la selezione ogni volta, Position : _TOP oppure _BOTTOM inserisce in cima o in fondo
function addToSelection(elenco,Unique,Testo,Valore,DefaultSelected, Selected, ResetSelection, Position) 
{
  Trovato=false;
  if (Unique)
  {
  	for (t=0;t<elenco.length;t++) 
  	{ 
      var elencoValue=elenco.options[t].value;
      var elencoText=elenco.options[t].text;
      if ((Testo.toUpperCase()==elencoText.toUpperCase()) || (Valore.toUpperCase()==elencoValue.toUpperCase())) Trovato=true;
  	}
  }
  if (Trovato)
  {
    alert('Tentativo di inserire un valore duplicato');
    return false;
  }
  else
  {
    if (ResetSelection) for (t=0;t<elenco.length;t++) elenco.options[t].selected=false;
    if (Position==_TOP) 
    {
    	var option = new Option();
    	elenco.options[elenco.length]=option;
		var number=elenco.length;
    	for (t=number-1;t>0;t--)
    	{
    		var opzionexhg=new Option (elenco.options[t-1].text,elenco.options[t-1].value,elenco.options[t-1].defaultSelected,elenco.options[t-1].selected);
      		elenco.options[t]=opzionexhg;
    	}
    }
  	var option = new Option(Testo,Valore,DefaultSelected,Selected);
  	elenco.options[((Position==_TOP)?0:elenco.length)]=option;
    return true;
  }
}



// Legge gli elenchi di modelli compresi in modelli-modulo.js
// Parametri : Tipo : Tipo di modello da leggere, Elenco : campo Select HTML dove inserire i valori
_HTMLMODULE = 1;
_CHIAVE = 0;
_VALORE = 1;
function GetModelli(Tipo,Elenco)
{
	if (Tipo==_HTMLMODULE)
	{
		while (Elenco.length>0) Elenco.options[Elenco.length-1]=null;
		Elenco.options[Elenco.length]=new Option("-- Seleziona un Modello --",-1,false,true);
		for(t=0;t<_ModuliHtml.length;t++) 
		  Elenco.options[Elenco.length]=new Option(_ModuliHtml[t][_CHIAVE],t,false,false);
	}
}

// Legge un valore di modello da modelli-modulo.js
// Parametri : Tipo : Tipo di modello da leggere, Numero : numero del modello
function GetModello(Tipo,Numero)
{
	if (Tipo==_HTMLMODULE)
	{
		return _ModuliHtml[Numero][_VALORE];
	}
}


// modifica i permessi per tutte le voci selezionate di un elenco a discesa
// Parametri : elenco : elenco da modificare, Lettura/Scrittura: True / False / Vuoto = legge valore corrente e lo nega,

function ChangePermission(elenco, Lettura, Scrittura) 
{
	for(t=0;t<elenco.length;t++)
		if (elenco.options[t].selected) 
	  	{
	  	Valore=elenco.options[t].value;
	  	OldLettura=Valore.charAt(Valore.indexOf('[')+1);
	  	OldScrittura=Valore.charAt(Valore.lastIndexOf('[')+1);
	  	if ((Lettura!="T" && Lettura!="F") || (Scrittura!="T" && Scrittura!="F")) 
	  	{
	  		Lettura=OldLettura;
	  		Scrittura=OldScrittura;
	  		if (Lettura=="F" && Scrittura=="F") 
	  			Lettura="T";
	  		else 
	  			if (Lettura=="T" && Scrittura=="F")
	  				Scrittura="T";
	  			else
	  				if (Lettura=="T" && Scrittura=="T")
	  					Scrittura=Lettura="F";
	  	}
	  	Valore=Valore.substring(0,Valore.indexOf('['));
	  	Valore=Valore+'['+Lettura+']'+'['+Scrittura+']';
	  	Testo=elenco.options[t].text;
	  	Testo=Testo.substring(0,Testo.lastIndexOf(']')-6)+'['+Lettura+']'+' ['+Scrittura+']'+Testo.substring(Testo.lastIndexOf(']')+2,1000);
	  	elenco.options[t].value=Valore;
	  	elenco.options[t].text=Testo;
	  	}	

}



function autoComplete (field, select, property, forcematch) {
	var found = false;
	for (var i = 0; i < select.options.length; i++) {
	if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
		found=true; break;
		}
	}
	if (found) { select.selectedIndex = i; }
	//else { select.selectedIndex = -1; }
	if (field.createTextRange) {
		if (forcematch && !found) {
			field.value=field.value.substring(0,field.value.length-1); 
			return;
			}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) {
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) {
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
				}
			}
		}
	}



// -----------------------------------------------------------
// FUZIONE CHE CONVALIDA FORM
// -----------------------------------------------------------
// usare in questo modo 
// es: <form name="form1" action="" onSubmit="return ValidateForm(this);">
//
// RICORDARSI DI DEFINIRE CAMPI OBBLIGATORI COME SEGUE ----- > fieldRequest
//  fieldRequest = new Array();
// Elenco dei campi richiesti  
// Valori ['NomeCampo', 'Msg Errore','tipo txt-data-email'];
//  fieldRequest[0] = ['STR_INTESTAZIONE', 'Titolo è richiesto','txt'];
function ValidateForm(nameForm)
{

  err='';

  // se non è definito usa questo per andare avanti senza errori
  if(undefined===window.fieldRequest)
  {
    fieldRequest = new Array();  
  }


  // Imposta forma di riferimento
  //form = document[nameForm];
  form = nameForm;

  for(i=0; i<fieldRequest.length; i++)
  {

	switch(fieldRequest[i][2])
	{
	
		case 'txt': 
			valueField = form[fieldRequest[i][0]].value;
			if(valueField=='')
				err += "\n"+(i+1)+' - '+fieldRequest[i][1];
			break;

		case 'data': 
			valueField = form[fieldRequest[i][0]].value;
			if((valueField.length < 10)||(valueField=='00/00/0000'))
				err += "\n"+(i+1)+' - '+fieldRequest[i][1];
			break;

		case 'email': 
			valueField = form[fieldRequest[i][0]].value;
			if(valueField!='')
			{
				p=valueField.indexOf('@');
				if(p<3 || p==(valueField.length-1))
					err += "\n"+(i+1)+' - '+fieldRequest[i][1];				
			}
			else
			{
				err += "\n"+(i+1)+' - '+fieldRequest[i][1];				
			}
			break;

		case 'privacy': 
			valueField = form[fieldRequest[i][0]][0].checked;
			if(!valueField)
				err += "\n"+(i+1)+' - '+fieldRequest[i][1];
			break;
	
		case 'cmb':
			valueField = form[fieldRequest[i][0]].value;
			alert("campo:"+valueField);
			if(valueField=='')
			{
				err += "\n"+(i+1)+' - '+fieldRequest[i][1];
			}
			break;

	}

  }


  if(err)
  {
	alert('ATTENZIONE! Si sono verificati i seguenti errori:'+err);
	return false;
  }
  else
	return true

}

