/*-----------------------------------------------------------
	Project: WE Londres	
	Date : 	July 2009
	Last Update : 01/09/09
	Author:	C2iS - AFO
	Summary : JS for all pages	
-----------------------------------------------------------*/

/*:::::::: INITS ::::::::::*/

$(document).ready(function() {
	/*functions for IE 6*/
	if ($.browser.msie && $.browser.version <= 6 ) {
		try {
		document.execCommand('BackgroundImageCache', false, true);
		} catch(e) {}		
		$('#mainMenu > li > ul , #mainMenu > li > dl').bgiframe();	
	}	
	/*end functions for IE 6*/
	
	/*functions for IE 6 & 7*/
	if ($.browser.msie && $.browser.version <= 7 ) {		
		sfHover(); 	
		if($('#themeWeekend').length) {
			clickOnTooltip();
		}
	}	
	/*end functions for IE 6 & 7*/
			
	lastItemMenu();	
	toggleFilterPict();
		
	if($('#contentHome').length) {
		initCarBestSellers(); //init carousel homepage
		initMap();  //init google Map sur la home
	}
		
	if($('#searchBox').length) {
		$('#searchBox .datePick').datePicker(); //init datepicker du moteur de recherche
		showSelects();
        $("#searchForm").validationEngine({
            inlineValidation: true, success :  false, failure : function() {}
        });
	}
    
	if($('#detailSlider').length) {			
		detailSlider();		//construction du bloc #detailSlider   
		autoScrollBar();	// ajout automatique scrollbar
		autoScrollBarPresta(); // ajout automatique scrollbar
		$('#detailSlider .datePick').datePicker(); //init datepicker 
        if($('.calPriceTable .datePick') && $('#id_startDate')) $('.calPriceTable .datePick').dpSetStartDate($('#id_startDate').val());
        if($('.calPriceTable .datePick') && $('#id_stopDate')) $('.calPriceTable .datePick').dpSetEndDate($('#id_stopDate').val());  
	}
	
	if($('#carouselContainer').length) {
		initCarousel(); // init carousel fiche sejour / fiche hotel
	}
	
	if($('#themeWeekend').length) {
		initTooltipWE(); // init du tooltip sur la page week-end
	}
	
	if($('#hotelServices').length) {
		initTooltipServices(); // init du tooltip services sur la page hotel
	}
		
	if($('#breadcrumbResa').length) {
		initBreadcrumbResa();  // gestion fil d'arianne dans le couloir de resa
	}
		
	if($('#allHotels').length) {		
		if($('#gMapContainer').length) {
			initMap(); // init Gmap sur page tous les hotels			
		}		
		exposeSearchBox(); // init du layer opacite au clic sur "choisir" (page tous les hotels)	
	}
		
	if($('#form_etape1').length) {
		radioChecking();
		//displayResaOption();
		$('#formResa .datePick').datePicker(); //init datepicker 
		autoScrollBarResa();

        $("#valid_etape1").click(function(){
            if($("#form_etape1 input:radio[name=outward]:checked").length!=1) {
                alert('Veuillez sélectionner un trajet aller');
            }
            else if($("#form_etape1 input:radio[name=return]:checked").length!=1) {
                alert('Veuillez sélectionner un trajet retour');
            }
            else {
              $('#form_etape1').submit();  
            }
        });
        
        // Coupon de réduction
        $("#valid_coupon").click(function() {
            var getdata = {coupon:$("#code_coupon").val()};
             $.get('/async/checkbon', getdata, function(data) {
                if(!isNaN(data)) {
                    $('#reduc').val(data);
                    $('#txt_reduc').text(data+'€ de réduction');
                }
                else {
                    alert(data);
                    $('#reduc').val('');
                    $('#code_coupon').val('');
                    $('#coupon').val('');
                    $('#txt_reduc').text('');
                }
                updateTotal();
            }, 'html');
            return false;
        });
	}
    
    if($('#form_londonbox').length) {
      
        $("#valid_londonbox").click(function(){
            var quantite = $("#form_londonbox #quantity").val();
            if(isNaN(parseInt(quantite))) {
                alert('Veuillez sélectionner la quantité de LondonBox que vous souhaitez réserver');
            }
            else {
              $('#form_londonbox').submit();  
            }
        });
        
        // Coupon de réduction
        $("#valid_coupon").click(function() {
            var getdata = {coupon:$("#code_coupon").val()};
             $.get('/async/checkbon', getdata, function(data) {
                if(!isNaN(data)) {
                    $('#reduc').val(data);
                    $('#txt_reduc').text(data+'€ de réduction');
                }
                else {
                    alert(data);
                    $('#reduc').val('');
                    $('#code_coupon').val('');
                    $('#coupon').val('');
                    $('#txt_reduc').text('');
                }
            }, 'html');
            return false;
        });
             
    }
    
    // Prestations annexes en option
    if($('.optionsDispo').length) {
        if($('dd.resaOption input.datePick').length) {
            $('dd.resaOption input.datePick').change(function() {
                var parent = $(this).parents('dl.accomodation:eq(0)');
                var id_prest = parent.find('#prestation').val();
                parent.find('dd.price').html('<img src="/images/common/loader.gif" />');
                var getdata = {date:$(this).val(), id_prest:id_prest, id_param0:parent.find('#param-'+id_prest+'-0').val(), id_param1:parent.find('#param-'+id_prest+'-1').val()};
                 $.get('/async/getprestationprice', getdata, function(data) {
                    parent.find('dd.price').html(data.price);
                    $("#prestTotal-"+id_prest).val(data.total);
                    updateTotal();
                }, 'json');
            });
        }
        $('.optionsDispo .chooseThis').click(function(){
            var parent = $(this).parents('dl.accomodation:eq(0)');
            var id_prest = parent.find('#prestation').val();
            if($("#prestationStatut-"+id_prest).val()==0) {
                $(this).text('supprimer cette option');
                $("#prestationStatut-"+id_prest).val(1);
            }
            else {
                $(this).text('reserver cette option');
                $("#prestationStatut-"+id_prest).val(0);
            }
            updateTotal();
            return false;
        });
    }
    
    // Envoi documents Voyage
    $('#document input[name=docDelivery]').click(function() {
        var price =$(this).attr('price');
        var id = $(this).val();
        $(this).parent('p').find('span.priceInfo').text('Inclus');
        $('#document input[name=docDelivery]').each(function(index){
            if($(this).val()!=id) {
                var itemprice =$(this).attr('price');
                var delta = itemprice - price;
                $(this).parent('p').find('span.priceInfo').text(delta+'€');
            }
            else if(index==0) $(this).parent('p').find('span.priceInfo').text('Offert');
        })
        updateTotal();
    });
    
    // Assurance
    $('#assurance input[name=assurance]').click(function() {
        var price =$(this).attr('price');
        //var id = $(this).val();
        if($(this).is(':checked')) $(this).parent('p').find('span.priceInfo').text('Inclus');
        else $(this).parent('p').find('span.priceInfo').html(price+'€ <small>par personne</small>');
        updateTotal();
    });
        
	
	if($('.alertBoxLink').length) {
		alertBox(); //alert box au clic sur "choisir" fiche sejour 
	}
	
    if($('#nbrRooms').length) {
        initConfigRoom(); // init du formulaire de configuration des chambres
    }
    
	if($('#ficheHotel').length) {
		showSelectsCalculator(); 
		colorSelectedPrice();
		if($('#roomConfig').length) {
			displayRoomConfig(); // affichage du bloc de configuration des chambres
		}
        $("#config_sejour").validationEngine({
            inlineValidation: true, success :  function() {
                    loadPrice();                    
                }, failure : false
        });
                    
        if($("#calcPrice_nbAdult").val()>0 && $("#calcPrice_dateDep").val().match(/^(\d{1,2}\/){2}\d{4}$/)) {
            loadPrice();
        }
	}
	
	if($('#eventCalendar').length) {
		hoverCalendar();
	}
	
	if($('#allResa').length) {
		initTableResa();
	}
    
    $('#type').change(function(){
        var query=window.location.search.substring(1);
        var vars = query.split("&");
        var newquery = '';
        for (var i = 0; i < vars.length; i++) {  
            var pair = vars[i].split("=");  
            if(pair[0]!='type') newquery+= pair[0]+'='+pair[1]+'&'; 
        }
        window.location.href = '/recherche?'+newquery+'type='+$(this).val();
    });
    
    $("#filterByCat, #filterByLabel").change(function(){
        initMap();
    });
	 
	/* ----------- CUFON FONT REPLACEMENT -----------*/
	if(document.getElementsByTagName('h2')) {
	Cufon.replace('h2');
	}		  
});


