/*-- Parametri globali - possono essere sovrascritti nel template --*/	
maxBambini = 5;
maxStanze = 5;
map_path='';
maxOccupanti=20;
showPreventivo=false;

$(document).ready(function() {


  // Box Newsletter
  $('#lnknewsletter a.open').click(function(){
	  if($("#regnwslttr").is(':visible'))
		  $('#regnwslttr').hide();
	  else
		  $('#regnwslttr').show();
  });	
  $("#regnwslttr #formnewsletter").submit(function(){
	  $("#regnwslttr .error").hide();
	  var check = checkFields($(this).attr('id'),true);
	  if(check!=true){
		  if(check.attr('name')=='email' && check.val().length > 0)
			  $('#error_email').show();
		  else
			  $('#error_obbl').show();
		  
		  return false;
	  }	  
	  $.get('.newsletter?modejs=1&' + $(this).serialize(),
		function(data){
		  $("#regnwslttr").html(data);
	  	}
	  );	  
	  return false;
  });  
  $("#regnwslttr .close").live('click',function(){
	  $("#regnwslttr").hide();
	  return false;
  });


  var banExpZIndex = 1000;
  $(".banexploder").each(function(){
    $(this).css('z-index',banExpZIndex);
    banExpZIndex = banExpZIndex -1;
  })
	
	// Lista Risultati - Offerte
	if($('.home_offerte #lnkdiv li,.vetrina_offerte #lnkdiv li').length > 0) {  
	    var url = window.location.href;
	    var anchorRes = url.split('#');
	    if(anchorRes.length == 2 && $('#lnkdiv li.cat' + anchorRes[1]).length >0){
	    	getListaOfferte($('#lnkdiv li.cat' + anchorRes[1] + ' a'));
	    }
	    else
	    	getListaOfferte($('#lnkdiv li a:first'));
	}
	  // Lista Risultati - Tab
	  if($('#lnkdiv li').length > 0) {  
	    $('#lnkdiv li').click(function() {
	      showBlockResult($(this));
	      //return false;
	    });
	    var url = window.location.href;
	    var anchorRes = url.split('#');
	    if(anchorRes.length == 2 && $('#lnkdiv li.cat' + anchorRes[1]).length >0)
	    	showBlockResult($('#lnkdiv li.cat' + anchorRes[1]));
//	    else
//	    	showBlockResult($('#lnkdiv li:first'));
	  }
	
	//Lista risultati offerte dentro la località
	$('.seloffers').change(function(){
		getListaStrutture($(this),'_list');
		return false;
	});
  
	// ------ Motore di Ricerca -------------------------
	// DatePicker
	$.datepicker.setDefaults($.extend({showMonthAfterYear: false}, 
			$.datepicker.regional[language],{ changeMonth: true },{ changeYear: true },{ yearRange: '2011:2012' },{ dateFormat: 'dd/mm/yy' }, {minDate: new Date()},{ showOn: 'both' },{ buttonImageOnly: true },
	{ buttonImage: '/images/calendar.gif' },{ buttonText: '' }));
	$("#arrivo").datepicker({
		   onSelect: function(dateText, inst) { 
		return selezionaDataPartenza(dateText);
		}
	});
	
	$('#partenza').datepicker({
		   onSelect: function(dateText, inst) { 
		return selezionaDataArrivo(dateText);
		}
	});
	
//	// Mostra / Nasconde la select Categoria Hotel /E mostra nasconde trattamento 
//	$("#sel_tipoalloggio").change(function() {
//		if ($(this).val() == 15) { $("#divcatHotel").show("slow"); } else { $("#divcatHotel").hide(); }
//		if($(this).val() == 100 || $(this).val() == 19 || $(this).val() == 21){
//			$("#selectTrattamento").val(0);
//		}
//	});	
	$("#nstanze").change(function() {
		var i;
		for(i=1;i <= maxStanze; i=i+1){
			if (i <= $(this).val())
				$("#stanza" + i).show("slow");
			else
				$("#stanza" + i).hide("slow");
		}
	}
	);

	var i;
	for(i=1;i <= maxStanze; i=i+1){
		$("#bambini" + i).change(function() {
			var indexBb = $(this).attr('id').replace('bambini','');
			if ($(this).val()==0)
				$("#containBambini" + indexBb).hide();
			else{
				$("#containBambini" + indexBb).show();
			}
			var j;
			for(j=1;j <= maxBambini; j=j+1){
				if (j <= $(this).val()){
					$("#etabambino" + indexBb + j).show();
					$("#etabambino" + indexBb + j).attr("disabled",false);
				}
				else{
					$("#etabambino" + indexBb + j).hide();
					$("#etabambino" + indexBb + j).attr("disabled",true);
				}
			}
		}
		);
	}
	
	
	//check dei campi del form
//	$("#ricercaEsperienza").submit(
//			function() {
//				if(checkRicercaEsperienza($(this))){
//					waitingMessage('images/ajax-loader.gif',waiting_message);
//					return true;
//				}
//				return false;
//			}
//	);
	
//	$("#ricercaEsperienza").submit(
//		function() {
//			try{
//				var act = $(this).attr('action');
//				act = act.replace('place','strutture');
//				$(this).attr('action',act);
//			}
//			catch(e){}
//		}
//	);
	
	//Gestione del "segue" nei template delel località
	$("#segue").toggle(
		function(){$("#testocompleto").show();$(this).html(lbl_nascondi);},
		function(){$("#testocompleto").hide();$(this).html(lbl_segue);}
	);
	
	// Chiude / Apre altri parametri di ricerca
	$("a#searchmore").toggle(function(){$("fieldset#servizi").show('slow');},function(){$("fieldset#servizi").hide('slow');});
	$("a.plus").toggle(
    function(){
      $(this).parent().find('.altriservizi').show();
      $(this).find('img').attr('src',$(this).find('img').attr('src').replace('plus','minus'));
    },
    function(){
      $(this).parent().find('.altriservizi').hide();
      $(this).find('img').attr('src',$(this).find('img').attr('src').replace('minus','plus'));
    }
  );
	
	
	//checkpacket codice sconto
	$('#codiceScontoButton').click(function(){
		ricalcola =true;
		$('#formpren').submit();
	});
	
	// Scheda Struttura
	$("#btn_descrizione a").click(function(){ 
		$(".infostruttura").hide();$("#dettagliStruttura").show();
		$("#navdetail li").removeClass();$("#btn_descrizione").addClass("active");	
		return false;
	});
	
	$("#btn_pacchetto a").click(function(){ 
		$(".infostruttura").hide();$("#dettagliPacchetto").show();
		$("#navdetail li").removeClass();$("#btn_pacchetto").addClass("active");	
		return false;
	});
	$("#btn_tariffe a").click(function(){ 
		$(".infostruttura").hide();$("#tariffeStruttura").show(); 
		$("#navdetail li").removeClass();$("#btn_tariffe").addClass("active");
		loadTariffe(idVendor);
		return false;
	});
	$("#btn_mappa a").click(function(){ 
		$(".infostruttura").hide();$("#mappaStruttura").show(); 
		$("#navdetail li").removeClass();$("#btn_mappa").addClass("active");	
		if(typeof(Gload)=='function'){
			try{
				Gload();doGLoad=false;
			}
			catch(e){};
		}
		return false;
	});
	$("#btn_offerteSpeciali a").click(function(){ 
		showOfferteSpeciali('offerteStruttura',idVendor);	
		return false;
	});
	$("#btn_giudizio a").click(function(){ 
		$(".infostruttura").hide();$("#giudizioStruttura").show(); 
		$("#navdetail li").removeClass();$("#btn_giudizio").addClass("active");	
		loadGiudizi("giudizioStruttura",idVendor,idLingua);
		return false;
	});	
	$("#btn_disponibilita a").click(function(){ 
		$(".infostruttura").hide();$("#disponibilita").show(); 
		$("#navdetail li").removeClass();$("#btn_disponibilita").addClass("active");
		loadDisponibilita('disponibilita',idVendor);
		return false;
	});	
	
  
	$(".struttura .trattamento .radio").live('click',function(){
    $('.sceglicamere tr.active').removeClass('active');
    $('.sceglicamere tr.rigatotale').hide();
		addPreventivo($(this).val());
		return false;
	});
	
	if(showPreventivo==true)
		addPreventivo(0);
	$(".searchstrutture .trattamento .radio").click(function(){
		var idVendor = $(this).parent().attr('id').replace('tratt','');
		aggiornaTrattamento($(this).val(),idVendor);
	});
	
	 $(".accomitem input.button").live('click',function(){
		  var valTratt=$(this).parents('.accomitem').find('.trattamento input:checked').val();
		  $('#hiddentrattamento').val(valTratt);
		  return true;
	  });
	 
	$(".searchstrutture .checkproduct,#prevcontainer .checkproduct").live('click',function(){
		//$('.sceglicamere input.button').attr('disabled',true);
      //$('.sceglicamere input.button').parent().addClass('disabled');
		  $('.sceglicamere tr.rigatotale').hide();
		  var table = $(this).parents('.sceglicamere');
		  buttonClass='prenota';
		  buttonText = lbl_prenota;
		  prezzoTotale = 0;
		  table.find('tbody').each(function(){
			  var hasChecked = false;
			  $(this).find('.checkproduct').each(function(){
				  if($(this).attr('checked') == true){
					  hasChecked = true;
					  var prezzo = $(this).parent().parent().find('.pricetot').val();
					  prezzo = prezzo.replace(/\./g , "").replace(',','.');
					  prezzoTotale = 1 * prezzo + prezzoTotale;  
					  var tdDisponibilita = $(this).parent().parent().find('.accdisp');
					  if(!tdDisponibilita.hasClass('disponibile')){
						  buttonClass='dispo';
						  buttonText = lbl_disponibilita;
					  }
				  }  
			  });
			  if(hasChecked == false){
				  $(this).find('.checkproduct').first().attr('checked',true);
				  var prezzo = $(this).parent().parent().find('.pricetot').val();
				  prezzo = prezzo.replace(/\./g , "").replace(',','.'); 
				  prezzoTotale += 1 * prezzo;
				  var tdDisponibilita = $(this).parent().parent().find('.accdisp');
				  if(!tdDisponibilita.hasClass('disponibile')){
					  buttonClass='dispo';
					  buttonText = lbl_disponibilita;
				  }
			  }
		  });
		  table.find('.totale').text(prezzoTotale.toFixed(2).replace(/\./g , ",") + " €");
		  var button = table.find('input.button');
		  button.val(buttonText);
		  button.removeClass('prenota').removeClass('dispo').addClass(buttonClass).parent();
		  table.find('tr.rigatotale').show();
	  }); 
	
	
	 $('.sceglicamere input.button').live('click',function(){
		  //Gestione del back nella ricerca. 
		  //Se esiste un idvendor su sceglicamere significa che prima ho scelto quello e lo devo gestire
		  $('.sceglicamere').each(function(){
			  var idv = $(this).data('idvendor');
			  if(idv && idv.length > 0){
				  $(this).find('input.radio').each(function(){
					  var oldN = $(this).attr('name');
					  oldN = oldN + '-' + idv;
				  	  $(this).attr('name',oldN);	
				  });
			  }
			  $(this).data('idvendor','');
		  });
		  
		  var split;
		  $(this).parents('.sceglicamere').find('input.radio').each(function(){
			  var name = $(this).attr('name');
			  split = name.split('-');
			  $(this).attr('name',split[0]);
		  });
		  $(this).parents('.sceglicamere').data('idvendor',split[1]);
	  });
	 
	//Se sono nel template struttura attivo il tab giusto a seconda dell'ancora
	if($('.struttura #navdetail').length > 0){
		var href = window.location.href;
		var split = href.split('#');
		var destTab='';
		if(split.length == 2)
			destTab = split[1];
		if(destTab=='mappa')
			$("#btn_mappa a").trigger('click');
		else if(destTab=='tariffe')
			$("#btn_tariffe a").trigger('click');
		else if(destTab=='disponibilita')
			$("#btn_disponibilita a").trigger('click');
		else if(destTab=='giudizioStruttura')
			$("#btn_giudizio a").trigger('click');
		else if(destTab=='offerteStruttura')
			$("#btn_offerteSpeciali a").trigger('click');
	}

  
  // PrettyPhoto script
  $("a.prettyphoto").prettyPhoto({
    animationSpeed: 'fast',
		showTitle: true,
		hideflash: false,
		theme: 'light_square'
  });
  
  // jQuery Tooltip
	$('.tooltip').tooltip({
		track: true,
		delay: 0,
		fixPNG: true,
		top: 15,
		left: 5,
		showURL: false
	});
  

  // LocGallery
  var iLocGallery = 1;
  var lastImage = $('.gallnav ul li').length;
  if (iLocGallery <= 1) { $(".gallnav p.bck a").hide(); }
  if (lastImage <=1){ $(".gallnav p.frw a").hide(); }
  $('#didasc span#maxph').html(lastImage);
  
  $('.gallnav p a').click(function(){
    
    $(this).show();
    var dir = $(this).parent().attr('class');
    
    //alert(dir);
    
    if (dir == "nav frw") {
      iLocGallery ++;
      $(".gallnav p.bck a").show();
      if (iLocGallery >= lastImage) { $(".gallnav p.frw a").hide(); }
    } 
    else if (dir == "nav bck") {
      iLocGallery --;
      $(".gallnav p.frw a").show();
      if (iLocGallery <= 1) { $(".gallnav p.bck a").hide(); }
    }
    
    $('.gallnav ul li').hide();
    $('.gallnav ul li#lg-' + iLocGallery).fadeIn(700);
    
    $('#didasc span#indexph').html(iLocGallery);
 
    //alert(dir+", "+iLocGallery);
    return false;
  });
  
  
  provIniziale = $('ul#changeprov').attr('class');
  
  /* Mappa change prov */
  $("ul#changeprov li a").mouseenter(function(){
    $('ul#changeprov').attr('class','ch-' + $(this).parent().attr('class'));
  });
  $("ul#changeprov").mouseleave(function(){
    $('ul#changeprov').attr('class',provIniziale);
  });
  

  // NewRotator
  $('#newrotator').gnuRotator('.controls', '.blockrot');


  // Cambio Lingua
  setLanguage(language);  
  $("#changelang").mouseenter(function(){
    $("p.langlabel").html("<span>" + cambia_lingua+ "</span>");
    $("ul.langs").show();
  });
  $("#changelang").mouseleave(function(){
    $("ul.langs").hide();
    setLanguage(language);
  });
  
  $(".home_offerte .lnkoffers a,.vetrina_offerte .lnkoffers a").click(function(){
	  getListaOfferte($(this));
  });
  
  $('#shownotetariffe').click(function(){
		$('#popupnotetariffe').show(500);
		return false;
	});

	$('#popupnotetariffe .close').click(function(){
		$('#popupnotetariffe').hide(500);
		return false;	
	})
  
  // GoogleMaps nelle liste
  $(".struttura .lnkmap a, .lnkmap a.mp").live('click',function(){
    $('.itemaccom').attr('style','z-index:1;'); /* IE7 z-index bugfix! - non rimuovere - */
    $(this).parent().parent().parent().parent().parent().attr('style','z-index:20;'); /* IE7 z-index bugfix! - non rimuovere -  */
    
    var values = $(this).attr('rel').split('-'); 
    if(!$('#map' + values[0]).is(':visible')){
      $(".boxmap").hide();
	    $('#map' + values[0]).show(); 
		  if(!$(this).data('createMap')){
			  var map = new GMap2(document.getElementById('map' + values[0]));
			  map.addControl(new GSmallMapControl());
			  map.addControl(new CloseControl());
			  var point = new GLatLng(values[1],values[2]);
			  map.setCenter(point, 7);
			  map.addOverlay(new GMarker(point));
			  $(this).data('createMap',true);
		  }		 
		  return false;
		}
    else {
		  $('#map' + values[0]).hide();
		}
    return false;
  });
  
//We define the function first
function CloseControl() {
}
CloseControl.prototype = new GControl();
CloseControl.prototype.initialize = function(map) {
var container = document.createElement("div");

var zoomOutDiv = document.createElement("div");
$(zoomOutDiv).addClass('close');
$(zoomOutDiv).html('X');
container.appendChild(zoomOutDiv);
//zoomOutDiv.appendChild(document.createTextNode("X"));
GEvent.addDomListener(zoomOutDiv, "click", function() {
 $('.boxmap').hide();
});

map.getContainer().appendChild(container);
return container;
}
CloseControl.prototype.getDefaultPosition = function() {
return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
}



  // Dettagli Richiesta/Prenotazione
  $(".acn_open span").live('click',function(){ // link Dettagli/Chiudi
    $(this).html(lbl_chiudi).parent().removeClass("acn_open").addClass("acn_close");
    $(this).parent().parent().parent().parent().find("tbody").fadeIn(500);
  });
  $(".acn_close span").live('click',function(){
    $(this).html(lbl_dettagli).parent().removeClass("acn_close").addClass("acn_open");
    $(this).parent().parent().parent().parent().find("tbody").fadeOut(500);
  });
  $("#detailaccom th .lnksconti").click(function(){  // link Sconti
    if ( $(this).parent().next().hasClass("acn_open") ) {
      $(this).parent().parent().parent().find(".acn_open").removeClass("acn_open").addClass("acn_close").html('<span>'+ lbl_chiudi +'</span>');
      $(this).parent().parent().parent().parent().find("tbody").fadeIn(500);
      return false;      
    } 
    else if ( $(this).parent().next().hasClass("acn_close") ) {
      $(this).parent().parent().parent().find(".acn_close").removeClass("acn_close").addClass("acn_open").html('<span>'+ lbl_dettagli +'</span>');
      $(this).parent().parent().parent().parent().find("tbody").fadeOut(500);
      return false;      
    }      
  });
  
  
  // Apre Codice Sconto
  $("p.vdiscode a").toggle(function(){
    $("#vformcodes").fadeIn(400);
  }, function(){
    $("#vformcodes").fadeOut(400);
  });
  

 	$(".modal").click(function(){
		var html ='';
		//$.append('<div id=\"modal\"></div>');	  
		try{
      $.ajax({
        async: false,
        type: "GET",
        url: urlNtScViagg,
        success: function(data){html = data;}
      });
      var initHtml = '';
      elem = $('#boxmodal').lightbox_me({
        centered: false, 
        onLoad: function() {
          initHtml = $('#boxmodal').html();
          $('#boxmodal').append(html);
        },
        onClose: function() {
          $('#boxmodal').html(initHtml);
        }
      });
		}
		catch(e){alert(e.message);return false;}
		return false;		  
	});



});
/* ----------------------------------------------------------------------------------------------
 *
 * fine (document).ready()
 *
 * ----------------------------------------------------------------------------------------------
 */




