/*******************************************************
 * NouvellesAntilles.com                               *
 * Authors: F.Delaneau, JM.Kawamura, P.Jimenez         *      
 * Last Uptade: 2008/04/01                             *
 *******************************************************/
var markersArray = [];

var bestRatesRowHeight;

$(document).ready(function(){     
	    //AN 5/14/2011 Adding Homepage Slide Buttons
    if($("select#datesflexible").length > 0 && $("select#datesflexible").selectToUISlider !== undefined){
        //datesflexible
        $("#datesflexibleSpan").text($('#datesflexible').val());
        /*
        $("select#datesflexible").selectToUISlider(); */
        var valores = new Array();
        $("select#datesflexible option").each(function(i, k){
            valores.push(k.value);
        });
        var sel = $('select#datesflexible');
        sel.parent().append('<div id="datesflexible_slider"></div>');
        $('#datesflexible_slider').slider({
            min: valores[0],
            max: valores.length-1,
            range: true,
            step: 1,
            range: 'min',
            slide: function(e, ui){
                
                var options = $('#datesflexible option');
                
                $('#datesflexible').val( options[ui.value].value );

                $("#datesflexibleSpan").text( options[ui.value].value );
                
                if($('#dateDepartEntreLe').length > 0) {
                	cc.recherche.updateDates();
                }                

            },
            value: sel.attr('selectedIndex'),
            values: sel.attr('selectedIndex')
        });
    }

    //dureesejour
    if($("select#dureesejourA, select#dureesejourB").length > 0){
        $("#dureesejourASpan").text($('#dureesejourA').val());
        $("#dureesejourBSpan").text($('#dureesejourB').val());
        $("select#dureesejourA, select#dureesejourB").selectToUISlider().next();
        if($('#dureeDeContainer').length > 0){ 
            if($('#dureesejourA').val() == $('#dureesejourB').val()){ 
            	$("#dureeDeContainer").css('visibility', 'hidden'); 
            	$("#rechercheNights").css({paddingRight:'10px', marginLeft: '-10px'}); 
            }
        }        
    }
    
    //calendar Dureesejour
    if($('#calendarDureesejourA').length > 0 && $("select#calendarDureesejourA").selectToUISlider !== undefined){
        var sel = $('select#calendarDureesejourA');
        $("#calendarDureesejourASpan").text($('#calendarDureesejourA').val());
        sel.parent().append('<div id="dureesejour_slider"></div>');

        $("#dureesejour_slider").slider({
            min: 0,
            max: 6,
            range: true,
            step: 1,
            range: 'min',
            slide: function(e, ui){
                
                var options = $('#calendarDureesejourA option');
                
                $('#calendarDureesejourA').val( options[ui.value].value );

                $("#calendarDureesejourASpan").text( options[ui.value].value );
                               
                updateCalendarOnChange();
            },
            value: sel.attr('selectedIndex'),
            values: sel.attr('selectedIndex')        	
        });     
    }
	
    //Budget
    if($('select#budgetValueA, select#budgetValueB').length > 0){
        $("#datesflexibleSpan").text($('#datesflexible').val());
        $("#dureesejourASpan").text($('#dureesejourA').val());
        $("#dureesejourBSpan").text($('#dureesejourB').val());
        $("#budgetValueASpan").text($('#budgetValueA').val());
        $("#budgetValueBSpan").text($('#budgetValueB').val());
        if($('#budgetValueB').val() < 9999){
            $('.show_at_max').addClass('hide');
            $('.hide_at_max').removeClass('hide');
            $("#budgetValueBSpan").text( $('#budgetValueB').val() );
        } else {
            $('.hide_at_max').addClass('hide');
            $('.show_at_max').removeClass('hide');
            $("#budgetValueBSpan").text('');
        }

        $('select#budgetValueA, select#budgetValueB').selectToUISlider();
    }

	//Retrieve initial values for calendar
	if(window.calendar_info){
		var month_selected = $("#monthcombo option[selected]").val();
		
        $('.btnNext').attr('title', $("#monthcombo option:eq(1)").text());
        
		$("#monthcombo option[value='" + month_selected + "']").attr("selected", "selected");
		
		var response = calendar_info;
		calendarInfo(response);          
	}
    if($("#MeilleursTarifs").length){
    	bestRatesRowHeight = visiblePackages / 2;
        bestRatesRowHeight = Math.round(bestRatesRowHeight) * $('#MeilleursTarifs ul').height();
        $('#MeilleursTarifs ul').height(bestRatesRowHeight);        
        //Scripts for Best Rates section 
        $(".best-rates").click(function(){
           if(!parseInt($(this).parent().find('#redirect').val())){
               a = document.getElementById('CalendarWrap-down'); 
               window.scrollTo(0,a.offsetTop);              
           }
 });

        $(".voir-les-autres-tarifs").click(function(){
           if(!parseInt($(this).parent().find('#redirect').val())){           
               a = document.getElementById('CalendarWrap-down'); 
               window.scrollTo(0,a.offsetTop);
           }
        });

        $(".MeilleursPrice").click(function(){
           if(!parseInt($(this).parent().find('#redirect').val())){           
               a = document.getElementById('CalendarWrap-down'); 
               window.scrollTo(0,a.offsetTop);
           }
        });

        $("#moinsSpan").hide();

        $("#moins_criteresMeilleurs").click(function(){
           $("#moinsSpan").hide();
           $("#plusSpan").show();
           $(".hidden_item_li").hide();
           $("#MeilleursTarifs ul").css('height', bestRatesRowHeight + 'px');
           $("#MeilleursTarifs ul").css('overflow', 'hidden');
        });

        $("#plus_criteresMeilleurs").click(function(){
           $("#plusSpan").hide();
           $("#moinsSpan").show();
           $(".hidden_item_li").show();
           $("#MeilleursTarifs ul").css('height', 'auto');
           $("#MeilleursTarifs ul").css('overflow', 'none');
        });         
    }
    if($("#antillesAirports").length>0){
        $("#departureAirport_3, #departureAirport").change(function(){
            toggleTariffButton($(this).val());
        });        
    }
    
    //Day text for date picker in travel search home page
    if($('#datedepart_dayname').length > 0){
    	datePickerDayText();
    }    
});

function datePickerDayText(){
	var date = $(".date-picker-recherche-voyage-hp").val();
	var m = date.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
	d = new Date(m[3],m[2]-1,m[1]);
	var dayNames = ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'];
	if ($("#wrap.it").length > 0) {
	    var dayNames = ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'];
	}
	if ($("#wrap.es").length > 0) {
	    var dayNames = ['Dom', 'Lun','Mar','Mi&eacute;','Jue','Vie','S&aacute;b'];
	}
	$('#datedepart_dayname').text(dayNames[d.getDay()]);	
}

function updateIcons(){
    allCheckedCritereVals=[];

    $("input[name='critere[]']:checked").each(function() {
           allCheckedCritereVals.push($(this).val());   
    });		
    //Post to update icons
    var departuredate = $('#datedepart').val() .split('/');
    var newdepartdate = departuredate[2] + '-' + departuredate[1] + '-' + departuredate[0];
    	    
    $.post("/service/ajax/index.php", { 
        sit_id: eval(window.sit_id)?sit_id:1,
        component: "hebergement_hebergement", 
        action: "ajax_recherche_utils", 
        task: "get_results_icons",
        datedepart: newdepartdate,
        departureAirport: $('#departureAirport').val(),	
        ile_dest_hotel: ''+$("#ile_dest_voyage").val(),
        type_id: ($("#hebergement_type_id").val() ? ''+$("#hebergement_type_id").val() : ''),
        dureesejourA: $('#dureesejourA').val(),
        dureesejourB: $('#dureesejourB').val(),
        datesflexible: $('#datesflexible').val(),
        budgetValueA: $('#budgetValueA').val(),
        budgetValueB: $('#budgetValueB').val(),	        
        commune_id: ($("#commune_id").val() ? ''+$("#commune_id").val() : ''),           
        hebergementNom: $("#hebergementNom").val(),
        recherche_form: 1,
        critere: ''+allCheckedCritereVals,
        actualPage: 1,
        promoOnly: $('#promoOnly').attr('checked')?1:0
        },
        
        function(data){
            var aiId = 0;
            critere = ''+allCheckedCritereVals;
        
            if(data){
                eval( ' json = ' +data);      
                if(json.sum > 0){
                    jQuery.each(json.iconsums, function(i, val) {
                        $("span[name='critere_result_container'][value="+i+"]").html('('+val+')');
                        });
                }else{
                    $("span[name='critere_result_container']").html('(0)');    
                }
                if(json.pensionsums){
                    jQuery.each(json.pensionsums, function(i, val) {
                        $("span[name='pension_result_container'][value="+i+"]").html('('+val+')');              
                    });
                }else{
                    $("span[name='pension_result_container']").html('(0)');    
                }
                if(json.sum){
                    $('#hotels_total').html('('+json.sum+')'); 
                }else{
                   $('#hotels_total').html('(0)'); 
                } 
            }
            
        });   		
}

/* BEGIN delay for extended combo auto close */
var autoCloseTimeOut;
var autoCloseLastClick = null;//Registers the time of the last user activity
function comboDelay(skipDelay){
	//skipDelay: Set to true if you want to skip the timer
	if(skipDelay == true){
		comboClose(skipDelay);
		return;
	}
	date = new Date();            
	autoCloseLastClick = date.getTime();
    clearTimeout(autoCloseTimeOut);
    autoCloseTimeOut = setTimeout("comboClose()", 10000);  
}

function comboClose(skipDelay){
	if(skipDelay==false){
    dateTwo = new Date();
    	if(dateTwo.getTime() - autoCloseLastClick < 19990) return;
	}
    $(".ui-dropdownchecklist-dropcontainer-wrapper").css('top', '-5000px');
    if($(".travelSearchRecherche").length > 0)
    	if($("#datedepart").leght > 0)
    	updateIcons();
}
/* END delay for extended combo auto close */       
        
 //TV 2/2/2011. Hide tariff button if an antilles city is selected. Display it otherwise
function toggleTariffButton(selectedCity){
    var antillesCities = $('#antillesAirports').val().split(",");
    
    inAntilles = false;
    for (n = 0; n < antillesCities.length; n++)
        if (selectedCity == antillesCities[n])
            inAntilles = true;
                  
    if(inAntilles){
        if($('#btn1').is(":visible"))
            $('#btn1, .Ou').hide();        
    }else{
        if(!$('#btn1').is(":visible"))
            $('#btn1, .Ou').css('display', 'block');
    }
}
 
    var Calendar = {
    createCalDay : function(data){

        var dayType = (data['type'] == undefined) ? '' : data['type'];
        var date = (data['date'] == undefined) ? '' : data['date'];
        var content = (data['content'] == undefined) ? '' : data['content'];
        var tooltipContent = (data['tooltip'] == undefined) ? '' : data['tooltip'];
        
        var tooltip = '';
        
        if (tooltipContent.length > 0){
        tooltip = tooltipContent;
        }
        
        if(dayType!=''){
            if(data['thickbox'] == 1){
                content = '<a class="thickbox" href="' + data['form_url'] + '&amp;?#TB_iframe&amp;height=500&amp;width=560"><div class="tsCalendarDay ' + dayType + '">'+tooltip+'<h3 class="' + dayType + '">'+ date +'</h3><div class="tsCalendarDay-DateBody">'+content+'</div></div></a>';                 
            }       
            else{
                content = '<a href="' + data['form_url'] + '"  target="_top"   ><div class="tsCalendarDay ' + dayType + '">'+tooltip+'<h3 class="' + dayType + '">'+ date +'</h3><div class="tsCalendarDay-DateBody">'+content+'</div></div></a>';               
            }                 
        }else{
        content = '<div class="tsCalendarDay ' + dayType + '">'+tooltip+'<h3 class="' + dayType + '">'+ date +'</h3><div class="tsCalendarDay-DateBody">'+content+'</div></div>';
        }
        return content;
    }

};      
function bestRatesInit(){
	  
    if($("#MeilleursTarifs").length){
        $('#MeilleursTarifs ul').height(bestRatesRowHeight);
        //Scripts for Best Rates section 
        $(".best-rates").click(function(){
           if(!parseInt($(this).parent().find('#redirect').val())){
               a = document.getElementById('CalendarWrap-down'); 
               window.scrollTo(0,a.offsetTop);              
           }
	});

        $(".voir-les-autres-tarifs").click(function(){
           if(!parseInt($(this).parent().find('#redirect').val())){           
               a = document.getElementById('CalendarWrap-down'); 
               window.scrollTo(0,a.offsetTop);
	   }
	});

        $(".MeilleursPrice").click(function(){
           if(!parseInt($(this).parent().find('#redirect').val())){           
               a = document.getElementById('CalendarWrap-down'); 
               window.scrollTo(0,a.offsetTop);
	   }
	});

        $("#moinsSpan").hide();

        $("#moins_criteresMeilleurs").click(function(){
           $("#moinsSpan").hide();
           $("#plusSpan").show();
           $(".hidden_item_li").hide();
           $("#MeilleursTarifs ul").css('height', bestRatesRowHeight + 'px');
           $("#MeilleursTarifs ul").css('overflow', 'hidden');
	});

        $("#plus_criteresMeilleurs").click(function(){
           $("#plusSpan").hide();
           $("#moinsSpan").show();
           $(".hidden_item_li").show();
           $("#MeilleursTarifs ul").css('height', 'auto');
           $("#MeilleursTarifs ul").css('overflow', 'none');
        });         
    }
	
   $(".best-rates").each(function(i){
       $(this).click(function(){
			clickedMe(i, $(this).parent().find('#nuits').val());     
	   });
   }); 
   
   $(".MeilleursPrice, .SurMesurePrice").each(function(i){
       $(this).click(function(){
			clickedMe(i, $(this).parent().find('#nuits').val());    
	   });
   });
   
   $(".voir-les-autres-tarifs").each(function(i){
	   $(this).click(function(){            
			clickedMe(i, $(this).parent().find('#nuits').val());    
	   });
   });   
   
   function clickedMe(i, nuits){
		$(".voyageSurMesure").hide();
		$(".dateDeparts").show();
		$("#liDeparts").removeClass();
		$("#liVoyage").addClass("desactivado");
		$("#monthcombo").attr('selectedIndex', i);
		
		$('#CalendarWrap-down-body').css('visibility', 'hidden');
		$('#loading-calendar').show();
					
		switch(parseInt(nuits)){
			case 6:
			case 7:
				$("#dureesejour").attr('selectedIndex', 0);
				break;
			case 8:
			case 9:
				$("#dureesejour").attr('selectedIndex', 1);
				break;
			default:
				$("#dureesejour").attr('selectedIndex', 2);
				break;
		}             
        request('departureAirport_3');         
   }        
	
    
  
 }