/*:::::::: FONCTIONS ::::::::*/
function lastItemMenu() {
	$('#mainMenu > li:last-child').addClass('lastItem');
}

//'#searchResults .filter a , #detailSlider > li .filterHotel a , #allHotels .filter a'
function toggleFilterPict() {
	$('#searchResults .filter a').click(function() {
		$(this).toggleClass('sortDecrease');
        if($(this).attr("class")=='sortDecrease') $('#searchResults ul li').sort(sortAlpha).appendTo('#searchResults ul');
        else $('#searchResults ul li').sort(sortAlphaDesc).appendTo('#searchResults ul');
		return false;
	});
}

$.fn.sort = function() {
   return this.pushStack( [].sort.apply( this, arguments ), []);
 };
 
function sortAlpha(a,b){  
    return $(a).find("span.price em").text() > $(b).find(".price em").text() ? 1 : -1;  
}
function sortAlphaDesc(a,b){  
    return sortAlpha(b,a);
}

/*gestion des select d'age des enfants dans le moteur de resa*/
function showSelects() {
	$('#searchBox .childAge').hide();	
			
	$('#searchBox #nbChild').change( function(){
		var kidNumber = this.options[this.selectedIndex].value;
		if(kidNumber != 0) {
			$('#searchBox .childAge').show();
			$('#searchBox .childAge select').hide();
            for(var i=1; i<=kidNumber; i++)	$('#ageChild'+i).show();			
		}	
		else {
			$('#searchBox .childAge').hide();
		}
	});
} 

