// JavaScript Document
	//Variabili js multilingua da mettere dentro all'xml
	msgElaborazione_js		= "Elaborazione in corso ...Vi preghiamo di attendere";
	msgVoli_js				= "Ricerca in corso dei voli sulla base dei dati inseriti...";
	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!";
	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>';
	//loadingMessageVoli	= '<div style="width:100%; text-align:center; font-size:12px; font-weight:bold;"><br /><br/>' + msgVoli_js +'<br /><br/><img src="/booking/images/ajax-loader.gif" style="margin:40px;"></div>';
	loadingMessage		= '<br /><br /><span class="dijitContentPaneLoading">' + msgElaborazione_js +'</span>';
	loadingMessageVoli	= '<br /><br /><span class="dijitContentPaneLoading">' + msgVoli_js +'</span>';
	
	if(typeof(cfw) == 'undefined') {var cfw = {}};
	
	function viewWApane(idPane, address){
		var TagPane = dijit.byId(idPane);
		var waDate = new Date;
		TagPane.cancel();
		if (address.indexOf('?')!=-1)
			TagPane.setHref(address+'&time='+waDate);
		else
			TagPane.setHref(address+'?time='+waDate);	
	}
	/*	
	function viewWApane(idPane, address, theMessage){
		var TagPane = dijit.byId(idPane);
		var waDate = new Date;
		TagPane.cancel();
		if (typeof theMessage == 'undefined')
			theMessage = msgElaborazione_js;
		TagPane.loadingMessage= theMessage;
		TagPane.setContent('<center>' + theMessage + '</center>');
		
		if (address.indexOf('?')!=-1)
			TagPane.setHref(address+'&time='+waDate);
		else
			TagPane.setHref(address+'?time='+waDate);		
	}
	*/
	
	function goToDeleteBooking(bkgcode,pkcompany)
		{			
			if (confirm(confirmAnnPrev_js))
				{
					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)) 
				{
					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 initFromOffer(address)
		{
			var stkPrenotazione = dijit.byId("myStackContainer");
			paneStep2 = dijit.byId("step2");
			stkPrenotazione.selectChild(paneStep2);

			viewWApane('step2',address);
		}

	function showWizardPane(wizard,pane)
		{
			var MainWizard = dijit.byId(wizard);
			var MainPane = dijit.byId(pane);
			MainWizard.onSelected(MainPane);
		}

	function checkpasseggeri(action) {
		var numberOfPax		= 0;
		var iCounter		= 0;
		var dayFieldValue	= "";
		var monthFieldValue	= "";
		var yearFieldValue	= "";
		var checkDateResult	= "";
		var codfisc 		= "";
		var prefixField 	= "";
		var re = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
		
		numberOfPax = dojo.byId('PAXNUMBER').value;
		
		if (typeof(action) != 'undefined')
			prefixField = "mod_";
		
		for (iCounter = 1; iCounter <= numberOfPax; iCounter++) {
			FirstName		= document.getElementById(prefixField + "passengers_" + iCounter + "__FIRSTNAME").value;				
			LastName		= document.getElementById(prefixField + "passengers_" + iCounter + "__LASTNAME").value;			
			objTitle		= document.getElementById(prefixField + "passengers_" + iCounter + "__TITLE");
			dayFieldValue 	= document.getElementById(prefixField + "passengers_" + iCounter + "__BIRTHDATE_DD").value;
			monthFieldValue	= document.getElementById(prefixField + "passengers_" + iCounter + "__BIRTHDATE_MM").value;
			yearFieldValue	= document.getElementById(prefixField + "passengers_" + iCounter + "__BIRTHDATE_YYYY").value;
			//codfisc 		= document.getElementById(prefixField + "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 (typeof(action) != 'undefined') {
				if (opt.core.trim(codfisc) == "" && iCounter == 1) {
					return alertCodFiscNull_js;
				}
			}
			*/			
			/*if (opt.core.trim(codfisc) != "" && ! re.test(codfisc.toUpperCase())) {
				return alertCheckCodFisc_js;
			}	*/		
		}
		
		if (document.getElementById("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 openTitlePane(pane)
		{
			var myPane = dijit.byId(pane);
			myPane.toggle();
		}

	function openProdottiTo(pane)
		{
			var myContent = dijit.byId(pane);
			myContent.toggle();			
			/*myContent.setHref(address);

			if (myDivContent.style.display!='none')
				myDivContent.style.display='none';
			else
				myDivContent.style.display='block';*/
		}

	
	function checkUpdatedPassengers(bkgcode,pkcompany)
		{
			//var btn = document.getElementById("closeButtonpratica");
				if (updatedPassengers) 
					{
						updatedPassengers = false;
						viewWApane('pratica_' + bkgcode,'pratiche_syncbooking.cfm?BKGCODE=' + bkgcode + '&PKCOMPANY=' + pkcompany);
					}
			//praticadlg.setCloseControl(btn);
		}
	
	function doSearchPratiche(){
		submitAjaxForm('SEARCHPRATICHE', submitAjaxForm_RicercaPratiche,'praticheelenco','<center><br /><br /><img src=/booking/images/ajax-loader.gif><br/><br /><strong>Aggiornamento archivio pratiche in corso...</strong><br/><br /></center>');
	}
	
	function gestionePratica(praticaItinerario, pkCompanyItinerario)
		{
			var myTabPane = dijit.byId("mainTab");
			var tabPratiche = dijit.byId("pratiche");
			var dlgPratica = dijit.byId("praticadlg");
			var stkPrenotazione = dijit.byId("myStackContainer");
			var paneStep1 = dijit.byId("step1");
			var waDate = new Date;
			
			if(praticaItinerario != undefined)
				bkgcode = praticaItinerario;
			if(pkCompanyItinerario != undefined)
				pkcompany = pkCompanyItinerario;			
		/*	myTabPane.selectChild('pratiche','booking');
			myWizard.onSelected(myWizard.getPanels()[0]);
			myWizard._onPreviousButtonClick();*/

			// svuoto carrello
			addCart('cart', 'carrello.cfm?clearCart');
			//CloseTitle();
			
			myTabPane.selectChild(tabPratiche);
			
			stkPrenotazione.selectChild(paneStep1);
			dlgPratica.show();
			viewWApane('praticaContent','/booking/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 submitAjaxFormResultImportaPratica(response)
		{
			var MainPane = dijit.byId("praticheimporta");
			MainPane.setContent(response);
			document.body.style.cursor = 'default';
		}
	

	function submitAjaxFormResultModificaPasseggeri(response)
		{
			var MainPane = dijit.byId("contentPratica");
			MainPane.setContent(response);
			updatedPassengers = true;
			document.body.style.cursor = 'default';		
		}
	

	submitAjaxFormmandanota = function(theForm)
		{
			dojo.io.bind({
			   handle: submitAjaxFormResultmandanota,
			   formNode: dijit.byId(theForm)
			});
			var MainPane = dijit.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 = dijit.byId("notaContent");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}
	submitAjaxForminseriscinota = function(theForm)
		{
			dojo.io.bind({
			   handle: submitAjaxFormResultinseriscinota,
			   formNode: dijit.byId(theForm)
			});
			var MainPane = dijit.byId("notaContent");
			MainPane.setContent(loadingMessage);
			document.body.style.cursor = 'wait';
		}
		
	function vaiSchedaProdotto(address)
		{
			var TagPane = dijit.byId('schedaProdottoContent');
			TagPane.setHref(address);
			TagPane = dijit.byId('schedaProdotto');
			TagPane.show();
		}	
	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 = dijit.byId("notaContent");
					MainPane.setContent(data);
					document.body.style.cursor = 'default';
				}
		}			
	function submitAjaxForm(theForm, handlerFunction, theTarget, theMessage)
		{
			if (typeof theMessage == 'undefined')
				theMessage = loadingMessage;
			
			dijit.byId(theTarget).setContent(theMessage);
			
			var kw = {		
					form: theForm,
			        load: handlerFunction,
			        error: function(data){
			        		console.error(data);
			                dijit.byId(theTarget).setContent('<br /><span class="dijitContentPaneError">Si &egrave; verificato un errore</span>');
			        }
			        
			};
			dojo.xhrPost(kw);
		}
			
	function submitAjaxForm_RisultatoProdottiCarrello(response)
		{
			var MainPane = dijit.byId("step2");			
			MainPane.setContent(response);			
			aggiornaVoli();
			document.body.style.cursor = 'default';
		}

	function submitAjaxForm_RisultatoPasseggeri(response)
		{			
		var step4Pane = dijit.byId("step4");
		step4Pane.setContent(response);
		document.body.style.cursor = 'default';
				
		}
	function submitAjaxForm_RisultatoBooking(response)
		{					
			var step5Pane = dijit.byId("step5");
			step5Pane.setContent(response);
			document.body.style.cursor = 'default';
		}
	function submitAjaxForm_credenziali(response)
		{
	
			var MainPane = dijit.byId("boxAgeContainer");
			MainPane.setContent(response);
			document.body.style.cursor = 'default';			
		}
	function submitAjaxForm_ModificaProfilo(response)
		{
			var MainPane = dijit.byId("boxAgeSettings");			
			MainPane.setContent(response);			
			document.body.style.cursor = 'default';
		}		
	function submitAjaxForm_ModificaProfiloAgente(response)
		{
			var MainPane = dijit.byId("agenti");			
			MainPane.setContent(response);			
			document.body.style.cursor = 'default';
		}	
	function submitAjaxForm_Registrazione(response)
		{
			var MainPane = dijit.byId("step2reg");			
			MainPane.setContent(response);			
			document.body.style.cursor = 'default';
		}	
	function submitAjaxForm_dlgage(response)
		{
	
			var MainPane = dijit.byId("boxAgeSettings");
			MainPane.setContent(response);
			document.body.style.cursor = 'default';			
		}
	function submitAjaxForm_RicercaPratiche(response)
		{
	
			var MainPane = dijit.byId("praticheelenco");
			MainPane.setContent(response);
			document.body.style.cursor = 'default';
				
		}	
	function submitAjaxForm_login(response)
		{
	
			var MainPane = dijit.byId("loginContent");
			MainPane.setContent(response);
			document.body.style.cursor = 'default';
				
		}		
	function submitAjaxForm_InserisiciNota(response)
		{	
			var MainPane = dijit.byId("notaContent");
			MainPane.setContent(response);
			document.body.style.cursor = 'default';
				
		}		
	function submitAjaxForm_InviaNota(response)
		{	
			var MainPane = dijit.byId("notaContent");
			MainPane.setContent(response);
			document.body.style.cursor = 'default';
				
		}
	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;
	}
// FUNZIONI GOTO per la NAVIGAZIONE	

function gotoStep2Cart() {
	var MainPane = dijit.byId("step2");
	var sMsg = checkSearchForm();
	if (sMsg == 'ok'){
		submitAjaxForm('SRC', submitAjaxForm_RisultatoProdottiCarrello,'step2');
	} else 	{
		alert(sMsg);
	}
}
	
function gotoStep3Cart() {			
	//goToQPA(); //Prendo tutti i parametri che mi servono per la qpa
	var MainPane = dijit.byId("step3");
	var myCartPane = dijit.byId('carttitle');
	var urlAddress = 'null';
	var returnValue = false;
	var waDate = new Date;
	var arrayTPCarrello = window.document.getElementsByName("TPCarrello");
	var aggregateTPCarrello = window.document.getElementById("aggregateTP").value;
	
	// Controllo se sia presente il primo valore di aggregateCarrello nel caso ce ne sia uno di quelli da controllare
	if (arrayTPCarrello.length > 0) {
		if(aggregateTPCarrello != '') {
			arrayAggregateTPCarrello = aggregateTPCarrello.split(";");
			// Controllo se c'e' nel carrello il primo valore di controllo (Hotel di solito)
			if((searchArrayValue(arrayTPCarrello, arrayAggregateTPCarrello[0])==false) && (searchArrayValue(arrayTPCarrello, arrayAggregateTPCarrello[1])==true)) {
				return "Non e' possibile prenotare un TRASPORTO senza aver selezionato un HOTEL";										
			}
		}
		if (myCartPane && myCartPane.open)  
			myCartPane.toggle();
		MainPane.setHref('step3_scelta_servizi.cfm'+'?time='+waDate);
	} else {
		return "Non e' stato inserito nessun prodotto nel carrello.";
	}	
}	

function gotoStep4() {
	var MainPane = dijit.byId("step4");	
	submitAjaxForm('QPA', submitAjaxForm_RisultatoPasseggeri,'step4');
}
	
function gotoStep5() {
	var result = '';
	result = checkpasseggeri();
		if (result=='ok') {
			var MainPane = dijit.byId("step5");			
			submitAjaxForm('PASSENGERS', submitAjaxForm_RisultatoBooking,'step5');
		}
		else {
			alert(result);
		}
}
	
		
//// 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 = dijit.byId(pane + 'Content');
			var myDivContent = dijit.byId(pane);
			var waDate = new Date;
			var myPane = dijit.byId('carttitle');
						
			myContent.setHref(address+'&time='+waDate);			
	}

	function showCartLabels() {
			var myPane = dijit.byId('carttitle');
			var testoCarrello = document.getElementById('pulsanteCarrello');
			if (myPane.open)
				testoCarrello.value = 'nascondi carrello';		
			else
				testoCarrello.value = 'visualizza carrello';		
	}

	function showCart() {
			var myPane = dijit.byId('carttitle');
			myPane.toggle();			
	}

	function CloseTitle() {
		var myPane = dijit.byId('carttitle');
		 myPane.toggle()
	}
	

	function changeSelectionLabel(source, destination, objRadio)
		{
			mySource = document.getElementById(source);
			myDestination = document.getElementById(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');
		if (arraySelectedDepts.length > 0) {
			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 != null)
				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;
			}	
		}
		
	}	