//Update calendar
var calendarRequest = null;
function request(comboId){
    if(comboId == '') 
        comboId = 'departureAirport_3';
		var datesplitted = $('#monthcombo').val().split("_");
        var dureesjourA = $('#calendarDureesejourA').val();
        var dureesjourB = dureesjourA;
        if(calendarRequest != null)
            calendarRequest.abort();
        calendarRequest =       
		$.post("/service/ajax/index.php", {
			component: "voyage_voyage", 
			action: "ajaxgetCalendarPackages", 
			//parameters
			liHebergementId: $('#hebergement_id').val(),
			lsDepartureDate: datesplitted[0],
			lsReturnDate: datesplitted[1],
            liNights: dureesjourA,
            liNights2: dureesjourB,
            sit_id: $('#sit_id').val(),
            rewriteurl: $('#rewriteurl').val(),
            voyage_id: $('#voyage_id').val(),
            comp_id: $('#comp_id').val(),
            departureAeroport: $('#' + comboId).val(),
            showBubble: $('#showBubble').val(),
            thickBox: $('#thickBox').val()
			},
			
			function(data){
				if(data){
					$('#CalendarWrap-down-body').css('visibility', 'hidden');
					$('#loading-calendar').show();
                    toggleNavigationButtons();
                    updateNavigationButtonsText(); 
                    eval('result = ' + data);
					$('#CalendarWrap-down-body').html('');
					for (index in result){
							$('#CalendarWrap-down-body').append(Calendar.createCalDay(result[index]));
						}    
					TooltipBubble();
					TB_init();
					$('#loading-calendar').hide();
					$('#CalendarWrap-down-body').css('visibility', 'visible');
				}                                
			});            
	}    
function updateCalendarOnChange(){
    if($("#monthcombo").length > 0) { //If we're in the calendar
       $('#CalendarWrap-down-body').css('visibility', 'hidden');
       $('#loading-calendar').show();
       request('departureAirport_3');
    }
}
 function calendarInfo(response) {
//Fiche Calendar Code
    bestRatesInit();      
    toggleTariffButton($("#departureAirport_3").val());      
	
    $(".btnVoyage").click(function(){
        $(".dateDeparts").hide();
        $(".voyageSurMesure").show();
        $("#calendarNavDown").hide();
        $("#liDeparts").addClass("desactivado");
        $("#liVoyage").removeClass();
    });
    
    $(".btnDeparts").click(function(){
        $(".voyageSurMesure").hide();
        $(".dateDeparts").show();
        $("#liDeparts").removeClass();
        $("#liVoyage").addClass("desactivado");
         $("#calendarNavDown").show();
    });
    
    //Calendar navigation  
    $(".btnBack").click(function(){
       var selected = $("#monthcombo").attr('selectedIndex');
       if(selected !=0){
           $('#CalendarWrap-down-body').css('visibility', 'hidden');
           $('#loading-calendar').show();
           $("#monthcombo").attr('selectedIndex', selected - 1);
           request('departureAirport_3');  
       }
         
    });
	
    $(".btnNext").click(function(){
       var selected = $("#monthcombo").attr('selectedIndex');
       if(selected != (math_months-1)){
           $('#CalendarWrap-down-body').css('visibility', 'hidden');
           $('#loading-calendar').show();
           $("#monthcombo").attr('selectedIndex', selected + 1);
           request('departureAirport_3');
           
       }
    });

    //Selection combos
    $("#monthcombo, #dureesejourA, #dureesejourB, #departureAirport_3").change(function(){
        updateCalendarOnChange();
    });
    // Old code of the calendar
    /* $("#monthcombo, #dureesejour, #departureAirport_3").change(function(){
        if($(this).attr('id')=='monthcombo'){ 
        }        
       $('#CalendarWrap-down-body').css('visibility', 'hidden');
       $('#loading-calendar').show();
       request('departureAirport_3');
    }); */
   
    $("#departureAirport_3, #departureAirport").change(function(){

       try{
           var loadingBestRatesPos = $('#MeilleursTarifs h3:first').position().top + 40; //40px offset   
       }
       catch(e){
           var loadingBestRatesPos = 0;
       }
       
       if(loadingBestRatesPos > 0) {
            $('#loading-best-rates').css('top', loadingBestRatesPos + 'px' );
            $('#loading-best-rates').show();
            $('#MeilleursTarifs ul').css('visibility','hidden');
            $("#moinsSpan").css('visibility','hidden');
            $("#plusSpan").css('visibility','hidden');
       }

       comboId = $(this).attr('id');

       $('#CalendarWrap-down-body').css('visibility', 'hidden');
       $('#loading-calendar').show();
       
       request(comboId);
       updateBestRates(comboId);
       toggleTariffButton($(this).val());
    });     
    
    function updateBestRates(comboId){
        if(comboId == '')
            comboId = 'departureAirport_3';
        
        $.post("/service/ajax/index.php", {
            component: "hebergement_hebergement", 
            action: "ajaxGetBestRates", 
            //parameters
            liHebergementId: $('#hebergement_id').val(),
            sit_id: $('#sit_id').val(),
            voyage_id: $('#voyage_id').val(),
            comp_id: $('#comp_id').val(),
            departureAeroport: $('#' + comboId).val(),
            rewriteurl: $('#rewriteurl').val()
            },
            
            function(data){
                if(data){
                   //If data is empty, dont destroy the container ('#MeilleursTarifs') so it doesnt brake the whole code
                   if($.trim(data) == ''){
                       data = '<div id="MeilleursTarifs" style="visibility: hidden;"><div id="loading-best-rates"><img src="/theme_front/theme_front_5/image/photo_gallery/lightbox-ico-loading.gif" alt="ACTUALISATION EN COURS..." width="24" height="24"><p><span>ACTUALISATION EN COURS...</span></p></div></div>';
                   }
                   
                   $('#MeilleursTarifs').css('visibility','hidden');
                   $('#loading-best-rates').show();
                   
                   $('#MeilleursTarifs').replaceWith(data);                    
                        
                   bestRatesInit();

                   $('#loading-best-rates').hide(); 
                }
            });
    }
    
    for (index in response){
       $('#CalendarWrap-down-body').append(Calendar.createCalDay(response[index]));
    }
     
     TooltipBubble();                                                                     
};

/**
 * Updates title attribute in navigation buttons
 * @author TV 14/02/2011
 */
 function updateNavigationButtonsText(){
     var selectedIndex = $("#monthcombo").attr('selectedIndex');
     var next = selectedIndex + 1;
     var previous = selectedIndex - 1; 
     $(".btnNext").attr('title', $("#monthcombo option:eq(" + next + ")").text());
     $(".btnBack").attr('title', $("#monthcombo option:eq(" + previous + ")").text());
 }
 
 /**
 * Display/hide navigation buttons
 * @author TV 14/02/2011
 */
 function toggleNavigationButtons(){
    var selectedIndex = $("#monthcombo").attr('selectedIndex');
    if(selectedIndex== 0){
        $('.btnBack').hide();
        if(!$('.btnNext').is(":visible")){
            $('.btnNext').css('display', 'block');
        }
    }else{
         if(selectedIndex == (math_months-1)){
             $('.btnNext').hide();
             if(!$('.btnBack').is(":visible")){
                $('.btnBack').css('display', 'block');                    
             }                
         }else{
              if(!$('.btnBack').is(":visible")){
                $('.btnBack').css('display', 'block');                    
             }
            if(!$('.btnNext').is(":visible")){
                $('.btnNext').css('display', 'block');
            }                                       
         }            
    }        
 }
 
function TooltipBubble(){
	$('.tsCalendarDay').each(function(){
		if ($(this).find('.TooltipBubble').length > 0){
            var bubble = $(this).find('.TooltipBubble');
			$(this).mouseover(function(){
				$(this).find('.TooltipBubble').show();
			});
			$(this).mouseout(function(){
				$(this).find('.TooltipBubble').hide();
			});
            $(this).find('.TooltipBubble').mousemove(function(){
                $(this).hide();
            });
		}
	});    
}
				   
//End Fiche Calendar Code

// pop-up     

$(document).ready( function() {
		$("a.popup").bind("click", function() {
				window.open(this.href);
				return false;
		});
});

$(document).ready( function() {
	$("input[name='pension[]']").change( function() {
		var n = $("input[name='pension[]']:checked").length;
		if(n==0){$(this).attr('checked', true); }
	});
});

// toggles
$(document).ready( function() {
		var div_toggle = new Array();
		$("div.toggle").each( function(i) {
				div_toggle.push($(this));
				var classe_toggle = "toggle-on";
				if ($("div.toggle")[i].className.search(/on/) != -1 || $("div.toggle")[i].className.search(/off/) != -1) {
						//La position du toggle est precisee
						if($("div.toggle")[i].className.search(/off/) != -1) {
								classe_toggle = "toggle-off";
								$("div:first", div_toggle[i]).css("display", "none");
						}
				} else {
						// default behavior
						if(i > 0 || $("div.toggle").length == 1) {
								classe_toggle = "toggle-off";
								$("div:first", div_toggle[i]).css("display", "none");
						}
				}
				$("*:first", $(this)).addClass("toggle").addClass(classe_toggle).click( function() {
						$("div:first", div_toggle[i]).slideToggle(100, function() {
								switch($("div:first", div_toggle[i]).css("display")) {
										case "none":
												$("*:first", div_toggle[i]).removeClass("toggle-on").removeClass("toggle-off").addClass("toggle-off");
												break;
										case "block":
												$("*:first", div_toggle[i]).removeClass("toggle-on").removeClass("toggle-off").addClass("toggle-on");
												break;
								}
						});
				});
		});
});

// toggles specifique TMS by JMK 2008/05/13
$(document).ready( function() {
		var div_toggleTMS = new Array();
		$("div.toggleTMS").each( function(i) {
				div_toggleTMS.push($(this));
				var classe_toggleTMS = "toggleTMS-on";
				if ($("div.toggleTMS")[i].className.search(/on/) != -1 || $("div.toggleTMS")[i].className.search(/off/) != -1) {
						//La position du toggleTMS est precisee
						if($("div.toggleTMS")[i].className.search(/off/) != -1) {
								classe_toggleTMS = "toggleTMS-off";
								$("div.toggleTMSContent", div_toggleTMS[i]).css("display", "none");
						}
				} else {
						// default behavior
						if(i > 0 || $("div.toggleTMS").length == 1) {
								classe_toggleTMS = "toggleTMS-off";
								$("div.toggleTMSContent", div_toggleTMS[i]).css("display", "none");
						}
				}
				$("*:first", $(this)).addClass("toggleTMS").addClass(classe_toggleTMS).click( function() {
						$("div.toggleTMSContent", div_toggleTMS[i]).slideToggle(100, function() {
								switch($("div.toggleTMSContent", div_toggleTMS[i]).css("display")) {
										case "none":
												$("*:first", div_toggleTMS[i]).removeClass("toggleTMS-on").removeClass("toggleTMS-off").addClass("toggleTMS-off");
												break;
										case "block":
												$("*:first", div_toggleTMS[i]).removeClass("toggleTMS-on").removeClass("toggleTMS-off").addClass("toggleTMS-on");
												break;
								}
						});
				});
		});
});


// slideshow
$(document).ready(function() {

		// translation of the thickbox CLOSE button
		if ($("#wrap.fr").length > 0){
				TB_language.closeText = "Fermer";
		}
		
		if ($("#wrap.it").length > 0){
				TB_language.closeText = "Vicino";
		}
		
		if ($("#wrap.es").length > 0){
				TB_language.closeText = "Cerrar";
		}
});

