function redirectItaliana(){
    window.location = "http://www.italiana.it";
}

function gestioneSinistrosita(formElement){
	var valoreElemScatenante = formElement.value;
	if (valoreElemScatenante=='N.D.' || valoreElemScatenante=='N.A.'){
		var idElemScatenante = formElement.id;
		var idArrayElemScatenante = idElemScatenante.split('.');
		var annoElemScatenante = idArrayElemScatenante[idArrayElemScatenante.length-1];
		var formInputs = $$('select');
		formInputs.each(function(e){
			var id = e.id;
			if (id.startsWith('calcolaclasse.sinistrosita.')){
				var idArray = id.split('.');
				var anno = idArray[idArray.length-1];
				if (anno==annoElemScatenante){
					$(id).options[formElement.selectedIndex].selected=true;
				}
			}
		});
	}
}

// Gestione con Ajax - Json

function busyEvent(formElement) {
	if ($(formElement.id+'_field')!=null){
		var busyImg = document.createElement('img');
		busyImg.src = "../images/ajax-loader.gif";
		busyImg.id = "ajaxLoaderImg";
		busyImg.setAttribute('style', 'vertical-align:middle;');
		$(formElement.id+'_field').appendChild(busyImg);
	}
	freezePage();
}

function fetchJSONData(formElement){
	// cancellazione eventuali errori
    if ($('errors')!=null){
	   $('errors').remove();
    }
	
	var form = formElement.form;
	var formId = formElement.form.id;
	var idCampo = formElement.id;
	var nomeCampo = formElement.name;
	var valoreCampo = formElement.value;
	var param = "tipoChiamata=ajax&chiaveCampoScatenante="+idCampo;
	
	var formInputs = $$('input');
	param = addParameters(formInputs, param);
	
	var formInputs = $$('select');
	param = addParameters(formInputs, param);
	
	var url = formId+'.action';
	
	var myAjax = new Ajax.Request(
	  url, 
	 {
	        method: 'post',
	        parameters: param,
	        onLoading: busyEvent(formElement),
	        onComplete: unFreezePage,
	        onSuccess: fetchSuccess,
	        onFailure: function(t){
		       t.submit();
	 		 }
	  });
}

function fetchSuccess(transport){
   if (200 == transport.status){
	    Element.remove("ajaxLoaderImg");
	    var campi = transport.responseJSON; //listaCampi
	    if (campi!=null){
		    for (var i=0; i<campi.length; i++){
		    	var campo = $(campi[i].chiave);
		    	if (campo!=null){
			    	if (campi[i].tipo=='lista'){
			    		var valoreDefault = campi[i].valoreDefault;
						var len = campo.options.length;  
						while (len >= 1) {  
							campo.remove(len-1);  
							len--;  
						}  
						var valori = campi[i].valoriDisponibili;
						var index = 0;
						for (var j=0; j<valori.length; j++){
							var codice = valori[j].codice;
							var etichetta = valori[j].etichetta;
							if (campo.name.indexOf('massimali')>0 && codice.startsWith('0')){
								continue;
							}
							campo.options[index]=new Option(etichetta==null?'':etichetta, codice, false, false);
							if (valoreDefault!=null && codice==valoreDefault){
								campo.options[index].selected=true;	
							}
							index++;
						}
			    	}
			    	else if (campi[i].tipo=='checkbox'){
			    		if (campi[i].valoreDefault!=null 
			    				&& campi[i].valoreDefault=='true'){
			    			campo.checked = true;
			    		}
			    		else {
			    			campo.checked = false;
			    		}
			    	}
			    	else if (campi[i].tipo=='testo'){
			    		if (campi[i].valoreDefault!=null){
			    			campo.value = campi[i].valoreDefault;
			    		}
			    	}
			    	var riga = campi[i].chiave+'_row';
					riga = riga.replace(".mese","");
					riga = riga.replace(".anno","");
			    	if (campi[i].abilitato){
				    	$(riga).show();
			    	}
			    	else {
			    		$(riga).hide();
			    	}
		    	}
		    }
	    }
	    else {
	    	alert("La sessione è scaduta. Ti preghiamo di accedere nuovamente.");
	    }
   }
}

