﻿/* SACD 2008 */
/* COMMON JAVASCRIPT FUNCTIONS */

/* ENABLE ROLLOVER ON TARGETED IMAGES (ALL BROWSERS) */
function imgRollover(elt) {
    jQuery(elt).each( function() {
		jQuery(this).hover(
			function() {
				jQuery(this).attr("src", jQuery(this).attr("src").replace("-off","-on"));
			},
			function () {
				jQuery(this).attr("src", jQuery(this).attr("src").replace("-on","-off"));
			}
		);
	});
}

/* POPULATE INPUTS WITH EXAMPLE TEXT TAKEN FROM INPUT TITLE */
eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('c.8.b=3(1){0.a(3(){$(0).9(3(){2($(0).4()==0.5){$(0).4("")}2(1){$(0).7(1)}}).6(3(){2($(0).4()==""){$(0).4(0.5)}2(1){$(0).d(1)}})})}',14,14,'this|focusClass|if|function|val|defaultValue|blur|addClass|fn|focus|each|toggleVal|jQuery|removeClass'.split('|'),0,{}))
function swapValue(elt) {
	jQuery(elt).toggleVal();
}

/* SAME HEIGHT FOR SAME CLASS ELEMENTS */
function sameHeight(elt) {
	var heightBlockMax=0;
	jQuery(elt).each(function(){ if( jQuery(this).height() > heightBlockMax ) heightBlockMax = jQuery(this).height(); }); // get max height
	if (jQuery.browser.msie) {
		if (parseInt(jQuery.browser.version) <= "6") {
			jQuery(elt).each(function(){ jQuery(this).css("height",heightBlockMax); }); // assign max height
		} else {
			jQuery(elt).each(function(){ jQuery(this).css("min-height",heightBlockMax); }); // assign max height
		}
	} else {
		jQuery(elt).each(function(){ jQuery(this).css("min-height",heightBlockMax); }); // assign max height
	}
	heightBlockMax=0;
}

/* FORM VALIDATION */
function formValidation(elt) {
	jQuery(":image").click(validationEmail);
	jQuery(elt).validationAideEnable(null,{showInlineMessages:true, showSummary:false});
}



function buildFormQuery() {
    var result = "";
    for (var i = 0; i < document.forms[0].elements.length; i++) {
        var el = document.forms[0].elements[i];

        if (el.tagName.toLowerCase() == "select"&&el.name!="c.de") {

            for (var j = 0; j < el.options.length; j++) {
                var op = el.options[j];
                if (op.selected && op.value!="")
                    result += "&" + encodeURI(el.name) + "=" + encodeURI(op.value);
            }
        } else if (el.tagName.toLowerCase() == "textarea") {
            result += "&" + encodeURI(el.name) + "=" + encodeURI(el.value);
        } else if (el.tagName.toLowerCase() == "input") {
            if (el.type.toLowerCase() == "checkbox" || el.type.toLowerCase() == "radio") {
                if (el.checked)
                    result += "&" + encodeURI(el.name) + "=" + encodeURI(el.value);
            } else if (el.type.toLowerCase() == "submit") {
               // if (el == submitButton) // is "el" the submit button that fired the form submit?
               //     result += "&" + encodeURI(el.name) + "=" + encodeURI(el.value);
            } else if (el.type.toLowerCase() != "button") {
                if(el.style.display != 'none' && el.value!="") {
                        result += "&" + encodeURI(el.name) + "=" + encodeURI(el.value);
                }
            }
        }
    }
    return result.substr(1, result.length - 1);
}

function buildForm() {
      var actionStr = document.forms[0].action;
      var varForm="c.de=";
      var getUrl;
      getUrl=actionStr;
      window.location.href= getUrl+ '/' + buildFormQuery()+"&c.de="+document.getElementById("destinationSearch").options[document.getElementById("destinationSearch").selectedIndex].value;
}