$(document).ready(function() {

		$("div.view").each(function(i) {

				// define a unique id for each slideshow
				var linkId = "id" + i;

				// translation of the title message on the medium size picture
				var imageZoom ="Click to enlarge the picture";

				// translation of the other thickbox buttons
				if ($("#wrap.fr").length > 0){
						TB_language.nextText = "Suivante &gt;";
						TB_language.prevText = "&lt; pr&eacute;c&eacute;dente";
						TB_language.navImageText = "Image";
						TB_language.navOfText = "sur";
						imageZoom ="Cliquez sur la photo pour la voir en grand";
				}
				
				if ($("#wrap.it").length > 0){
						TB_language.nextText = "Accanto &gt;";
						TB_language.prevText = "&lt; Precedente";
						TB_language.navImageText = "Immagine";
						TB_language.navOfText = "di";
						imageZoom ="Cliccare per ampliare la foto";
				}
				
				if ($("#wrap.es").length > 0){
						TB_language.nextText = "Siguiente &gt;";
						TB_language.prevText = "&lt; Anterior";
						TB_language.navImageText = "Imagen";
						TB_language.navOfText = "de";
						imageZoom ="Click para agrandar la imagen";
				}

				// force medium photo dimensions
				$("img.big", this).width(338);
				$("img.big", this).height(230);

				// add a link with thickbox behavior to the medium image
		$("img.big:first", this).wrap("<a id=\"" + linkId + "\" class=\"link_to_big_picture \" Title=\"" + imageZoom + "\" href=\"" + $('img.big', this).attr("src").replace(/medium/, "large") + "\" ></a>"); // @CHANGED thickbox class removed.
				// @NEW add "loupe" icon
		$("a.link_to_big_picture").append("<img src=\"theme_front/theme_front_5/image/contenu/loupe.png\" class=\"loupe\" alt=\"Zoom\" Title=\"" + imageZoom + "\"/>");
				// $("a.link_to_big_picture:first", this).unbind();

		// @NEW open the thickbox
		$('#'+linkId).click(function(event){
			// stop default behaviour
			event.preventDefault();
			
			// remove click border
			this.blur();
			
			// Search for all the images
			var thumbs = $('ul.thumb li a'); // $('div.view ul.thumb li a')
			
			// Search for the link of the images which is p
			for( var i = 0; i<thumbs.length; i++ ){
				if( thumbs[i].href.search( this.href ) != -1 ){ // if( this.getAttribute('href') == thumbs[i].getAttribute('href') ){
					TB_show(thumbs[i].title, thumbs[i].href, thumbs[i].rel); // Opening the thickbox
					break;
				}
			}
			
		});
			   
				// modifiy thumbnails onclick behavior
				$('ul.thumb li a', this).each(function() {
						$(this).click(function(event) {

								// force to ignore the default href target
								event.preventDefault();

								// set the medium photo src
								$("#"+linkId+" img.big").attr("src", $(this).attr("href"));

								// set the big photo href
								$("#"+linkId).attr("href", $(this).attr("href"));
						});
				});
		});
});
$(document).ready(function() {
	var thumbs = $('ul.thumb li');
	
	var display = 8;
	
	var previous = $('div.nav a.previous');
	var next = $('div.nav a.next');

	var thumbs = $('ul.thumb li');
	
	// initial hides
	for( var i = 0; i < thumbs.length; i++ ){
		if( i > (display - 1) ){
			$(thumbs[i]).hide();
		}
	}
	
	if( thumbs.length > display ){
	previous.click(function(event){
		event.preventDefault();
		
			for( var first = 0; first < thumbs.length; first++ )
			if( $(thumbs[first]).css('display') != "none" )
				break;
		
		if( first > ( display -1 ) ){
				for( var i = first; i < ( first + display ); i++ )
				if( thumbs[i] )
					$(thumbs[i]).hide();
				
				for( var i = first - 1; i >= ( first - display ); i-- )
				if( thumbs[i] )
						$(thumbs[i]).fadeIn('slow');
				
			$('span#start').text(i+2);
			$('span#end').text( first );
				
				if($('span#start').text() == 1)
					$('div.nav a.previous').hide();
				else
					$('div.nav a.previous').show();
				
				if($('span#end').text() == thumbs.length)
					$('div.nav a.next').hide();
				else
					$('div.nav a.next').show();
		}
		
	});

	next.click(function(event){
		event.preventDefault();
		
			for( var first = 0; first < thumbs.length; first++ )
			if( $(thumbs[first]).css('display') != "none" )
				break;
		
			if((thumbs.length - first) > display ){
				for(var i = first; i < (first + display); i++)
				if( thumbs[i] )
					$(thumbs[i]).hide();
				
				for(var n = i; n < (i + display); n++)
					if(thumbs[n])
						$(thumbs[n]).fadeIn('slow');
				else
					break;
			
				$('span#start').text( i + 1);
				$('span#end').text(n);
				
				if($('span#start').text() == 1)
					$('div.nav a.previous').hide();
				else
					$('div.nav a.previous').show();
				
				if($('span#end').text() == thumbs.length)
					$('div.nav a.next').hide();
				else
					$('div.nav a.next').show();
		}
	});

	var toText = 'to';
	
	if ($("#wrap.fr").length > 0)
		toText = '&agrave;';
		
	if ($("#wrap.it").length > 0)
		toText = "a";
		
	if ($("#wrap.es").length > 0)
		toText = "a";
	
	previous.after( " <strong>&nbsp;<span id=\"start\">1</span> " + toText + " <span id=\"end\">" + display + "</span>&nbsp;</strong> ");
		previous.hide();
	next.before( " <strong>&nbsp;" + thumbs.length + " </strong> ");
	}else{
		$('div.nav').css('display', 'none');
	}
});

// tabs
$.tabs = function(containerId, start) {
		var onClass = 'over';
		var id = '#' + containerId;
		var i = (typeof start == "number") ? start - 1 : 0;				// define default selected tab
// this comment is to fix the bug of the ticket #354 $(id + '/div').css({display:"none"});							// hide all
		$(id + '>div:eq(' + i + ')').css({display:"block"});			// show current
		$(id + '>ul>li:nth-child(' + (i+1) + ')').addClass(onClass);	// set current tab class
		$(id + '>ul>li>a').click( function() {							// on tabs click
				if (!$(this.parentNode).is('.' + onClass)) {				// if not current tab
						var re = /([_\-\w]+$)/i;								// save RegEx to get new id
						var target = $('#' + re.exec(this.href)[1]);			// save target
						if (target.size() > 0) {								// if a target exists
								$(id + '>div:visible').css({display:"none"});		// hide visible div
								target.animate({opacity:"show"}, "slow");			// show selected div's with transition
								$(id + '>ul>li').removeClass(onClass);				// clean classes
								$(this.parentNode).addClass(onClass);
						} else {												// if no target exists
								alert('No container available !');					// display an alert if selected id has no div container
						}
				}
				return false;
		});
};

$(document).ready( function() {
		// init tabs behaviours
		if(typeof($.tabs) == 'function'){
			$.tabs('container');
			$.tabs('container2');
			$.tabs('infospassagers', 2);
			$.tabs('reglements', 2);
		}
});

// print
$(document).ready( function() {
		$(".print a").click( function(i) {
				window.print();
				return false;
		});
});


// FAQ toggle
$(document).ready( function() {
		$('dl.faq dd').toggle();				// first hide all definitions
		$('dl.faq dt.on').next().toggle();		// open flagged definitions
		$('dl.faq dt').click( function() {		// onClick on the definition title
				$(this).next().slideToggle('100');	// open definition with animation
		});
});


// form buttons
$(document).ready( function() {
		try {
				parseHTMLInputs();
		}
		catch (failure) {

		}
});

function parseHTMLInputs() {
				var button = /button|reset|submit/i;
				var inputs = document.getElementsByTagName('input');
				var l = inputs.length-1;
				//var l = $("input").length-1;

				for(var input, type, i=l ; i>=0 ; i--) {
						input = inputs.item(i);
						if(input && button.test(input.type)) {
								type = button.exec(input.type)[0];
								replaceHTMLInput(input, type);
						}
				}
		}

function replaceHTMLInput(input, type) {
		var form = input.form;
		var link = document.createElement('a');
		var span = document.createElement('span');
		span.appendChild(document.createTextNode(input.value));
		link.appendChild(span);
		link.setAttribute('href', '#');
		input.parentNode.replaceChild(link, input);

		switch(type) {
				case 'submit':
						link.onclick = function() { if(!form.onsubmit || form.onsubmit()) form.submit(); }
						break;
				case 'reset':
						link.onclick = function() { form.reset(); }
						break;
				case 'button':
						link.onclick = function() { if(!form.onsubmit || form.onsubmit()) form.submit(); }
						break;
		}
}


/* --------------------------------------------------------------------------------------
		IE 6 specific bypasses
----------------------------------------------------------------------------------------- */
// hover everything
$(document).ready( function() {
		if ($.browser.msie) {
				$(".hover").addClass("hover-off").hover(
						function()
						{
								$(this).removeClass("hover-off").addClass("hover-on");
						},
						function()
						{
								$(this).removeClass("hover-on").addClass("hover-off");
						}
				);
		}
});

// add emty strong element to the description title
$(document).ready(function() {
		if ($.browser.msie) {
				$('div.detail h3 a').append("<strong></strong>");
		}
});

// add non breakable space at the footers end to prevent a weired text ghost
$(document).ready(function() {
		if ($.browser.msie) {
				$('div#footer p.legal').append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		};
});

$(document).ready(function() {
		if ($.browser.msie) {
				$('dl.faq dt:first').before("<dt>&nbsp;</dt>");
		};
});

/* --------------------------------------------------------------------------------------
		init Thickbox
		WARNING : MUST REMAIN THE LAST ELEMENT CALLED ONCE THE DOM MODIFICATIONS ARE DONE.
----------------------------------------------------------------------------------------- */
$(document).ready( TB_init );

/**
* Ajout SQLI
*/

function numericStrictlyPositive(obj) {
		var StrValidChars = "0123456789.,";
		var StrString;
		var StrChar;

		StrString = obj.value;

		if (StrString != '' && StrString != 0) {
				for (i = 0 ; i < StrString.length ; i++) {
					  StrChar = StrString.charAt(i);
					  if (StrValidChars.indexOf(StrChar) == -1){
							   return false;
					  }
				}
		}
		else {
				return false;
		}
		return true;
}

// Fonction AJAX
function createXMLHttpRequest() {
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try { return new XMLHttpRequest(); } catch(e) {}
   alert("XMLHttpRequest n'est pas supporté, mettez à jour votre navigateur, merci.");
   return null;
}

function setAndExecute(divId,innerHTML){
		var div = document.getElementById(divId);
		if(div != null) {
			div.innerHTML = innerHTML;
			var x = div.getElementsByTagName("script");
			for(var i=0;i<x.length;i++)   {
					eval(x[i].text);
			}
		}
}

function miseAJourCalendrier(mois,annee,encart,sit_id) {
		var xhr_object = createXMLHttpRequest();

		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?component=agenda_evenement&action=get_calendrier&mois='+mois+'&annee='+annee+'&encart='+encart+'&sit_id='+sit_id, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
						setAndExecute('encartCalendrier',xhr_object.responseText);
				}
		}
		xhr_object.send(null);
}

function miseAJourCategories(compId, sit_id) {
		var xhr_object = createXMLHttpRequest();

		var themeId = document.getElementById("agenda_theme_id").value;

		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?component=agenda_evenement&action=get_categorie&theme_id='+themeId+'&comp_id='+compId+'&sit_id='+sit_id, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 ) {
						document.getElementById('combo_categorie').innerHTML = xhr_object.responseText;
				}
		}
		xhr_object.send(null);
}

function miseAJourEncartAgenda(compId,type) {
		var xhr_object = createXMLHttpRequest();

		var date_debut = '';
		var date_fin = '';
		var ile_destination = '';

		if ( document.getElementById("datedepart") ) {
				date_debut = document.getElementById("datedepart").value;
		}
		if ( document.getElementById("dateretour") ) {
				date_fin = document.getElementById("dateretour").value;
		}
		if ( document.getElementById("destination_id") ) {
				ile_destination = document.getElementById("destination_id").value;
		}

		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=agenda_evenement&action=get_encart_agenda_selection_compte&date_debut='+date_debut+'&date_fin='+date_fin+'&ile_destination='+ile_destination+'&comp_id='+compId+'&type='+type, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
						setAndExecute('encartTransverseCalendrier',xhr_object.responseText);
				}
		}
		xhr_object.send(null);
}

function miseAJourEncartPayer2FoisSansFrais() {
		
		if ( document.getElementById("encartPayer2FoisSansFrais") ) {
		
				var xhr_object = createXMLHttpRequest();
				
				var package_online = '';
		
				if ( document.getElementById("package_online") ) {
						package_online = document.getElementById("package_online").value;
				}
		
				// On ouvre la requete vers la page desirée
				xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=voyage_voyage&action=get_encart_payer_2_fois_sans_frais&package_online='+package_online, true);
				xhr_object.onreadystatechange = function(){
						if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
								setAndExecute('encartPayer2FoisSansFrais',xhr_object.responseText);
						}
				}
				xhr_object.send(null);
		}
}