function step2FromHome()
		{
			submitAjaxForm('formStep', submitAjaxForm_RisultatoProdottiCarrello,'step2');
			var stkPrenotazione = dijit.byId("myStackContainer");
			paneStep2 = dijit.byId("step2");
			stkPrenotazione.selectChild(paneStep2);				
		}
function checkSearchForm() {
	var msgResult = "ok";
	
	objDestSelected = document.getElementById('SRC_PRP_1');	
	if (objDestSelected.value == '')
		msgResult = "selezionare almeno una destinazione";
	/*
	var objStartDate = dijit.byId("SRC_PERIOD_BEGIN");
	if (! objStartDate.isValid())
		msgResult = "Data partenza non valida";
	*/	
	return msgResult;
}
	
function showBookFromItinerary(pratica, pkCompany) {
	gestionePratica(pratica, pkCompany);
	submitAjaxForm('SEARCHPRATICHE', submitAjaxForm_RicercaPratiche, 'praticheelenco');
}	

function organizeStep(pageNumber) {	
	prevStep = document.getElementById('currentStepId').value;	
	if(pageNumber == 'step2')
		if(pageNumber>prevStep) gotoStep2Cart();
	if(pageNumber == 'step3')
		if(pageNumber>prevStep) gotoStep3Cart();	
	if(pageNumber == 'step4')
		if(pageNumber>prevStep) gotoStep4();	
	if(pageNumber == 'step5')
		if(pageNumber>prevStep) gotoStep5();		
	if(pageNumber == 'step6')
		if(pageNumber>prevStep) gestionePratica();		
	enableLblSteps(pageNumber);
	// Se vado in avanti disabilito continua, se torno indietro lo abilito	
	if(pageNumber>prevStep)		
		dijit.byId("next").setDisabled(true);	
	else
		dijit.byId("next").setDisabled(false);		
}