/*gestion des select d'age des enfants dans le claculateur de prix*/
function showSelectsCalculator() {
	$allSelects = $('#calcPrice_ageChild1 , #calcPrice_ageChild2 , #calcPrice_ageChild3 , #calcPrice_ageChild4');
	$allSelects.hide();	
			
	$('#calcPrice_nbChild').change( function(){
		var kidNumber = this.options[this.selectedIndex].value;
		if(kidNumber != 0) {	
			$allSelects.hide();
            for(var i=1; i<=kidNumber; i++) $('#calcPrice_ageChild'+i).show();
		}	
		else {
			$allSelects.hide();
		}
	});
} 

/*coloration des prix choisis - fiche hotel + affichage du détail du tarif */
function colorSelectedPrice() {
	$('#ficheHotel table.selectRoomPrice td input[checked]').parent().addClass('selected');
	$('#ficheHotel table.selectRoomPrice td input[type="radio"]').click(function() {
        
		$(this).parent('td').siblings('td').removeClass('selected').parent('tr').siblings('tr').find('td').removeClass('selected');		
		$(this).parent('td').addClass('selected');
        $("#formPrice #ISOdateDep").val($(this).attr('date'));
        $("#formPrice #id_category").val($(this).attr('id_category'));
        $("#detailPrice").html('<div style="min-height:130px; width:40px; margin:auto; padding:30px;"><img src="/images/common/loader.gif" /></div>');
        var info = {date:$(this).attr('date'), id_category:$(this).attr('id_category'), id_hotel:$('#id_hotel').val(), id_sejour:$('#id_sejour').val()};
        $.get('/async/getdetailprice', info, function(data) {
            $("#detailPrice").html(data);
            
            $.get('/async/getroomconfig', null, function(data) {
                $("#formRoomConfig").html(data);
                initConfigRoom();
            }, 'html');
            
            return false;
            //colorSelectedPrice();
        }, 'html');

	});
}

