$(document).ready(function() {

					/* Get children age */
					$('#nChildren').change(function() {
						var existingChildInput = $('.inputChild').length;
						var iVal = $(this).val();

						$('#childBlock').empty();

						if (iVal > 0){
							var titolo = "Et&agrave; bambini:<br /><br />";
							
							$('#childBlock').append(titolo);
							var x = 14; // eta massima che hanno
										// messo nella struttura
							
							for (j = 1; j <= x; j++){
								var option = option + '<option value="' + j + '">' + j + '</option>';
							}

							for (i = 0; i < iVal; i++){
								var childBlock = '<div class="inputChild"><label for="age_' + i + '">Et&agrave;: </label>';
								var select = '<select name="age_' + i + '" id="age_' + i + '" style="width: 50px;">';
								var select = select + option + '</select>';
												
												// var childBlock += '<input
												// type="text" name="age_' + i +
												// '" id="age_' + i + '"
												// style="width: 50px;" />':
								var childBlock = childBlock + select + '</div>';

								$('#childBlock').append(childBlock);
							}

							$('#childBlock').show('blind');
							$('#age').val(1);
						} else {
							$('#childBlock').hide('blind');
							$('#age').val(0);
						}

						return false;
					});
					/* Get children age */


					/* Suggest start */
					// $("input.autocomplete").autocomplete( emails, {
					$("input.autocomplete").autocomplete(
							baseUrl + "/ricerca/getcitylist/", {
								minChars : 0,
								width : 310,
								autoFill : false,
								formatItem : function(row, i, max) {
									return row[0];
								},
								formatResult : function(row) {
									return row[0].replace(/(<.+?>)/gi, '');
								}
							});

					$("input.autocompleteHotel").autocomplete(
							baseUrl + "/ricerca/gethotellist/", {
								minChars : 0,
								width : 310,
								autoFill : false,
								formatItem : function(row, i, max) {
									return row[0];
								},
								formatResult : function(row) {
									return row[0].replace(/(<.+?>)/gi, '');
								}
							});

					/** ***** NAVE ***** */
					$('#nave-departureCity').result(
							function(event, data, formatted) {
								$('#boat-departureCity').val(data[1]);
							});

					$('#nave-returnCity').result(
							function(event, data, formatted) {
								$('#boat-returnCity').val(data[1]);
							});

					/** ***** VOLO ***** */
					$('#volo-departureCity').result(
							function(event, data, formatted) {
								$('#flight-departureCity').val(data[1]);
							});

					$('#volo-returnCity').result(
							function(event, data, formatted) {
								$('#flight-returnCity').val(data[1]);
							});

					/** ***** AUTO ***** */
					$('#auto-departureCity').result(
							function(event, data, formatted) {
								$('#car-departureCity').val(data[1]);
							});

					/*
					 * $('#auto-returnCity').result(function(event, data,
					 * formatted){ $('#car-returnCity').val(data[1]); });
					 */

					/** ***** HOTEL ***** */

					/** ***** PACCHETTO ***** */
					$('#pck-destination').result(
							function(event, data, formatted) {
								$('#package-destination').val(data[1]);
							});

					/* Suggest end */
					function setDatePlusOne(dateText) {
						var updatedDate;
						var aElements = dateText.split("/");
						var aNumberOfDays = {
							"01" : 31,
							"02" : 28,
							"03" : 31,
							"04" : 30,
							"05" : 31,
							"06" : 30,
							"07" : 31,
							"08" : 31,
							"09" : 30,
							"10" : 31,
							"11" : 30,
							"12" : 31
						}

						if (isLeapYear) {
							aNumberOfDays['02'] = 29;
						}

						if (parseInt(aElements[0]) == parseInt(aNumberOfDays[aElements[1]])) {
							aElements[0] = 1;
							aElements[1] = parseInt(aElements[1], 10) + 1;
						} else {
							aElements[0] = parseInt(aElements[0].toString().replace(/^0/g, '')) + 1;
						}
						
						updatedDate = aElements[0] + '/' + aElements[1] + '/' + aElements[2];
						return updatedDate;
					}

					$.datepicker.setDefaults($.extend( {
						showMonthAfterYear : false
					}, $.datepicker.regional['']));
					$("#startDate").datepicker($.datepicker.regional['it']);
					$('#startDate').datepicker(
							'option',
							$.extend( {
								showMonthAfterYear : false,
								minDate : new Date(),
								onSelect : function(dateText, inst) {
									$('#endDate').attr('value',
											setDatePlusOne(dateText));
								}
							}, $.datepicker.regional['it']));
					$("#startDate_2").datepicker($.datepicker.regional['it']);
					$('#startDate_2').datepicker(
							'option',
							$.extend( {
								showMonthAfterYear : false,
								minDate : new Date(),
								onSelect : function(dateText, inst) {
									$('#endDate_2').attr('value',
											setDatePlusOne(dateText));
								}
							}, $.datepicker.regional['it']));

					$("#endDate").datepicker($.datepicker.regional['it']);
					$('#endDate').datepicker('option', $.extend( {
						showMonthAfterYear : false,
						minDate : new Date()
					}, $.datepicker.regional['it']));

					$("#startDate-volo")
							.datepicker($.datepicker.regional['it']);
					$('#startDate-volo').datepicker(
							'option',
							$.extend( {
								showMonthAfterYear : false,
								minDate : new Date(),
								onSelect : function(dateText, inst) {
									$('#endDate-volo').attr('value',
											setDatePlusOne(dateText));
								}
							}, $.datepicker.regional['it']));

					$("#endDate-volo").datepicker($.datepicker.regional['it']);
					$('#endDate-volo').datepicker('option', $.extend( {
						showMonthAfterYear : false,
						minDate : new Date()
					}, $.datepicker.regional['it']));

					$("#pickUpDate").datepicker($.datepicker.regional['it']);
					$('#pickUpDate').datepicker(
							'option',
							$.extend( {
								showMonthAfterYear : false,
								minDate : new Date(),
								onSelect : function(dateText, inst) {
									$('#dropOffDate').attr('value',
											setDatePlusOne(dateText));
								}
							}, $.datepicker.regional['it']));

					$("#dropOffDate").datepicker($.datepicker.regional['it']);
					$('#dropOffDate').datepicker('option', $.extend( {
						showMonthAfterYear : false,
						minDate : new Date()
					}, $.datepicker.regional['it']));

					$("#checkInDate").datepicker($.datepicker.regional['it']);
					$('#checkInDate').datepicker(
							'option',
							$.extend( {
								showMonthAfterYear : false,
								minDate : new Date(),
								onSelect : function(dateText, inst) {
									$('#checkOutDate').attr('value',
											setDatePlusOne(dateText));
								}
							}, $.datepicker.regional['it']));

					$("#checkOutDate").datepicker($.datepicker.regional['it']);
					$('#checkOutDate').datepicker('option', $.extend( {
						showMonthAfterYear : false,
						minDate : new Date()
					}, $.datepicker.regional['it']));

					$("#startDate-pack")
							.datepicker($.datepicker.regional['it']);
					$('#startDate-pack').datepicker(
							'option',
							$.extend( {
								showMonthAfterYear : false,
								minDate : new Date(),
								onSelect : function(dateText, inst) {
									$('#endDate-pack').attr('value',
											setDatePlusOne(dateText));
								}
							}, $.datepicker.regional['it']));

					$("#endDate-pack").datepicker($.datepicker.regional['it']);
					$('#endDate-pack').datepicker('option', $.extend( {
						showMonthAfterYear : false,
						minDate : new Date()
					}, $.datepicker.regional['it']));

					/* Filtra risultati Sidebar */
					$('#filters li h3').bind('click', function() {
						var div_content = $(this).next('.content');

						div_content.toggleClass('closed');
						$(this).toggleClass('close');

						return false;
					});
					/* Filtra risultati Sidebar */

					/* Form di ricerca Sidebar */
					$('#form-container').tabs( {
						cache : false
					});
					
					iTabSelected = parseInt(iTab);
					$('#form-container').tabs('select', iTabSelected);
					
					/* Form di ricerca Sidebar */

					/* Date form di ricerca laterale */
					$.datepicker.setDefaults($.extend( {
						showMonthAfterYear : false
					}, $.datepicker.regional['']));
					$("#startDate").datepicker($.datepicker.regional['it']);
					$('#startDate').datepicker('option', $.extend( {
						showMonthAfterYear : false,
						minDate : new Date()
					}, $.datepicker.regional['it']));

					$("#endDate").datepicker($.datepicker.regional['it']);
					$('#endDate').datepicker('option', $.extend( {
						showMonthAfterYear : false,
						minDate : new Date(),
						maxDate : '+3M'
					}, $.datepicker.regional['it']));

					/* validazione del form hotel */

					($('#form2').submit(function() {

						/*
						 * if ($('input[name=hotelName]').val() == "") {
						 * alert("Inserire il nome dell'hotel");
						 * //$('input[name=hotelName]').css("background-color","#FE9900");
						 * $('input[name=hotelName]').focus(); return false; }
						 */
					/*	if (subdomain == 'www') {
							if ($('input[name=destination]').val() == "") {
								alert("Inserire la destinazione");
								// $('input[name=destination]').css("background-color","#FE9900");
							$('input[name=destination]').focus();
							return false;
						}
					}
*/
					if ($('input[name=checkInDate]').val() == "") {
						alert("Inserire la data di check in");
						// $('input[name=checkInDate]').css("background-color","#FE9900");
						$('input[name=checkInDate]').focus();
						return false;
					}
					if ($('input[name=checkOutDate]').val() == "") {
						alert("Inserire la data di check out");
						// $('input[name=checkOutDate]').css("background-color","#FE9900");
						$('input[name=checkOutDate]').focus();
						return false;
					}

					if ($('#nChildren').val() > 0) {
						for (i = 0; i < $('#nChildren').val(); i++) {
							if ($('#age_' + i).val() == "") {
								alert("Inserire l'\eta\' del bambino");
								$('#age_' + i).focus();
								return false;
								break;
							}
						}
					}
					return true;
				})	);

					/*
					 * Riepilogo acquisto: aggiornamento prezzo supplementi
					 */
					var initPrice = $('.pricedetails var').text();
					var initAddonPrice = $('.pricedetails #addonPrice var').text();
					initPrice = parseFloat(initPrice.replace('.', '').replace(',', '.'));
					initAddonPrice = parseFloat(initAddonPrice.replace('.', '').replace(',', '.'));
					
					//var oldPrice = $(this).parents('.supplementi').find('._7 var').text();
					//oldPrice = parseFloat( oldPrice.replace(',', '.') );
					
					$('.supplementi ._2 input[type=checkbox]').each(function() {
						$(this).click(function() {
							var totalPrice = $('.pricedetails #totalPrice var').text();
							totalPrice = parseFloat(totalPrice.replace('.', '').replace(',', '.'));
							
							var singlePrice = $('.pricedetails #price var').text();
							singlePrice = parseFloat(singlePrice.replace('.', '').replace(',', '.'));

							var addonPrice = $(this).parents('.supplementi').find('._7 var').text();
							addonPrice = parseFloat(addonPrice.replace('.', '').replace(',', '.'));
							
							var importoDovuto = $('.pricedetails #importoDovuto var').text();
							importoDovuto = parseFloat(importoDovuto.replace('.', '').replace(',', '.'));
							
							var lastDovuto = $('.pricedetails #importoDovuto var').text();
							lastDovuto = parseFloat(lastDovuto.replace('.', '').replace(',', '.'));

							if (parseInt($(this).parents('.supplementi').find('.hiddenInput var').text()) == 1){
								$(this).parents('.supplementi').find('#number_adult_guests').attr('disabled', '');
								$(this).parents('.supplementi').find('#number_child_guests').attr('disabled', '');
								
								$(this).parents('.supplementi').find('.hiddenInput var').text(0);

								var initAddonPrice2 = $('.pricedetails #addonPrice var').text();
								initAddonPrice2 = parseFloat(initAddonPrice2.replace('.', '').replace(',', '.'));
								
								var initCommPrice = $('.pricedetails input#splComm').val();
								var totalNoCommPrice = $('.pricedetails input#splNoComm').val();
								
								//initCommPrice = parseFloat(initCommPrice.replace(',', '.'));
								var totalAddonPrice = parseFloat(eval(initAddonPrice2 - addonPrice));
								
								initCommPrice = totalAddonPrice;
								initCommPrice = parseFloat(eval(initCommPrice - totalNoCommPrice));
								
								var tPrice = parseFloat(eval(totalPrice - addonPrice));
								
								var percent = 0;
								
								var importoDovuto = 0;
								var restToPay = 0;
								
								if( $(this).parents('.supplementi').find('input#commissionabile').val() == 0 )
								{
									totalNoCommPrice = eval(parseFloat(totalNoCommPrice) - addonPrice);
								}
								
								var splComm = 0;
								/*
								 * dobbiamo gestire qui il fatto della supplemento commisionabile
								 */
								
									var newSinglePrice = $('.pricedetails #price var').text();
									newSinglePrice = parseFloat(newSinglePrice.replace('.', '').replace(',', '.'));
								
								if( $(this).parents('.supplementi').find('input#commissionabile').val() == 1 )
								{
									splComm = parseFloat(eval(totalAddonPrice - totalNoCommPrice));
									$('input#splComm').val( splComm );
									newSinglePrice = parseFloat(eval(singlePrice + splComm));
								}
								else
								{
									$('input#splNoComm').val(parseFloat(totalNoCommPrice));
									newSinglePrice = parseFloat(eval(newSinglePrice + parseFloat(eval(totalAddonPrice - totalNoCommPrice))));
								}
								
								if( $('.pricedetails #importoDovuto input#paymentType').val() == 4 || $('.pricedetails #importoDovuto input#paymentType').val() == 2 )
								{
									percent = parseInt($('.pricedetails #importoDovuto input#ratePercent').val());
									importoDovuto = parseFloat(newSinglePrice * percent / 100);
									restToPay = parseFloat(tPrice - importoDovuto);
									
									restToPay = restToPay.toFixed(2).toString().replace('.', ',');
									$('.pricedetails #restToPay var').text(restToPay);
									$('.pricedetails #restToPay input#restante').val(restToPay.replace('.', '').replace(',', '.'));
								}else{
									importoDovuto = tPrice;
								}
								
								
								
								
								importoDovuto = importoDovuto.toFixed(2).toString().replace('.', ',');
								tPrice = tPrice.toFixed(2).toString().replace('.', ',');
								
								totalAddonPrice = totalAddonPrice.toFixed(2).toString().replace('.', ',');
								
								$('.pricedetails #totalPrice var').text(tPrice);
								$('.pricedetails #formTotalPrice').val(tPrice.replace('.', '').replace(',', '.'));
								$('.pricedetails #addonPrice var').text(totalAddonPrice);
								$('.pricedetails #totAddonPrice').val(totalAddonPrice);
								
								$('.pricedetails #importoDovuto var').text(importoDovuto);
								$('.pricedetails #importoDovuto input#importoDovuto').val(importoDovuto.replace('.', '').replace(',', '.'));

								$('.pricedetails').effect('highlight', {}, 1000);
								
								// initAddonPrice
								// =
								// totalAddonPrice;
								} else if (parseInt($(this).parents('.supplementi').find('.hiddenInput var').text()) == 0) {
									$(this).parents('.supplementi').find('#number_adult_guests').attr('disabled', 'disabled');
									$(this).parents('.supplementi').find('#number_child_guests').attr('disabled', 'disabled');
									
									var initAddonPrice2 = $('.pricedetails #addonPrice var').text();
									initAddonPrice2 = parseFloat(initAddonPrice2.replace('.', '').replace(',', '.'));
									
									var initCommPrice = parseFloat($('.pricedetails input#splComm').val());
									var totalNoCommPrice = parseFloat($('.pricedetails input#splNoComm').val());

									//initCommPrice = parseFloat(initCommPrice.replace(',', '.'));
									var totalAddonPrice = parseFloat(eval(addonPrice + initAddonPrice2));
									
									initCommPrice = totalAddonPrice;
									initCommPrice = parseFloat(eval(initCommPrice - totalNoCommPrice));
									
									$('.pricedetails #addonPrice var').text(totalAddonPrice.toFixed(2).toString().replace('.', ',')).effect('highlight');
									$('.pricedetails #totAddonPrice').val(totalAddonPrice);

									if( $(this).parents('.supplementi').find('input#commissionabile').val() == 0 )
									{
										totalNoCommPrice = eval(parseFloat(totalNoCommPrice) + addonPrice);
									}
									
									/*
									 * dobbiamo gestire qui il fatto della supplemento commisionabile
									 */
									var splComm = 0;
									
									var tPrice = parseFloat(eval(addonPrice + totalPrice));
									var percent = 0;
									var importoDovuto = 0;
									var restToPay = 0;
									
									var newSinglePrice = $('.pricedetails #price var').text();
									newSinglePrice = parseFloat(newSinglePrice.replace('.', '').replace(',', '.'));
									
									if( $(this).parents('.supplementi').find('input#commissionabile').val() == 1 )
									{
										splComm = parseFloat(eval(totalAddonPrice - totalNoCommPrice));
										$('input#splComm').val( splComm );
										newSinglePrice = parseFloat(eval(singlePrice + splComm));
									}
									else
									{
										$('input#splNoComm').val(parseFloat(totalNoCommPrice));
										newSinglePrice = parseFloat(eval(newSinglePrice + parseFloat(eval(totalAddonPrice - totalNoCommPrice))));
									}

									if( $('.pricedetails #importoDovuto input#paymentType').val() == 4 || $('.pricedetails #importoDovuto input#paymentType').val() == 2 )
									{
										percent = parseInt($('.pricedetails #importoDovuto input#ratePercent').val());
										importoDovuto = parseFloat(newSinglePrice * percent / 100);
										restToPay = parseFloat(tPrice - importoDovuto);

										restToPay = restToPay.toFixed(2).toString().replace('.', ',');
										$('.pricedetails #restToPay var').text(restToPay);
										$('.pricedetails #restToPay input#restante').val(restToPay.replace('.', '').replace(',', '.'));
									}else{
										importoDovuto = tPrice;
									}
									
									totalAddonPrice = totalAddonPrice.toFixed(2).toString().replace('.', ',');
									
									
									importoDovuto = importoDovuto.toFixed(2).toString().replace('.', ',');
									tPrice = tPrice.toFixed(2).toString().replace('.', ',');
									
									$('.pricedetails #totalPrice var').text(tPrice);
									$('.pricedetails #formTotalPrice').val(tPrice.replace('.', '').replace(',', '.'));
									$('.pricedetails #importoDovuto var').text(importoDovuto);
									$('.pricedetails #importoDovuto input#importoDovuto').val(importoDovuto.replace('.', '').replace(',', '.'));
									
									$('.pricedetails').effect('highlight', {}, 1000);
									
									$(this).parents('.supplementi').find('.hiddenInput var').text(1);
									
									initAddonPrice = totalAddonPrice;
								}

							});
					});

					$('.supplementi ._1 #number_adult_guests').each(function() {
										$(this).change(function() {
										
											
											var oldPrice = $(this).parents('.supplementi').find('._7 var').text();
											oldPrice = parseFloat( oldPrice.replace('.', '').replace(',', '.') );
											
											var iVal = parseInt( $(this).val() );
											
											
											
											var nNotti = parseInt( $(this).parents('.supplementi').find('._4 #nNotti').text() );
		
											var nPersone = parseInt( $(this).parents('.supplementi').find('._4 #nPersone').text() );
											
											var totalPrice = $(this).parents('.supplementi').find(' ._7 var');
											totalPriceNumber = parseFloat( totalPrice.text().replace('.', '').replace(',', '.') );
	
											var iAddonPrice = $(this).parents('.supplementi').find('._5 var').text();
											iAddonPrice = parseFloat( iAddonPrice.replace('.', '').replace(',', '.') );
	
											var iNumChildren = parseInt( $(this).parents('.supplementi').find('._1 #number_child_guests').val() );

											var percentDiscount = parseInt( $(this).parents('.supplementi').find('._1 #childDiscount').text() );
											
											if($(this).parents('.supplementi').find('input#riduzioneBambino').val() == 0) {
												percentDiscount = 0;
											}
											var isAvailable = parseInt( $(this).parents('.supplementi').find('._1 #isAvailable').text() );

											if( iNumChildren ){
												var iNewVal = parseInt( eval(iVal + iNumChildren) );
											} else {
												var iNewVal = parseInt(iVal);
											}

											if (iNumChildren) {
												if (isAvailable) {
													var priceAdults = parseFloat( eval(iVal * iAddonPrice) );
													var priceChildr = parseFloat( eval(iAddonPrice - ((iAddonPrice * percentDiscount) / 100)) * iNumChildren );
													var finalPrice = parseFloat( eval(priceAdults + priceChildr) );
												} else {
													var finalPrice = parseFloat( eval(iNewVal * iAddonPrice) );
												}
											} else {
												var finalPrice = parseFloat( eval(iNewVal * iAddonPrice) );
											}
											
											var newValue = parseFloat( eval(finalPrice * nNotti) );
											
											$(this).parents('.supplementi').find('._4 #nPersone').text(iNewVal);
	
											$(this).parents('.supplementi').find('._4').effect('highlight', {}, 500).effect('highlight', {}, 500);
											
											newValue = newValue.toFixed(2).toString().replace('.', ',');
											totalPrice.text(newValue);
											
											$(this).parents('.supplementi').find(' ._7 var').effect('highlight', {}, 500).effect('highlight', {}, 500);


											/* SELECT numero persone che hanno selezionato il supplemento */
											$(this).next().val(iNewVal);
											$(this).parents('._1').find('input#number_adult_guests_hidden').val(iVal);
											/* SELECT numero persone che hanno selezionato il supplemento */
											
											
											/* Aggiorna prezzi */
											var totalRoomPrice = $('.pricedetails #totalPrice var').text().replace('.', '').replace(',', '.');
											totalRoomPrice = parseFloat(totalRoomPrice);
											
											if( parseInt($(this).parents('.supplementi').find('.hiddenInput var').text()) == 1 ){
												
												if (iNumChildren){
													var iNewVal = parseFloat( eval(iVal + iNumChildren) );
												} else {
													var iNewVal = parseFloat(iVal);
												}

												if (iNumChildren){
													if (isAvailable){
														var priceAdults = parseFloat(eval(iVal * iAddonPrice));
														var priceChildr = parseFloat(eval(iAddonPrice - ((iAddonPrice * percentDiscount) / 100)) * iNumChildren);
														var finalPrice = parseFloat(eval(priceAdults + priceChildr));
													} else {
														var finalPrice = parseFloat(eval(iNewVal * iAddonPrice));
													}
												} else {
													var finalPrice = parseFloat(eval(iNewVal * iAddonPrice));
												}

												var newValue = parseFloat(eval(finalPrice * nNotti));
										
												var newDiff = parseFloat(eval(oldPrice - newValue));

												var tPrice = parseFloat(eval(totalRoomPrice - newDiff));
												
											
												var percent = 0;
												var importoDovuto = 0;
												var restToPay = 0;
												
												if( $('.pricedetails #importoDovuto input#paymentType').val() == 4 || $('.pricedetails #importoDovuto input#paymentType').val() == 2 )
												{
													percent = parseInt($('.pricedetails #importoDovuto input#ratePercent').val());
													importoDovuto = parseFloat(tPrice * percent / 100);
													restToPay = parseFloat(tPrice - importoDovuto);

													restToPay = restToPay.toFixed(2).toString().replace('.', ',');
													$('.pricedetails #restToPay var').text(restToPay);
													$('.pricedetails #restToPay input#restante').val(restToPay.replace('.', '').replace(',', '.'));
												}else{
													importoDovuto = tPrice;
												}
											
												importoDovuto = importoDovuto.toFixed(2).toString().replace('.', ',');
											
												tPrice = tPrice.toFixed(2).toString().replace('.', ',');
												
												var oldNewValue = $('.pricedetails #addonPrice var').text();
												oldNewValue = parseFloat(oldNewValue.replace('.', '').replace(',', '.'));
												var newAddonP = oldNewValue - newDiff;
												
												var initCommPrice = parseFloat($('.pricedetails input#splComm').val());
												var totalNoCommPrice = parseFloat($('.pricedetails input#splNoComm').val());

												//initCommPrice = parseFloat(initCommPrice.replace(',', '.'));

												initCommPrice = parseFloat(eval(newAddonP - initCommPrice));
												
												/*
												 * dobbiamo gestire qui il fatto della supplemento commisionabile
												 */
												if( $(this).parents('.supplementi').find('input#commissionabile').val() == 1 )
												{
													$('input#splComm').val( parseFloat(eval(initCommPrice - totalNoCommPrice)) );
												}
												else
												{
													$('input#splNoComm').val(parseFloat(initCommPrice));
												}
												
												newAddonP = newAddonP.toFixed(2).toString().replace('.', ',');

												/*
												 * dobbiamo gestire qui il fatto della supplemento commisionabile
												 */
												if( $(this).parents('.supplementi').find('li._3 input#commissionabile').val() == 1 )
												{
													$('input#splComm').val(newAddonP);
												}
												
												$('.pricedetails #totalPrice var').text(tPrice);
												$('.pricedetails #importoDovuto var').text(importoDovuto);
												$('.pricedetails input#importoDovuto var').text(importoDovuto);
												$('.pricedetails #importoDovuto input#importoDovuto').val(importoDovuto.replace('.', '').replace(',', '.'));
												$('.pricedetails #formTotalPrice').val(tPrice.replace('.', '').replace(',', '.'));
												$('.pricedetails #addonPrice var').text(newAddonP);
												$('.pricedetails #totAddonPrice').val(newAddonP);
												$('.pricedetails').effect('highlight', {}, 1000);
												
											}
										});
									});

					/* Select bambini */
					$('.supplementi ._1 #number_child_guests').each(function() {
							$(this).change(function() {
								var oldPrice = $(this).parents('.supplementi').find('._7 var').text();
								oldPrice = parseFloat(oldPrice.replace(',','.'));

								
								var iVal = parseInt($(this).val());
								var nNotti = parseInt($(this).parents('.supplementi').find('._4 #nNotti').text());
								var nPersone = parseInt($(this).parents('.supplementi').find('._4 #nPersone').text());
								var sTotalPrice = $(this).parents('.supplementi').find(' ._7 var');
								totalPrice = parseFloat(sTotalPrice.text().replace('.', '').replace(',', '.'));
								
								var iAddonPrice = $(this).parents('.supplementi').find('._5 var').text();
								iAddonPrice = parseFloat(iAddonPrice.replace(',', '.'));
										
								var iNumChildren = parseInt($(this).parents('.supplementi').find('._1 #number_adult_guests').val());
								var percentDiscount = parseInt($(this).parents('.supplementi').find('._1 #childDiscount').text());
								var isAvailable = parseInt($(this).parents('.supplementi').find('._1 #isAvailable').text());

								if($(this).parents('.supplementi').find('input#riduzioneBambino').val() == 0) {
									percentDiscount = 0;
								}
								
								
								$(this).parents('._1').find('input#number_child_guests_hidden').val(iVal);
								
								if (iNumChildren) {
									var iNewVal = parseFloat(eval(iVal + iNumChildren));
								} else {
									var iNewVal = parseFloat(iVal);
								}

								
								
								
									if (isAvailable) {
										var priceAdults = parseFloat(eval(iNumChildren * iAddonPrice));
										var priceChildr = parseFloat(eval(iAddonPrice - ((iAddonPrice * percentDiscount) / 100)) * iVal);
										var finalPrice = parseFloat(eval(priceAdults + priceChildr));
									} else {
										var finalPrice = parseFloat(eval(iNewVal * iAddonPrice));
									}

								var newValue = parseFloat(eval(finalPrice * nNotti));

								
								
								$(this).parents('.supplementi').find('._4 #nPersone').text(iNewVal);
								$(this).parents('.supplementi').find('._4').effect('highlight', {},500).effect('highlight', {}, 500);

								sTotalPrice.text(newValue.toFixed(2).toString().replace('.', ','));
								sTotalPrice.effect('highlight',{},500).effect('highlight',{}, 500);

								/* Aggiorna prezzi */
								var totalRoomPrice = $('.pricedetails #totalPrice var').text();
								totalRoomPrice = parseFloat(totalRoomPrice.replace('.', '').replace(',', '.'));

								if (parseInt($(this).parents('.supplementi').find('.hiddenInput var').text()) == 1) {
									if (iNumChildren) {
										var iNewVal = parseFloat(eval(iVal + iNumChildren));
									} else {
										var iNewVal = parseFloat(iVal);
									}

								if (iNumChildren) {
									if (isAvailable) {
										var priceAdults = parseFloat(eval(iNumChildren * iAddonPrice));
										var priceChildr = parseFloat(eval(iAddonPrice - ((iAddonPrice * percentDiscount) / 100)) * iVal);
										var finalPrice = parseFloat(eval(priceAdults + priceChildr));
									} else {
										var finalPrice = parseFloat(eval(iNewVal * iAddonPrice));
									}
								} else {
									var finalPrice = parseFloat(eval(iNewVal * iAddonPrice));
								}

								var newValue = parseFloat(eval(finalPrice * nNotti));
								var newDiff  = parseFloat(eval(oldPrice - newValue));
								newDiff = newDiff.toFixed(2);
								
								/* ############################ */
								var tPrice   = parseFloat(eval(totalRoomPrice - newDiff));
								
								var percent = 0;
								var importoDovuto = 0;
								var restToPay = 0;

								if( $('.pricedetails #importoDovuto input#paymentType').val() == 4 || $('.pricedetails #importoDovuto input#paymentType').val() == 2 )
								{
									percent = parseInt($('.pricedetails #importoDovuto input#ratePercent').val());
									importoDovuto = parseFloat(tPrice * percent / 100);
									restToPay = parseFloat(tPrice - importoDovuto);

									restToPay = restToPay.toFixed(2).toString().replace('.', ',');
									$('.pricedetails #restToPay var').text(restToPay);
									$('.pricedetails #restToPay input#restante').val(restToPay.replace('.', '').replace(',', '.'));
							
								}else{
									importoDovuto = tPrice;
								}
								
								importoDovuto = importoDovuto.toFixed(2).toString().replace('.', ',');
								
								$('.pricedetails #importoDovuto var').text(importoDovuto);
								$('.pricedetails input#importoDovuto var').text(importoDovuto);
								$('.pricedetails #importoDovuto input#importoDovuto').val(importoDovuto.replace('.', '').replace(',', '.'));
								/* ############################ */
								
								var oldNewValue = $('.pricedetails #addonPrice var').text();
								oldNewValue     = parseFloat(oldNewValue.replace('.', '').replace(',','.'));
								oldNewValue = oldNewValue.toFixed(2);

								$('.pricedetails #totalPrice var').text(tPrice.toFixed(2).toString().replace('.', ','));
								$('.pricedetails #formTotalPrice').val(tPrice);

								var diff = parseFloat(oldNewValue - newDiff);
								
								$('.pricedetails #addonPrice var').text(diff.toFixed(2).toString().replace('.', ','));
								
								
								$('.pricedetails #totAddonPrice').val(diff);
								$('.pricedetails').effect('highlight',{},1000);
								
								
							}
						});
					});

					/* Ricerca stanze, aggiornamento numero stanze */
					/* Ricerca stanze, aggiornamento numero stanze */
					$('.tb_hotel .numStanze')
							.each(
									function() {

										var roomPrice = $(this).parents('.tb_hotel').find('var#finalPrice').text();
										var oldRoomPrice = $(this).parents('.tb_hotel').find('var#finalOldPrice').text();
										
										roomPrice = parseFloat( roomPrice.replace('.', '').replace(',', '.') );
										oldRoomPrice = parseFloat( oldRoomPrice.replace('.', '').replace(',', '.') );
										
										$(this).change(function() {

										var newRoomPrice = parseFloat( roomPrice * parseInt($(this).val()) );
										var newOldRoomPrice = parseFloat( oldRoomPrice * parseInt($(this).val()) );

										if (newRoomPrice < roomPrice) {
											
											var finalPrice = roomPrice - newRoomPrice;
											finalPrice = finalPrice.toFixed(2).toString().replace('.', ',');
											
											$(this).parents('.tb_hotel')
												   .find('var#finalPrice')
												   .text(finalPrice);
												
											var oldFinalPrice = oldRoomPrice - newOldRoomPrice;
											oldFinalPrice = oldFinalPrice.toFixed(2).toString().replace('.', ',');
											
											$(this).parents('.tb_hotel')
												   .find('var#finalOldPrice')
												   .text(oldFinalPrice);

											$(this).parents('.tb_hotel')
													.find('li.finalPrice')
													.effect('highlight', {}, 500)
													.effect('highlight', {}, 500);

											$(this).parents('.tb_hotel')
													.find('form input[name=r]')
													.val($(this).val());
											finalPrice = finalPrice.toString().replace(',', '.');
											$(this).parents('.tb_hotel')
													.find('form input[name=totalPrice]')
													.val(finalPrice);
											alert(finalPrice);
										} else {
											
											newRoomPrice = newRoomPrice.toFixed(2).toString().replace('.', ',');
											$(this).parents('.tb_hotel')
													.find('var#finalPrice')
													.text(newRoomPrice);
											
											newOldRoomPrice = newOldRoomPrice.toFixed(2).toString().replace('.', ',');
											$(this).parents('.tb_hotel')
												   .find('var#finalOldPrice')
												   .text(newOldRoomPrice);
											
											$(this).parents('.tb_hotel')
													.find('li.finalPrice')
													.effect('highlight', {}, 500)
													.effect('highlight', {}, 500);

											$(this).parents('.tb_hotel')
													.find('form input[name=r]')
													.val($(this).val());
											
											newRoomPrice = newRoomPrice.toString().replace(',', '.');
											$(this).parents('.tb_hotel')
													.find('form input[name=totalPrice]')
													.val(newRoomPrice);
											
										}
									});
								});

					/* form registrazione dopo riepilogo */
					$('span.detectRegistration').click(function() {
						$('form#registrazione').toggle('blind');
						$('form#login-form').toggle('blind');
						return false;
					});

					$('span#wantFatt').toggle(function() {

						$('#wantFattInt').val(1);
						$('#fatturazione').show('blind');
						$('.fattura span').text('si');
						return false;
					}, function() {

						$('#wantFattInt').val(0);
						$('#fatturazione').hide('blind');
						$('.fattura span').text('no');
						return false;
					});

					/* Velo generale Hotels */
					$('#hotels')
							.click(
									function() {
										$('.altrialloggi-container:visible').hide('blind');
										$('#alloggi').parents('li').removeClass('nav-current');
										
										var needQuery = parseInt($('#needQuery')
												.text());

										$(this).parents('li').toggleClass('nav-current');
										
										$('.hotels-container').toggle('blind');

										if (needQuery) {
											$
													.getJSON(
															baseUrl + '/hotel/index/format/json/',
															{
																's' : subdomainId
															},
															function(data) {
																$('#hotel-res')
																		.empty();
																$
																		.each(
																				data.aHotels,
																				function() {
																					var aHotels = this;
																					var stelle = this.stelle;
																					var hotelList = '';

																					$
																							.each(
																									aHotels.hotels,
																									function() {
																										hotelList += '<li><a href="'
																												+ baseUrl
																												+ '/hotels/'
																												+ this.name
																												+ '/'
																												+ subdomain
																												+ '">'
																												+ this.name
																												+ '</a></li>';
																									});

																					if (aHotels.hotels.length) {
																						$(
																								'#hotel-res')
																								.append(
																										'<ul>'
																												+

																												'<li>'
																												+ '<ul>'
																												+ '<li><div class="stelle stelle-'
																												+ stelle
																												+ '"><img src="'
																												+ baseUrl
																												+ '/styles/'
																												+ moduleName
																												+ '/images/stelle.jpg"  /></div></li>'
																												+ hotelList
																												+ '</ul>'
																												+ '</li>'
																												+

																												'</ul>');
																					}

																				});
																$('#needQuery')
																		.text(0);
															});
											/* End JSON */
										}

									});

					$('.hotels-container .close').click(function() {
						$('.hotels-container').hide('blind');
					});
					/* Velo generale Hotels */

					/* Velo generale Altri Alloggi */
					$('#alloggi')
							.click(
									function() {
										$('.hotels-container:visible').hide('blind');
										$('#hotels').parents('li').removeClass('nav-current');
										
										var needQuery = parseInt($(
												'#needQuery-alloggi').text());

										$(this).parents('li').toggleClass(
												'nav-current');
										$('.altrialloggi-container').toggle('blind');

										if (needQuery) {
											$
													.getJSON(
															baseUrl + '/hotel/alloggi/format/json/',
															{
																's' : subdomainId
															},
															function(data) {
																$(
																		'#alloggi-res')
																		.empty();
																$
																		.each(
																				data.aHotels,
																				function() {
																					var aHotels = this;
																					var category = this.category;
																					var hotelList = '';

																					$
																							.each(
																									aHotels.hotels,
																									function() {
																										hotelList += '<li><a href="'
																												+ baseUrl
																												+ '/hotels/'
																												+ this.name
																												+ '/'
																												+ subdomain
																												+ '">'
																												+ this.name
																												+ '</a></li>';
																									});

																					if (aHotels.hotels.length) {
																						$(
																								'#alloggi-res')
																								.append(
																										'<ul>'
																												+

																												'<li>'
																												+ '<ul>'
																												+ '<li><div class="category">'
																												+ category
																												+ '</div></li>'
																												+ hotelList
																												+ '</ul>'
																												+ '</li>'
																												+

																												'</ul>');
																					}

																				});
																$(
																		'#needQuery-alloggi')
																		.text(0);
															});
											/* End JSON */
										}

									});

					$('.altrialloggi-container .close').click(function() {
						$('.altrialloggi-container').hide('blind');
					});
					/* Velo generale Altri Alloggi */

					$('.maps').click(function() {

						$('.map_google').toggleClass('display-block');

						return false;
					});

					/* Scambio foto dettaglio */
					$('#foto_p li').click(
							function() {
								$('.foto_grande img').attr('src', $(this).find('img').attr('alt'));
								return false;
							});

					$('.close-dettaglio-struttura').click(function() {
						// alert("OK");
							$(this).parents('ul.prima').next().toggle('blind');
							
							$(this).parents('.close').find('div').toggle();
									/*function(){
										
									},
									function(){}
								);*/
							
							return false;
						});

					$('.close-dettaglio-camere').click(function() {
						// alert("OK");
							$('#camere').toggle('blind');
							
							$(this).parents('.close').find('div').toggle();
									/*function(){
										
									},
									function(){}
								);*/
							
							return false;
						});
					/* jScrollPane foto dettaglio hotel */
					$('.scroll_pane').jScrollPane( {
						dragMaxHeight : 40,
						dragMinHeight : 40,
						scrollbarWidth : 22,
						scrollbarMargin : 6
					});

					// Nifty("div#fotoGrande","big");

					//rollhover tasti dettaglio hotel
					$('.aTasti img').hover(function() {
						this.src = this.src.replace("normal/", "rollover/");

					},
					function() {
						this.src = this.src.replace("rollover/", "normal/");

					}
					);
					
/* Tooltip generici */
$('#cc_cvc').tooltip({
	showUrl: false,
	bodyHandler: function(){
		return $('.cvc_tooltip').html();
	}
});

$('#cc_number').tooltip({
	showUrl: false,
	bodyHandler: function(){
		return $('.number_tooltip').html();
	}
});
$('.notePopup').tooltip({
	showUrl: false,
	bodyHandler: function(){
		return $(this).next().html();
	}
});

$("a#single_image").fancybox(); 

$('a.photogallery_btn').click(function(){
	$(this).parents('ul').next().find('a.building').click();
	return false;
});

$('a.building').fancybox();

/* ************  FORM AFFILIAZIONE  ************ */
	$('#theType').change(function(){
		if( $(this).val() == 2 ){
			$('#nstelle').show('blind');
		}else{
			$('#stelle option[value=0]').attr('selected', 'selected');
			$('#nstelle').hide('blind');
		}
		
		return false;
	});
	
	/* Selezione Citta in funzione della regione */
	$('#regione').change(function(){
		$('#city').empty();
		$.getJSON(baseUrl + '/' + moduleName + '/' + controllerName + '/get-city/format/json/?rid=' + $(this).val(), function(data){
			$.each(data.aCities, function(){
				$('#city').append('<option value="' + this.id + '">' + this.name + '</option>');
			});
		});
	});
	
/* ************  FORM AFFILIAZIONE  ************ */

/* ### OFFERTE SPECIALI ### */
//dettaglio offerta//

$('._3_3 .dettaglioOfferta').toggle(function(){
	var key = $(this).attr('name');
	keys = key.split('_');

	$(this).parents('td').siblings('._2_2').find('.offertaStrutturaClose').addClass('hidden');
	$(this).parents('tr').next().find('.dettaglio').addClass('hidden');
	$(this).parents('tr').next().find('.dettaglio_' + keys[0] + '_' + keys[1]).removeClass('hidden');
	
	$('.offer_' + keys[0] + '_' + keys[1]).removeClass('hidden');
	$('.offer_' + keys[0] + '_' + keys[1] + ' .dettaglio').removeClass('hidden');
	
}, function(){
	var key = $(this).attr('name');
	keys = key.split('_');

	$(this).parents('td').siblings('._2_2').find('.offertaStrutturaClose').addClass('hidden');
	$(this).parents('tr').next().find('.dettaglio').addClass('hidden');
	$(this).parents('tr').next().find('.dettaglio_' + keys[0] + '_' + keys[1]).removeClass('hidden');
	
	$('.offer_' + keys[0] + '_' + keys[1]).removeClass('hidden');
	$('.offer_' + keys[0] + '_' + keys[1] + ' .dettaglio').addClass('hidden');
});

$('a.closethis').click(function(){
	$(this).parent('.dettaglio').addClass('hidden');
	return false;
});

$('.offertaStruttura .open-all').click(function(){
	$(this).parents('.offertaStruttura').find('.close-all').show('blind');
	$(this).hide('blind');
	
	$('.offertaStrutturaDettaglio').find('.dettaglio').css('display', 'block');

	return false;
});

$('.offertaStruttura .close-all').click(function(){
	$(this).parents('.offertaStruttura').find('.open-all').show('blind');
	$(this).hide('blind');
	
	$('.offertaStrutturaDettaglio').find('.dettaglio').css('display', 'none');
	
	return false;
});
/* ### OFFERTE SPECIALI ### */


	$('.payment-answer').click(function(){
		$('.conferma').hide('blind');
		$('.payment-card-info').show('blind');
		$('#payment-card-info-input').attr('value', 1);
		return false;
	});
	
	$('.payment-answer-bonifico').click(function(){
		$('.payment-card-info').hide('blind');
		$('.conferma').show('blind');
		$('#payment-card-info-input').attr('value', 0);
		return false;
	});
/* ### RICERCA TUTTE LE STRUTTURE ### */

$('.allBuilding').change(
							function() {
								if (this.checked) {
									$('.destination').addClass(
											'nascondiLocalitaNomeHotel');
									$('.hotelName').addClass(
											'nascondiLocalitaNomeHotel');
											
									//$('input#destination').val('');
								} else {
									$('.destination').removeClass(
											'nascondiLocalitaNomeHotel');
									$('.hotelName').removeClass(
											'nascondiLocalitaNomeHotel');
								}
							});


/* Invia email ad amico */
$('#jsonForm-container-confirm').click(function(){
	$(this).hide();
	$('#jsonForm-container').show();
});

function processJson(data) { 
    // 'data' is the json object returned from the server 

	$('#jsonForm-container').hide();
	$('#jsonForm-container-confirm').append('<span class="response">' + data.message + '</span>');
	
}

	$('#jsonForm').ajaxForm({ 
        // dataType identifies the expected content type of the server response 
        dataType:  'json',
	
		beforeSend: function(){
			var string = $('#jsonForm').find('input#emailamico').val();
			
			if( string == '' )
			{
				alert('Inserire un indirizzo e-mail.');
				return false;
			}
			
			if( string.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1 )
			{
				alert('Indirizzo e-mail non valido.');
				return false;
			}
		},
        // success identifies the function to invoke when the server response 
        // has been received 
        success: processJson
    });


	$('#form-newsletter').ajaxForm({ 
        // dataType identifies the expected content type of the server response 
        dataType:  'json',
	
		beforeSend: function(){
			var string = $('#form-newsletter').find('input#email-news-letter').val();
			
			if( string == '' )
			{
				alert('Inserire un indirizzo e-mail.');
				return false;
			}
			
			if( string.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1 )
			{
				alert('Indirizzo e-mail non valido.');
				return false;
			}
		},
        // success identifies the function to invoke when the server response 
        // has been received 
        success: function (data){
			alert(data.message);
			return false;
		}
    });
	/*
	$('.stampa img').click(function(){
		var id = $(this).attr('alt');
		$(id).print();
	});*/
	 
});
