// JavaScript Document
	//Variabili js multilingua da mettere dentro all'xml
	msgElaborazione_js		= "Elaborazione in corso ...";
	confirmAnnPrev_js 		= "Sei proprio sicuro di voler annullare la pratica in preventivo?";
	confirmPraticaOK_js 	= "Sei proprio sicuro di voler annullare la pratica gia' confermata?";
	confirmPraticaRQ_js 	= "Sei proprio sicuro di voler annullare la pratica in richiesta?";
	confirmPraticaOP_js 	= "Sei proprio sicuro di voler annullare la pratica in opzione?";
	returnRegAccept_js 		= "Occorre accettare prima di continuare";
	alertErrNumeric_js 		= "inserire solo valori numerici";
	alertErrNomePax_js 		= "Inserire il nome e il cognome di tutti i passeggeri.";
	alertErrChIfPax_js		= "Per tutti i Child e gli Infant e' necessario inserire la data di nascita.";
	alertBanconista_js		= "Il banconista e' obbligatorio";
	alertBirthPaxDate_1_js	= "La data di nascita del ";
	alertBirthPaxDate_2_js	= " passeggero deve essere valida e nel formato gg/mm/aaaa";
	alertBirthPaxMonth_1_js	= "Il mese della data di nascita del ";
	alertBirthPaxMonth_2_js	= " passeggero deve essere un numero compreso tra 1 e 12";
	alertBirthPaxDay_1_js	= "Il giorno della data di nascita del ";
	alertBirthPaxDay_2_js	= " passeggero deve essere un numero compreso tra 1 e 31";
	alertCheckMonth31_1_js	= "Il mese ";
	alertCheckMonth31_2_js	= " della data di nascita del ";
	alertCheckMonth31_3_js	= " passeggero non ha 31 giorni!";	
	alertCheckFeb_1_js		= "Febbraio ";
	alertCheckFeb_2_js		= " non ha ";
	alertCheckFeb_3_js		= " giorni!";
	alertCodFiscNull_js     = "Codice fiscale obbligatorio per primo pax"
	alertCheckCodFisc_js    = "Codice fiscale non inserito correttamente";
	msgAttention			= "ATTENZIONE:";
	
	buttonClicked 		= '';
	step2NoWizardButton = '';
	noWizard 			= true;
	updatedPassengers   = false;
	bkgcode				= '';
	pkcompany			= '';
	loadingMessage		= '<div style="width:100%; text-align:center; font-size:12px; font-weight:bold;"><br /><br/>' + msgElaborazione_js +'<br /><br/><img src="/booking/images/ajax-loader.gif" style="margin:40px;"></div>';
	
	if(typeof(cfw) == 'undefined') {var cfw = {}};

	function goToDeleteBooking(bkgcode,pkcompany)
		{			
			if (confirm(confirmAnnPrev_js))
				{
					cfw.viewWApane('contentPratica','/booking/pratica_dettaglio.cfm?bkgcode='+bkgcode+'&pkcompany='+pkcompany+'&stato=DP')
				}
		}

	function goToDeleteConfirmBooking(bkgcode,pkcompany,statoPratica)
		{			
			if (statoPratica == 'OK')
				messageConfirm = confirmPraticaOK_js;
			if (statoPratica == 'RQ')
				messageConfirm = confirmPraticaRQ_js;
			if (statoPratica == 'OP')
				messageConfirm = confirmPraticaOP_js;		
				
			if (confirm(messageConfirm)) 
				{
					apriWait('TO', 300, 150);
					cfw.viewWApane('contentPratica','/booking/pratica_dettaglio.cfm?bkgcode='+bkgcode+'&pkcompany='+pkcompany+'&stato=DB')
				}
		}	

	function sistemazioni(codice, tipo)
		{
			var campoJs = document.getElementsByName(tipo + "_" + codice);
							
			var i = 0;
			var returnValue = '';			
			for (i=0;i<campoJs.length;i++)
				{
					if(campoJs[0].type == 'select-one')
						returnValue = returnValue + campoJs[i].options[campoJs[i].selectedIndex].value;
					else
						returnValue = returnValue + campoJs[i].value;	
					if (i!=campoJs.length-1)
						returnValue = returnValue + ','
				}
			return returnValue;
		}

	function showLogin()
		{
			cfw.loginModaledlg.show();
		}

	function initFromOffer(address)
		{
			var MainPane = dojo.widget.byId('step2');
			showWizardPane('steps','wstep2');
			MainPane.setUrl(address);			
		}

	function showWizardPane(wizard,pane)
		{
			var MainWizard = dojo.widget.byId(wizard);
			var MainPane = dojo.widget.byId(pane);
			MainWizard.onSelected(MainPane);
		}

	function registrazioneCheckAgreement() 
		{
			var frm = document.forms['formregistrazione'];
			var accetto = frm.accetto;
			if (!accetto.checked) 
				{
					return returnRegAccept_js;
				}
		}
		
	function anno(valore)
		{
			var i=new RegExp("[0-9]");
			if  ((!(i.test(valore)))&&valore!='')
				alert(alertErrNumeric_js);
			if (valore.length==2)
				{
					if (valore>5)
						valore = '19' + valore;
					else
						valore = '20' + valore;
				}
			return valore
		}

	function checkpasseggeri() {
		var numberOfPax		= 0;
		var iCounter		= 0;
		var dayFieldValue	= "";
		var monthFieldValue	= "";
		var yearFieldValue	= "";
		var checkDateResult	= "";
		var codfisc = "";
		var re = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;

		numberOfPax = dojo.byId('PASSENGERS').PAXNUMBER.value;
		
		for (iCounter = 1; iCounter <= numberOfPax; iCounter++) {
			FirstName		= dojo.byId("passengers_" + iCounter + "__FIRSTNAME").value;				
			LastName		= dojo.byId("passengers_" + iCounter + "__LASTNAME").value;			
			objTitle		= dojo.byId("passengers_" + iCounter + "__TITLE");
			dayFieldValue 	= dojo.byId("passengers_" + iCounter + "__BIRTHDATE_DD").value;
			monthFieldValue	= dojo.byId("passengers_" + iCounter + "__BIRTHDATE_MM").value;
			yearFieldValue	= dojo.byId("passengers_" + iCounter + "__BIRTHDATE_YYYY").value;
			//codfisc 		= dojo.byId("passengers_" + iCounter + "__CODFISC").value;
			
			if (objTitle.type == 'select-one') {
				titleName		= objTitle.options[objTitle.selectedIndex].value;	
			} else {
				titleName		= objTitle.value;	
			}
			
			if (((titleName == 'CHD') || (titleName == 'INF')) && ((dayFieldValue == '') && (monthFieldValue == '') && (yearFieldValue == ''))) {
				return alertErrChIfPax_js;
			}
			
			if ((dayFieldValue != '') || (monthFieldValue != '') || (yearFieldValue != '')) {
				checkDateResult	= checkDate(monthFieldValue + "/" + dayFieldValue + "/" + yearFieldValue, iCounter);
				if (checkDateResult != '') {
					return checkDateResult;
				}
			}
			
			if ((FirstName == '' || LastName == '')) {
				return alertErrNomePax_js;
			}
			/*
			if (opt.core.trim(codfisc) == "" && iCounter == 1) {
				return alertCodFiscNull_js;
			}
			
			if (opt.core.trim(codfisc) != "" && ! re.test(codfisc.toUpperCase())) {
				return alertCheckCodFisc_js;
			}
			*/ 
		}
		
		if (dojo.byId("banconista").value=='')
			return alertBanconista_js;
		
		return "ok";
	} 
	
	function checkDate(dateStr, IdPax) {
		var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
		var matchArray = dateStr.match(datePat); // is the format ok?
		var lstErrori = "";
	
		if (matchArray == null) {
			lstErrori = lstErrori + "\r" + alertBirthPaxDate_1_js +IdPax +alertBirthPaxDate_2_js;
			return lstErrori;
		}
		
		month 	= matchArray[1]; // p@rse date into variables
		day 	= matchArray[3];
		year 	= matchArray[5];
		
		if (month < 1 || month > 12) { // check month range
			lstErrori = lstErrori + "\r" + alertBirthPaxMonth_1_js + IdPax + alertBirthPaxMonth_2_js;
			return lstErrori;
		}
		
		if (day < 1 || day > 31) {
			lstErrori = lstErrori + "\r" + alertBirthPaxDay_1_js + IdPax + alertBirthPaxDay_2_js;
			return lstErrori;
		}
		
		if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			lstErrori = lstErrori + "\r" + alertCheckMonth31_1_js + month + alertCheckMonth31_2_js + IdPax + alertCheckMonth31_3_js;
			return lstErrori;
		}
		if (month == 2) { // check for february 29th
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day > 29 || (day==29 && !isleap)) {
				lstErrori = lstErrori + "\r" + alertCheckFeb_1_js + year + alertCheckFeb_2_js + day + alertCheckFeb_3_js;
				return lstErrori;
			}
		}
		return lstErrori; // date is valid
	}	
	function cancPax(keyPax) {
		window.document.cancelForm.KEYPAXTODEL.value = keyPax;
		window.document.cancelForm.submit();
	}

	function gocheckformmodificaprofiloagenti()
		{
			var lstErrori 		= msgAttention;

			with (window.document.modificaprofiloagente)
				{
					if (!(isAlphabeticString(USR_NOME.value)))
						{
							lstErrori += "\r\nCampo nome non corretto (inserire almeno 3 caratteri)";
						}
					if (!(isAlphabeticString(USR_COGNOME.value)))
						{
							lstErrori += "\r\nCampo cognome non corretto (inserire almeno 3 caratteri)";
						}
					if (!(isEmail(USR_EMAIL.value)))
						{
							lstErrori += "\r\nEmail non corretta";
						}
				}

			if (lstErrori != msgAttention)
				{
					alert(lstErrori);
				}
			else
				submitAjaxForm('modificaprofiloagente', submitAjaxFormResultModificaprofiloAgente, 'agenti');
		}

	function gocheckformmodificaprofilo()
		{
			var lstErrori 		= msgAttention;

			with (window.document.formmodificaprofilo)
				{
					if (!(isCF(USR_CODFISC.value)))
						{
							lstErrori += "\r\nCodice Fiscale non corretto";
						}
					if (isTelFax(USR_TELEFONO.value)=='')
						{
							lstErrori += "\r\nInserire un numero di telefono corretto (solo caratteri numerici)!";
						}
					if (isTelFax(USR_FAX.value)=='')
						{
							lstErrori += "\r\nInserire il numero di fax (solo caratteri numerici)";
						}	
					if (!(isPIVA(USR_PIVA.value)) && (USR_PROVINCIA.options[USR_PROVINCIA.selectedIndex].value != 'TI')&&(USR_PROVINCIA.options[USR_PROVINCIA.selectedIndex].value != '--'))
						{
							lstErrori += "\r\nPartita IVA non corretta";
						}
					if (!(isAddress(USR_INDIRIZZO.value)))
						{
							lstErrori += "\r\n\Indirizzo non corretto";
						}
					if (!(isCAP(USR_CAP.value)))
						{
							lstErrori += "\r\n\CAP non corretto";
						}
					if (!(isAlphabeticString(USR_LOCALITA.value)))
						{
							lstErrori += "\r\n\Localita' non corretta";
						}
					if (USR_PROVINCIA.value == '')
						{
							lstErrori += "\r\n\Provincia non corretta";
						}
					}

			if (lstErrori != msgAttention)
				{
					alert(lstErrori);
				}
			else
				checkformmodificaprofilo ();
		}

	cfw.submitAjaxFormModificaprofilo = function(theForm)
		{
			dojo.io.bind({
			   handle: cfw.submitAjaxFormResultModificaprofilo,
			   formNode: dojo.byId(theForm)
			});
			var MainPane = dojo.widget.byId("profilotab1");
			MainPane.setContent(loadingMessage);
			document.body.style.cursor = 'wait';
		}

	cfw.submitAjaxFormResultModificaprofilo = function(type, data, evt)
		{
			if (type == 'error')
				  alert('Si è verificato un errore che è stato segnalato al nostro Staff.\nSi prega di riprovare più tardi.');
			else
				{
					var MainPane = dojo.widget.byId("profilotab1");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

	function checkformmodificaprofilo()
	
		{
			var myForm = dojo.byId('formmodificaprofilo')
			dojo.require("dojo.validate.check");
			  var profile = {
			   trim: 		["USR_AGENZIA","USR_TELEFONO","USR_FAX","USR_INDIRIZZO","USR_CAP","USR_LOCALITA"],
			   required: 	["USR_AGENZIA","USR_TELEFONO","USR_FAX","USR_INDIRIZZO","USR_CAP","USR_LOCALITA"],
			   uppercase: 	[],
			   lowercare: 	[],
			   ucfirst:		[],
			   digit:		["USR_TELEFONO","USR_FAX","USR_CAP"],
			   constraints:
					{
						
					}
			  };
			myValidation = dojo.validate.check(myForm,profile);
			if (myValidation.isSuccessful())
				
					cfw.submitAjaxFormModificaprofilo(formmodificaprofilo);
				
			else
				{
					
						alert('dati incompleti');
						return false;
					
				}
		}


	function gocheckformregistrazione()
		{
			var lstErrori 		= msgAttention;
			with (window.document.formregistrazione)
				{
					if (!(isAlphabeticString(USR_NOME.value)))
						{
							lstErrori += "\r\nCampo nome reponsabile non corretto (inserire almeno 3 caratteri)";
						}
					if (!(isAlphabeticString(USR_COGNOME.value)))
						{
							lstErrori += "\r\nCampo cognome reponsabile non corretto (inserire almeno 3 caratteri)";
						}
					if (!(isEmail(USR_EMAIL.value)))
						{
							lstErrori += "\r\nEmail non corretta";
						}
					if (!(isCF(USR_CODFISC.value)))
						{
							lstErrori += "\r\nCodice Fiscale non corretto";
						}
					if (isTelFax(USR_TELEFONO.value)=='')
						{
							lstErrori += "\r\nInserire un numero di telefono corretto (solo caratteri numerici)!";
						}
					if (isTelFax(USR_FAX.value)=='')
						{
							lstErrori += "\r\nInserire il numero di fax (solo caratteri numerici)";
						}	
					if (!(isPIVA(USR_PIVA.value)) && (USR_PROVINCIA.options[USR_PROVINCIA.selectedIndex].value != 'TI')&&(USR_PROVINCIA.options[USR_PROVINCIA.selectedIndex].value != '--'))
						{
							lstErrori += "\r\nPartita IVA non corretta";
						}
					if (!(isAddress(USR_INDIRIZZO.value)))
						{
							lstErrori += "\r\n\Indirizzo non corretto";
						}
					if (!(isCAP(USR_CAP.value)))
						{
							lstErrori += "\r\n\CAP non corretto";
						}
					if (!(isAlphabeticString(USR_LOCALITA.value)))
						{
							lstErrori += "\r\n\Localita' non corretta";
						}
					if (USR_PROVINCIA.value == '')
						{
							lstErrori += "\r\n\Provincia non corretta";
						}
					if (lstErrori != msgAttention)
						{
							return lstErrori;
						}
					}

			checkformregistrazione();
		}

	function openTitlePane(pane)
		{
			var myPane = dojo.widget.byId(pane);
			myPane.onLabelClick();
		}

	function openProdottiTo(pane,address)
		{
			var myContent = dojo.widget.byId(pane + 'Content');
			var myDivContent = dojo.byId(pane);
			myContent.setUrl(address);

			if (myDivContent.style.display!='none')
				myDivContent.style.display='none';
			else
				myDivContent.style.display='block';
		}

	/*
	function openProdottiTo(pane,address)
		{
			paneTo = pane;
			dojo.io.bind({
			   load: openProdottiToResult,
			   url: address
			});
			document.body.style.cursor = 'wait';

		}

	function openProdottiToResult(type, data, evt)
		{
			if (type == 'error')
				  alert('Si è verificato un errore che è stato segnalato al nostro Staff.\nSi prega di riprovare più tardi.');
			else
				{
					var myContent = dojo.widget.byId(paneTo + 'Content');
					var myPane = dojo.widget.byId(paneTo);
					myContent.setContent(data);
					document.body.style.cursor = 'default';
					myPane.onLabelClick();
				}
		}
	*/

	function checkUpdatedPassengers(bkgcode,pkcompany)
		{
			var btn = document.getElementById("closeButtonpratica");
				if (updatedPassengers) 
					{
						updatedPassengers = false;
						cfw.viewWApane('pratica_' + bkgcode,'pratiche_syncbooking.cfm?BKGCODE=' + bkgcode + '&PKCOMPANY=' + pkcompany);
					}
			cfw.praticadlg.setCloseControl(btn);
		}

	function gestionePratica()
		{
			var myWizard = dojo.widget.byId("steps");
			var myTabPane = dojo.widget.byId("idealwebtabs");
			var myWizardPane1 = dojo.widget.byId("step1");
			var waDate = new Date;
			
			try {
			myTabPane.selectChild('pratiche','booking');			
			}
			catch(e){
				myTabPane.selectChild('booking','booking');
			}
			myWizard.onSelected(myWizard.getPanels()[0]);
			myWizard._onPreviousButtonClick();
			
			
			// svuoto carrello
			/*addCart('cart', 'carrello.cfm?clearCart');
			CloseTitle();*/

			cfw.praticadlg.show();
			cfw.viewWApane('praticaContent','pratica.cfm?BKGCODE='+bkgcode+'&PKCOMPANY='+pkcompany+'&justConfirmed=true&tick='+waDate);
		}

<!--- funzione per la scelta del report in layout/booking_report_default.cfm --->
	function scegliReport(myRadioButton,myQryString)
		{
			var counter = 0;
			var myvar	= '';
			for (counter = 0; counter < myRadioButton.length; counter++)
				{ 
					if (myRadioButton[counter].checked)
						{ 
							myvar = myRadioButton[counter].value; 
						} 
				} 
			window.open('/booking/pratica_report_show.cfm?'+myQryString+'&ReportType='+myvar);
		}


	function handleWizardButtons(display)
		{
			var myWizardButtons = domGeElByAttributeValue('div','dojoAttachPoint','wizardControlContainerNode')[0];
			myWizardButtons.style.display=display;
		}
		
	function hideGestionePratica()
		{
			var Donebutton = domGeElByAttributeValue('input','dojoAttachPoint','doneButton')[0];
			Donebutton.style.display = 'none';
		}
		
	function nextPanelWizardManage(address)
		{
			var myWizard = dojo.widget.byId("steps");
			step2NoWizardButton = address;
			buttonClicked = 'next';
			myWizard._onNextButtonClick();
		}
		
	function nextprevWizardManage()
		{
			var Nextbutton = domGeElByAttributeValue('input','dojoAttachPoint','nextButton')[0];
			var Prevbutton = domGeElByAttributeValue('input','dojoAttachPoint','previousButton')[0];
			dojo.event.connect(Nextbutton, "onmousedown", 
				function(evt){
					{
						buttonClicked = 'next';
					}
				}
				);
			dojo.event.connect(Prevbutton, "onmousedown", 
				function(evt){
					{
						buttonClicked = 'prev';
					}
				}
				);
		}
	

	function submitAjaxFormResultImportaPratica(type, data, evt)
		{
			if (type == 'error')
				{
				  alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
				 }
			else
				{
					var MainPane = dojo.widget.byId("praticheimporta");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

	function submitAjaxFormResultRegistrazione(type, data, evt)
		{
			if (type == 'error')
				{
				  alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
				 }
			else
				{
					var MainPane = dojo.widget.byId("step3registrazione");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

	function submitAjaxFormResultModificaPasseggeri(type, data, evt)
		{
			if (type == 'error')
				{
				  alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
				 }
			else
				{
					var MainPane = dojo.widget.byId("contentPratica");
					MainPane.setContent(data);
					updatedPassengers = true;
					document.body.style.cursor = 'default';
				}
		}

	function submitAjaxFormResultModificaprofiloAgente(type, data, evt)
		{
			if (type == 'error')
				 alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
			else
				{
					var MainPane = dojo.widget.byId("agenti");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

	cfw.submitAjaxFormmandanota = function(theForm)
		{
			dojo.io.bind({
			   handle: submitAjaxFormResultmandanota,
			   formNode: dojo.byId(theForm)
			});
			var MainPane = dojo.widget.byId("notaContent");
			MainPane.setContent(loadingMessage);
			document.body.style.cursor = 'wait';
		}
	function submitAjaxFormResultmandanota(type, data, evt)
		{
			if (type == 'error')
				{
					alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
				}
			else
				{
					var MainPane = dojo.widget.byId("notaContent");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}
	cfw.submitAjaxForminseriscinota = function(theForm)
		{
			dojo.io.bind({
			   handle: submitAjaxFormResultinseriscinota,
			   formNode: dojo.byId(theForm)
			});
			var MainPane = dojo.widget.byId("notaContent");
			MainPane.setContent(loadingMessage);
			document.body.style.cursor = 'wait';
		}
	function submitAjaxFormResultinseriscinota(type, data, evt)
		{
			if (type == 'error')
				{
					alert(data);
					alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
				}
			else
				{
					var MainPane = dojo.widget.byId("notaContent");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}
		
	function vaiSchedaProdotto(address)
		{
			var TagPane = dojo.widget.byId('schedaProdottoContent');
			TagPane.setUrl(address);
			TagPane = dojo.widget.byId('schedaProdotto');
			TagPane.show();
		}

	cfw.viewWApane = function(mypane,address)
		{
			var TagPane = dojo.widget.byId(mypane);
			var waDate = new Date;
			TagPane.setUrl(address+'&time='+waDate);
		}

	function submitAjaxForm(theForm, handlerFunction, theTarget, theMessage)
		{
			if (typeof theMessage == 'undefined')
				theMessage = loadingMessage;
			 dojo.io.bind({
			   handle: handlerFunction,
			   formNode: dojo.byId(theForm)
			});
			var MainPane = dojo.widget.byId(theTarget);
			MainPane.setContent(theMessage);
			document.body.style.cursor = 'wait';
		}
		
	function submitAjaxForm_RisultatoProdotti(type, data, evt)
		{		
			handleWizardButtons('');
		
			if (type == 'error')
				{
				  alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
				 }
			else
				{
					var MainPane = dojo.widget.byId("step2");
					if (noWizard==true)
						{
							var myWizard = dojo.widget.byId("steps");
							myWizard.nextButton.style.display = "none";
						}
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

	function submitAjaxForm_RisultatoProdottiCarrello(type, data, evt)
		{
			if (type == 'error')
				{
				  alert("Si e' verificato un errore che e' stato segnalato al nostro Staff.\nSi prega di riprovare piu' tardi.");
				 }
			else
				{
					var MainPane = dojo.widget.byId("step2");
					if (noWizard==true)
						{
							var myWizard = dojo.widget.byId("steps");
						}
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

	function submitAjaxForm_RisultatoPasseggeri(type, data, evt)
		{
			handleWizardButtons('');

			if (type == 'error')
				{
				  alert('Si è verificato un errore che è stato segnalato al nostro Staff.\nSi prega di riprovare più tardi.');
				 }
			else
				{
					var MainPane = dojo.widget.byId("step4");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

		
	function submitAjaxForm_RicercaPratiche(type, data, evt)
		{
			if (type == 'error')
				{
				  alert('Si è verificato un errore che è stato segnalato al nostro Staff.\nSi prega di riprovare più tardi.');
				 }
			else
				{
					var MainPane = dojo.widget.byId("praticheelenco");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}	

	function submitAjaxForm_RisultatoBooking(type, data, evt)
		{
			handleWizardButtons('');

			if (type == 'error')
				{
				  alert('Si è verificato un errore che è stato segnalato al nostro Staff.\nSi prega di riprovare più tardi.');
				 }
			else
				{
					var MainPane = dojo.widget.byId("step5");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}
		
	function submitAjaxForm_login(type, data, evt)
		{
			if (type == 'error')
				{
				  alert('Si è verificato un errore che è stato segnalato al nostro Staff.\nSi prega di riprovare più tardi.');
				 }
			else
				{
					var MainPane = dojo.widget.byId("boxContainer");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}

	function submitAjaxForm_loginprivati(type, data, evt)
		{
			if (type == 'error')
				{
				  alert('Si è verificato un errore che è stato segnalato al nostro Staff.\nSi prega di riprovare più tardi.');
				 }
			else
				{
					var MainPane = dojo.widget.byId("registrazione");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}
	function gotoStep2Cart()
		{
			var MainPane = dojo.widget.byId("step2");

			if (buttonClicked=='next')
				{
					if (checkForm())
						{
							submitAjaxForm('SRC', submitAjaxForm_RisultatoProdottiCarrello,'step2');
						}
					else 
						{
							return 'selezionare almeno una destinazione';
						}
				}
		}
		
	function gotoStep2()
		{
			var MainPane = dojo.widget.byId("step2");

			if (buttonClicked=='next')
				{
					if (checkSearchForm())
						{
							handleWizardButtons('none');
							submitAjaxForm('SRC', submitAjaxForm_RisultatoProdotti,'step2');
						}
					else 
						{
							return 'selezionare almeno una destinazione';
						}
				}
		}
	
	function searchArrayValue(objArray, lstValore) {
		var bResult = false;

		for(var i=0; i < objArray.length; i++) {		
			arrayValori = lstValore.split(",");
			for(var n=0; n < arrayValori.length; n++) {		
				if(objArray[i].value == arrayValori[n]) {				
					bResult = true;
					break;
				}
			}	
		}
		
		return bResult;
	}
		
	function gotoStep3Cart()
		{
			
			//goToQPA(); //Prendo tutti i parametri che mi servono per la qpa
			var MainPane = dojo.widget.byId("step3");
			var myCartPane = dojo.widget.byId('carttitle');
			var urlAddress = 'null';
			var returnValue = false;
			var waDate = new Date;

			if (buttonClicked=='next')
				{
					if (step2NoWizardButton=='')
						{
							if (myCartPane.open)  
								myCartPane.onLabelClick();
							MainPane.setUrl('step3_scelta_servizi.cfm'+'?time='+waDate);
						}
					else
						{
							handleWizardButtons('none');
							MainPane.setUrl(step2NoWizardButton+'&time='+waDate);
							step2NoWizardButton = '';
						}

				}
		}	

	function gotoStep3()
		{
			
			//goToQPA(); //Prendo tutti i parametri che mi servono per la qpa
			var MainPane = dojo.widget.byId("step3");
			var urlAddress = 'null';
			var returnValue = false;
			var waDate = new Date;

			if (buttonClicked=='next')
				{
					if (step2NoWizardButton=='')
						{
							radioSelected = document.getElementsByName("prodottoto");
							for (var i=0;i<=radioSelected.length-1; i++) 
								{
									if (radioSelected[i].checked!=false) 
										{
											urlAddress = radioSelected[i].value
											break;
										}
								}
							if (urlAddress!='null')
								{
									MainPane.setUrl(urlAddress+'&time='+waDate);
								}
							else
								{
									return 'selezionare un prodotto!';
								}
						}
					else
						{
							handleWizardButtons('none');
							MainPane.setUrl(step2NoWizardButton+'&time='+waDate);
							step2NoWizardButton = '';
						}

				}
		}	

	function gotoStep4()
		{
			if (buttonClicked=='next')
				{
					var MainPane = dojo.widget.byId("step4");
					handleWizardButtons('none');
					submitAjaxForm('QPA', submitAjaxForm_RisultatoPasseggeri,'step4');
				}
			else
				{
					var myWizard = dojo.widget.byId("steps");
					myWizard.nextButton.style.display = "none";
				}
		}
		
	function gotoStep5()
		{
			var result = '';
			if (buttonClicked=='next')
				{
					result = checkpasseggeri();
					if (result=='ok')
						{
							var MainPane = dojo.widget.byId("step5");
							handleWizardButtons('none');
							submitAjaxForm('PASSENGERS', submitAjaxForm_RisultatoBooking,'step5');
						}
					else 
						return result;
				}
		}
		
		
	function domGeElByAttributeValue(element,attribute,value)
		{
			var nodes = document.getElementsByTagName(element);
			var res = new Array();
			for(var i=0;i<nodes.length;i++) 
				{
					if(nodes[i].getAttribute(attribute) == value) 
						{
							res.push(nodes[i]);
						}
				}
			return res;
		}
		
//// FUNZIONI PER LA GESTIONE DELLE CAMERE MULTIPLE		
	function createRooms(howMany, propertyCode)
		{					
			var mySource 		= document.getElementById('SourceDiv');
			var myDestination 	= document.getElementById('DestinationDIV_' + propertyCode);							
			for(var i=1;i<=howMany;i++) {							
				mySourceCopy = mySource.cloneNode(true);			
				numberElements = (myDestination.childNodes.length);					
				mySourceCopy.removeAttribute("id");						
				//Replico la variabile dinamica con il numero dell'elemento		
				mySourceCopy.innerHTML = mySourceCopy.innerHTML.replace(/@num@/gi, (numberElements+1));
				mySourceCopy.innerHTML = mySourceCopy.innerHTML.replace(/@propCode@/gi, propertyCode);	
				// Rimetto lo stile a visible (togliendolo)
			    mySourceCopy.removeAttribute("style");
			    // Inserisco il nuovo nodo
				myDestination.appendChild(mySourceCopy);			
			}							
		}
	function deleteRooms(howMany, propertyCode)
		{
			var myDestination 	= document.getElementById('DestinationDIV_' + propertyCode);
			for(var n=1;n<=howMany;n++) {
				myDestination.removeChild(myDestination.lastChild);
			}							
		}
	function manageRooms(propertyCode) {		
			var myDestination 	= document.getElementById('DestinationDIV_' + propertyCode);
			var mySelHowMany	= document.getElementById('HowMany_' + propertyCode);
			numberElements = (myDestination.childNodes.length);
			if(mySelHowMany.type== 'radio') 		
				roomSelected = opt.form.getCheckboxValues(mySelHowMany.name); 				
			else 			
				roomSelected = mySelHowMany.options[mySelHowMany.selectedIndex].value;			
			deltaRooms = roomSelected-numberElements;
			// Se seleziono 1 camera li cancello tutti			
			if(roomSelected == 1)
				deltaRooms = -numberElements;
				
			if(deltaRooms > 0) {
				createRooms(deltaRooms, propertyCode); 		
			}
			if(deltaRooms < 0) {
				deleteRooms(Math.abs(deltaRooms), propertyCode);
			}
	}	
	function checkRooms(propertyCode, adults, childs, infants){
			errorMessage = msgAttention;
			bShowMessage = false;
			btoReturn = true;
			var mySelHowMany	= document.getElementById('HowMany_' + propertyCode);
			if (mySelHowMany && mySelHowMany.type=="select-one" && mySelHowMany.selectedIndex != 0){
				numTotalRooms = mySelHowMany.options[mySelHowMany.selectedIndex].value;
				adTotal = sistemazioni(propertyCode, 'ad');
				chTotal = sistemazioni(propertyCode, 'ch');
				inTotal = sistemazioni(propertyCode, 'in');
				
				arrayAd = adTotal.split(',');
				arrayCh = chTotal.split(',');
				arrayIn = inTotal.split(',');
				
				sumAd = 0;
				sumCh = 0;
				sumIn = 0;
				
				for (i=0;i<arrayAd.length;i++) {
					sumAd = parseInt(sumAd) + parseInt(arrayAd[i]);					
				}
				for (i=0;i<arrayCh.length;i++) {
					sumCh = parseInt(sumCh) + parseInt(arrayCh[i]);						
				}
				for (i=0;i<arrayIn.length;i++) {
					sumIn = parseInt(sumIn) + parseInt(arrayIn[i]);					
				}
				
				for (i=1;i<=numTotalRooms;i++) {
					valueField = document.getElementById("values_" + propertyCode + "_" + i);					
					if(valueField.value == 0) {
						errorMessage = errorMessage + "\nLa camera " + i + " non ha selezionato nessun componente, selezionarne o diminuire il numero di camere.";
						bShowMessage = true;						
					}					
				}
							
				if(sumAd != adults) {			
					errorMessage = errorMessage + "\nIl numero degli Adults totali non e' corretto, selezionarne: " + adults;
					bShowMessage = true;
				}	
				if(sumCh != childs) {
					errorMessage = errorMessage + "\nIl numero dei Child totali non e' corretto, selezionarne: " + childs;
					bShowMessage = true;
				}	
				if(sumIn != infants){
					errorMessage = errorMessage + "\nIl numero degli Infants totali non e' corretto, selezionarne: " + infants;
					bShowMessage = true;
				}			
					
				if(bShowMessage) {
					alert(errorMessage);	
					btoReturn = false;
				}			
			}	
			return btoReturn;			
	}
	function setValueRooms(codId) {
		adObj = document.getElementById("ad_" + codId);
		chObj = document.getElementById("ch_" + codId);
		inObj = document.getElementById("in_" + codId);
		
		var totalValue = adObj.options[adObj.selectedIndex].value;
		
		if(chObj.type == 'select-one')
			totalValue = parseInt(totalValue) + parseInt(chObj.options[chObj.selectedIndex].value);
		else
			totalValue = parseInt(totalValue) + parseInt(chObj.value);	
		if(inObj.type == 'select-one')
			totalValue = parseInt(totalValue) + parseInt(inObj.options[inObj.selectedIndex].value);
		else
			totalValue = parseInt(totalValue) + parseInt(inObj.value);
		
		var valueField = document.getElementById("values_" + codId);
		valueField.value = totalValue;		
	}
	
	function addCart(pane, address) {
			var myContent = dojo.widget.byId(pane + 'Content');

				var myDivContent = dojo.byId(pane);
				var waDate = new Date;
				var myPane = dojo.widget.byId('carttitle');
				alert();
			if(myPane != 'undefined') {		
				alert('entrato');		
				if (!myPane.open)  
					showCart();
				showCartLabels();
				
				myContent.setUrl(address+'&time='+waDate);
			}	
							alert('non entrato');		
			
	}

	function showCartLabels() {
			var myPane = dojo.widget.byId('carttitle');
			var testoCarrello = dojo.byId('pulsanteCarrello');
			if (myPane.open)
				testoCarrello.value = 'nascondi carrello';		
			else
				testoCarrello.value = 'visualizza carrello';		
	}

	function showCart() {
			var myPane = dojo.widget.byId('carttitle');
			myPane.onLabelClick();
			showCartLabels();
	}

	function CloseTitle() {
		var myPane = dojo.widget.byId('carttitle');
		 myPane.onLabelClick();
	}
	

	function changeSelectionLabel(source, destination, objRadio)
		{
			mySource = dojo.byId(source);
			myDestination = dojo.byId(destination);
			mySource.innerHTML  = myDestination.innerHTML ;
			var classSerIDvalue = objRadio.getAttribute("opt:classserID");
			if(classSerIDvalue != null) {			
				setRadioQpaOptions(classSerIDvalue);
				var radioCodSelected = objRadio.getAttribute("opt:codDept");			
				if(radioCodSelected != ''){
					arraySelectedCod = getElementsByAttribute('opt:codSelected', radioCodSelected, 'option');
					if(arraySelectedCod.length >0)
						arraySelectedCod[0].selected=true;
				}		
			}	
		}
	function setQpaOptions(objOptions) {
		valoretoSelect = objOptions.options[objOptions.selectedIndex].getAttribute("opt:codselected");		
		arraySelectedDepts = getElementsByAttribute('opt:codDept', valoretoSelect, 'input');
		var indexSelected = 0;
		for(sel=0;sel<arraySelectedDepts.length; sel++) {
			if(arraySelectedDepts[sel].getAttribute("opt:avail") >0) {					
				indexSelected=sel;	
				break;
			}	
		}
		arraySelectedDepts[indexSelected].click();		
		var classSerIDvalue = arraySelectedDepts[indexSelected].getAttribute("opt:classserID");
		if (classSerIDvalue)
			setRadioQpaOptions(classSerIDvalue);			
	}
	
	function setRadioQpaOptions(classSerIDvalue) {
		arraySelectedClass = getElementsByAttribute('opt:classserID', classSerIDvalue, 'input');
		for(sel1=0;sel1<arraySelectedClass.length; sel1++) {
			if(!arraySelectedClass[sel1].checked){
				arraySelectedClass[sel1].click();
				break;
			}	
		}
		
	}

	// document.getElementsByAttribute([string attributeName],[string attributeValue],[string:tagType],[boolean isCommaHyphenOrSpaceSeparatedList:false])
	function getElementsByAttribute(attrN,attrV,tagType,multi){
	    attrV=attrV.replace(/\|/g,'\\|').replace(/\[/g,'\\[').replace(/\(/g,'\\(').replace(/\+/g,'\\+').replace(/\./g,'\\.').replace(/\*/g,'\\*').replace(/\?/g,'\\?').replace(/\//g,'\\/');
	    if(!tagType)
	    	tagType='*';
	    var
	        multi=typeof multi!='undefined'?
	            multi:
	            false,
	        cIterate=document.getElementsByTagName(tagType),
	        aResponse=[],
	        attr,
	        re=new RegExp(multi?'\\b'+attrV+'\\b':'^'+attrV+'$'),
	        i=0,
	        elm;       
	    while((elm=cIterate.item(i++))){
	        attr=elm.getAttributeNode(attrN);
	        if(attr &&
	            attr.specified &&
	            (re.test(attr.value) || ListFind(attr.value, attrV)) //check per liste o valori singoli
	        )
	            aResponse.push(elm);
	    }
	    return aResponse;
}

	function ListFind(l,v,d){
		l = l + ""; // cheap way to convert to a string
		if(!d){d = ",";}
		var r = 0;
		var listToArray = l.split(d);
		for (var i=0; i < listToArray.length; i++){		
			if (listToArray[i] == v){
				r = i + 1;
				break;
			}
		}
		return r;
	}
	function selectDeptPlace(nomeCombo, valoreDept){		
		objCombo = document.getElementById(nomeCombo);
		for (var i=0; i < objCombo.options.length; i++){
			if (objCombo.options[i].getAttribute("opt:codselected")==valoreDept){
				objCombo.options[i].selected=true;
				setQpaOptions(objCombo);			
				break;
			}				
		}
		
	}
	
	function selectDispFly(valoreCampo){		
		arrayTrasnsp = getElementsByAttribute("name", valoreCampo, 'input');		
		for (var i=0; i < arrayTrasnsp.length; i++){			
			if (arrayTrasnsp[i].getAttribute("opt:avail") >0){
				arrayTrasnsp[i].click();
				break;
			}				
		}
		
	}
	function getGGselected(ggID) {
		objselect = document.getElementById(ggID);
		valore = objselect.options[objselect.selectedIndex].value;
		
		return valore;
	}
	
	function padDigit(digit) {
	if(digit < 10) { 
			return "0" + digit;
		} else { 
			return digit;
		}
	}	
	function dateAdd(baseStr,days) {
		baseTime = baseStr.split("/");
		time = new Date(parseInt(baseTime[2]),parseInt(baseTime[1]-1),parseInt(baseTime[0]));
		time = new Date(time.valueOf()+ (days*1000*3600*24));
		return padDigit(time.getDate())+"/"+padDigit(time.getMonth()+1)+"/"+time.getFullYear();

	}			
	function checkSearchForm() {
		var bResult = false;
		objComboDest = dojo.widget.byId('destination_2');
		if (!objComboDest)
			bResult = true;
		else if(objComboDest.selectedResult != null)
			bResult = true;
		return bResult;
	}
	function cercaADV() {
		cfw.agenziadlg.show();
		cfw.viewWApane('agenziaContent','cercaAgenzia_cginova.cfm');
	}		
	
function doLogin() {
	var s1 = opt.core.trim(document.agenzie2.username.value);
	var s2 = opt.core.trim(document.agenzie2.password.value);
	if (s1 == '' || s2 == '') {
		alert('Inserire username e password per proseguire!')
		document.agenzie2.username.focus();
		return false;
	}
	document.agenzie2.username.value = s1;
	document.agenzie2.password.value = s2;
	submitAjaxForm('agenzie2', submitAjaxForm_login, 'boxForSubmitAjax');
}		
function doContinua() {
	var s1 = opt.core.trim(document.frmUsrPrivato.USR_NOME.value);
	var s2 = opt.core.trim(document.frmUsrPrivato.USR_COGNOME.value);
	var s3 = opt.core.trim(document.frmUsrPrivato.USR_EMAIL.value);
	var s4 = opt.core.trim(document.frmUsrPrivato.USR_TELEFONO.value);
	
	if (s1 == '' || s2 == '' || s3 == '' || s4 == '') {
		alert('Inserire nome, cognome , email e telefono per proseguire!')
		document.frmUsrPrivato.USR_NOME.focus();
		return false;
	}
	if (! opt.validator.isEmail(s3)) {
		alert('Indirizzo email non valido');
		document.frmUsrPrivato.USR_EMAIL.focus();
		return false;
	}
	
	document.frmUsrPrivato.USR_NOME.value = s1;
	document.frmUsrPrivato.USR_COGNOME.value = s2;
	document.frmUsrPrivato.USR_EMAIL.value = s3;			
	document.frmUsrPrivato.USR_TELEFONO.value = s4;
	submitAjaxForm('frmUsrPrivato', submitAjaxForm_loginprivati, 'boxForSubmitAjax2', '<strong>Iscrizione in corso</strong>....<br/>');	
}

function setNextButtonVisibility(vis) {
	var myWizard = dojo.widget.byId("steps");
	myWizard.nextButton.style.display = vis;
}	

function addTabPratiche(){			
	var tc = dojo.widget.byId("idealwebtabs");
	var objTab = dojo.widget.byId("pratiche");
	if (objTab == null) {
		var cp = dojo.widget.createWidget("ContentPane", {id:"pratiche",label:"PRATICHE",href:"pratiche.cfm"});
		tc.addChild(cp);
	}		
}

function refreshHeaderBooking(sHtml) {
	var objDiv = document.getElementById('usrIdentify');	
	objDiv.innerHTML = sHtml;	
}

function addTabPreventivo(saldo){			
	var tc = dojo.widget.byId("praticatabs");
	var objTab = dojo.widget.byId("preventivo");
	if (objTab == null) {
		var cp = dojo.widget.createWidget("ContentPane", {id:"preventivo",label:"Conferma Preventivo",href:"/booking/ajax/dati_conferma_preventivo.cfm?saldo=" + saldo});
		tc.addChild(cp);
	}	
	tc.selectChild('preventivo');	
}
function addTabRegistrazione(doOption,bkgCode){	
	var tc = dojo.widget.byId("praticatabs");
	var objTab = dojo.widget.byId("registrazione");
	if (objTab == null) {
		var cp = dojo.widget.createWidget("ContentPane", {id:"registrazione",label:"Registrazione",href:"/booking/ajax/registrazione_privato.cfm?creaOpzione=" + doOption + "&bkgCode=" + bkgCode});
		tc.addChild(cp);
	}	
	tc.selectChild('registrazione');	
}
function choosePreven(scelta) {
	if (scelta == 'BO') {
		var butt = document.getElementById('confermaOpzione');
		butt.onclick();
		var tc = dojo.widget.byId("praticatabs");
		var objTab = dojo.widget.byId("contentPratica");
		if (objTab != null) 
			tc.selectChild('contentPratica');			
	}	
	if (scelta == 'AG')
		trovaAgenzia();		
}
function trovaAgenzia(){			
	var tc = dojo.widget.byId("praticatabs");
	var objTab = dojo.widget.byId("AgenziaContent");
	if (objTab != null) 
		tc.selectChild('AgenziaContent');	
}
function changeStartDateScheda(){
	var objStartDate = dojo.widget.byId("startDateScheda");
	var objEnbDate = dojo.widget.byId("endDateScheda");
	var GGperiod = 7;
	objEnbDate.setDate(dojo.date.add(objStartDate.getDate(), dojo.date.dateParts.DAY, parseInt(GGperiod)));		
}
function checkPrivacy(blnChecked) {
	var objButton = document.getElementById('btnRegPrivato');
	objButton.disabled = ! blnChecked;
}	