function miseAJourEncartNaEnregistreBagages() {
		
		if ( document.getElementById("encartNaEnregistreBagages") ) {
		
				var xhr_object = createXMLHttpRequest();
				
				var activation_bagages_plus = '';
		
				if ( document.getElementById("activation_bagages_plus") ) {
						activation_bagages_plus = document.getElementById("activation_bagages_plus").value;
				}
		
				// On ouvre la requete vers la page desirée
				xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=portlet_info&action=get_encart_na_enregistre_bagages&activation_bagages_plus='+activation_bagages_plus, true);
				xhr_object.onreadystatechange = function(){
						if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
								setAndExecute('encartNaEnregistreBagages',xhr_object.responseText);
						}
				}
				xhr_object.send(null);
		}
}

function miseAJourFicheVoyage() {
		var xhr_object = createXMLHttpRequest();

		var id_devis = $("select#id_devis option:selected").val();
		
		if ( $("small#flagAPartirDe").val() != null ) {
				var flag_apartirde = 1;
		}
		else {
				var flag_apartirde = 0;
		}
		
		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=voyage_voyage&action=get_infos_package&id_devis='+id_devis+'&flag_apartirde='+flag_apartirde, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
						setAndExecute('encartInfosPackage',xhr_object.responseText);
				}
		}
		xhr_object.send(null);
}

// Mise en session des dates pour la Vente en Ligne de loisirs
function setDateEnSession(prestationId, dateLib) {
		var xhr_object = createXMLHttpRequest();
		
		var dateLoisir = $("#"+dateLib+"_"+prestationId).val();
		
		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=selection&action=set_date_session_loisir&prestation_id='+prestationId+'&date='+dateLoisir+'&date_lib='+dateLib, true);
		xhr_object.send(null);
}


// Gestion de la Vente en Ligne de loisirs
function calculPrixLoisir(prestationId,typePax) {
		var xhr_object = createXMLHttpRequest();
		
		var nbPax = $("#"+typePax+"_"+prestationId).val();
		
		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=selection&action=get_tarif_loisir&prestation_id='+prestationId+'&type_pax='+typePax+'&nb_pax='+nbPax, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
						// Récupération des tarifs unitaires et total
						InfosTarifsReponse = xhr_object.responseText;
						var reg=new RegExp("[|]+", "g");
						var infosTarifs = InfosTarifsReponse.split(reg);
						var prixParTypePax = Math.round( parseFloat(infosTarifs[0])*100 )/100;
						var prixTotalTypePax = Math.round( parseFloat(infosTarifs[1])*100 )/100;
												
						// MAJ du prix pour le type de pax passé en paramètre
						var prixTypePax= Math.round( parseFloat(prixTotalTypePax)*100 )/100;
						if ( isNaN(prixTypePax) ) prixTypePax=0;
						$("#prix_"+typePax+"_"+prestationId).val( prixTypePax );
						$("#lib_prix_"+typePax+"_"+prestationId).html( nbPax + 'x' + prixParTypePax + ' \u20AC = <strong>' + prixTypePax + ' \u20AC</strong>');
						
						// MAJ du prix total de la prestation
						var prix_adulte_prestation = $("#prix_adulte_"+prestationId).val();
						if ( prix_adulte_prestation=='' || prix_adulte_prestation==null ) prix_adulte_prestation=0;
						else prix_adulte_prestation = Math.round( parseFloat(prix_adulte_prestation)*100)/100;
						
						var prix_enfant_prestation = $("#prix_enfant_"+prestationId).val();
						if ( prix_enfant_prestation=='' || prix_enfant_prestation==null ) prix_enfant_prestation=0;
						else prix_enfant_prestation = Math.round( parseFloat(prix_enfant_prestation)*100)/100;
						
						var prix_bebe_prestation = $("#prix_bebe_"+prestationId).val();
						if ( prix_bebe_prestation=='' || prix_bebe_prestation==null ) prix_bebe_prestation=0;
						else prix_bebe_prestation = Math.round( parseFloat(prix_bebe_prestation)*100)/100;
						
						var prix_total_prestation = Math.round(	( prix_adulte_prestation + prix_enfant_prestation + prix_bebe_prestation )*100 )/100;
						
						$("#prix_total_"+prestationId).val( prix_total_prestation );
						$("#lib_prix_total_"+prestationId).html( prix_total_prestation + ' \u20AC TTC');
						
						// MAJ du prix total du panier
						var prixTotal=0;
						var listPrestationId = $("#list_prestation_id").val();
						var reg=new RegExp("[,]+", "g");
						var list = listPrestationId.split(reg);
						for (var i=0; i<list.length; i++) {
								prixTotal = prixTotal + Math.round(	parseFloat($("#prix_total_"+list[i]).val())*100 )/100;
						}
						
						$("#prix_total").val( prixTotal );
						$("#lib_prix_total").html( prixTotal + ' \u20AC TTC');
				}
		}
		xhr_object.send(null);
}

// Gestion des Assurances TMS
$(document).ready(function() {
		
		var temp = 0;
		
		$("input.tms").click(function () {
				
				  temp++;
				  var input_PaxTMS = new Array();
				  var getstr = "demande_id=" + $("input#demande_id").val() + "&";
				  getstr += "TMS_idTypeVoyage=" + $("input#TMS_idTypeVoyage").val() + "&";
				  if ( $("input#TMS_SouscriptionTardive").val() == 1) {
						getstr += "TMS_SouscriptionTardive=" + $("input#TMS_SouscriptionTardive").val() + "&";
				  }
				  
				  $("input.tms").each( function(i) {
						input_PaxTMS.push($(this));
						if ($("input.tms")[i].checked) {
								getstr += $("input.tms")[i].name + "=" + $("input.tms")[i].value + "&";
						} else {
								getstr += $("input.tms")[i].name + "=0&";
						}
				  });
				  
				  var xhr_object = createXMLHttpRequest();
				  
				  $("#multirisques").html( maj_en_cours_txt );
				  $("input#TMS_MR").val( '' );
				  $("input#TMS_MR_ID_DEVIS").val( '' );
				  $("#avant_sejour").html( maj_en_cours_txt );
				  $("input#TMS_AV").val( '' );
				  $("input#TMS_AV_ID_DEVIS").val( '' );
				  $("input#montant").val( maj_en_cours_txt );
				  $("span.prix_sejour").text( maj_en_cours_txt );
				  $('input#montant').attr("readonly","true");
				
				  if ( $("input:checkbox.tms:checked").length == 0 ) {
						$("div#msgErreurPax").show("slow");
						temp = 0;
				  
						  $("#multirisques").html( maj_impossible_txt );
						  $("input#TMS_MR").val( '' );
						  $("input#TMS_MR_ID_DEVIS").val( '' );
						  $("#avant_sejour").html( maj_impossible_txt );
						  $("input#TMS_AV").val( '' );
						  $("input#TMS_AV_ID_DEVIS").val( '' );
						  $("input#montant").val( maj_impossible_txt );
						  $("span.prix_sejour").text( maj_impossible_txt );
						  $('input#montant').attr("readonly","true");
				  }
				  else {
						$("div#msgErreurPax").slideUp();

						  // On ouvre la requete vers la page desirée
						  xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=compte&action=get_tarifs_assurance_tms&'+getstr, true);
						  xhr_object.onreadystatechange = function(){
						  if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
							  if ( temp == 1 ) {
								  var docXML = xhr_object.responseXML;
								  var multirisquesPass = false;
								  $(docXML).find("assurance").each(function() { 
									var assurance = $(this);
									if (multirisquesPass == false) {
										$("#multirisques").html( assurance.attr("prime") +' &euro;' );
										$("input#TMS_MR").val( assurance.attr("prime") );
										$("input#TMS_MR_ID_DEVIS").val( assurance.attr("idDevis") );
										multirisquesPass = true;
									}
									else {
										$("#avant_sejour").html( assurance.attr("prime") +' &euro;' );
										$("input#TMS_AV").val( assurance.attr("prime") );
										$("input#TMS_AV_ID_DEVIS").val( assurance.attr("idDevis") );
									}
								  });
								  
								  if ( $("input[type=radio][name=TMS]:checked").attr("id") == 'TMS_NO' ) {
										prixSejour = parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
										prixSejour = Math.round(prixSejour*100)/100;
										if ( prixSejour < 0 ) prixSejour = 0;
										prixSejourMin = '0';
								  }
								  else {
										prixSejour = parseFloat( $("input[type=radio][name=TMS]:checked").val() ) + parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
										prixSejour = Math.round(prixSejour*100)/100;
										prixSejourMin = parseFloat( $("input[type=radio][name=TMS]:checked").val() ) + parseFloat( $("input#montant_acompte_ss_ass_reference").val() - parseFloat( $("input#montant_acompte_total_reference").val() ) );
										prixSejourMin = Math.round(prixSejourMin*100)/100;
								  }
								  $("span.prix_sejour").text( prixSejourMin + ' \u20AC' );
								  $("input#montant").val( prixSejour );
								  $('input#montant').removeAttr("readonly"); 
								  if ( temp > 0 ) temp--;
							  }
							  else {
								  if ( temp > 0 ) temp--;
							  }
						  }
				  }
				  xhr_object.send(null);
				  }
		});
		
		$("input:radio#TMS_MR").click(function () {

				prixSejour = parseFloat( $("input:radio#TMS_MR").val() ) + parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
				prixSejour = Math.round(prixSejour*100)/100;
				prixSejourMin = parseFloat( $("input:radio#TMS_MR").val() ) + parseFloat( $("input#montant_acompte_ss_ass_reference").val() ) - parseFloat( $("input#montant_acompte_total_reference").val() );
				prixSejourMin = Math.round(prixSejourMin*100)/100;
				if ( prixSejour < 0 ) prixSejour = 0;
				if ( isNaN(prixSejour) ) {
						prixSejour = recalcul_txt;
						$("span.prix_sejour").text( prixSejour );
				}
				else {
						$("span.prix_sejour").text( prixSejourMin + ' \u20AC' );
				}
				$("input#montant").val( prixSejour );
				$("input#TMS_Type_Assurance").val( $("input[type=radio][name=TMS]:checked").attr("id") );
				$("label#cgvTms").show("slow");
				
		});
		
		$("input:radio#TMS_AV").click(function () {

				prixSejour = parseFloat( $("input:radio#TMS_AV").val() ) + parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
				prixSejour = Math.round(prixSejour*100)/100;
				prixSejourMin = parseFloat( $("input:radio#TMS_AV").val() ) + parseFloat( $("input#montant_acompte_ss_ass_reference").val() ) - parseFloat( $("input#montant_acompte_total_reference").val() );
				prixSejourMin = Math.round(prixSejourMin*100)/100;
				if ( prixSejour < 0 ) prixSejour = 0;
				if ( isNaN(prixSejour) ) {
						prixSejour = recalcul_txt;
						$("span.prix_sejour").text( prixSejour );
				}
				else {
						$("span.prix_sejour").text( prixSejourMin + ' \u20AC' );
				}
				$("input#montant").val( prixSejour );
				$("input#TMS_Type_Assurance").val( $("input[type=radio][name=TMS]:checked").attr("id") );
				$("label#cgvTms").show("slow");
		});
		
		$("input:radio#TMS_NO").click(function () {
				prixSejour = parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
				prixSejour = Math.round(prixSejour*100)/100;
				if ( prixSejour < 0 ) prixSejour = 0;
				$("span.prix_sejour").text( '0 \u20AC' );
				$("input#montant").val( prixSejour );
				$("input#TMS_Type_Assurance").val( $("input[type=radio][name=TMS]:checked").attr("id") );
				$("label#cgvTms").slideUp();
				
		});
		
		if ( $("input[type=radio][name=TMS]:checked").attr("id") == 'TMS_MR' ) {
				prixSejour = parseFloat( $("input:radio#TMS_MR").val() ) + parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
				prixSejour = Math.round(prixSejour*100)/100;
				prixSejourMin = parseFloat( $("input:radio#TMS_MR").val() ) + parseFloat( $("input#montant_acompte_ss_ass_reference").val() ) - parseFloat( $("input#montant_acompte_total_reference").val() );
				prixSejourMin = Math.round(prixSejourMin*100)/100;
				if ( prixSejour < 0 ) prixSejour = 0;
				if ( prixSejourMin < 0 ) prixSejourMin = 0;
				$("span.prix_sejour").text( prixSejourMin + ' \u20AC' );
				$("input#montant").val( prixSejour );
				$("input#TMS_Type_Assurance").val( $("input[type=radio][name=TMS]:checked").attr("id") );
				$("label#cgvTms").show("slow");
		}
		
		if ( $("input[type=radio][name=TMS]:checked").attr("id") == 'TMS_AV' ) {
				prixSejour = parseFloat( $("input:radio#TMS_AV").val() ) + parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
				prixSejour = Math.round(prixSejour*100)/100;
				prixSejourMin = parseFloat( $("input:radio#TMS_AV").val() ) + parseFloat( $("input#montant_acompte_ss_ass_reference").val() ) - parseFloat( $("input#montant_acompte_total_reference").val() );
				prixSejourMin = Math.round(prixSejourMin*100)/100;
				if ( prixSejour < 0 ) prixSejour = 0;
				if ( prixSejourMin < 0 ) prixSejourMin = 0;
				$("span.prix_sejour").text( prixSejourMin + ' \u20AC' );
				$("input#montant").val( prixSejour );
				$("input#TMS_Type_Assurance").val( $("input[type=radio][name=TMS]:checked").attr("id") );
				$("label#cgvTms").show("slow");
		}
		
		if ( $("input[type=radio][name=TMS]:checked").attr("id") == 'TMS_NO' ) {
				prixSejour = parseFloat( $("input#montant_acompte_ss_ass").val() ) - parseFloat( $("input#montant_acompte_total").val() );
				prixSejour = Math.round(prixSejour*100)/100;
				if ( prixSejour < 0 ) prixSejour = 0;
				$("span.prix_sejour").text( '0 \u20AC' );
				$("input#montant").val( prixSejour );
				$("input#TMS_Type_Assurance").val( $("input[type=radio][name=TMS]:checked").attr("id") );
				$("label#cgvTms").slideUp();
		}

});