function buildForm2() {
      var actionStr = document.forms[0].action;
      var varForm="c.de=";
      var getUrl;
      getUrl=actionStr;
      window.location.href= getUrl+ '/' + "c.de="+document.getElementById("destinationSearch").options[document.getElementById("destinationSearch").selectedIndex].value
										+ "&c.th="+document.getElementById("themeSearch").options[document.getElementById("themeSearch").selectedIndex].value
										+ "&dmy="+document.getElementById("monthSearch").options[document.getElementById("monthSearch").selectedIndex].value
										+ "&dpci="+document.getElementById("citySearch").options[document.getElementById("citySearch").selectedIndex].value;
}

function buildFormAffinage() {
      var actionStr = document.forms[0].action;
      var varForm="";
      var search="c.de=";
      var nbVar=0;
      var destinationValue=document.getElementById("destinationSearch").options[document.getElementById("destinationSearch").selectedIndex].value;
	 if(document.getElementById("regionSearchbox").value!=""){
	  	search +=document.getElementById("regionSearchbox").options[document.getElementById("regionSearchbox").selectedIndex].value}
	 else{search +=destinationValue;}
      var getUrl;
      getUrl=actionStr;
      window.location.href= getUrl+ '/' + buildFormQuery()+"&"+search;
}




function validationEmail(){
	  var mail;
	  mail = document.getElementById("nlEmail").value;
	  if(mail!=""){
      	if ((mail.indexOf("@")>=0)&&(mail.indexOf(".")>=0)) {
      	} else {
      	   document.getElementById("nlEmail").title="emailFalse - Format d'email incorrect";
      	}
      }
      else{document.getElementById("nlEmail").title="emailEmpty - Veuillez saisir votre email";}
}


function updateRegion(value){
// On recupere le code de la ville selectionn??e
    var selectedCountryCode = document.getElementById("destinationSearch").options[document.getElementById("destinationSearch").selectedIndex].value;
    var j=1;
    document.getElementById("regionSearchbox").options.length=0;
    document.getElementById("regionSearchbox").options[0] = new Option("Toutes les regions","");
    for(var i = 0; i < destRegionArray.length; i++) {
        var regionCode=destRegionArray[i].split("|")[0];
        var regionLabel=destRegionArray[i].split("|")[1];
        if (selectedCountryCode!=""&&(regionCode.split(".")[0]==selectedCountryCode)) {
				if(value==regionCode){
                document.getElementById("regionSearchbox").options[j] = new Option(regionLabel,regionCode,false,true);
                }
                else{
                document.getElementById("regionSearchbox").options[j] = new Option(regionLabel,regionCode,false,false);
                }

               j++;
            }
        }
}
/* SUCKERFISH DROPDOWN MENUS */
function mySuperfish(elt) {
	jQuery(elt).superfish({
		pathClass : 'current'
	}).find('ul').bgIframe();
}

/* HOME CAROUSEL (LODGES AND HOTELS) */
function homeCarousel(elt) {
    jQuery(elt).jCarouselLite({
        scroll: 1,
        btnNext: ".next",
        btnPrev: ".prev",
		visible: 1,
        auto: 3000,
	    speed: 1000
    });
	jQuery(elt).addClass('carouselEnabled');
}

/* PRODUCT PAGE CAROUSEL (PICTURES) */
function productPicsCarousel(elt) {
	jQuery(elt).addClass('carouselEnabled');
	// get total number of items
	var elementQuantity = jQuery(elt+' li').size();
	// add the prev/next buttons and the counter
	jQuery(elt).append('<span class="prev"></span>');
	jQuery(elt).append('<span class="counter"></span>');
	jQuery(elt).append('<span class="next"></span>');
	// initialize the counter
	jQuery(elt+' .counter').html('<strong>1</strong>/'+elementQuantity);
	// disable the prev button for a start
	jQuery(elt+' .prev').addClass('disabled');
	// launch carousel
    jQuery(elt).jCarouselLite({
        scroll: 1,
        btnNext: ".next",
        btnPrev: ".prev",
		visible: 1,
	    speed: 500,
		circular: false,
		afterEnd: function(curr, itemLength) {
			// get id and then number of current step
            var currentId = jQuery(curr).attr('id');
			var currentElement = parseInt(currentId.charAt(currentId.length-1),10);
            // update counter
			jQuery(elt+' .counter').html('<strong>'+currentElement+'</strong>/'+elementQuantity);
    	}
    });
    jQuery('.diapo a').click( function () {
        var newTitle = jQuery(this).children('img').attr('title');
        var newSrc = jQuery(this).attr('href');
        // update image with imported src and title attributes
        jQuery("#bigPic").children('img').attr("src",newSrc).attr("title",newTitle);
        // if legend container exists, change text to imported title attribute
        if (jQuery('#bigPicLegend').size() > 0) {
            jQuery('#bigPicLegend').text(newTitle);
        }
        return false;
    });
}