function enableLblSteps(StepNumber){
	for(i=1;i<6; i++) {
		if ('step'+i == StepNumber){
			var objLabel = document.getElementById('lbl_'+StepNumber);
			objLabel.style.fontWeight = 'bold';
			objLabel.style.fontSize = '12px';
			objLabel.style.color='#6C8AC9';
			highlight(objLabel,'#000000',4);
		}else{
			document.getElementById('lbl_step'+i).style.fontWeight = 'normal';
			document.getElementById('lbl_step'+i).style.fontSize = '9px';
			document.getElementById('lbl_step'+i).style.color='#000000';
		}	
	} 
}
function highlight(theNode,endcolor,times) {
	var sColor = theNode.style.color;
	if (typeof(times) == 'undefined') 
		times=1;
	
	if (times > 0) {
		var anim = dojo.animateProperty({
			node: theNode,
			duration: 800,
			properties: {
				color: { start:endcolor, end: sColor }
			},
			onEnd: function(){ theNode.style.color = sColor; highlight(theNode,endcolor,times-1)}
		});	
		anim.play();
	}	
}
function getOrderDate(idPropCode) {
	objEndDate = dijit.byId(idPropCode+"_dataIn");
	//valore = objEndDate.getValue().getFullYear().toString() + (objEndDate.getValue().getMonth()+1).toString() + objEndDate.getValue().getDate().toString();
	valore = dateFormat(objEndDate.getValue(), 'yyyymmdd');
	return 	valore;	
}
function getDuration(idPropCode) {
		objStartDate = dijit.byId(idPropCode+"_dataIn");
		objEndDate = dijit.byId(idPropCode+"_dataOut");
		
		var gg = dojo.date.difference(objStartDate.getValue(), objEndDate.getValue(), 'day');

		return gg;
	}