function addParameters(formInputs, param){
	formInputs.each(function(e){
		var riga = e.id + '_row';
		riga = riga.replace(".mese","");
		riga = riga.replace(".anno","");
		if ($(riga)!=null){
			var nomeCampo = e.name;
			var abilitato = $(riga).getStyle('display');
			if (abilitato!=null && abilitato!='none'){
				if (nomeCampo.startsWith('valoriCampo')){
					 var valoreCampo = e.value;
					 if (e.type!=null && e.type=="checkbox"){
						 valoreCampo = e.checked;
					 }
					 param += "&"+nomeCampo+'='+valoreCampo;
				 }
			}
		}
	});
	return param;
}

function selezionaRiga(formId){
	var oldColor = formId.parentNode.style.backgroundColor;
	if (oldColor=='rgb(255, 255, 255)'){
		formId.parentNode.style.backgroundColor="rgb(239, 246, 251)";
	}
}
function selezionaRigaPermanente(formId){
	for (f=0; f < document.forms.length; f++)
	{
	  for(i=0; i < document.forms[f].length; i++)
	  {
	    if (document.forms[f][i].type == "radio")
	    {
	      var riga = document.forms[f][i].parentNode.parentNode;
	      riga.style.backgroundColor="rgb(255, 255, 255)";
	    }
	  }
	}
	formId.parentNode.parentNode.style.backgroundColor="rgb(223, 242, 255)";
}
function deselezionaRiga(formId){
	var oldColor = formId.parentNode.style.backgroundColor;
	if (oldColor=='rgb(239, 246, 251)'){
		formId.parentNode.style.backgroundColor="rgb(255, 255, 255)";
	}
}


if(typeof auto=="undefined"){
	var auto={};
}
auto.form=new function(){
	
	this.populateMethod=function(formToSubmit,method)
	{
		if (typeof method!="undefined")
		{
			var el=document.createElement("input");
   		   	el.id=formToSubmit.name+"_autosubmit_"+method;
   		   	el.type = "hidden";
            el.name = "method:"+method;
            el.value = "go";
            formToSubmit.appendChild(el);
		}
	}
	this.populateDivsVisibility=function(formToSubmit)
	{
		var collection = document.getElementsByTagName('div');
		for(i=0; i < collection.length; i++)
		{
			if(collection[i].id.indexOf("divDati")!=-1)
			{
				var flagId = formToSubmit.id+"_flag_"+collection[i].id;
				var flagShowToRemove = document.getElementById(flagId);
				if (flagShowToRemove!=null && flagShowToRemove!=undefined){
					formToSubmit.removeChild(flagShowToRemove);
				}
				var flagShowId=document.createElement("input");
				flagShowId.id=flagId;
				flagShowId.type = "hidden";
			    flagShowId.name = "flag"+collection[i].id;
			    
			    var stato = collection[i].style.display;    
				if(stato == "none"){
					flagShowId.value = "false";
				}
				else{
					flagShowId.value = "true";
				}
				formToSubmit.appendChild(flagShowId);
			}
		}
	}
	this.populateFocusId=function(formToSubmit,formElement)
	{
		var focusId=document.createElement("input");
   		focusId.id=formToSubmit.name+"_focus_";
   		focusId.type = "hidden";
        focusId.name = "focusId";
        focusId.value = formElement.id;
        formToSubmit.appendChild(focusId);
	}

	this.submitMyForm=function(formElement,method)
	{
		var formToSubmit=formElement.form;
		if (method!=null && method=='update'){
			fetchJSONData(formElement);
		}
		else{
			this.populateDivsVisibility(formToSubmit);
			this.populateMethod(formToSubmit,method);
			this.populateFocusId(formToSubmit,formElement);
			freezePage();
			formToSubmit.submit();
		}
	}

	this.submitMyFormWithoutFocusId=function(formElement,method)
	{
		var formToSubmit=formElement.form;
		this.populateDivsVisibility(formToSubmit);
		this.populateMethod(formToSubmit,method);
		formToSubmit.submit();
	}

	
	this.scrollTo=function(formElementId)
	{
		// se c'è un errore, nessun scrolling
		if ($('errors').innerHTML.indexOf('fieldErrors')!=-1
				|| $('errors').innerHTML.indexOf('fieldWarning')!=-1){
			try {
				$('errors').focus();
	    	} catch(e) {} // suppress focus errors
			return true;
		}
		
		var formElement=document.getElementById(formElementId);
		var currentElement=formElement;
		var selectedPosX = 0;
  		var selectedPosY = 0;  		
		if (currentElement != null){
			try {
				currentElement.focus();
	    	} catch(e) {} // suppress focus errors
			var selectedPosY = currentElement.offsetTop;
			while(currentElement.offsetParent){
				if(currentElement==document.getElementsByTagName('body')[0]){
					break;
				}
				else{
					selectedPosY=selectedPosY+currentElement.offsetParent.offsetTop;
					currentElement=currentElement.offsetParent;
				}
			}
			currentElement = currentElement.offsetParent;
			selectedPosY-=150;
			if (selectedPosY<400) selectedPosY=0;
			if (selectedPosY<0) selectedPosY=0;
	  		window.scrollTo(selectedPosX,selectedPosY);
		}
		else{
			scrollToFirstElement();
		}
	}
}