/* PRODUCT PAGE FREE ESTIMATE */
function freeEstimate(elt){
	jQuery(elt).addClass('offLeft');
	jQuery('#childrenQuant').change(function() {
		jQuery(elt).addClass('offLeft');
		var divToShowQuant = jQuery('#childrenQuant option:selected').val();
		if(divToShowQuant) {
			for (i = 0;  i < divToShowQuant;  ++i ) {
            	var myNum = i+1;
				jQuery('#addField'+myNum).removeClass('offLeft');
			}
		}
	} );
};

/* DATE PICKER */
function myDatePicker(elt) {
    jQuery(elt).datepicker(jQuery.extend({},jQuery.datepicker.regional["fr"],{
        beforeShow: customRange,
		showAnim: "fadeIn",
		dateFormat: "dd/mm/yy",
		firstDay: 1,
	    changeFirstDay: false,
		showOn: "both",
	    buttonImage: "/CS/img/bt-calend.gif",
	    buttonImageOnly: true
	})).attr("readonly", "readonly");
    function customRange(input) {
	    return {
	    	minDate: (input.id == "customRetDate" ? jQuery("#customDepDate").datepicker("getDate") : null),
	        maxDate: (input.id == "customDepDate" ? jQuery("#customRetDate").datepicker("getDate") : null)
		};
	}
}


/* PRODUCT PAGE TABS */
function myTabs(elt) {
	jQuery(elt).addClass('tabsEnabled');
	jQuery('.tabContent').addClass('offLeft');
	jQuery('.tabContent:first').removeClass('offLeft');
	jQuery('#topTabs li:first').addClass('selected');
	jQuery('#bottomTabs li:first').addClass('selected');
	jQuery(elt+' a').click(function() {
		var tabContentToShow = jQuery(this).attr('href');
		var tabToShow = jQuery(tabContentToShow).attr('id');
		jQuery('.tabContent').addClass('offLeft');
		jQuery(tabContentToShow).removeClass('offLeft');
		jQuery(elt+' li').removeClass('selected');
		jQuery(elt+' li.'+tabToShow+'Tab').addClass('selected');
	});
	jQuery('#getPrice a').click(function() {
		var tabContentToShow = jQuery(this).attr('href');
		var tabToShow = jQuery(tabContentToShow).attr('id');
		jQuery('.tabContent').addClass('offLeft');
		jQuery(tabContentToShow).removeClass('offLeft');
		jQuery(elt+' li').removeClass('selected');
		jQuery(elt+' li.'+tabToShow+'Tab').addClass('selected');
	});
}