function getStartDate(idPropCode) {
		objStartDate = dijit.byId(idPropCode+"_dataIn");
	
		strStartDate = dateFormat(objStartDate.getValue(), 'dd/MM/yyyy');
		return 	strStartDate;	
	}	
function getEndDate(idPropCode) {
		objEndDate = dijit.byId(idPropCode+"_dataOut");
		strEndDate = dateFormat(objEndDate.getValue(), 'dd/MM/yyyy');

		return 	strEndDate;	
}	

function setProdGG(idPropCode, tipo, fixedGG) {
	if(fixedGG != undefined) {
		objStartDate 	= dijit.byId(idPropCode+"_dataIn");
		objEndDate 		=  dijit.byId(idPropCode+"_dataOut");		
		objEndDate.value(dojo.date.add(objStartDate.getValue(), 'day', parseInt(fixedGG-1)));	
		objGG = document.getElementById(idPropCode+"_gg");
		if(fixedGG == 1)
				objGG.innerHTML = fixedGG + " giorno";							
			else
				objGG.innerHTML = fixedGG + " giorni";	
		var gg = parseInt(fixedGG-1);	
	} else {				
		objGG = document.getElementById(idPropCode+"_gg");
		objbtnAdd = document.getElementById(idPropCode+"_btnAdd");
		objbtnAdd.disabled = false;
		var gg = getDuration(idPropCode);
		if( gg<1){
			alert('La data di Out deve essere maggiore della data di In');
			objGG.innerHTML ="";
			objbtnAdd.disabled = true;
		} else {					
			if(gg == 1){
				if(tipo == 'HOTEL') 
					suffix = " notte";
				else 
				 	suffix = " gg";
			}					
			else {
				if(tipo == 'HOTEL') 
					suffix = " notti";
				else 
				 	suffix = " gg";						
			}
			if(tipo != 'HOTEL')
				objGG.innerHTML = parseInt(gg+1) + suffix;
			else					
				objGG.innerHTML = gg + suffix;
		}	
	}		
	colorDays(idPropCode, gg);		
	objGG.style.background= '';
	document.getElementById(idPropCode+'_gg').focus();
}	
function colorDays(idPropCode, numGG) {
	objStartDate = dijit.byId(idPropCode+"_dataIn");
	arrayDate = getElementsByAttribute('idData',idPropCode,'div');
	for (var j=0; j < arrayDate.length; j++){			
		arrayDate[j].style.background = '#F3F3F6';
	}			
	
	for (var i=0; i <= numGG; i++){			
		//divDataId = idPropCode+"_"+dojo.date.strftime(dojo.date.add(objStartDate.getDate(), dojo.date.dateParts.DAY, i) ,"%Y%m%d");					
		divDataId = idPropCode+"_"+ dateFormat(dojo.date.add(objStartDate.getValue(), 'day',i) ,"yyyyMMdd");					
		objDivData = document.getElementById(divDataId);
		if(objDivData)
			objDivData.style.background = 'silver';			
	}	
}
function changePackageDate(dataIn, dataOut,targetPath, pkProdto) {
	/*targetPath = targetPath.replace('@datapar@', dataIn);
	targetPath = targetPath.replace('@datafine@', dataOut);*/
	targetPath = targetPath +"&dataIn="+dataIn+"&dataOut="+dataOut;
	viewWApane('divCambioDate','/booking/cambioDatePackage.cfm?'+targetPath+'&filteredPkProdTo='+pkProdto);
	dijit.byId('dlgCambioData').show();
}	

