var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

var myScreenWidth = 0, myScreenHeight = 0;

var closeWithOverlay= true;

// REDIMENSIONNEMENT DE LA FENETRE
function sizeWindow() {
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myScreenWidth = window.innerWidth;
        myScreenHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myScreenWidth = document.documentElement.clientWidth;
        myScreenHeight = document.documentElement.clientHeight;
    }
}

var scrolling = function(elt){
    var speed = elt;
    jQuery('a[href^="#"]').bind('click',function(){
        var id = jQuery(this).attr('href');
        if(id == '#')
            goTo('body');
        else
            goTo(id);
        return(false);
    void(0);
    });
    function goTo(ancre){jQuery('html,body').animate({scrollTop:jQuery(ancre).offset().top},speed,'swing',function(){
          if(ancre != 'body')
                window.location.hash = ancre;
          else
              window.location.hash = '#';
          jQuery(ancre).attr('tabindex','-1');
          jQuery(ancre).focus();
          jQuery(ancre).removeAttr('tabindex');
      });
    }
};

function heightWrapper() {
    var heightUnderfooter = $('#underfooter .gestion').height();
    var heightFooter = $('#footer').height();
    var heightHeader = $('#header').height();
    var errorPage = myScreenHeight - (heightUnderfooter + heightFooter + heightHeader) - 45;
    $('#error-404').height(errorPage);
}

function heightBigSlider() {
    var heightUnderfooter = $('#underfooter .gestion').height();
    var heightHeader = $('#header').height();
    var heightAccroche = $('#accroche-hp').height();
    var heightSlider = myScreenHeight - (heightUnderfooter + heightHeader + heightAccroche) - 26;
    $('.sliderTop-hp, .sliderTop-hp #contentSliderTop, .sliderTop-hp #contentSliderTop .headerimg').height(heightSlider);
}

var etabLayerList = function() {
    $('#etab-layer').css("left" , "0").css("width", "605px");
}
var etabLayerCarte = function() {
    $('#etab-layer').css("left" , "-90px").css("width", "940px");
}

var resetItemNavEtab = function() {
    $('#etab-layer .primary-nav li').removeClass('active').addClass('not-active');
    $('#etab-layer .primary-nav li.underfooter-view-1').removeClass('not-active').addClass('active');
}

var resetNavEtab = function() {
   $('.underfooter-view').hide();
   $('.underfooter-view-1').show();
   //$('#etab-layer-count').removeClass('content-2').addClass('content-1');
}
var resetAllFooterNav = function() {
    $('.overlay-bottom').hide();
    $('#close-footer .content .left li.overlay').each(function(i,item) {
        $('#'+$(this).data('related')).hide();
        $(this).removeClass('selected');
    });    
    resetItemNavEtab ();
    etabLayerList ();
    resetNavEtab ();
}
// URL POUR REFERENCEMENT
var urlLocationRel = function(url) {
    window.open(url);
}