function showBlockResult(itemLi){
  itemLi.parent().find('li').removeClass('active');
    itemLi.addClass('active');
     
    var idCat = itemLi.find('a').attr('id').replace('tab','');
    $('div.blockresults').css('display','none');
    $('#listcat' + idCat).fadeIn('slow').css('display','block');
    $('#hide_tipoalloggio').val(idCat);
}



// Cambia contenuti nel Box Scheda Struttura
function setBoxDetails(clkButt) {
  $("#detnav li").removeClass("active"); 
  $('.' + clkButt).parent().addClass("active");
  $(".dyncnt").hide();

  if (clkButt == "bx-descr") {      $("#details").show();}
  else if (clkButt == "bx-rooms") { $("#rooms").show();}
  else if (clkButt == "bx-maps") {  $("#maps").show();setGoogleMap();}
  else if (clkButt == "bx-opin") {  $("#opinions").show();}
  else if (clkButt == "bx-req") {   $("#request").show();}
}

//Mappa di google
function setGoogleMap(){
	if(typeof(Gload)=='function'){
		try{
			Gload();doGLoad=false;
		}
		catch(e){};
	}
	return false;
}

// Rileva e scrive Lingua Corrente
function setLanguage(lng) {
  var selCodeIt = '<span class="flag"><img src="' + rootImages + '/flag-it.gif" alt="Versione italiana" />Italiano</span>';
  var selCodeEn = '<span class="flag"><img src="' + rootImages + '/flag-en.gif" alt="English version" />English</span>';
  var selCodeDe = '<span class="flag"><img src="' + rootImages + '/flag-de.gif" alt="Deutsch version" />Deutsch</span>';
  var selCodeEs = '<span class="flag"><img src="' + rootImages + '/flag-es.gif" alt="Version española" />Español</span>';
  var selCodeFr = '<span class="flag"><img src="' + rootImages + '/flag-fr.gif" alt="Version française" />Français</span>';
  
  if (lng == "it") { $("ul.langs a.it").parent().addClass("active");$("p.langlabel").html(selCodeIt); }
  else if (lng == "en") { $("ul.langs a.en").parent().addClass("active");$("p.langlabel").html(selCodeEn); }
  else if (lng == "de") { $("ul.langs a.de").parent().addClass("active");$("p.langlabel").html(selCodeDe); }
  else if (lng == "es") { $("ul.langs a.es").parent().addClass("active");$("p.langlabel").html(selCodeEs); }
  else if (lng == "fr") { $("ul.langs a.fr").parent().addClass("active");$("p.langlabel").html(selCodeFr); }
}