// Gestion des onglets du moteur de Recherche en HomePage 25/07/08
function ongletshp (b) {
		document.getElementById('rechercheVoyage').style.display = (b!=1? 'none':'block');
		document.getElementById('rechercheHotel').style.display = (b!=2? 'none':'block');
		document.getElementById('rechercheAvion').style.display = (b!=3? 'none':'block');
		document.getElementById('rechercheVoiture').style.display = (b!=4? 'none':'block');
		var label = document.getElementById('mainLabel');
		if(b==1) label.innerHTML = document.getElementById('labelVoyage').value;
		if(b==2) label.innerHTML = document.getElementById('labelHotel').value;
		if(b==3) label.innerHTML = document.getElementById('labelVol').value;
		if(b==4) label.innerHTML = document.getElementById('labelVoiture').value;
}

// Gestion de l'offre selectionnee dans le resultat de recherche de Dispos 30/07/08

function choix_rangees_cocher(id_cocher, id_rangee){
		window.setTimeout("colorer_rangee('"+id_cocher+"','"+id_rangee+"')",300); //la temporisation est nécessaire parce que le gestionnaire d'événement est déclenché avant que la case à cocher ne soit commutée...
		return true;
}
function colorer_rangee(id_cocher, id_rangee){
		document.getElementById(id_rangee).className = ((document.getElementById(id_cocher).checked) ? "choisi" : "pas_coche");
}
function rangee_choix_option(id_cocher, id_rangee,count){
		window.setTimeout("colorer_rang_option('"+id_cocher+"','"+id_rangee+"','" + count + "')",300); //la temporisation est nécessaire parce que le gestionnaire d'événement est déclenché avant que la case à cocher ne soit commutée...
		return true;
}
function colorer_rang_option(idcheckcommon, idrowcommon, count){
		for (i = 1; i <= count; i++){
				id_rangee = "" + idrowcommon + i;;
				id_cocher = "" + idcheckcommon + i;
				document.getElementById(id_rangee).className = ((document.getElementById(id_cocher).checked) ? "choisi" : "pas_coche");
		}
}

function colorer_radios(radio_name) {
		var radios = document.getElementsByName(radio_name);
		for(i=0;i<radios.length;i++) {
				radios[i].parentNode.parentNode.className = ((radios[i].checked) ? "choisi" : "pas_coche");
		}
}

$(document).ready(function() {
		colorer_radios('devis_choisi');
});

function miseDemande(field_name, table_name, assoc_name, pid, lang) {
		var xhr_object = createXMLHttpRequest();
		
		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=acces_pro&action=ajax_info_type&table_name='+table_name+'&field_name='+field_name+'&assoc_name='+assoc_name+'&pid='+pid+'&lang='+lang, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 ) {
						document.getElementById('type_container').innerHTML = xhr_object.responseText;
				}
		}
		xhr_object.send(null);
}
function misePeriodicite(period_id) {
		var n = document.getElementById("agenda_evenement_period_num_dans_mois");
		var njemes = document.getElementById("agenda_evenement_period_compte_dans_mois");
		switch (period_id){
				case 1:
						n.disabled = false;
						njemes.disabled = true;
						for (i=0; i<7; i++) document.getElementById("agenda_evenement_period_jour"+i).disabled = true;
						document.getElementById('n_container').innerHTML = '<em>*</em>';
						document.getElementById('njemes_container').innerHTML = '';
						document.getElementById('jour_container').innerHTML = '';	
						break;
				case 2:
						n.disabled = true;
						njemes.disabled = false;
						for (i=0; i<7; i++) document.getElementById("agenda_evenement_period_jour"+i).disabled = false;
						document.getElementById('n_container').innerHTML = '';
						document.getElementById('njemes_container').innerHTML = '<em>*</em>';
						document.getElementById('jour_container').innerHTML = '<em>*</em>';
						break;
				case 3:
						n.disabled = true;
						njemes.disabled = true;
						for (i=0; i<7; i++) document.getElementById("agenda_evenement_period_jour"+i).disabled = false;
						document.getElementById('n_container').innerHTML = '';
						document.getElementById('njemes_container').innerHTML = '';
						document.getElementById('jour_container').innerHTML = '<em>*</em>';
						break;
				default:
						n.disabled = true;
						njemes.disabled = true;
						for (i=0; i<7; i++) document.getElementById("agenda_evenement_period_jour"+i).disabled = true;
						document.getElementById('n_container').innerHTML = '';
						document.getElementById('njemes_container').innerHTML = '';
						document.getElementById('jour_container').innerHTML = '';
						break;
		}
}

function miseAJourCommunes(communeId, lang, sit_id) {
		var xhr_object = createXMLHttpRequest();

		var ileId = document.getElementById("ile_dest_hotel").value;

		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?component=recherche&action=ajax_communes&ile_id='+ileId+'&lang='+lang+'&sit_id='+sit_id, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 ) {
						document.getElementById('commune_container').innerHTML = xhr_object.responseText;
				}
		}
		xhr_object.send(null);
}

function miseAJourIles(zoneId, lang) {
		
		var xhr_object = createXMLHttpRequest();

		zoneId = document.getElementById("zone_id").value;

		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=guide_article&action=ajax_iles&zone_id='+zoneId+'&lang='+lang, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 ) {
						document.getElementById('ile_container').innerHTML = xhr_object.responseText;
				}
		}
		xhr_object.send(null);
}

function miseAJourRegion(ileId, lang) {
		
		var xhr_object = createXMLHttpRequest();
		
		ileId = document.getElementById("ile_id").value;

		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=guide_article&action=ajax_region&ile_id='+ileId+'&lang='+lang, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 ) {
						document.getElementById('region_container').innerHTML = xhr_object.responseText;
				}
		}
		xhr_object.send(null);
}

function miseAJourCommune(regionId, lang) {
		
		var xhr_object = createXMLHttpRequest();

		regionId = document.getElementById("region_id").value;

		// On ouvre la requete vers la page desirée
		xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=guide_article&action=ajax_commune&region_id='+regionId+'&lang='+lang, true);
		xhr_object.onreadystatechange = function(){
				if ( xhr_object.readyState == 4 ) {
						document.getElementById('commune_container').innerHTML = xhr_object.responseText;
				}
		}
		xhr_object.send(null);
}

function disp_confirm()
{
var r=confirm("Do you want to add photos/videos to your article?");
if (r==true)
  {
  //document.write("You pressed OK!");
  }
else
  {
  //document.write("You pressed Cancel!");
  }
}

function containsDropDown(dd, val) {
	for ( var i = 0; i < dd.options.length; i++ ) {
		if ( dd.options[i].value == val ) {
			return 1;
		}
	}
	return 0;
}

function setAirportDropDownValue(dd, val) {
	for ( var i = 0; i < dd.options.length; i++ ) {
		if ( dd.options[i].value == val ) {
						dd.options[i].selected = true;
						return;
		}
	}
}

function deleteAirportDropDownValue(dd, val) {
		if(val == '') return;
	for ( var i = 0; i < dd.options.length; i++ ) {
		if ( dd.options[i].value == val ) {
						dd.remove(i);
						return;
		}
	}
}

function findDropDownInside(element) {
		var children = element.childNodes;
		var result;
		for(i=0;i<children.length;i++) {
				if(children[i].options != undefined){
						result = children[i];
						break;
				}
		}
		return result;
}

function miseAJourAeroports(aeroportSel, updateListId) {
		// finding dropdown to update
		var updateList = document.getElementById(updateListId);
		// getting its container
		var updateListContainer = updateList.parentNode;
		
		// saving properties to restore later
		var className = updateList.className;
		var id = updateList.id;
		var name = updateList.name;
		var onchange = updateList.onchange;
		var val = updateList.value;
		
		// getting new content containers
		var antillaises = document.getElementById('liste_antillaises');
		var tous = document.getElementById('liste_tous');

		// changing dropdown according to current selection
		if(containsDropDown(findDropDownInside(antillaises), aeroportSel)) {
				updateListContainer.innerHTML = tous.innerHTML;
		} else {
				updateListContainer.innerHTML = antillaises.innerHTML;
		}
		
		// finding new dropdown in changed container
		var newdropdown = findDropDownInside(updateListContainer);
		// restoring properties
		newdropdown.name = name;
		newdropdown.id =id;
		newdropdown.className = className;
		newdropdown.onchange = onchange;
		
		// deleting selected destination
		deleteAirportDropDownValue(newdropdown, aeroportSel);
		// restoring selection
		setAirportDropDownValue(newdropdown, val);
}