// CHARGEMENT DE LA PAGE
$(document).ready(function(){

    // GESTION DE L'ALTERNATIF
    $('#global').removeClass('global-not-js').addClass('global-width-js');

    //  NAVIGATION PRINCIPALE
    $('#nav-principal ul.sub-menu').hide();
    $('#nav-principal li.menu-item').hover(function(){
        $(this).addClass('hover');
        $('ul.sub-menu',this).show();
    }, function(){
        $(this).removeClass('hover');
        $('ul.sub-menu',this).hide();
    });

    // ANCRE
    scrolling(1500);

    //  LIEN JS
    $(".link-js").delegate("a.furl", "click", function(){
        var url = $(this).data('furl');
        var target = $(this).attr('target');
        switch( target ){
            case '_blank':
                window.open(url);
                break;
            case '_self':
            default:
                window.location.href = url;
                break;
        }
        return false;
    });

    // MENU HAUT
    BrowserDetect.init();       
    var tabHeight = new Array();
    $('#header > .nav li a, #header > .nav li span.active').each(function(){
        var heightGlobal = $(this).parents('li').height();
        if(BrowserDetect.browser == "Explorer"  && BrowserDetect.version == "7"){
            var height = (heightGlobal - $(this).height())/2 + 3;
        } else {
            var height = (heightGlobal - $(this).height())/2;
        }

        $(this).css('margin-top',height);
    });

    //  POUR OUVRIR LES OFFRES EN IFRAME
    $(".link-offres").delegate("a.furl[target='dispoprice']", "click", function(){
        var url = $(this).data('furl');
        jQuery('#wrapper .content').html('<iframe width="980" height="1800" name="dispoprice" src="'+url+'" style="border:0px transparent"></iframe>');
        return false;
    });

    // LETTRINE HP
    var lettrine = $('#accroche-hp h2').text().substr(0,1);
    $('#lettrine span').html(lettrine);
    
    var hauteurContent = $('#accroche-hp h2').height();
    switch (hauteurContent){
        case 54:
            $('#accroche-hp').removeClass('bannerDefault').addClass('bannerSize2');
            break;
        case 81:
        case 82:
            $('#accroche-hp').removeClass('bannerDefault').addClass('bannerSize3');
            break;
        case 108:
        case 109:
            $('#accroche-hp').removeClass('bannerDefault').addClass('bannerSize4');
            break;
    }
  
    // TOOLTIP
    $('.tipsy-s').tipsy({gravity: 's'});
    $('.tipsy-w').tipsy({gravity: 'w', html: true});


    // MIN SLIDER HP OFFRES
    $('#slider2').bxSlider({
        infiniteLoop: true,
        auto: false,
        speed: 300,
        pager: true           
    });

    // SKIN FORM
    $(".formlang select, .form-resa select, .form-resa .submit, #newsletter .submit, .uniform select, .uniform input").uniform(); // BANDEAU LANGUE

    // CALENDRIER
    var dates = $( ".calendar-input" ).datepicker({
        buttonImage: "/content/themes/twentyten/css/images/commun/vide.gif",
        showOn: "button",
        buttonImageOnly: true,
        defaultDate: "+1w",
        changeMonth: false,
        numberOfMonths: 1,
        minDate : new Date(),
        onSelect: function( selectedDate ) {
            var option = $(this).attr('class').search( 'from' ) != -1 ? "minDate" : "maxDate",
            myclass = $(this).attr('class').search( 'from' ) != -1 ? "from" : "to",
            instance = $( this ).data( "datepicker" );
            date = $.datepicker.parseDate(
                instance.settings.dateFormat ||
                $.datepicker._defaults.dateFormat,
                selectedDate, instance.settings );
                
            // prepare la date de depart (date de fin) qui est la date darrivee + 1 jour
            date.setDate( date.getDate() + 1 );
            
            dates.not( '.'+myclass ).datepicker( "option", option, date );
            dates.filter( '.'+myclass ).val( selectedDate );
        },
        // format input form to push in input hidden
        onClose: function(dateText, inst) {
            var f = $(this).closest('form');
            var dateformat = inst.settings.dateFormat ||
                $.datepicker._defaults.dateFormat;
            datefrom = $.datepicker.parseDate(dateformat, $('.from', f).val());
            dateto = $.datepicker.parseDate(dateformat, $('.to', f).val() );
            jQuery('.fromday', f).val( datefrom.getDate() ) ;
            jQuery('.frommonth', f).val( datefrom.getMonth()+1 );
            jQuery('.fromyear', f).val( datefrom.getFullYear() );
            jQuery('.nbdays', f).val( daydiff(datefrom, dateto) );
        }
    });

    $("#social-toolbar").hide();
    $(".share").click(function(){
        $("#social-toolbar").toggle();
    });

    // TOGGLE RESA HEADER
    $(".home #resa-small .container").delay(5000).queue( function(){
        $(this).hide();
    });
    $("body:not(.home) #resa-small .container").hide();
    
    $("#resa-small .top").click(function(){
        $(this).toggleClass(function() {
            if ($(this).is('.more')) {
                return 'less';
            } else {
                return 'more';
            }
        });
        $("#resa-small .container").toggle();
    });

    // GESTION DE L UNDERFOOTER
    $('#close-footer-link').click(function() {
        $('#close-footer').removeClass('close').addClass('open');
        $('#open-footer').removeClass('open').addClass('close');
        $('.overlay-bottom').hide();
        resetAllFooterNav();
    });

    $('#open-footer-link').click(function() {
        $('#close-footer').removeClass('open').addClass('close');
        $('#open-footer').removeClass('close').addClass('open');
    });

    //RESA FOOTER
    $('#tabs li').click(function() {
        $('#tabs li').removeClass('active').addClass('default');
        $(this).removeClass('default').addClass('active');
        $('#typelink').val($(this).data('id'));        
    });
    //ETAB FOOTER
    $('#etab-layer .nav-1 li').click(function() {
        $('#etab-layer .nav-1 li').removeClass('active').addClass('default');
        $(this).removeClass('default').addClass('active');
        if($(this).data('typeetab') == 1){
           $('#etab-layer-count').removeClass('content-2').addClass('content-1');
        }
        else {
            $('#etab-layer-count').removeClass('content-1').addClass('content-2');
        }
        // LISTE LVL2
        $('div.nav-2 ul').addClass('nav-none').removeClass('nav-bloc');
        $('ul.nav-2-'+$(this).data('id')).removeClass('nav-none').addClass('nav-bloc');
        // LISTE LVL3
        $('div.nav-3 ul').addClass('nav-none').removeClass('nav-bloc');
        $('ul.nav-3-'+$(this).data('id')).removeClass('nav-none').addClass('nav-bloc');
        // CARTE
        $('.carte-view').addClass('nav-none').removeClass('nav-bloc');
        $('.carte-view-'+$(this).data('id')).removeClass('nav-none').addClass('nav-bloc');
        
    });
    //ETAB NIVEAU 2
    $('div.nav-2 ul.nav-bloc li').live('hover',function() {
        $('div.nav-2 ul.nav-bloc li').removeClass('active').addClass('default');
        $(this).addClass('active').removeClass('default');
        //NIV 3
        $('div.nav-3 ul').addClass('nav-none').removeClass('nav-bloc');
        $('ul.nav-3-'+$(this).data('id')).removeClass('nav-none').addClass('nav-bloc');
    });
    //ETAB NIV 3
    $('div.nav-3 ul.nav-bloc li').live('hover',function() {
        $('div.nav-3 ul.nav-bloc li').removeClass('active').addClass('default');
        $(this).addClass('active').removeClass('default');
    });

    //FOOTER ELEMENT
    $('#close-footer .content .left li.overlay').click(function(event) {
        if($(event.target).hasClass('overlay') || $(event.target).parent('li.overlay').length > 0) {
            $(this).siblings('li').each(function(i,item) {
                $('#'+$(this).data('related')).hide();
                $(this).removeClass('selected');
            });
            if($(this).hasClass('selected')) {
                $('#'+$(this).data('related')).hide();
                $('.overlay-bottom').hide();
                $(this).removeClass('selected');
            } else {
                $('.overlay-bottom').show();
                $(this).addClass('selected');
                $('#'+$(this).data('related')).show();
            }
        }
    });

    $('.overlay-bottom').click(function() {
        if(closeWithOverlay===true) {
            resetNavEtab();
            etabLayerList ();
            resetAllFooterNav();
            resetItemNavEtab ();
        }
    });
     $('#underfooter .form-big-resa input.submit').click(function() {
        if(closeWithOverlay===true) {
            resetNavEtab();
            etabLayerList ();
            resetAllFooterNav();
            resetItemNavEtab ();
        }
    });

    // NAVIGATION NAV ETABLISSEMENT

    // ON MASQUE LE LIEN QUI POINTE VERS LA LISTE DES ETABLISSEMENTS
    var secondaryNavEtab = "";
    $('#secondary-nav-etab').css("display", "none");

    resetNavEtab ();
    $('#etab-layer .primary-nav li').click(function() {
        if ($(this).data('view') != 3){
           $('#etab-layer .primary-nav li').removeClass('active').addClass('not-active');
           $('#etab-layer .primary-nav li.underfooter-view-'+$(this).data('view')).removeClass('not-active').addClass('active');
           $('#etab-layer div.underfooter-view').hide();
           $('#etab-layer div.underfooter-view-'+$(this).data('view')).show();
           if ($(this).data('view') == 1){
              etabLayerList ();
           }
           else {
               etabLayerCarte ();
           }
        }
    });

    // 404
    $('#ponctuation').html('!');
    var decoError = $('#error-404 .title').width() - $('#error-404 .s-title').width() - 15;
    $('#decoError').css("width" , decoError).css("right", $('#error-404 .s-title').width()+15);

    // TAILLE DE LA FENETRE
    sizeWindow();
    heightWrapper();

    // SLIDER HP BIG
    heightBigSlider();

    // RESIZE
    $(window).resize(function () {
        sizeWindow();
        heightWrapper();
        heightBigSlider();
    });

    // LINK JS
   /* $('.link-js').each(function(){
       var urlReplaceSource = $('a.replace[href!="#"]',$(this));
       $('a.replace[href="#"]',$(this)).each(function(){
           $(this).attr('href',urlReplaceSource.attr('href'));
       });
    });
    */

    // SWITCH LANGUAGE
    jQuery("#wpml-select").change( function(){
        window.location = jQuery("#wpml-select").val() ;
    });

});