function getListaOfferte(link,template){
	  $("#lnkdiv li").removeClass('active');
	  link.parent().addClass('active');
	var par=link.attr('rel');
	  var split = par.split('/');
	  var params = split[0];
	  
	  var parameters = {};
	  
	  parameters['idcat'] = split[0];
	  parameters['idvcat'] = split[1];
	  parameters['off'] = split[2];
	  if(template!=undefined)
		  parameters['template'] = template;
	  
	  $.post(".eshop?action=lsubreg", parameters,function(data){
		  $('.listoffers').html(data);
	  });
	  return false;
}

function getListaStrutture(select,template){
	  var par=select.val();
	  var split = par.split('/');
	  var params = split[0];
	  
	  var parameters = {};
	  
	  parameters['idcat'] = split[0];
	  parameters['idvcat'] = split[1];
	  if(split.length == 3)
		  parameters['off'] = split[2];
	  if(template!=undefined)
		  parameters['template'] = template;
	  
	  $.post(".eshop?action=lsubreg", parameters,function(data){
		  $('#liststrutt' + parameters['idvcat']).html(data);
	  });
	  return false;
}

function goToAnchor(select){
	  location.href="#" + $(select).val();
	  return false;
}

function filtraPerClasse(select){
		var classToSel= $(select).val();
	$('.itemaccom').each(function(){
		if(classToSel=='' || $(this).hasClass( classToSel ))
			$(this).show();
		else
			$(this).hide();
	});
}
//---------------------------------------------------------------------------------
//----------------------Funzioni per il motorino-----------------------------------
//---------------------------------------------------------------------------------
function selezionaDataPartenza(dateText){
	if($('#partenza').val() || $('#partenza').val()==''){
		var d=dateText.substr(0,2) * 1;
		var m=dateText.substr(3,2) * 1 - 1;
		var y=dateText.substr(6,4) * 1;
		var dataArrivo = new Date(y,m,d,0,0,0);
		
		var check = /^([0-9]{2})([\/]{1})([0-9]{2})([\/]{1})([0-9]{4})$/;
		var result = check.test ( $('#partenza').val() );
		if(result){
			var textDPart = $('#partenza').val();
			var mPar = textDPart.substr(3,2) * 1 - 1
			var dataPartenza = new Date(textDPart.substr(6,4),mPar,textDPart.substr(0,2),0,0,0);
			if(dataPartenza.getTime() > dataArrivo.getTime())
				return false;
		}
		
		dataArrivo.setDate(dataArrivo.getDate());
		
		d = dataArrivo.getDate();
		m = dataArrivo.getMonth() + 1;
		y = dataArrivo.getYear();
	
		if(y < 1900)
			y = 1900 + y;
		if(m < 10)
			m = '0' + m;
		if(d < 10)
			d= '0' + d;
		
	
		var parText = d + '/' + m 
		+ '/' + y;
		$('#partenza').val(parText);
	}
	return false;
}