function initConfigRoom() {
    /*
    $("#formRoomConfig").submit(function(){
        checkRooms();  
        return false;
    });*/
    $("#room_category").change(function(){
        $("select[name=room\[\]]'").each(function() {
            var id_category = $("#room_category").val();
            var chbrType= $(this).val();
            var nbChildMax = Acat[id_category]['nbrChild'+chbrType];
            var capaciteTxt = 'Capacité maximum de la chambre : jusqu\'à '+chbrType+' adulte';
            if(chbrType>1) capaciteTxt+= 's';
            capaciteTxt+=' et '+nbChildMax+' enfant';
            if(nbChildMax>1) capaciteTxt+= 's';
            $(this).parent('p').find('span.maxSizeInfo').html(capaciteTxt);
        })
    });
    initRooms();
    $("#nbrRooms").change(function(){
       var newNbrRooms = $(this).val();
       var actualNbrRooms = $("#formRoomConfig div").length;
       if(newNbrRooms < actualNbrRooms) {
           $("#formRoomConfig div:gt("+(newNbrRooms-1)+")").remove();
       }
       else if(newNbrRooms > actualNbrRooms) {
           
           var nbChildMax = Acat[$("#room_category").val()]['nbrChild1'];
           var capaciteTxt = 'Capacité maximum de la chambre : jusqu\'à 1 adulte et ';
           capaciteTxt+=' et '+nbChildMax+' enfant';
           if(nbChildMax>1) capaciteTxt+= 's';
           
           for(var i=actualNbrRooms; i < newNbrRooms; i++ ) {
               $("#formRoomConfig div:eq(0)").clone(true).insertBefore("#endRommConfig");
               $("#formRoomConfig div:eq("+i+") strong").html('Chambre '+(i+1)+' :');
               $("#formRoomConfig div:eq("+i+") select[name=room\[\]] option:first").attr('selected', 'selected');
               $("#formRoomConfig div:eq("+i+") select#nbAdult option:gt(1)").remove();
               $("#formRoomConfig div:eq("+i+") select#nbAdult option:eq(1)").attr('selected', 'selected');
               $("#formRoomConfig div:eq("+i+") select#nbChild option:gt(1)").remove();
               $("#formRoomConfig div:eq("+i+") select#nbChild option:first").attr('selected', 'selected');
               $("#formRoomConfig div:eq("+i+")").find('span.maxSizeInfo').html(capaciteTxt);
           }
       }
       initRooms();
    });
}

function initRooms() {
    $("select[name=room\[\]]'").change(function(){
         var id_category = $("#room_category").val();
         var chbrType= parseInt($(this).val());
         var nbChildMax = parseInt(Acat[id_category]['nbrChild'+chbrType]);
         var capaciteTxt = 'Capacité maximum de la chambre : jusqu\'à '+chbrType+' adulte';
         if(chbrType>1) capaciteTxt+= 's';
         capaciteTxt+=' et '+nbChildMax+' enfant';
         if(nbChildMax>1) capaciteTxt+= 's';
         $(this).parent('p').find('span.maxSizeInfo').html(capaciteTxt);
         var parentdiv = $(this).parents('div:eq(0)');
         parentdiv.find("#nbAdult option").remove();
         for(var c=0; c<=chbrType; c++) parentdiv.find("#nbAdult").append($('<option></option').val(c).html('0'+c));
         parentdiv.find("#nbAdult option:last").attr('selected', 'selected');
         parentdiv.find("#nbChild option").remove();
         for(var c=0; c<=(chbrType+nbChildMax); c++) parentdiv.find("#nbChild").append($('<option></option').val(c).html('0'+c));
    });
}

/*affichage du bloc de modification de config des chambres*/
function displayRoomConfig() {
	$roomConfigBloc = $("#roomConfig");
	$roomConfigBloc.hide();
	
	$('#ficheHotel a.changeRoomConfig').click( function() {
		$roomConfigBloc.slideToggle();
		return false;
	});
}