function parseDate(str) {
    var mdy = str.split('/')
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function daydiff(first, second) {
    return (second-first)/(1000*60*60*24)
}

function teqhhotelDispoprice(myForm){
        teqhhotelFormValidation(myForm, 0);
}

// Form validation with control
function teqhhotelFormValidation(myForm, mandatoryCode){
        if (mandatoryCode == 1 && myForm.AccessCode.value == "") {
                alert("You must type in your code ID");
                return (false);
        }
        myForm.action = FBRESA + "dispoprice.phtml";
        if (FB_useGoogleAnalytics) {
                sessId = generateSession();
                profilValue = escape("SESSION=" + sessId + "&CODE=GoogleAnalytics");
                if ((typeof myForm.profil) == "undefined") {
                        var newInput = document.createElement("input");
                        newInput.setAttribute("type", "hidden");
                        newInput.setAttribute("name", "profil");
                        newInput.setAttribute("value", profilValue);
                        myForm.appendChild(newInput);
                } else {
                        myForm.profil.value = profilValue;
                }
        }
        //window.open('http://www.google.fr','dispoprice', 'toolbar=no,width=800,height=550,menubar=no,scrollbars=yes,resizable=yes');

        jQuery('#wrapper .content').html('<iframe width="980" height="1800" name="dispoprice" src="" style="border:0px transparent"></iframe>');

        myForm.submit();
        if (FB_useGoogleAnalytics) {
                var cname = "";
                if ((typeof myForm.AccountName) != "undefined" && myForm.AccountName.value != "")
                        cname = myForm.AccountName.value;
                else
                        cname = myForm.Clusternames.value;
                transferGAdata(sessId, cname);
        }
        return (true);
}