auto.formats=new function(){
	this.formatNumber= function(vInput,e)
	{
		var vInputValue = trim(vInput.value);
		var whichCode = (window.Event) ? e.which : e.keyCode;
		var keyCodeToEsclude = new Array(8,36,37,39,46);
		for (i=0; i < keyCodeToEsclude.length; i++) {
			if (whichCode == keyCodeToEsclude[i]){
				return true;
			}
		}
		vInput.value = "";
		var numberCheck = "0123456789";
		if (vInputValue!=null && vInputValue.length>0){
			for (i=0; i < vInputValue.length; i++)
			{
				if (numberCheck.indexOf(vInputValue.charAt(i)) != -1) {
					vInput.value = vInput.value + vInputValue.charAt(i);
				}
			}
		}
		return vInput.value;
	}
	this.formatDate= function(vDateName, e, dateCheck, dateType)
	{
		var vDateValue=trim(vDateName.value);
		var strSeperator = "/"; 
		var vDateType = 1; // Global value for type of date format 
						   //- 1 = dd/mm/yyyy
		                   //- 2 = mm/yyyy
		var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
		vDateType = dateType;
		var whichCode = (window.Event) ? e.which : e.keyCode;
		var keyCodeToIgnore = new Array('8');
		for (i=0; i < keyCodeToIgnore.length; i++) {
			if (whichCode == keyCodeToIgnore[i]){
				return true;
			}
		}
		this.formatNumber(vDateName, e);
		if (vDateType == 1) {
			if (vDateValue.length == 2) {
				vDateName.value = vDateValue+strSeperator;
			}
			if (vDateValue.length == 5) {
				vDateName.value = vDateValue+strSeperator;
		    }
			if (vDateValue.length > 10) {
				vDateName.value = vDateName.value.substring(0,10);
		    }
		}
		if (vDateType == 2) {
			if (vDateValue.length == 2) {
				vDateName.value = vDateValue+strSeperator;
			}
			if (vDateValue.length > 7) {
				vDateName.value = vDateName.value.substring(0,7);
		    }
		}
		return true;
	}
	this.formatQuattroRuote=function(formElement)
	{
		var textToFormat=formElement.value;
		if (textToFormat.length>0)
		{
			if (textToFormat.charAt(0)!='0') formElement.value = '0'+textToFormat;	
		}
	}
}