// GMap coordinates filters
function coorFilter(event){
		var keysAllowed = [109,110,190,8,9,13,35,36,37,39,46,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
		var key = event.which;
		var proccess = false;
		
		for(var x=0; x < keysAllowed.length; x++){
				if(key == keysAllowed[x]){
						proccess = true;
						break;
				}
		}
		
		if(proccess){
				if(key == 110 || key == 190 || key == 109){
						if(key == 110 || key == 190){
								var points = this.value.match(/(\.)/g);
						if(points && points.length == 1){
							//return false;
								proccess = false;
						}
						}
						if(key == 109){
								if(this.value[0] != '-'){
										var points = this.value.match(/(\-)/g);
								if(points && points.length == 1){
									//return false;
										proccess = false;
								}
								}else{
										return false;
								}
						}
				}else{
						if(key != 8 && key != 9 && key != 13 && key != 35 && key != 36 && key != 37 && key != 39 && key != 46){
								var matches = /\.([0-9]+)/.exec(this.value);
							if(matches && matches.length == 2){
								if(matches[1].length >= _maxLimit){
									//return false;
										proccess = false;
								}
							}
						}
				}
		}
		return proccess;
}

var _maxLimit = 6;
$(document).ready(function(){
	if($('#GMLat').length == 1 && $('#GMLon').length == 1){
		// Latitude input
		$('#GMLat').keydown(coorFilter);
		$('#GMLon').keydown(coorFilter);
	}
});

function GeoLocation(elem){
	this.holder = elem;
	this.lat = 0.0;
	this.lng = 0.0;
	this.zoom = 20;
	this.markerTitle = '';
}
GeoLocation.prototype.setDefault = function(lat, lng, zoom){
	this.defLat = parseFloat(lat);
	this.defLng = parseFloat(lng);
	this.defZoom = parseInt(zoom);
}
GeoLocation.prototype.buildMap = function(){
	if(this.timeOut){
		clearTimeout(this.timeOut);
	}
	
	this.map = new GMap2(this.holder);
	this.map.removeMapType(G_NORMAL_MAP);
	this.map.removeMapType(G_SATELLITE_MAP);
	this.map.addMapType(G_PHYSICAL_MAP);
	this.map.disableDoubleClickZoom();
	this.map.enableScrollWheelZoom();
	this.map.addControl(new GMapTypeControl());
	this.map.addControl(new GSmallMapControl());
	
	if(this.lat && this.lng){
		this.map.setCenter(new GLatLng(this.lat, this.lng), this.zoom);
		this.createMarker();
	}else{
				this.map.setCenter(new GLatLng(this.defLat, this.defLng), this.defZoom);
	}
	
	GEvent.bind(this.map,"click", this, function(overlay, latlng){
		if(latlng){
			this.lat = latlng.lat();
			this.lng = latlng.lng();
			this.zoom = this.map.getZoom();
			this.createMarker();
			this.onComplete();
		}
	});
	GEvent.bind(this.map,"zoomend", this, function(oldLevel, newLevel){
		this.zoom = newLevel;
		this.onComplete();
	});
}
GeoLocation.prototype.createMarker = function(){
	if(this.marker){
		this.map.removeOverlay(this.marker);
	}
	
	this.marker = new GMarker(new GLatLng(this.lat, this.lng), {draggable: true});
	
	GEvent.bind(this.marker, "dragstart", this, function(){
		this.map.closeInfoWindow();
	});
	GEvent.bind(this.marker, "click", this, function(){
		this.marker.openInfoWindowHtml(this.markerTitle);
	});
	GEvent.bind(this.marker, "dragend", this, function(latlng){
		this.lat = latlng.lat();
		this.lng = latlng.lng();
		this.zoom = this.map.getZoom();
		this.marker.openInfoWindowHtml(this.markerTitle);
		this.onComplete();
	});
	
	this.map.addOverlay(this.marker);
	this.marker.openInfoWindowHtml(this.markerTitle);
}

GeoLocation.prototype.onComplete = function(){};                                  

function communeTextHandler(options) {  

	//re-bind lost listener for AJAX request !!! 
	//TV 11/10/2010. Now managing the sendrequest trough the 'onClick' function in order to send only one request 
	//when user selectes several checkboxes
    //if(typeof (window.onClick) == 'function') {
		// function exists, so we can now bind it
    //    $("#commune_id").bind("change", onClick);
    //}


	var selectedOptions = options.filter(":selected");
	var countOfSelected = selectedOptions.size();
	var size = options.size();
	switch(countOfSelected) {
		case 0: return $("#select_tr").text();
		case 1: return selectedOptions.text();
		case size: return $("#commune_id option")[0].innerHTML;
		default: return countOfSelected + ' ' + $("#commune_tr").text();
	}
}

var dropdownCheckTimer; //A control for the disabledCombo 1 sec timeout, so it can be cleared
var dropdownCheckPageLoad = 1;
function replaceDropdown(id) {
    //if the page just loaded or the #commune_container dropdown tab (hotel) is selected, update the dropdown
    if($('#commune_container').parents('div.contentRecherche').css('display') == 'block' || dropdownCheckPageLoad == 1) {
	if(id>0) {
                disableCombo();
                clearTimeout(dropdownCheckTimer);
            var commune_id = ($("#commune_id_url").val() != null)?$("#commune_id_url").val():'';
            ajaxUrl = '/service/ajax/index.php?sit_id=11&component=recherche&action=ajax_communes&ile_id='+id+'&commune_id='+commune_id;
            
                if(!($.browser.msie && $.browser.version == 6)){ //IE6 fix, using iFrames instead of AJAX, responsetext (data) is useless... (IE6 Only, maybe gzip??)
                    $.get(ajaxUrl, function(data) {
                    //Populates the combo
		    $('#commune_container').html(data);
                    $("#commune_id").dropdownchecklist({
                        firstItemChecksAll: true, 
                        maxDropHeight: 300, 
                        textFormatFunction:communeTextHandler
                    } );
                    $('input[id*=commune_id], .ui-dropdownchecklist, .ui-dropdownchecklist-item').bind("click", function(){
                        comboDelay();
                    });
                    //Auto close with no delay on mouse out
                    $(".ui-dropdownchecklist-dropcontainer").mouseleave(function(){
                        comboDelay(true);
                    });
                    //Reset timer on mouse move
                    $(".ui-dropdownchecklist-dropcontainer").mousemove(function(){
                        comboDelay();
                  });
             });
            } else {
                    $('#ie6AjaxIframe').remove();
                    $('body').append('<iframe id="ie6AjaxIframe" name="ie6AjaxIframe" src="'+ajaxUrl+'" width="0" height="0" style="display: none; visibility: hidden"></iframe>')
                    setTimeout(function(){
                            data = $('#ie6AjaxIframe').contents().find('body').html();
                            $('#commune_container').html(data);
                            $("#commune_id").dropdownchecklist({
                              firstItemChecksAll: true, 
                              maxDropHeight: 300, 
                              textFormatFunction:communeTextHandler
                            });
                    }, 1000); //A 1 second delay just in case the iframe havent loaded yet...
                }
    } else {
		//TV 12/10/2010 This timeout avoids a bug that causes that when we have two island selected and quickly deselect and select one of the two,
		//the commune combo is activated with two island selected
            dropdownCheckTimer = setTimeout("disableCombo()", 1000);
	}
        dropdownCheckPageLoad = 0;
	}
}
//Disable commune combo
function disableCombo(){
		var content = $("#commune_disabled").html();
		$('#commune_container').html(content);    
}
//Little Google Map        
function createLittleGoogleMap(geolocalisation_zoom, geolocalisation_latitude, geolocalisation_longitude){
	if (GBrowserIsCompatible()) {
		var mapsw = new GMap2(document.getElementById("littleGoogleMapdiv"));
		var zoom = geolocalisation_zoom;     
		zoom = zoom - 2;
		mapsw.setCenter(new GLatLng(geolocalisation_latitude, geolocalisation_longitude), zoom); 
		mapsw.setMapType(G_NORMAL_MAP);
		mapsw.getContainer().lastChild.style.zIndex = "-1"; 
		mapsw.addControl(new GSmallZoomControl());   
		mapsw.disableDragging();     
		// mapsw.setUIToDefault(); 
	}
}

// Activating dropdownchecklists in search form
$(document).ready(function() {
	if ($("#ile_dest_hotel option")[0] != null) {
		$("#ile_dest_hotel option")[0].checked = false;
		$("#ile_dest_hotel").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 250, textFormatFunction: function(options) {
			var selectedOptions = options.filter(":selected");
			var countOfSelected = selectedOptions.size();
			var size = options.size();
			switch(countOfSelected) {
				case 0: replaceDropdown(0); return $("#select_tr").text();
				case 1: replaceDropdown(selectedOptions.val()); return selectedOptions.text();
				case size: replaceDropdown(0); return $("#toutes").text();
				default: replaceDropdown(0); return countOfSelected + " " + $("#destinations").text() ;
			}
		}});
	}
    
	if ($("#hebergement_type_id option")[0] != null) {
		$("#hebergement_type_id option")[0].checked = false;
		// ROP 30/11/10 New Changes
		if($("#hebergement_type_id").dropdownchecklist != null){
			$("#hebergement_type_id").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 230, textFormatFunction: function(options) {
				var selectedOptions = options.filter(":selected");
				var countOfSelected = selectedOptions.size();
				var size = options.size();
				switch(countOfSelected) {
				case 0: return $("#select_tr").text();
				case 1: return selectedOptions.text();
				case size: return $("#tous").text();     
				default: return countOfSelected + " " + $("#typesHebergements").text(); 
				}
			}});
		}
	}
    
    
    if ($("#hebergement_type_id_btnSejour option")[0] != null) {
        $("#hebergement_type_id_btnSejour option")[0].checked = false;
        if($("#hebergement_type_id_btnSejour").dropdownchecklist != null){
            $("#hebergement_type_id_btnSejour").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 230, textFormatFunction: function(options) {
                var selectedOptions = options.filter(":selected");
                var countOfSelected = selectedOptions.size();
                var size = options.size();
                switch(countOfSelected) {
                case 0: return $("#select_tr").text();
                case 1: return selectedOptions.text();
                case size: return $("#tous").text();     
                default: return countOfSelected + " " + $("#typesHebergements").text(); 
                }
            }});
        }
    }
    
    // ROP 18/5/11 New Listbox about the pensions for the search
    if ($("#pension_id option")[0] != null) {
        $("#pension_id option")[0].checked = false;
        if($("#pension_id").dropdownchecklist != null){
            $("#pension_id").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 180, textFormatFunction: function(options) {
                var selectedOptions = options.filter(":selected");
                var countOfSelected = selectedOptions.size();
                var size = options.size();
                switch(countOfSelected) {
                case 0: return $("#select_tr_pension").text();
                case 1: return selectedOptions.text();
                case size: return $("#touspens").text();     
                default: return countOfSelected + " " + $("#typesPensions").text(); 
                }
            }});
        }
    }    
	if ($("#ile_dest_voyage option")[0] != null) {
		$("#ile_dest_voyage option")[0].checked = false;
       // ROP 11/2/11 condiction if not found function DropdowncheckList
       if($("#ile_dest_voyage").dropdownchecklist != null){
		$("#ile_dest_voyage").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 250, textFormatFunction: function(options) {
			var selectedOptions = options.filter(":selected");
			var countOfSelected = selectedOptions.size();
			var size = options.size();
			switch(countOfSelected) {
				case 0: replaceDropdown(0); return $("#select_tr").text();
				case 1: replaceDropdown(selectedOptions.val()); return selectedOptions.text();
				case size: replaceDropdown(0); return $("#toutes").text();
				default: replaceDropdown(0); return countOfSelected + " " + $("#destinations").text() ;
			}
		}});
	}
    }
    
    
    //Bind elements to auto close the dropdown lists
    $('input[id*=ile_dest_voyage], input[id*=hebergement_type_id], input[id*=commune_id], .ui-dropdownchecklist').bind("click", function(){comboDelay();});
    //Auto close with no delay on mouse out
    $(".ui-dropdownchecklist-dropcontainer").mouseleave(function(){comboDelay(true);});
    //Reset timer on mouse move
    $(".ui-dropdownchecklist-dropcontainer").mousemove(function(){comboDelay();});
    
	if ($("#lieu_depart_voyage option")[0] != null) {
		$("#lieu_depart_voyage option")[0].checked = false;
        // ROP 11/2/11 condiction if not found function DropdowncheckList
        if($("#lieu_depart_voyage").dropdownchecklist != null){
		$("#lieu_depart_voyage").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 50, textFormatFunction: function(options) {
			var selectedOptions = options.filter(":selected");
			var countOfSelected = selectedOptions.size();
			var size = options.size();
			switch(countOfSelected) {
				case 0: replaceDropdown(0); return $("#select_tr").text();
				case 1: replaceDropdown(selectedOptions.val()); return selectedOptions.text();
				case size: replaceDropdown(0); return $("#toutes").text();
				default: replaceDropdown(0); return countOfSelected + " " + $("#destinations").text() ;
			}
		}});
	}
    }
}); 

// Activating dropdownchecklists in big google map
$(document).ready(function() {
	if ($("#TB-bigGoogleMapWrap").length != 0) {
		$("#commune_id").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 300, textFormatFunction:function(options) {
			var selectedOptions = options.filter(":selected");
			var countOfSelected = selectedOptions.size();
			var size = options.size();
			switch(countOfSelected) {
				case 0: return $("#select_tr").text();
				case 1: return selectedOptions.text();
				case size: return $("#commune_id option")[0].innerHTML;
				default: return countOfSelected + ' ' + $("#commune_tr").text();
			}
		}} );
		$("#hebergement_type_id").dropdownchecklist({ firstItemChecksAll: true, maxDropHeight: 230, textFormatFunction: function(options) {
			var selectedOptions = options.filter(":selected");
			var countOfSelected = selectedOptions.size();
			var size = options.size();
			switch(countOfSelected) {
				case 0: return $("#select_tr").text();
				case 1: return selectedOptions.text();
				case size: return $("#tous").text();     
				default: return countOfSelected + " " + $("#typesHebergements").text(); 
			}
		}}); 
	}
});

//The function to generate the ajax content
function getAjaxListeVoyageContent(index, params){
        $.post('/service/ajax/index.php', {sit_id:11, component:"voyage_voyage",action:"ajax_liste_voyage", mpfirst:index,args:params}, function(data){ 
            $("#main").html(data);
			if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
			TB_init();
		});
	}

function getAjaxListeVoyageContentSort(index, sort, params){
        $.post('/service/ajax/index.php', {sit_id:11, component:"voyage_voyage",action:"ajax_liste_voyage", mpfirst:index, sortResult:sort,args:params}, function(data){ 
            $("#main").html(data); 
			 if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }               
			 TB_init();
		});
	}
	

//The function to generate the ajax content
function getAjaxResultsVoyageContent(index, params){
        $.post('/service/ajax/index.php', {sit_id:11, component:"recherche",action:"ajax_recherche_voyage", mpfirst:index,args:params}, function(data){ 
			$("#voyageResults").html(data);
			if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
			TB_init();
		});
	}

function getAjaxResultsVoyageContentSort(index, sort, params){
        $.post('/service/ajax/index.php', {sit_id:11, component:"recherche",action:"ajax_recherche_voyage", mpfirst:index, sortResult:sort,args:params}, function(data){ 
			$("#voyageResults").html(data); 
			 if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }               
			 TB_init();
		});
	}                                    
 
function getAjaxResultsTravel(index, pageNumber, sort, promoOnly, criteres, ileDest, params){
        $.post('/service/ajax/index.php',
        {
            component:"recherche",
            action:"ajax_recherche_voyage",
            mpfirst:index,
            sortResult:sort,
            actualPage:pageNumber,
            promoOnly:promoOnly,
            critere: criteres,
            ile_dest_voyage: ileDest,
            pagination: true,
            args:params
        },
        function(data){
            if($("#main").html(data)){
                $($('input:radio[name=sort]')[sort]).attr('checked','checked');
                $('#promoOnly').attr('checked',promoOnly==1?'checked':'');
            }
             if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
             TB_init();
        });
}

function getAjaxResultsBestQuality(index, pageNumber, sort, promoOnly, criteres, ileDest, params){

        $.post('/service/ajax/index.php',
        {
            component:"voyage_voyage",
            action:"ajax_liste_best_quality",
            mpfirst:index,
            sortIndex:sort,
            actualPage:pageNumber,
            promoOnly:promoOnly,
            critere: criteres,
            ile_dest_voyage: ileDest,
            pagination: true,
            args:params
            
        },
        function(data){
            if($("#main").html(data)){
                $($('input:radio[name=sort]')[sort]).attr('checked','checked');
                $('#promoOnly').attr('checked',promoOnly==1?'checked':'');
            }
             if ($('.overlay').css('display') != 'none') {$('.overlay').fadeOut(4500);}
             TB_init();
        });
}

function getAjaxResultsTematics(index, pageNumber, sort, promoOnly, themeid){
    $.post('/service/ajax/index.php',
    {
        component:"voyage_voyage",
        action:"liste_voyage_par_theme",
        mpfirst:index,
        sortResult:sort,
        actualPage:pageNumber,
        promoOnly:promoOnly,
        pagination: true,
        theme_id:themeid
    },
    function(data){
        if($("#main").html(data)){
            $($('input:radio[name=sort]')[sort]).attr('checked','checked');
            $('#promoOnly').attr('checked',promoOnly==1?'checked':'');
        }
         if ($('.overlay').css('display') != 'none') {$('.overlay').fadeOut(4500);}
         TB_init();
    });
}