function openChangeProdDate(dataIn, dataOut, idTab, tipo) {
	viewWApane('divCambioDate','/booking/cambioDate.cfm?dataIn='+dataIn + '&dataOut='+dataOut+'&idTab='+idTab+ '&Tipo='+tipo);
	dijit.byId('dlgCambioData').show();
}
function modifyProdDate(idtab, tipo, dataStart){
	if(tipo == 'PACKAGE' || tipo == 'MAGDAN'){
		if(typeof(dataStart) == 'undefined'){
			strStartDate = dateFormat(dijit.byId('startDate_Change').getValue(), 'yyyy-MM-dd');
			strEndDate = dateFormat(dijit.byId('endDate_Change').getValue(), 'yyyy-MM-dd');
		} else {
			strStartDate = dataStart;
			strEndDate = strStartDate;
		}
		targetPath	= document.getElementById('pathProds').value;
		targetPath = targetPath.replace("@dataBegin@",strStartDate);
		targetPath = targetPath.replace("@dataEnd@",strEndDate);
		step2FromTappe(targetPath);
	} else {
		if(typeof(dataStart) == 'undefined'){
			strStartDate = dateFormat(dijit.byId('startDate_Change').getValue(), 'MM/dd/yyyy');
			strEndDate = dateFormat(dijit.byId('endDate_Change').getValue(), 'MM/dd/yyyy');
		} else {
			strStartDate = dataStart;
			strEndDate = strStartDate;
		}
		targetPath	= document.getElementById('pathProds_'+tipo).value;
		targetPath = targetPath.replace(/@dataBegin@/g,strStartDate);
		targetPath = targetPath.replace(/@dataEnd@/g,strEndDate);
		viewWApane(idtab, targetPath);		
		}
	chiudiCambioDate();			
}	
function chiudiCambioDate(){
	dijit.byId('dlgCambioData').hide();
}
function step2FromTappe(address) {
	var stkPrenotazione = dijit.byId("myStackContainer");	
	viewWApane('step2',address);		
	paneStep2 = dijit.byId("step2");
	stkPrenotazione.selectChild(paneStep2);		
}			
function checkEndDateChange(){
	objStartDate = dijit.byId("startDate_Change");
	objEndDate 	= dijit.byId("endDate_Change");	
	objBtnModify = dijit.byId('btnModifyDate');
	if(objEndDate<=objStartDate){
		objBtnModify.setDisabled(true);
		alert("La data di Out non puo' essere uguale o minore a quella di In");
	}else{	
		objBtnModify.setDisabled(false);
	}
}		
function showHelpTlp(objImg,toLeft,over,pixover) {	
	if (typeof(toLeft) == 'undefined')
		toLeft = true;
	if (typeof(over) == 'undefined')
		over = false;	
	if (typeof(pixover) == 'undefined')
		pixover = 0;	
		
	var imgElem = objImg;
	var offsetLeft= -3;
	var offsetTop= +15;
	for (var tmpElem = imgElem;tmpElem!=null;tmpElem=tmpElem.offsetParent) {
		offsetLeft+=tmpElem.offsetLeft;
		offsetTop+=tmpElem.offsetTop;
	}	
	var sLink = "/booking/main_adv/incentivazioni.cfm";
	var oDivHelp = document.getElementById('helpAnimDiv');
	
	var posx = offsetLeft;
	var posy = offsetTop;
	
	if (! toLeft) 
		posx = offsetLeft - 220;		
	if (over)
		posy = offsetTop - pixover;
	
    oDivHelp.style.display = '';     
	oDivHelp = dijit.byId('helpAnimDiv')	
	oDivHelp.setHref(sLink);
	
	var fadeIn = dojo.fadeIn({node: "helpAnimDiv",duration: 1000});
	var wipeIn = dojo.fx.wipeIn({node: "helpAnimDiv",duration: 1000});
	var slideLeft = dojo.fx.slideTo({node: "helpAnimDiv",duration: 1000, left: posx, top:posy});
	var animIn = dojo.fx.combine([fadeIn, wipeIn, slideLeft]);
	var currentAnimation = animIn;
	currentAnimation.play();	
}			

function hideHelp() {
	var fadeOut = dojo.fadeOut({node: "helpAnimDiv",duration: 1000});
    var wipeOut = dojo.fx.wipeOut({node: "helpAnimDiv",duration: 1000});
    var slideRight = dojo.fx.slideTo({node: "helpAnimDiv",duration: 1000, left: (screen.width/2), top: 80});
    var animOut = dojo.fx.combine([fadeOut, wipeOut, slideRight]);
  
	var currentAnimation = animOut;	
	currentAnimation.play();
}

function doBooking(address) {
	var waDate = new Date;
	var customStyle='alwaysRaised=yes'; 
	var bckresolution = 'high';
	if (screen.width < 1024) { 
		customStyle +=',scrollbars=yes';
		bckresolution = 'low';
	}
	customStyle += ',centerscreen';
	var separator = "?";
	if (address.indexOf("?") != -1)
		separator = "&";
		
	return opt.core.openWin(address + separator + 'waDate=' + waDate + '&res='+bckresolution, 'bookpage', 1020, 700, customStyle);		
}