function conferma () {
  return confirm('Terminare il preventivo?');
}

function confermaCancellazionePreventivo() {
	var numPreventivoSelezionato = null;
	var formInputs = $$('input');
	formInputs.each(function(e){
		 if (e.type!=null && e.type=='radio'){
			 if (e.checked){
				 numPreventivoSelezionato = e.value;
			 }
		 }
	});
	if (numPreventivoSelezionato!=null){
		return confirm('Eliminare il Preventivo Num. ' + numPreventivoSelezionato + '?');
	}
	return true;
}

function azzeraCampiRicerca() {
	var formInputs = $$('input');
	formInputs.each(function(e){
		 if (e.type!=null && e.type=='text'){
			 e.value = "";
		 }
	});
}

function scrollToFirstElement()
{
	var bFound = false;
	for (f=0; f < document.forms.length; f++)
	{
	  for(i=0; i < document.forms[f].length; i++)
	  {
	    if (document.forms[f][i].type != "hidden" && document.forms[f][i].disabled != true)
	    {
		  try {
    	      document.forms[f][i].focus();
    	  } catch(e) {} // suppress focus errors
          var bFound = true;
	    }
	     if (bFound == true)
	      break;
	  }
	  if (bFound == true)
	    break;
	}
}

function loadNavigation(label)
{
	var tableNavigation = document.getElementById("tabellaNavigazione");
	var tableBody = document.createElement("tbody");
	var row = document.createElement("tr");
	var labels = new Array("PRODOTTO", "CONTRAENTE-VEICOLO", "TARIFFAZIONE-GARANZIE", "RIEPILOGO", "SALVATAGGIO");
	for (i=0;i<labels.length;i++)
	{
		var cell = document.createElement("td");
		cell.setAttribute("align","center");
		if (labels[i]==label){
			cell.style.fontWeight = "bold";	
		}
	    var cellText = document.createTextNode(labels[i]);
	    cell.appendChild(cellText);
	    row.appendChild(cell);
	    
	    if (i!=labels.length-1){
	    	var separatorText = document.createTextNode(">");
			var cellSeparator = document.createElement("td");
			cellSeparator.appendChild(separatorText);
		    row.appendChild(cellSeparator);	
	    }
	}
	tableBody.appendChild(row);
    tableNavigation.appendChild(tableBody);
}

function ovverrideLabelWith(item, newLabel)
{
	if (window.document.getElementById(item)!=null){
		window.document.getElementById(item).innerHTML = newLabel;
	}
}

function openClose(item, imgId, endTitleId)
{
	var elemento = window.document.getElementById(item);
	var image = window.document.getElementById(imgId);
	var endTitolo = window.document.getElementById(endTitleId);
	stato = elemento.style.display;
	if(stato == "none"){
		elemento.style.display = "";
		if (image!=null){
			image.src = "../images/sectionMinimizeButton.gif";
			image.title = "Riduci";
		}
		if (endTitolo!=null) {
			endTitolo.innerHTML = "";
		}
		if ("divGaranzie"==item){
			ovverrideLabelWith("spanGaranziePremioNetto", "Premio Netto");
			ovverrideLabelWith("spanGaranziePremioLordo", "Premio Lordo");
			ovverrideLabelWith("spanGaranziePremioLordoAnnuo", "Premio Lordo Annuo");
		}
	}
	else{
		elemento.style.display = "none";
		if (image!=null){
			image.src = "../images/sectionExpandButton.gif";
			image.title = "Espandi";
		}
		if (endTitolo!=null) {
			endTitolo.innerHTML = " ...";
		}
		if ("divGaranzie"==item){
			ovverrideLabelWith("spanGaranziePremioNetto", "&nbsp;");
			ovverrideLabelWith("spanGaranziePremioLordo", "&nbsp;");
			ovverrideLabelWith("spanGaranziePremioLordoAnnuo", "&nbsp;");
		}
	}
}