/* ALPHABETICAL HOTEL LIST ACCORDION */
function hotelListAccordion(elt) {
	jQuery('#hotelListContainer').prepend('<p id="linkToggleAllHotels"><span class="openLink">Tout montrer</span> | <span class="closeLink">Tout cacher</span></p>');
	jQuery(elt).addClass('accordionEnabled');
	jQuery(elt).children('dd').hide();
	jQuery(elt).children('dt').attr('title','Montrer');
	jQuery(elt).children('dt.active').attr('title','Cacher').next('dd').show();
	jQuery(elt).children('dt').click(function() {
		jQuery(this).toggleClass('active');
		jQuery(this).next('dd').slideToggle();
		var linkToActivate = jQuery(this).attr('id');
		var linkToActivate = '#'+linkToActivate;
		jQuery('.letterList a[@href='+linkToActivate+']').toggleClass('active');
		if (jQuery(this).attr('class')=="active") {
        	jQuery(this).attr('title','Cacher');
		} else {
        	jQuery(this).attr('title','Montrer');
		}
	});
	jQuery('#linkToggleAllHotels .openLink').click(function() {
		jQuery(elt).children('dd').slideDown();
		jQuery(elt).children('dt').addClass('active').attr('title','Cacher');
		jQuery('.letterList a').addClass('active');
	});
	jQuery('#linkToggleAllHotels .closeLink').click(function() {
		jQuery(elt).children('dd').slideUp();
		jQuery(elt).children('dt').removeClass('active').attr('title','Montrer');
		jQuery('.letterList a').removeClass('active');
	});
	jQuery('.letterList a').click(function() {
		var toShow = jQuery(this).attr('href');
		toShow = jQuery(toShow).attr('id');
		jQuery(this).addClass('active');
		jQuery(elt).children('dt#'+toShow).addClass('active');
		jQuery(elt).children('dt#'+toShow).next('dd').slideDown();
	});
}

/* FORM VALIDATION */
function formValidationCustom(elt) {
	jQuery(elt).prepend('<div id="ClientValidationSummary"></div>');
	jQuery(elt).validationAideEnable(null, {summaryMessage:"<h3>Merci de corriger les erreurs suivantes :</h3>"});
}

jQuery(document).ready(function() {

    /* ADD hasJS CLASS TO BODY FOR ABS/REL POSITIONNING */
	jQuery("body").addClass("hasJS");

    /* HIDE QUICK LINKS */
	jQuery('#quickAccess').addClass('offLeft');
	if (parseInt(jQuery.browser.version) <= "6") { jQuery('#logoContact').append('<span id="logoContactBg">&nbsp;</span>'); }

    /* SAME HEIGHT FOR HOME BLOCKS */
	// if (jQuery('#homeTextContent .homeText').size() > 1) { initSameHeight = sameHeight('#homeTextContent .homeText'); }

    /* CONTACT FORM VALIDATION */
	if (jQuery('#nlForm').size() > 0) { initFormValidation = formValidation('#nlForm'); }

	/* POPULATE INPUTS WITH EXAMPLE TEXT TAKEN FROM INPUT TITLE */
	if (jQuery('.swapValue').size() > 0) { initSwapValue = swapValue('.swapValue'); }

    /* SUCKERFISH DROPDOWN MENUS */
    if (jQuery('ul#mainNav').size() > 0) { initMainNav = mySuperfish("ul#mainNav"); }

    /* PRODUCT PAGE TABS */
    if (jQuery('.tabs').size() > 0) { initTabs = myTabs('.tabs'); }

    /* HOME CAROUSEL */
    if (jQuery('#homeCarousel').size() > 0) { initHomeCarousel = homeCarousel('#homeCarousel'); }

    /* PRODUCT PAGE CAROUSEL */
    if (jQuery('#productPicsCarousel').size() > 0) { initProductPicsCarousel = productPicsCarousel('#productPicsCarousel'); }

	/* PRODUCT PAGE FREE ESTIMATE */
	if (jQuery('.addField').size() > 0) { initFreeEstimate = freeEstimate('.addField'); }

	/* HOTEL LIST ACCORDION */
	if (jQuery('.accordion').size() > 0) { initHotelListAccordion = hotelListAccordion('.accordion'); }

	/* CUSTOM SAFARI FORM VALIDATION */
	if (jQuery('#customSafari').size() > 0) { initFormValidation = formValidationCustom('#customSafari'); }

	/* DATE PICKERS */
	if (jQuery('.datePicker').size() > 0) { initMyDatePicker = myDatePicker('.datePicker'); }

});

/* Image Random*/