function getAjaxResultsVoyage(index, pageNumber, sort, promoOnly, criteres, ileDest, params){
    $.post('/service/ajax/index.php',
    {
        component:"voyage_voyage",
        action:"ajax_liste_voyage",
        mpfirst:index,
        sortIndex:sort,
        actualPage:pageNumber,
        promoOnly:promoOnly,
        critere: criteres,
        ile_dest_voyage: ileDest,
        pagination: true,
        args:params
    },
    function(data){
        if($("#main").html(data)){
            $($('input:radio[name=sort]')[sort]).attr('checked','checked');
        }
         if ($('.overlay').css('display') != 'none') {$('.overlay').fadeOut(4500);}
         TB_init();
    });
}

/**
* 
*/
function getAjaxListeVoyageContentRecherche(index, params){
	params['sit_id'] = 11;								  
	$.post('/service/ajax/index.php', params, function(data){ 
        $("#main").html(data);
		if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
		$('#searchButton').html("Rechercher");
		TB_init();
	});
}

$(document).ready(function(){
	if(window.noThickbox==1){
		//Syncing date pickers
		$("#date-picker2").bind("change", function(){
			$("#date-picker3").val($("#date-picker2").val());
			setDateDropDowns($("#date-picker3").attr('id'), 1);
			ficheHebergementVoyage_changeThickboxParameters(1, 2);
		});
		$("#date-picker3").bind("change", function(){
			$("#date-picker2").val($("#date-picker3").val());
			setDateDropDowns($("#date-picker2").attr('id'), 1);
			$("#date-picker2_day").addClass("picker_day"); //This class is removed when the above line is executed
			ficheHebergementVoyage_changeThickboxParameters(1, 2);
		});
	}
 });

// Import external parameters in thickbox
function ficheHebergementVoyage_changeThickboxParameters(noThickbox, datePickerId) {

	// Récupération de la date en cours
	var datedepart_string = $('#date-picker' + datePickerId).val();
	
	// Récupération du nombre de nuits en cours
	var nb_nuits_string = $('.duree').val();
	
	// Récupération du nombre d'adultes
	var nb_adultes_string = $('#adultes_0').val();
	// Récupération du nombre d'enfants
	var nb_enfants_string = $('#enfants_0').val();
	// Récupération du nombre de bébés
	var nb_bebes_string = $('#bebes_0').val();

	// Récupération du nombre d'adultes
	var nb_adultes_1_string = $('#adultes_1').val();
	// Récupération du nombre d'enfants
	var nb_enfants_1_string = $('#enfants_1').val();
	// Récupération du nombre de bébés
	var nb_bebes_1_string = $('#bebes_1').val();
	
	// Récupération du nombre d'adultes
	var nb_adultes_2_string = $('#adultes_2').val();
	// Récupération du nombre d'enfants
	var nb_enfants_2_string = $('#enfants_2').val();
	// Récupération du nombre de bébés
	var nb_bebes_2_string = $('#bebes_2').val();    
	
	// Récupération identifiant de devis
	if($('#package_auto_id').length == 0) {
		var package_auto_id_string = '';
		insertStatistiqueAction('H_DP_OUI_VOY_TB');
	}
	else {
		var package_auto_id_string = $('#package_auto_id').val();
		insertStatistiqueAction('V_DP_OUI_VOY_TB');
	}
	
	var url = $('#reservationBtnUrl').val();
	
	var reg=new RegExp("[?]+", "g");
	var url_tab=url.split(reg);
	
	var new_url = url_tab[0]+'?';
	if(!noThickbox){
		new_url += url_tab[1];
	}
	new_url += 'date_depart='+datedepart_string+'&';
	new_url += 'duree='+nb_nuits_string+'&';
	if(noThickbox){
		new_url += 'adults_0='+nb_adultes_string+'&';
		new_url += 'children_0='+nb_enfants_string+'&';
		new_url += 'baby_0='+nb_bebes_string+'&';
		new_url += 'adults_1='+nb_adultes_1_string+'&';
		new_url += 'children_1='+nb_enfants_1_string+'&';
		new_url += 'baby_1='+nb_bebes_1_string+'&';
		new_url += 'adults_2='+nb_adultes_2_string+'&';
		new_url += 'children_2='+nb_enfants_2_string+'&';
		new_url += 'baby_2='+nb_bebes_2_string+'&';                
		new_url += 'hebergementId='+$('#hebergement_id').val()+'&'; 
		new_url += 'num_rooms=' + $('#num_rooms_' + datePickerId).val() +'&';       
        new_url += 'aeroport='+$('#departureAirport').val()+'&';
	}else{
		new_url += 'adultes='+nb_adultes_string+'&';
		new_url += 'enfants='+nb_enfants_string+'&';
		new_url += 'bebes='+nb_bebes_string+'&';        
	}

	new_url += 'package_auto_id='+package_auto_id_string+'&?';
	new_url += url_tab[2];

	$('#reservationBtn1').attr('href',new_url);
	$('#reservationBtn2').attr('href',new_url);
	$('#reservationBtn3').attr('href',new_url);
	
	return true;
}


 function getAjaxListeRechercheContentRecherche(index, params){
		 
		$.post('/service/ajax/index.php', {sit_id:11, component:"hebergement_hebergement",action:"ajax_liste_recherche", mpfirst:index,args:params}, function(data){ 
			$("#hebergementList").html(data);
			if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
			$('#searchButton').html("Rechercher");
			TB_init();
		});
	}
	
//The function to generate the ajax content
function getAjaxListeRechercheContent(index, params){
		$.post('/service/ajax/index.php', {sit_id:11, component:"hebergement_hebergement",action:"ajax_liste_recherche", mpfirst:index,args:params}, function(data){ 
			$("#hebergementList").html(data);
			if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
			TB_init();
		});
	}
	
function getAjaxListeRechercheContentSort(index, sort, params){
		$.post('/service/ajax/index.php', {sit_id:11, component:"hebergement_hebergement",action:"ajax_liste_recherche", mpfirst:index, sortResult:sort,args:params}, function(data){ 
			$("#hebergementList").html(data); 
			 if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }               
			 TB_init();
		});
	}
	
	
	
	
// ROP 26/11/10 functions necesary for link pagination from small google map    
function getAjaxListeLinkContentLink(index, params){   
		$.post('/service/ajax/index.php', {sit_id:11, component:"hebergement_hebergement",action:"ajax_liste_link", mpfirst:index,args:params}, function(data){ 
			$("#hebergementListlink").html(data);
			if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
			$('#searchButton').html("Rechercher");
			TB_init();
		});
	}
	
//The function to generate the ajax content
function getAjaxListeLinkContent(index, params){
		$.post('/service/ajax/index.php', {sit_id:11, component:"hebergement_hebergement",action:"ajax_liste_link", mpfirst:index,args:params}, function(data){ 
			$("#hebergementListlink").html(data);
			if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }
			TB_init();
		});
	}
	
function getAjaxListeLinkContentSort(index, sort, params){
		$.post('/service/ajax/index.php', {sit_id:11, component:"hebergement_hebergement",action:"ajax_liste_link", mpfirst:index, sortResult:sort,args:params}, function(data){ 
			$("#hebergementListlink").html(data); 
			 if ($('.overlay').css('display') != 'none') { $('.overlay').fadeOut(4500); }               
			 TB_init();
		});
	}         
				 
  
//La funcion para generar el contenido con ajax
function getAjaxBigGoogleSearch(){               
		
				allCheckedPensionVals=[];
				$("input[name='pension[]']:checked").each(function  () {
					allCheckedPensionVals.push($(this).val());
				});
  
				allCheckedCritereVals=[];
				$("input[name='critere[]']:checked").each(function() {
					 allCheckedCritereVals.push($(this).val());
				});
				
				$.post('/service/ajax/index.php', {sit_id:11, component:"hebergement_hebergement", action:"ajax_big_map_search", 
													 ile_dest_hotel: ''+$("#ile_dest_hotel").val(), 
													 type_id: ($("#hebergement_type_id").val() ? ''+$("#hebergement_type_id").val() : ''), 
													 commune_id: ($("#commune_id").val() ? ''+$("#commune_id").val() : ''), 
													 hebergementNom: ''+$("#hotel_name").val(), 
													 pension: ''+allCheckedPensionVals, 
													 critere: ''+allCheckedCritereVals }, function(response){ 
														 
			   map.clearOverlays();
			   eval("hotels = " + response); 
			   
				//ROP 28/9/10 Make the icon to show casitas!!
				var iconsmall = new GIcon();
				iconsmall.image = "theme_front/theme_front_5/image/contenu/icon-gmap-zoomed.png";
				iconsmall.shadow = "theme_front/theme_front_5/image/contenu/mm_20_shadow.png";
				iconsmall.iconSize = new GSize(20, 30);
				iconsmall.shadowSize = new GSize(20, 18);
				iconsmall.iconAnchor = new GPoint(10, 30);
				iconsmall.infoWindowAnchor = new GPoint(3, 3); 

		returnPoints = [];
		var a = 0; 
		// Value's condiction important.               
		var aces = 0;
		var lslatitude = null;
		var lslongitude = null;
		var lszoom = null;             
                var licounthotels = hotels.length;
                var markerBounds = new GLatLngBounds(); // Center all the makers 
																			 
                // ROP 1/7/11 Show or Hide the Big google map
                if(licounthotels == 0){
                    //$('#isleMap').css("display","none");
                    if($('#isleMap').css("display") == 'block')
                        $('#isleMap').toggle("slow");                     
                } else {                   
                   if($('#isleMap').css("display") != 'block')
                      $('#isleMap').toggle("slow"); 
                }
                                                                             
                for(var i=0; i < licounthotels; i++) {     
				  //  if(1 == 1 || commune_id == null || commune_id == hotels[i].commune_id){
						// Values Necesary
						var point = null;
						var InfoHTML = null;
						var marker1 = null;
						var stan = hotels[i].standing.length/2;  
						  
						  aces = 1;                                      
						// conditions values importants
						if(aces == 1) {                   
							var point = new GLatLng(hotels[i].geolocalisation_latitude, hotels[i].geolocalisation_longitude);
							returnPoints[a++] = point;
							InfoHTML = hotels[i].description;                             
							var option = iconsmall; //{icon: iconsmall, title: hotels[i].name, zIndexProcess:1}
							marker1 = createMarker(point, InfoHTML, option, "", 400);
							map.addOverlay(marker1);
                                                        markerBounds.extend(point); // Fill MakerBounds to know  the corresponding zoom
							 
						// aLocations[i] = new Array(marker, "xx", InfoHTML, point);                                
							
                                                        // ROP 1/10/10 Verify if they come with the values necesary
							if(hotels[i].latitude_city != null && hotels[i].longitude_city != null && i < 1){
							   var lslatitude = hotels[i].latitude_city;
							   var lslongitude = hotels[i].longitude_city;
							   var lszoom = hotels[i].zoom_city;      
							}
							
							// resert value again to repect
							aces = 0;  
						}
					//}
				}
			   
                                // ROP 1/10/10 Condiction for Center map in Commune
				if(lslatitude != null && lslongitude != null){
                                     //var latlng = new GLatLng(lslatitude, lslongitude) ;                   
                                     //map.setCenter(latlng.getCenter(), latlng.getZoom()); 
                                     map.setCenter(markerBounds.getCenter(), map.getBoundsZoomLevel(markerBounds));
				}         
			   
			         // alert($("#commune_id").val().length);
				if($("#commune_id").val().length > 1){
					var str = $("#coordIle").val();
					var geo_lat = str.split(",")[0];
					var geo_long = str.split(",")[1];
					var zoom = str.split(",")[2];
					var latlng = new GLatLng(geo_lat, geo_long) ;
					map.setCenter(latlng, zoom - 1);  
				} else {
					//map.returnToSavedPosition(); 
				}
				
				// ---
				$('.btnBuscar').html("Rechercher des h&eacute;bergements"); 
				// not necesary  
				// updateCartLinks();
				TB_init();
			});
	}
	
function updateCartLinks() {           
	//add an Hebergement to the shopping cart
	// $(".cart").click(addToCartAjax);       
}
	
$(document).ready(function(){ 
	// ROP 12/11/10
	// not necesary
	// updateCartLinks();
   
	$('#moduleRecherche, #soyezZen, #orangeAvisVoyageurs, #blockBlueBlockAgenda, #blockOrangeBlockListeImgSmall').click(function(){
		$('#blockOrangeBlockListeImgSmall_2').remove();
		$('#blockOrangeBlockListeImgSmall').css("top",0);
		$('#blockOrangeBlockListeImgSmall').css('opacity', 1);
		$('#moduleRecherche').css('top', 0);
		$('#moduleRecherche').css('opacity', 1);
		$('#soyezZen').css('top',0);
		$('#soyezZen').css('opacity', 1);    
		$('#blockOrangeAvisVoyageurs').css('top',0);
		$('#blockOrangeAvisVoyageurs').css('opacity', 1);
		$('#blockBlueBlockAgenda').css('top',0);
		$('#blockBlueBlockAgenda').css('opacity', 1);   
															  
	});               
});    