var waitElement="assente";
function freezePage()
{	
	var freezeDiv = document.getElementById("parentDiv");
	var tabPrincipale = document.getElementById("formPrincipale");
	var tabErrori = document.getElementById("errors");
	var newWidth  = 0;
	var newHeight = 0;
	if (tabErrori!=null){
		if (tabErrori.offsetHeight>0){
			newHeight += tabErrori.offsetHeight;
			newHeight += 8;
		}
	}
	if (tabPrincipale!=null){
		newWidth += tabPrincipale.offsetWidth;
		newHeight += tabPrincipale.offsetHeight;	
	}
	freezeDiv.style.width = newWidth;
	freezeDiv.style.height = newHeight;
	freezeDiv.style.display = 'inline';
	
	//opacizza(freezeDiv,20);
}

function opacizza(oggetto,opacity){
	if(document.all){ // se sto usando internet explorer
    	oggetto.style.filter = "alpha(opacity=" + opacity+ ")";
  	}else{
    	oggetto.style.opacity = opacity / 100;
	}
}

function unFreezePage()
{	
	var freezeDiv = document.getElementById("parentDiv");
	if (freezeDiv!=null){
		freezeDiv.style.width = 0;
		freezeDiv.style.height = 0;
		freezeDiv.style.display = 'none';
	}
}

function popUpStampa(actionName){
	if (!window.focus){
		return true;	
	}
	var action;
	if (typeof(actionName) == 'string')
	   action=actionName;
	else
	   action=actionName.href;
	// se c'è un errore, nessun scrolling
	if (!($('errors').innerHTML.indexOf('fieldErrors')!=-1
			|| $('errors').innerHTML.indexOf('fieldWarning')!=-1)){
		window.open(action, '', '');
	}
	return false;
}

function trim(stringa){
	if (stringa!=null){
		while (stringa.substring(0,1) == ' '){
	        stringa = stringa.substring(1, stringa.length);
	    }
	    while (stringa.substring(stringa.length-1, stringa.length) == ' '){
	        stringa = stringa.substring(0,stringa.length-1);
	    }
	}
    return stringa;
}

function controllaSubmitSelezioneProdotto(codiceCompagnia){
	var dataDecorrenza = $('polizza.datadecorrenza').value;
	var currentDate=new Date();
	var dataDec=new Date(currentDate);
	dataDec.setFullYear(dataDecorrenza.substring(6,10),parseInt(dataDecorrenza.substring(3,5))-1,dataDecorrenza.substring(0,2));
	var limitDec=new Date(currentDate);
	limitDec.setDate(limitDec.getDate()+61);
	var prodotto = $('prodotto.codice');
	if (Math.ceil(((((dataDec.getTime()-currentDate.getTime()) / 1000) / 60) / 60) / 24)>=0 && Math.ceil(((((limitDec.getTime() - dataDec.getTime()) / 1000) / 60) / 60) / 24)>0){
		for(i=0; i < prodotto.options.length; i++){
			if (prodotto.options[i].selected){
				if (prodotto.options[i].value=="2254"){  // storica
					if (codiceCompagnia!=null){
						var popupUrl;
						var nome;
						if (codiceCompagnia=='1'){
							popupUrl='../html/rma/PremiRCAStoriche.html?1';
							nome = 'AutoStorica';
						}
						else if (codiceCompagnia=='Q') {
							popupUrl='../html/pie/PremiRCAStoricheP.html?2';
							nome = 'InAutoClassica';
						}
						if (popupUrl!=null){
							window.open(popupUrl,nome,'width=710,height=300,scrollbars=yes,resizable=no,status=no,location=no,toolbar=no');
							return false;
						}
					}
				}
			}
		}
	}
	return true;
}