function randomImage(value) {
	var panoramiquePictureArray = new Array("/CS/images/bandeau/petitelephant.jpg","/CS/images/bandeau/petitelephants.jpg","/CS/images/bandeau/petitrhino.jpg","/CS/images/bandeau/petitzebre.jpg","/CS/images/bandeau/kenyap04.jpg","/CS/images/bandeau/kenyap06.jpg","/CS/images/bandeau/kenyap07.jpg","/CS/images/bandeau/kenyap08.jpg","/CS/images/bandeau/namibiep02.jpg","/CS/images/bandeau/kenyap01.jpg","/CS/images/bandeau/kenyap05.jpg","/CS/images/bandeau/namibiep01.jpg","/CS/images/bandeau/namibiep03.jpg");
	var bgImage = panoramiquePictureArray[(Math.round(Math.random()*(panoramiquePictureArray.length-1)))];
	if (document.getElementById("panoramique") != null) {
		document.getElementById("panoramique").src = bgImage;
		document.getElementById("panoramique").alt = value;
	}
}

function randomImageHome(value) {
	var panoramiquePictureArray = new Array("/CS/images/bandeau/rhino.jpg","/CS/images/bandeau/tortilis.jpg","/CS/images/bandeau/guepard.jpg","/CS/images/bandeau/oryx.jpg","/CS/images/bandeau/kenya10.jpg","/CS/images/bandeau/kenya06.jpg","/CS/images/bandeau/kenya03.jpg","/CS/images/bandeau/namibie05.jpg","/CS/images/bandeau/namibie03.jpg","/CS/images/bandeau/kenya11.jpg","/CS/images/bandeau/kenya08.jpg","/CS/images/bandeau/kenya05.jpg","/CS/images/bandeau/kenya02.jpg");
	var bgImage = panoramiquePictureArray[(Math.round(Math.random()*(panoramiquePictureArray.length-1)))];
	if (document.getElementById("panoramique") != null) {
		document.getElementById("panoramique").src = bgImage;
		document.getElementById("panoramique").alt = value;
	}
}

function randomImageProd(value1, value2) {
	var panoramiquePictureArray = new Array("/CS/images/bandeau/petitelephant.jpg","/CS/images/bandeau/petitelephants.jpg","/CS/images/bandeau/petitrhino.jpg","/CS/images/bandeau/petitzebre.jpg","/CS/images/bandeau/kenyap04.jpg","/CS/images/bandeau/kenyap06.jpg","/CS/images/bandeau/kenyap07.jpg","/CS/images/bandeau/kenyap08.jpg","/CS/images/bandeau/namibiep02.jpg","/CS/images/bandeau/kenyap01.jpg","/CS/images/bandeau/kenyap05.jpg","/CS/images/bandeau/namibiep01.jpg","/CS/images/bandeau/namibiep03.jpg");
	var bgImage = panoramiquePictureArray[(Math.round(Math.random()*(panoramiquePictureArray.length-1)))];
	if (document.getElementById("panoramique") != null) {
		document.getElementById("panoramique").src = bgImage;
		document.getElementById("panoramique").alt = "Voyage, circuit ou séjour "+value1+" "+value2;
	}
}



function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 ;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function SetCriteriaSelectionnees(){
  	var dpci=document.getElementById("citySearch").value;
	var th=document.getElementById("themeSearch").value;
	var de=document.getElementById("destinationSearch").value;
	strCriteriaOffresSelectionnees = "dpci="+dpci+"&c.th="+th+"&c.de="+de;
	Selection('/ajaxResults.jsp', strCriteriaOffresSelectionnees);
}
function Selection(pageName, params){
	xhOffresSelectionnees = GetXmlHttpObject();
	if(xhOffresSelectionnees == null){
		alert ("Votre navigateur ne supporte pas AJAX!");
  		return;
  	}
	var url = pageName + "?" + params ;
	xhOffresSelectionnees.open("GET",url,true);
	xhOffresSelectionnees.send(null);
	}


function GetXmlHttpObject(){
	var xmlHttp = null;
	try{
  		// Firefox, Opera 8.0+, Safari
  		xmlHttp = new XMLHttpRequest();
  	}
	catch(e){
  		// Internet Explorer
  		try{
    		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    	}
  		catch(e){
    		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    	}
  	}
	return xmlHttp;
}