function addToCartAjax(HebId) {          
			
			// ROP 15/11/10 NOT NECESARY , THIS PARAMETER COMES FROM THE FUNCTION
			//var HebId = this.id.substring(5);              
			var caption = this.title;  
			//set a temporary label and animation when loading
			$('#add_to_cart_'+HebId).html('<div id="cart_'+HebId+'">'+$("#hebergement_En_cours").val()+' <img height="16" width="16" align="absmiddle" src="theme_front/theme_front_5/image/module/hebergement/cart_loading2.gif"/></div>');
			//Set the item in SESSION and retrieve the HTML to add to the shopping_cart template ("encart_selection.tpl")
			$.post('/service/ajax/index.php?sit_id=11&component=selection&action=ajax_encart_selection&addCart_id='+HebId, function(data) {                                                       

				  //clean any previous shopCArt_ajax_content to avoid id conflits
				  $('#add_shopCart_ajax_content').html("");
								
				  // add the new item to the shopping_cart template
				  $('.orange_fonce').html($(data).find('.orange_fonce').html());
				  $('#type_offre').html($(data).find('#type_offre').html());  
				  $('#selection_compte_nombre').html($('#selection_nombre').html());
				  
				  $('#add_shopCart_ajax_content').html(data);                                
				  TB_show("", '#TB_inline?height=450&width=215&inlineId=add_shopCart_ajax_content', "HLA"/*group*/);                  
				  
				//if the template is not visible process an animation to put the shopping_cart template over the others in the left bar
				/*if($(document).scrollTop() > 200)
				  {                  
					  OtherTemplatesOpacity = 0.3;
					  windowsOffsetTop = 200;
					  HeightUp = $('#blockOrangeBlockListeImgSmall').height();

					  scroll = $(document).scrollTop()-windowsOffsetTop;
					  //create the template that will appear where the user is in the document (a copy of shopping_cart template)
					  DuplicatedTemplate = '<div class="block orange blockListeImgSmall" id="blockOrangeBlockListeImgSmall_2" style="position: relative; z-index:100;" >'+
																																	$('#blockOrangeBlockListeImgSmall').html()+'</div>';
					  //add the shopping_cart template to the left bar
					  $("#left").prepend(DuplicatedTemplate);
					  
					  //fix the position of the other templates in the left side bar because the new template added
					  $('#blockOrangeBlockListeImgSmall').css("top", -HeightUp-50);
					  $('#blockOrangeBlockListeImgSmall').css('opacity', OtherTemplatesOpacity);
					  $('#moduleRecherche').css('top', -HeightUp-50);
					  $('#moduleRecherche').css('opacity', OtherTemplatesOpacity);
					  $('#soyezZen').css('top', -HeightUp-50);
					  $('#soyezZen').css('opacity', OtherTemplatesOpacity);
					  $('#blockOrangeAvisVoyageurs').css('top', -HeightUp-50);
					  $('#blockOrangeAvisVoyageurs').css('opacity', OtherTemplatesOpacity);
					  $('#blockBlueBlockAgenda').css('top', -HeightUp-50);
					  $('#blockBlueBlockAgenda').css('opacity', OtherTemplatesOpacity);

					  //SlowDown the new template
					  $('#blockOrangeBlockListeImgSmall_2').animate({top: scroll}, 'slow');                               

					  //Remove the template used in the animation and fixed the position of the others with his remotion
					  setTimeout ( function(){              
							$('#blockOrangeBlockListeImgSmall_2').remove();
							$('#blockOrangeBlockListeImgSmall').css("top",0);
							$('#blockOrangeBlockListeImgSmall').css('opacity', 1);
							$('#moduleRecherche').css('top', 0);
							$('#moduleRecherche').css('opacity', 1);
							$('#soyezZen').css('top',0);
							$('#soyezZen').css('opacity', 1);    
							$('#blockOrangeAvisVoyageurs').css('top',0);
							$('#blockOrangeAvisVoyageurs').css('opacity', 1);
							$('#blockBlueBlockAgenda').css('top',0);
							$('#blockBlueBlockAgenda').css('opacity', 1);                                          
					  }, 5000);
				  }
				  */                                                                                               
				  //Set the label an icon that indicate the item added
				  $('#add_to_cart_'+HebId).html('<div id="cart_'+HebId+'">'+$("#hebergement_Ajoute").val()+' <img height="16" width="16" align="absmiddle" src="theme_front/theme_front_5/image/module/hebergement/cart.png"/></div>');                                            
			});
								
		//return false;    
}
   
	$('#moduleRecherche, #soyezZen, #orangeAvisVoyageurs, #blockBlueBlockAgenda, #blockOrangeBlockListeImgSmall').click(function(){
		   
		$('#blockOrangeBlockListeImgSmall_2').remove();
		
		$('#blockOrangeBlockListeImgSmall').css("top",0);
		$('#blockOrangeBlockListeImgSmall').css('opacity', 1);
		$('#moduleRecherche').css('top', 0);
		$('#moduleRecherche').css('opacity', 1);
		$('#soyezZen').css('top',0);
		$('#soyezZen').css('opacity', 1);    
		$('#blockOrangeAvisVoyageurs').css('top',0);
		$('#blockOrangeAvisVoyageurs').css('opacity', 1);
		$('#blockBlueBlockAgenda').css('top',0);
		$('#blockBlueBlockAgenda').css('opacity', 1);   
															  
	});               

// Insert statistics in table aol_statistique_action
function insertStatistiqueAction(statut) {

	var xhr_object = createXMLHttpRequest();

	// AJAX Call to insert statistics
	xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=voyage_voyage&action=insert_statistique_action&statut='+statut, true);
	xhr_object.send(null);
}

// Insert statistics in table dp_statistique_action
function insertDPStatistiqueAction(statut) {

	var xhr_object = createXMLHttpRequest();
	
	// AJAX Call to insert statistics
	xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=dynamic_packaging&action=insert_dp_statistique_action&statut='+statut, true);
	xhr_object.send(null);
}

//Detecting HomePage on ie7 
$(document).ready(function(){
    //track de concours button click
    if ($('#btnGrandJeuConcours').length){
        $('#btnGrandJeuConcours').click(function(){
            $.post("/service/ajax/index.php", {
                component: "jeu_concours", 
                action: "ajaxTrackJeuConcours", 
                //parameters   
                stajeuconcours_click: '1'
            },
            function(data){
                document.location.href= $('#btnGrandJeuConcours').attr('href');
            });
            return false;
        });
    }
    if($.browser.msie){
        if($.browser.version=="7.0" || $.browser.version=="6.0" ){
            
            if ($('#btnGrandJeuConcours').length){
                $('#menu li.submenu').css("background", "url(/theme_front/theme_front_5/image/module/menu/sub-menuBlue.gif) left top"); 
                $('#menu li.submenu a').css("background", "url(/theme_front/theme_front_5/image/module/menu/sub-menuBlue.gif) right top");
                $("#menu li.submenu ul li a, #menu li.submenu.hover-on ul li a").css('background', '');
            }  
        }
    }
});

function dp_progressbar(){    
	$.fn.reportprogress = function(val,maxVal) {            
		var max=100;
		if(maxVal)
			max=maxVal;
		return this.each(
			function(){        
				var div=$(this);
				var innerdiv=div.find(".progress");
				
				if(innerdiv.length!=1){                        
					innerdiv=$("<div class='progress'></div>");                    
					div.append("<div class=''>&nbsp;</div>");
					$("<span class=''>&nbsp;</span>").css("width",div.width()).appendTo(innerdiv);                    
					div.append(innerdiv);                    
				}
				var width=Math.round(val/max*100);
				innerdiv.css("width",width+"%");    
				div.find(".text").html();
			}        
		);      
	};    
}

function update(){
		$("#progressbar").reportprogress(++pct);
		if(pct==100){
				clearInterval(handle);
				pct=0;
		}
}

function stepper_sync(min_value, max_value, duree){
			var sync = function(elem){
			$('#numericStepper',$('.lenght-flight')).each(function(){
				if(this != elem && typeof(this.numericStepper )!= 'undefined'){
					this.numericStepper.setValue(elem.getValue(), false);
				}
			});  
			if(window.noThickbox==1){
				ficheHebergementVoyage_changeThickboxParameters(1, 2);
			}                
		}
		
		$('.numericStepper').each(function(i){
			$(this).get(0).className='numericStepper'+i;
			var num = new NumericStepper('.numericStepper'+i);    
			num.setParams({minValue:min_value, maxValue:max_value,onChange:function(elem){sync(elem);}});
			num.setValue(duree);
		});      
}


function updateDateDepart(num){ 
    // ROP  22/12/10  Knows from where comes the parameter
    if($('#departureAirport').val() != null && $('#departureAirport').val() != ''){
        paysDom = $('#departureAirport').val();
    }// ..
        
    // ROP 21/12/10 new ways to date
    var date_depart_day = $('#date-picker'+ num +'_day').val();    
    var date_depart_my = $('#date-picker'+ num +'_month').val();
    
    dMonthYear = date_depart_my.split('_');
    dMonth = parseInt(dMonthYear[1]);
    dYear = parseInt(dMonthYear[0]);
    dateDepartVoyage = dYear+'/'+dMonthYear[1]+'/'+date_depart_day;  
    date = new Date(dateDepartVoyage);                             
    
    $("#datedepart").val(dateDepartVoyage);
    var xhr_object = createXMLHttpRequest();
    
    if(paysDom === '' || ileDom === ''){                
        _setUpdatedDate(date, 0, 0);            
    }else{
            
    xhr_object.open("GET", '/service/ajax/index.php?sit_id=11&component=selection&action=ajax_get_decalage_horaire&pays_id='+paysDom+'&ile_id='+ileDom+'&sit_id='+sit_id+'', true);            
    xhr_object.onreadystatechange = function(){

            if ( xhr_object.readyState == 4 && xhr_object.status == 200 ) {
                response = xhr_object.responseText;                                                     
                decalage = response.split('-');
                dDepart = parseInt(decalage[0]);
                dRetour = parseInt(decalage[1]);
              _setUpdatedDate(date, dDepart, dRetour);
            }                
        }
            
        xhr_object.send(null);
    }                          
};

// 
function _setUpdatedDate(date, dDepart, dRetour){    
        // ROP 22/12/10 Get values necesary
        var dateDepartFinal = $("#datedepart").val();
        
        dDayMonthYear = dateDepartFinal.split('/');
        dDay = parseInt(dDayMonthYear[0]);
        dMonth = parseInt(dDayMonthYear[1]);
        dYear = parseInt(dDayMonthYear[2]);             
        // ROP 21/12/10 Set date with new values
        date = new Date(dateDepartFinal);            
                    
        if(isNaN(dDepart)){
            plus_depart = 0;  
        }else {
            plus_depart = dDepart;
        }
                    
        date.setDate(date.getDate() + parseInt($(".duree").val()) + parseInt(plus_depart)); 
        $(".dateDepartIle").html(weekDays[date.getDay()] + ' ' + date.getDate() + ' ' + months2[date.getMonth()] + ' ' + date.getFullYear());
        
        disDay = date.getDate();
        disDay = (disDay < 10) ? '0' + disDay : disDay;
        
        disMonth = date.getMonth() + 1;
        disMonth = (disMonth < 10) ? '0' + disMonth : disMonth;
        
        disYear = date.getFullYear();
        
        dateDepartShort = disDay+'/'+disMonth+'/'+disYear;            
        $(".date_short_depart").html(dateDepartShort);
        // $(".dateretour").get(0).value = dateDepartShort;            
                    
        if(isNaN(dRetour)){
            plus_retour = 0;
        }else {
            plus_retour = dRetour;
        }
        
        // Get values of listbox " departureAirport "
        var departCity = $('#departureAirport').get(0);
        departCity = departCity.options[departCity.selectedIndex].text;
            
        if(plus_retour == 0){
            $('#questionHelpTooltip').css('margin', '-129px 0 0 60px'); // Show Bubble more small
            $('.info_vol_alert').css('display', 'none'); 
            $('#retour_show_date_ile .name_ville_depart').html('&agrave; ' + departCity);                                
             
        } else {
            // ROP 22/12/10 Necesary to show
            // For a single accommodation (prepare that case). the condition to be  false to new changes
            if($('#departureAirport').val() == null && false){
                $("#questionHelpTooltip-top").css('height', '40px'); 
                $("#questionHelpTooltip").css('margin', '-78px 0 0 60px');
                $('.info_vol_alert').css('display', 'none');
                $('#retour_show_date_ile').hide();
                $('#retour_show_date_heberguement').show();
            } else {
                $('#questionHelpTooltip').css('margin', '-200px 0 0 60px'); // Show Bubble more size normal                    
                $('#retour_show_date_ile .name_ville_depart').html('&agrave; ' + departCity);
                $('.info_vol_alert').css('display', 'block');
                $('.info_vol_alert .name_ville_depart').html('&agrave; ' + departCity);   
            }
        }      
        
        date.setDate(date.getDate() + plus_retour);
        $(".dateRetournCity").html(weekDays[date.getDay()] + ' ' + date.getDate() + ' ' + months2[date.getMonth()] + ' ' + date.getFullYear());
        
        disDay = date.getDate();
        disDay = (disDay < 10) ? '0' + disDay : disDay;
        
        disMonth = date.getMonth() + 1;
        disMonth = (disMonth < 10) ? '0' + disMonth : disMonth;
        
        disYear = date.getFullYear();
        
        dateRetourShort = disDay+'/'+disMonth+'/'+disYear;
        $(".date_short_retour").html(dateRetourShort);
}   