/*Gestion des blocs deroulants sur les fiches sejours */
function detailSlider() {
	$contentSlider = $('#detailSlider > li > .contentSlider');
	$sliderTrigger = $('#detailSlider > li > h4');
	$filterHotel = $('#detailSlider > li > .filterHotel');
	$contentSlider.hide();
	$filterHotel.hide();
	$('#openIt').show().prev('h4').addClass('active').siblings('.filterHotel').show(); //ouverture par defaut
	
	if($('#openIt #gMapContainer').length) {
		initMap(); // init Gmap sur detailSlider si l'onglet de la carte est ouvert par defaut
	}
	
	$sliderTrigger.click(function() {				
		if ($(this).next(".contentSlider:visible").length != 0) {
            $(this).removeClass("active").next(".contentSlider").slideUp("normal");
			$filterHotel.hide();
		}
		else {
            $contentSlider.slideUp("normal");
			$sliderTrigger.removeClass("active");
			$filterHotel.hide();
            $(this).addClass("active").next(".contentSlider").slideDown("normal");						
			$(this).siblings('.filterHotel').show();			
        }	
		if($('#gMapContainer').length) {
			initMap(); // init Gmap sur detailSlider	(a lancer apres la construction du detailSlider si Gmap cache par defaut)	
		}
	});
}

/*Ajout automatique d'une scrollbar si plus de 3 hotels dans la liste des hotels proposes dans la fiche séjour*/
function autoScrollBar() {
	$('#detailSlider > li div.contentSlider').each(function() {
		var nbHotel = $(this).children('dl.accomodation').length;
		if(nbHotel > 3) {		
			$(this).addClass('autoScrollBar');
		}
	});	
}

/*Ajout automatique d'une scrollbar si plus de 2 options inclus dans le forfait dans la fiche séjour*/
function autoScrollBarPresta() {
	$('#detailSlider > li div.contentSlider').each(function() {
		var nbPresta = $(this).children('dl.prestaInclus').length;
		if(nbPresta > 2) {		
			$(this).addClass('autoScrollBar');
		}
	});
}

/*Ajout automatique d'une scrollbar si plus de 2 options disponibles dans le recap de resa*/
function autoScrollBarResa() {
	$('#formResa .optionsDispo').each(function() {
		var nbOptions = $(this).children('dl.accomodation').length;
		if(nbOptions > 2) {				
			$(this).addClass('autoScrollBarResa');
		}
	});
}

/*Init carousel fiche sejour*/
function initCarousel() {
    if($("#carouselContainer .carousel_outer ul li").length == 0) return;
	 $("#carouselContainer .carousel_outer").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
		visible: 4
		//circular: false 
    });
	
	$("#carouselContainer .carousel_outer li img").click(function() {
		$("#carouselContainer #placeholder").attr("src", $(this).attr("src"));
	});
} 


/*Init carousel homepage*/
function initCarBestSellers() {
	 $("#carousel_bestSellers .carousel_outer_bestSellers").jCarouselLite({
        btnNext: ".nextHome",
        btnPrev: ".prevHome",		
		visible: 3
		//circular: false 
    });
	
	$itemBestSellers = $('#carousel_bestSellers .carousel_outer_bestSellers li');
	var display_timeout = 0;
	
	/*gestion du calque au survol des items de carousel*/
	$itemBestSellers.hover(function() {
		if(display_timeout != 0) {
				clearTimeout(display_timeout);
		}
		var this_element = this;
		display_timeout = setTimeout(function() {
			display_timeout = 0;		
			$(this_element).find('.bestSellerImg').stop().fadeTo("normal", 0.3 , function() {
				$(this_element).children('span.details').show();
			});			
			}, 250);	
	},function() {
		if(display_timeout != 0) {
				clearTimeout(display_timeout);
			}
		$itemBestSellers.children('span.details').hide();
		$('.bestSellerImg').stop().fadeTo("fast", 1);
	});
	
	/*clic sur le calque recupere le lien autour de l'image*/	
	$itemBestSellers.children('span.details').click(function() {
		window.location=$(this).prev('a').attr("href");
		return false;
	});
}

/*Tooltip page Week end*/
function initTooltipWE() {	
	$('#themeWeekend li img').tooltip({ 
		track: true, 
		delay: 0, 
		showURL: false, 
		showBody: " - ", 
		left: 15 
	});
} 

/*Tooltip Services fiche hotel*/
function initTooltipServices() {	
	$('#hotelServices li > img').tooltip({ 
		track: true, 
		delay: 0, 
		showURL: false, 
		showBody: " - ", 
		extraClass: "tipServices",
		left: 7 
	});
} 