function selezionaDataArrivo(dateText){
	if($('#arrivo').val() || $('#arrivo').val()==''){
		var d=dateText.substr(0,2) * 1;
		var m=dateText.substr(3,2) * 1 - 1;
		var y=dateText.substr(6,4) * 1;
		var dataPartenza = new Date(y,m,d,0,0,0);
		
		var check = /^([0-9]{2})([\/]{1})([0-9]{2})([\/]{1})([0-9]{4})$/;
		var result = check.test ( $('#arrivo').val() );
		if(result){
			var textDPart = $('#arrivo').val();
			var mPar = textDPart.substr(3,2) * 1 - 1
			var dataArrivo = new Date(textDPart.substr(6,4),mPar,textDPart.substr(0,2),0,0,0);
			if(dataPartenza.getTime() > dataArrivo.getTime())
				return false;
		}
		
		dataPartenza.setDate(dataPartenza.getDate());
		
		
		
		d = dataPartenza.getDate();
		m = dataPartenza.getMonth() + 1;
		y = dataPartenza.getYear();
	
		if(y < 1900)
			y = 1900 + y;
		if(m < 10)
			m = '0' + m;
		if(d < 10)
			d= '0' + d;
		
	
		var parText = d + '/' + m 
		+ '/' + y;
		$('#arrivo').val(parText);
	}
	return false;
}