/*simile le clic sur les images avec tooltip pour IE6 / IE7*/
function clickOnTooltip() {
	$("#themeWeekend li img").click(function(){
		window.location=$(this).parent('span').parent('a').attr("href");
		return false;
	});
}

/*Fil d'arianne couloir de resa : ajout dynamique d'une class en fonction du li qui a la class .current*/
function initBreadcrumbResa() {
	$crumbResa = $('#breadcrumbResa');
    $crumbResa.children('li').each(function(i){
        if($(this).hasClass('current')) {
            $crumbResa.addClass('current'+(i+1));
        }
    })  
}

/*mise en avant visuelle des options de reservation*/
function radioChecking() {
	$('#formResa fieldset.bigRadios input[checked]').parent().addClass('selected');
	$('#formResa fieldset.bigRadios input[type="radio"]').click(function() {
		$(this).parent('p').siblings('p').removeClass('selected');
		$(this).parent('p').addClass('selected');
	});
}

/*layer d'opacite pour mettre en avant le Moteur Recherche*/
function exposeSearchBox() {   
    $(".chooseThis").click(function() {   		
        $('#searchBox').expose({api: true}).load();  		
	}); 
}

/*alert Box - fiche séjour*/
function alertBox() {

   $('.alertBoxLink').click(function (e) {
       e.preventDefault();
       var blocToShow = $(this).attr('href').split('#');          
       $("#"+blocToShow[1]).modal();
       return false;
   });
}

/*resa etape 1 - affichage bloc resa des options au clic sur choisir
function displayResaOption() {
	$resaOptions = $('#formResa .optionsDispo dd.resaOption');
	$resaOptions.hide();
	
	$('#formResa .optionsDispo .chooseThis').click(function() {		
		$(this).parent('dd').next('dd.resaOption').slideToggle();		
		return false;
	});
}*/

/*hover d'une cellule du calendrier contenant un lien vers un evenement*/
function hoverCalendar() {
	$('#eventCalendar td').each(function() {
		if($(this).children('a').length) {
			$(this).hover(function() {
				$(this).addClass('hovered');
			},function(){
				$(this).removeClass('hovered');
			});
		}
	});
}

/*caher / deplier de la page reservation - mon compte*/
function initTableResa() {
	$('#allResa tr.detailedRecap td .recapContainer').hide();
	$('#allResa tr.detailedRecap td:last').addClass('lastTd');
	$('#allResa tr:not(.detailedRecap)').click(function() {
		$('#allResa tr').removeClass('active');
		$('#allResa tr.detailedRecap td .recapContainer').slideUp();
		$(this).next('tr.detailedRecap').find('.recapContainer:hidden').slideToggle('normal' , function() {
			$(this).parent('td').parent('tr').prev('tr').addClass('active');
		});		
	});
}

/*Menu for IE6 / IE7*/
sfHover = function() {
	var sfEls = document.getElementById("mainMenu").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {			
			this.className+=" sfhover";			
		}
		sfEls[i].onmouseout=function() {			
			this.className=this.className.replace(new RegExp("sfhover\\b"), "");
		}
	}
}


/*GOOGLE MAPS*/
function initMap() {
	var map = new google.maps.Map2(document.getElementById("gMapContainer"));
	map.setCenter(new google.maps.LatLng(51.500152,-0.126236), 13);
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GMapTypeControl());

	// custom markers Welondres
	var WelondresIcon = new GIcon(G_DEFAULT_ICON);
	WelondresIcon.image = "/images/common/gMap_marker.png";
	WelondresIcon.shadow = "/images/common/shadow50.png";
	WelondresIcon.iconSize = new GSize(20, 34);
	WelondresIcon.shadowSize = new GSize(37, 34);

	// Set up our GMarkerOptions object
	markerOptions = { icon:WelondresIcon };
	
   
    //Array des markers
    var hotelMarkers = [];
    var markerProduct = [];
    
    map.clearOverlays();
    var bounds = new GLatLngBounds;
    
    var cat = $("#filterByCat").val();
    var typo = $("#filterByLabel").val();

    var j = 0;
    $(".gMap_infoWindow").each(function(i) {
        id_product = this.getAttribute('id_product');
        if(cat && cat!='' && cat!=this.getAttribute('cat')) {
            $("#detail_"+id_product).css('display', 'none');
            return true;
        }
        var Atypo = this.getAttribute('ids_typo').split(',');
        if(typo && typo!='0' && $.inArray(typo, Atypo) == -1) {
            $("#detail_"+id_product).css('display', 'none');
            return true;
        }
        
        hotelMarkers[j] = new GMarker(new GLatLng(this.getAttribute("lat"), this.getAttribute("lng")), markerOptions);
        bounds.extend(hotelMarkers[j].getLatLng());
        map.addOverlay(hotelMarkers[j]);
        markerProduct[j] = id_product;
        $("#detail_"+id_product).css('display', 'block');
        j++;
            
    });

    if(hotelMarkers.length==0) map.setCenter(new google.maps.LatLng(51.500152,-0.126236), 13);
    else if(hotelMarkers.length==1) map.setCenter(hotelMarkers[0].getLatLng(), 13);
    else {
      map.setZoom(map.getBoundsZoomLevel(bounds));
      map.setCenter(bounds.getCenter());
    }
	
    $(hotelMarkers).each(function(i,marker){
        GEvent.addListener(marker, "click", function() {
            map.savePosition();
            
            var pt = map.fromLatLngToContainerPixel(marker.getLatLng());
            var mapSW = map.fromLatLngToDivPixel(map.getBounds().getSouthWest());
            var mapNE = map.fromLatLngToDivPixel(map.getBounds().getNorthEast());
            panX = (Math.round(mapNE.x/2) - 20 - pt.x);
            panY = (240 - pt.y);

            map.panBy(new GSize(panX,panY));
            
            $(".gMap_infoWindow").hide();  
            $("#infoWindow_"+markerProduct[i]).appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));    
               var markerOffset = map.fromLatLngToDivPixel(marker.getPoint());
            $("#infoWindow_"+markerProduct[i]).show().css({ top:markerOffset.y - 215, left:markerOffset.x -58 });
        });  
    });
    
    GEvent.addListener(map, 'dragend', function(){
        redraw();
    });
    
    GEvent.addListener(map, 'zoomend', function(){
        redraw();
    });
    
    function redraw() {
        $(".gMap_infoWindow").hide();
        
        if($('.allHotelsList').length) {
            var Zbounds = map.getBounds();
            
            $(".gMap_infoWindow").each(function(i) {
                id_product = this.getAttribute('id_product');
                if(cat && cat!='' && cat!=this.getAttribute('cat')) {
                    $("#detail_"+id_product).css('display', 'none');
                    return true;
                }
                var Atypo = this.getAttribute('ids_typo').split(',');
                if(typo && typo!='0' && $.inArray(typo, Atypo) == -1) {
                    $("#detail_"+id_product).css('display', 'none');
                    return true;
                }
                if(!Zbounds.containsLatLng(new GLatLng(this.getAttribute("lat"), this.getAttribute("lng")))) {
                    $("#detail_"+id_product).css('display', 'none');
                    return true;
                }
                $("#detail_"+id_product).css('display', 'block');                    
            });
            
        }
        return false;
    }
  
	//fermeture des infos window au clic
	$('.closeWindow').click(function() {
        map.returnToSavedPosition();
		$(".gMap_infoWindow").hide();  
		return false;
	});
}


function subscribe() {    
    $.get('/async/subscribe', {address:$('#emailNewsletter').val()}, function(data) {
        $("#alertBox p").html(data);
        $('#alertBox').modal({position: ["50%","15%"]});
        $('#emailNewsletter').val('');
    }, 'html');
}

function find_password() {    
    $.get('/async/password', {address:$('#forgotPass_email').val()}, function(data) {
        $("#form_forgottenPass").html(data);
        return false;
    }, 'html');
}

function searchForm() {
    return true;
}