function checkRicercaEsperienza(ric){
	$('.error').hide();
	$('.evidenzia').removeClass('evidenzia');
	$('#afterpartenza').hide();
	var ck = checkFields(ric.attr('id'),true);
	if(ck == true)
		if(isArrivoAfterPartenza())
			;
		else{
			$('#afterpartenza').show();
			return false;
		}
	else{
		var blockError = ck.parents('fieldset').find('.error:not(#afterpartenza)');
		if(blockError.length > 0)
			blockError.show();
		else
			ck.parents('.blockseparator').find('.error:not(#afterpartenza)').show();
		return false;
	}
	return checkMaxOccupanti();
}
function checkLocalitaProvincia(field){
	var n=field.selectedIndex;	
	var provincia=document.getElementById('provincia');
	var localita=document.getElementById('localita');
	if(n==0){
		provincia.disabled=false;
		localita.disabled=false;
	}
	else{
		if(field.id=="provincia")localita.disabled=true;
	else provincia.disabled=true;
	}
}
function isArrivoAfterPartenza(){
	var p=$('#partenza');
	var a=$('#arrivo');
	try{
		var valueA=a.val();
		var d=valueA.substr(0,2);
		var m=valueA.substr(3,2) * 1 - 1;
		var y=valueA.substr(6,4);
		
		var dataArrivo = new Date(y,m,d,0,0,0);
		
		var valueP=p.val();
		if(valueP){
			var dO=valueP.substr(0,2);
			var mO=valueP.substr(3,2) * 1 - 1;
			var yO=valueP.substr(6,4);
			var dataPar = new Date(yO,mO,dO,0,0,0);
			
			if(dataPar.getTime() <= dataArrivo.getTime())
			if(valueP && valueP.length){
				return false;
			}
		}
		return true;
	}
	catch(e){ alert(e.message);}
	}
function checkMaxOccupanti(){
	var numStanze = $('#stanze').val() * 1;
	var i=1;
	if(maxStanze == 1 || maxOccupanti==0)
		return true;
	
	for(i=1;i<=numStanze;i=i+1){
		var adulti = $("#adulti" + i).val() * 1;
		var bb = $("#bambini" + i).val() * 1;
		var infantAmmessi = 0;
		if(vendor_category_id == 19 || vendor_category_id == 21){
			for(j=1;j<=bb;j=j+1){
				var etaBambino = $('#etabambino' + i + j).val() * 1;
				if(etaBambino==1)
					infantAmmessi = 1;
			}
		}
		var occupanti = adulti + bb - infantAmmessi;
		if(occupanti > maxOccupanti){
			//alert("L'appartamento " + i + " non può contenere " + adulti + " adulti e " + bb + " bambini. Suddividere gli occupanti in più appartamenti");
			alert(lbl_struttura + ' ' + i + ' ' + lbl_nonaccoglie + ' ' + adulti + ' ' + lbl_adulti + ' ' + lbl_e + 
					' ' + bb + ' ' + lbl_bb + ' ' + lbl_suddiv);
			return false;
		}
	}
	return true;
}
//------------------------------------------------------------------------------------------
//----------------CHECK FORM-----------------------------------------------------------------
//-------------------------------------------------------------------------------------------
/*-----DIPENDENTE DA JQUERY*/
function checkFields(form,noAlert){
	var doReturn =checkCampiObbligatori(form,noAlert);
	if(doReturn==true)doReturn = checkCampiEmail(form,noAlert);
	if(doReturn==true)doReturn = checkCampiNumerici(form,noAlert);
	if(doReturn==true)doReturn = checkCampiData(form,noAlert);	
	return doReturn;
}	
function checkCampiObbligatori(form,noAlert){return checkCampo(form,'fieldObbligatorio','Compila tutti i campi obbligatori',noAlert);}	
function checkCampiEmail(form,noAlert){return checkCampo(form,'email','Attenzione, il formato dell\'e-mail non e\' corretto',noAlert);}
function checkCampiNumerici(form,noAlert){return checkCampo(form,'digit','Attenzione, I valori devono essere numerici',noAlert);}	
function checkCampiData(form,noAlert){return checkCampo(form,'date','Per le date utilizzare il formato : gg/mm/aaaa',noAlert);}
function checkCampo(form,classe,frase,noAlert){
	var doReturn = true;
	var checkMandatory =false; 
	if(classe == 'fieldObbligatorio')checkMandatory = true;
	
	var check = false;
	var assertEmpty=false;
	if(classe == 'email'){
		check = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$/i;
		assertEmpty=true;
	}
	else if(classe=='date'){
		check = /^([0-9]{2})([\/]{1})([0-9]{2})([\/]{1})([0-9]{4})$/;
		assertEmpty=true;
		}
	else if(classe=='digit'){
		check = /^([0-9\.])*$/;
		assertEmpty=true;
	}
	
	$("#" + form + ' .' + classe).each(
		function(i){
			var val = trim(this.value);
			if($(this).attr('type')=='radio'){
				val = $("input[@name='" + $(this).attr('name')  + "']:checked").val();
				if(!val)
					val='';
			}
			
			if($(this).attr('type')=='checkbox'){
				if(!$(this).is(':checked'))
					val='';
			}
			
			if(checkMandatory && this.disabled!=true && val.length < 1){
				if(!noAlert){
					alert(frase);
					$(this).addClass('error');
					$(this).focus();
					doReturn = false;
					return false;
				}
				else{
					$(this).addClass('evidenzia');
					doReturn = $(this);
					return $(this);
				}
			}
			if(checkMandatory == false && 
			(assertEmpty==false || assertEmpty==true && val.length >0) ) {
				if(check && !check.test(val)) {
					if(!noAlert){
						alert(frase);
						$(this).addClass('error');
						$(this).focus();
						doReturn = false;
						return false;
					}
					else{
						$(this).addClass('evidenzia');
						doReturn = $(this);
						return $(this);
					}
				}
			}
		}
	)
	return doReturn;
}	
function trim(stringa){
	while (stringa.substring(0,1) == ' '){stringa = stringa.substring(1, stringa.length);}
	while (stringa.substring(stringa.length-1, stringa.length) == ' '){stringa = stringa.substring(0,stringa.length-1);}
	return stringa;
}
//-----------------------------------------------------------------------------------------------
//-----------------------FINE CHECK FORM---------------------------------------------------------
//-----------------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------------------
//-------------------------Schede struttura funzioni--------------------------------------------------
//----------------------------------------------------------------------------------------------------
/*-----------------carica i tab del viewplace-------*/
function loadTariffe(idvendor,mode,idTab){
	if(mode=='undefined' || !mode)mode='onlytariffe';
	var tab=document.getElementById('tariffeStruttura');
	if(idTab)
		tab=document.getElementById(idTab);
	
	if(tab && idvendor){
		var sel1=document.getElementById('product1');
		var sel2=document.getElementById('product2');
		var stringProduct='';
		if(sel1 && sel2){
		stringProduct='&idproduct1='+sel1.options[sel1.selectedIndex].value+
		'&idproduct2='+sel2.options[sel2.selectedIndex].value
	}
	var params='modejs=1&action=viewplace&idvendor='+idvendor+'&mode='+mode+stringProduct;
	$.get('.eshop?' + params, function(data){$(tab).html(data);});
	return false;
	}
}
function loadDisponibilita(idtab,idvendor,month){
	parameterMonth='';
	if(month)
		parameterMonth='&month='+month;
	var tab=document.getElementById(idtab);
	if(tab && idvendor){
		var params='modejs=1&action=viewplace&idvendor='+idvendor+'&mode=onlydisponibilita'+parameterMonth;
		$.get('.eshop?' + params, function(data){$(tab).html(data);});
		return false;
	}
}
function checkSelectTariffe(){
	var sel1=document.getElementById('product1');
	var sel2=document.getElementById('product2');
	var btn=document.getElementById('btn_confronta');
	if(sel1.selectedIndex==sel2.selectedIndex)btn.disabled=true;
	else btn.disabled=false;
	}
function loadGiudizi(idtab,idV, idL ){
	var tab=document.getElementById(idtab);
	if(tab && idV && idL){
		var params='.questionari?modejs=1&action=giudizi&id=1&idV='+idV+'&idLingua='+idL;
		$.get(params, function(data){$(tab).html(data);});
	}
	return false;
}
function loadOfferteSpeciali(idtab,idvendor){
	var tab=document.getElementById(idtab);
	if(tab && idvendor){
		var params='.eshop?action=viewplace&modejs=1&idvendor='+idvendor+'&mode=onlyofferte';
		$.get(params, function(data){$(tab).html(data);});
	}
}
function showOfferteSpeciali(idtab,idvendor){
	$(".infostruttura").hide();$("#offerteStruttura").show(); 
	$("#navdetail li").removeClass();$("#btn_offerteSpeciali").addClass("active");	
	loadOfferteSpeciali(idtab,idvendor);
	return false;
}