function loadPrice() {
    
    $("#formPrice").html('<div style="min-height:330px; width:40px; margin:auto; padding:30px;"><img src="/images/common/loader.gif" /></div>');
    $.get('/async/getformprice', $('#config_sejour').serializeArray(), function(data) {
        $("#formPrice").html(data);
        colorSelectedPrice();
        $('#ficheHotel a.changeRoomConfig').click( function() {
            $roomConfigBloc.slideToggle();
            return false;
        });
        $.get('/async/getroomconfig', null, function(data) {
            $("#formRoomConfig").html(data);
            initConfigRoom();
        }, 'html');
    }, 'html');
}

function checkRooms() {

    var adultTot = $("#calcPrice_nbAdult").val();
    var childTot = $("#calcPrice_nbChild").val();
    var adult = 0;
    var child = 0;
    
    var id_category = $("#room_category").val();
    
    $("#formRoomConfig select[name=room\[\]]'").each(function(index) {
         var chbrType= parseInt($(this).val());
         var nbChildMax = Acat[id_category]['nbrChild'+chbrType];
         var nbAdultForRoom = parseInt($(this).parents('div:eq(0)').find("#nbAdult").val());
         var nbChildForRoom = parseInt($(this).parents('div:eq(0)').find("#nbChild").val());
         adult+= parseInt(nbAdultForRoom);
         child+= parseInt(nbChildForRoom);
         
         if(nbAdultForRoom > chbrType) {
             alert('Le nombre d\'adultes est supérieur à la capacité maximale de la chambre '+(index+1));
             return false;
         }
         
         if(nbChildForRoom > (nbChildMax+(chbrType-nbAdultForRoom))) {
             alert('Le nombre d\'enfants est supérieur à la capacité maximale de la chambre '+(index+1));
             return false;
         }
         
         var capaciteTxt = 'Capacité maximum de la chambre : jusqu\'à '+chbrType+' adulte';
         if(chbrType>1) capaciteTxt+= 's';
         capaciteTxt+=' et '+nbChildMax+' enfant';
         if(nbChildMax>1) capaciteTxt+= 's';
         $(this).parent('p').find('span.maxSizeInfo').html(capaciteTxt);
    });
    
    if(adult!=adultTot) {
        alert('Le nombre d\'adultes dans la configuration des chambres est différent du total d\'adulte');
        return false;
    }
    if(child!=childTot) {
        alert('Le nombre d\'enfants dans la configuration des chambres est différent du total d\'enfant');
        return false;
    }
        
    $.get('/async/getformprice', $("#formRoomConfig").serializeArray(), function(data) {
        $("#formPrice").html(data);
        colorSelectedPrice();
        /*$('#ficheHotel a.changeRoomConfig').click( function() {
            $roomConfigBloc.slideToggle();
            return false;
        });*/
    }, 'html');
    return false;
}

function updateTotal() {
    
    var nbAdult = parseInt($('#nbAdult').val());
    var nbChild = parseInt($('#nbChild').val());
    var nbPers  = nbAdult + nbChild;
    
    var total = 0;
    // total forfait
    total+= parseInt($('#totalForfait').val());
    
    // Bon de réduc ?
    var reduc = $('#reduc').val();
    if(!isNaN(reduc) && reduc!='') {
        total-=parseInt(reduc);
    }

    $(".optionsDispo input[name=prestation\[\]]").each(function() {
        var id_prest = $(this).val();
        if($("#prestationStatut-"+id_prest).val()==1) {
            var totalPrest = parseInt($("#prestTotal-"+id_prest).val());
            total+=totalPrest;
        }
    });
    
    var delivery = parseInt($('fieldset#document input[name=docDelivery]:checked').attr('price'));
    total+=delivery;
    
    if($('#assuranceAnnul').is(':checked')) {
        var assurance = parseInt($('#assuranceAnnul').attr('price'));
        total+=assurance * nbPers;
    }
    
    
    if(!isNaN(total)) $("#total").text(total+'€');
    else $("#total").text("Prix en demande");
    
}

function check_formPrice() {
    if($('input[type=radio][name=selectRoomPrice]:checked').length==0) {
        alert('Vous devez sélectionner une date de départ en cochant un bouton radio dans le tableau');
        return false; 
    }
    else return true;
}