function loadFoto(idtab, idvendor ){
	var tab=document.getElementById(idtab);
	var params='.eshop?modejs=1&action=viewplace&idvendor='+idvendor+'&mode=onlyfoto';
	$.get(params, function(data){$(tab).html(data);});
}
function loadDescrizione(idvendor){	
	var tab=document.getElementById('dettagliStruttura');
	var params='.eshop?modejs=1&action=viewplace&idvendor='+idvendor+'&modejs=1';
	$.get(params, function(data){$(tab).html(data);});
}
function addPreventivo(trattamento){
	$("#preventivo").show();
	var params=$("#ricercaEsperienza").serialize();
	params+='&count=1&modejs=1';
	if(trattamento!=undefined)
		params+='&trattamento=' + trattamento;
	
	$.post(".eshop", params,
		function(data){
			$("#preventivo").html(data);
		}
	);
	return false;
}
function aggiornaTrattamento(trattamento,idvendor){
	var params=$("#ricercaEsperienza").serialize();
	params+='&count=1&modejs=1';
	params+='&trattamento=' + trattamento;
	params+='&idvendor=' + idvendor+'&action=result-strutture';
	params+='&template=eshop/_searchstrutture';
	$.post(".eshop", params,
		function(data){
			$('#boxvendor' + idvendor).html(data);
		}
	);
	return false;
}
////---------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------ACCOMODATION---------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function Accomodation(arrivo,partenza,categoria,idPreventivo,localita,provincia,idVendor){
	this.fullProduct=[];
	this.provincia=provincia;
	this.localita=localita;
	this.dataArrivo=arrivo;
	this.dataArrivoPerCalcolo=null;
	this.dataPartenza=partenza;
	this.dataPartenzaPerCalcolo=null;
	this.priceOldYear=null;
	this.categoria=categoria;
	this.idPreventivo=idPreventivo;
	this.idVendor=idVendor;
	this.tabCount;
	this.parameters;
	this.lang=null;
	this.changeLanguage = function(select){
		this.lang = select.options[select.selectedIndex].value;
		return false;
	}
	
	this.getFullProducts = function(){
		return this.fullProduct;
	}
	this.addFullProduct= function(fp){
		this.fullProduct.push(fp);
	}
	/**
	*@param mode vale 1 per le ricerche per localita e 2 per le ricerche per provincia
	*
	*/
	this.goToSearch=function(mode,categoria,noFilterUnit){
		var cat = this.categoria;
		if(categoria && categoria!=0)
			cat = categoria;
		var myForm = document.createElement("form");
		myForm.method='post';
		myForm.action = '.it.eshop';
		myForm.appendChild(newInput('action','search-strutture'));
		
		myForm.appendChild(newInput('idPreventivo',this.idPreventivo));
		myForm.appendChild(newInput('orderBy','5'));
		myForm.appendChild(newInput('tipoalloggio',cat));
		myForm.appendChild(newInput('trattamento',this.fullProduct[0].trattamento ));
		myForm.appendChild(newInput('arrivo',this.dataArrivo));
		myForm.appendChild(newInput('partenza',this.dataPartenza));
		myForm.appendChild(newInput('stanze',this.fullProduct.length));
		
		if(noFilterUnit)
			myForm.appendChild(newInput('noFilterUnit',"1"));
		
		if(mode){
			if(mode == 1)
				myForm.appendChild(newInput('localita',this.localita));
			else if(mode==2)
				myForm.appendChild(newInput('provincia',this.provincia));
		}
		var i=0;
		for(i=0;i<this.fullProduct.length;i=i+1){
			var lbl_ad = 'adulti' + (i+1);
			var lbl_bb = 'bambini' + (i+1);
			myForm.appendChild(newInput(lbl_ad,this.fullProduct[i].adulti));
			myForm.appendChild(newInput(lbl_bb,this.fullProduct[i].etaBambini.length));
			var j=0;
			for(j=0;j<this.fullProduct[i].etaBambini.length;j=j+1){
				var lbl_etabb = 'etabambino' + (i + 1) + (j + 1);
				myForm.appendChild(newInput(lbl_etabb,this.fullProduct[i].etaBambini[j]));
			} 
		}
		
		document.body.appendChild(myForm) ;
		myForm.submit() ;
		document.body.removeChild(myForm) ;
		return true;
	}
	
	
	
	this.getParameters  = function(){
		var parameters = {};
		parameters['stanze'] = this.fullProduct.length;
		for(i=1;i<=this.fullProduct.length;i=i+1){
			var fp = this.fullProduct[i-1];
			parameters['trattamento'] = fp.trattamento;
			parameters['ignoreMinNinghts'] = fp.ignoreMinNights;
			parameters['adulti' + i]=fp.adulti;
			parameters['bambini' + i]=fp.etaBambini.length;
			for(j=1;j<=fp.etaBambini.length;j=j+1){
				parameters['etabambino' + i + j]=fp.etaBambini[j-1];
			}
		}
		parameters['arrivo'] = this.dataArrivo;
		parameters['partenza'] = this.dataPartenza;
		if(this.dataArrivoPerCalcolo)parameters['arrivopercalc'] = this.dataArrivoPerCalcolo;
		if(this.dataPartenzaPerCalcolo)parameters['partenzapercalc'] = this.dataPartenzaPerCalcolo;
		if(this.priceOldYear)parameters['priceoldyear']='1';
		return parameters;
	}
	function newInput(attribute,value){
		var myInput = document.createElement("input") ;
		myInput.setAttribute("name", attribute) ;
		myInput.setAttribute("value", value);
		return myInput;
	}
}
//---------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------FULL PRODUCT---------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function FullProduct(adulti,prezzo,trattamento,ignoreMinNights){
	this.adulti=adulti;
	this.etaBambini=[];
	this.prezzo=prezzo;
	this.trattamento=trattamento;
	this.ignoreMinNights = 0;
	if(ignoreMinNights)
		this.ignoreMinNights = ignoreMinNights;
	
	this.addBambino=function(eta){
		this.etaBambini.push(eta);
	}
}
//---------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------EASY BOOKING---------------------------------------------------
//--------------------------------------------------------------------------------------------------------------
function addEasyBooking(titolo){
	$("#preventivo").show();
	params=$("#ricercaEsperienza").serialize();
	params+='&modejs=1&mode=vendor' + '&note=' + titolo;
	$.post(".eshop", params,
		function(data){
			$("#preventivo").html(data);
		}
	);
	return false;
}
function loadEasyBooking(form,caption,note,idTab){
	try{
		if(idTab==undefined || idTab=='')
			idTab = 'easybooking';
		tab=document.getElementById(idTab);
		var params='.eshop?' + $(form).serialize();
		if(note){act = act + '&note=' + note;}
		$.get(params, function(data){$(tab).html(data);});
	}
	catch(e){alert(e.message);}
	return false;
}


//--------------------------------------------------------------------------
//----lighbox me------------------------------------------------------------
//--------------------------------------------------------------------------
(function($) {

  $.fn.lightbox_me = function(options) {

    return this.each(function() {

        var
          opts = $.extend({}, $.fn.lightbox_me.defaults, options),
          $overlay = $('<div class="' + opts.classPrefix + '_overlay"/>'),
          $self = $(this),
          $iframe = $('<iframe id="foo" style="; display:none;margin:0;padding:0;width:100%;height:100%;position:absolute;top:0;left:0;border:none;z-index:' + (opts.zIndex + 1) + ';"/>'),
          ie6 = ($.browser.msie && $.browser.version < 7);


        /*----------------------------------------------------
           DOM Building
        ---------------------------------------------------- */
        if (ie6) {
            //alert('ie6 alert');
            var src = /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank';
            $iframe.attr('src', src);
            $('body').append($iframe);
        } // iframe shim for ie6, to hide select elements
        $('body').append($self).append($overlay);


        /*----------------------------------------------------
           CSS stuffs
        ---------------------------------------------------- */

        // set css of the modal'd window
        setSelfPosition();
        $self.css({left: '50%', marginLeft: ($self.outerWidth() / 2) * -1,  zIndex: (opts.zIndex + 3) });


        // set css of the overlay

        setOverlayHeight(); // pulled this into a function because it is called on window resize.
        $overlay
                .css({ position: 'absolute', width: '100%', top: 0, left: 0, right: 0, bottom: 0, zIndex: (opts.zIndex + 2), display: 'none' })
                .css(opts.overlayCSS);


        /*----------------------------------------------------
           Animate it in.
        ---------------------------------------------------- */

        $overlay.fadeIn(opts.overlaySpeed, function() {
            $self[opts.appearEffect](opts.lightboxSpeed, function() { setOverlayHeight(); opts.onLoad()});
        });



        /*----------------------------------------------------
           Bind Events
        ---------------------------------------------------- */

        $(window).resize(setOverlayHeight)
                 .resize(setSelfPosition)
                 .scroll(setSelfPosition)
                 .keypress(observeEscapePress);
        $self.find(opts.closeSelector).add($overlay).click(function() { closeLightbox(); return false; });
        $self.bind('close', closeLightbox);
        $self.bind('resize', setSelfPosition);
        $self.find('.' + opts.closeSelector).live('click', closeLightbox);

        

        /*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
          -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */


        /*----------------------------------------------------
           Private Functions
        ---------------------------------------------------- */

        /* Remove or hide all elements */
        function closeLightbox() {
            if (opts.destroyOnClose) {
                $self.add($overlay).remove();
            } else {
                $self.add($overlay).hide();
            }

            $iframe.remove();

            $(window).unbind('resize', setOverlayHeight);
            $(window).unbind('resize', setSelfPosition);

            opts.onClose();
        }


        /* Function to bind to the window to observe the escape key press */
        function observeEscapePress(e) {
            if(e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which==0)) closeLightbox();
        }


        /* Set the height of the overlay
                : if the document height is taller than the window, then set the overlay height to the document height.
                : otherwise, just set overlay height: 100%
        */
        function setOverlayHeight() {
            if ($(window).height() < $(document).height()) {
                $overlay.css({height: $(document).height() + 'px'});
            } else {
                $overlay.css({height: '100%'});
                if (ie6) {$('html,body').css('height','100%'); } // ie6 hack for height: 100%; TODO: handle this in IE7
            }
        }


        /* Set the position of the modal'd window ($self)
                : if $self is taller than the window, then make it absolutely positioned
                : otherwise fixed
        */
        function setSelfPosition() {
            var s = $self[0].style;

            if (($self.height() + 80  >= $(window).height()) && ($self.css('position') != 'absolute' || ie6)) {
                var topOffset = $(document).scrollTop() + 40;
                $self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})
                if (ie6) {
                    s.removeExpression('top');
                }
            } else if ($self.height()+ 80  < $(window).height()) {
                if (ie6) {
                    s.position = 'absolute';
                    if (opts.centered) {
                        s.setExpression('top', '(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"')
                        s.marginTop = 0;
                    } else {
                        var top = (opts.modalCSS && opts.modalCSS.top) ? parseInt(opts.modalCSS.top) : 0;
                        s.setExpression('top', '((blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"')
                    }
                } else {
                    if (opts.centered) {
                        $self.css({ position: 'fixed', top: '50%', marginTop: ($self.outerHeight() / 2) * -1})
                    } else {
                        $self.css({ position: 'fixed'}).css(opts.modalCSS);
                    }

                }
            }
        }

    });
  };
  $.fn.lightbox_me.defaults = {

      // animation
      appearEffect: "fadeIn",
      overlaySpeed: 300,
      lightboxSpeed: "fast",

      // close
      closeSelector: ".close",
      closeClick: true,
      closeEsc: true,

      // behavior
      destroyOnClose: false,

      // callbacks
      onLoad: function() {},
      onClose: function() {},

      // style
      classPrefix: 'lb',
      zIndex: 999,
      centered: false,
      modalCSS: {top: '50%'},
      overlayCSS: {background: 'black', opacity: .8}
  }
})(jQuery);


