$(document).ready(function(){
  var classResaName = $("#center").attr("class").toString();
  if ($(".magazine")) {
    $(".blockThalassa").height($(".listeDestination").height() + 272);
  }
  else{ $(".blockThalassa").height($(".listeDestination").height()+285);}
    if(classResaName == "reservationSimple"){
    $(".blockThalassa").height(620);
  }
  loadBackGround();
  showselectEnfant();
  initLoaderBP();
  initPopins();
  resizeOverlayForPopin();
  activeMenu();
  showFenetre();
  //document.getElementById("what").onmousemove = position;
  setEventMain();
  searchEngine();
  simpleReservation();
  selectSousMenu();
  abonnement();
  selectExperts();
  getBienreunirPdf();
  changeSoinAZ();
  selectExpertDetail();
  searchEngineMagazine();
	initEarlyBooking();
    changeDispo();
  /***slimbox***/
    tooltip();//active les tooltip simple
    imagePreview();//active les tooltip image preview
    screenshotPreview();//active les tooltip lien avec preview

    $("a[rel^='prettyPhoto']").prettyPhoto({
      animationSpeed: 'normal', /* fast/slow/normal */
      padding: 40, /* padding for each side of the picture */
      opacity: 0.35, /* Value betwee 0 and 1 */
      showTitle: true, /* true/false */
      allowresize: true, /* true/false */
      counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
      theme: 'light_rounded' /* light_rounded / dark_rounded / light_square / dark_square */
    });
  /*****/
  if($(".agenda").length){
    monthAgenda();
    offersAgenda();
    popinAgenda();
  }
  destinationContentsTabs();
});

function destinationContentsTabs() {

    /******** Code wich hides comments zone **********/
    $("div.navigationInterne div.sousMenu a.avis").parents("li").remove();
    $("#commentZone").remove();
    /******** End Code wich hides comments zone **********/

    $("div.sousMenu li a").click(function() {
        if ($(this).hasClass("withoutDiapo")) {
            $("div.blocDiapo").hide();
            $("div.resultList").hide();
        } else {
            $("div.blocDiapo").show();
            $("div.resultList").show();
        }
    });
    $('#doZone div.blockArticle a, #seeZone div.blockArticle a').live('click', function() {
        var href = $(this).attr("href");
        if (href.indexOf("#") > -1) {
            href = href.substring(href.indexOf("#"), href.length);
        }
        var id = $(this).parents("div.blockArticle").attr("id");
        if (id === href.replace("#", "")) {
            var height = $("#" + id).height();
            $("#" + id).children().each(function() {
                if(!$(this).hasClass("btmcorner")) {
                    $(this).remove();
                }
            });
            $("#" + id).find(".btmcorner").before("<div class='loading' style='height:"+ height + "px;'>chargement</div>");
            $.ajax({
                url: "/fr/components/ajax/ajaxDestinationTabs.jsp?action=close&code=" + id,
                success: function(data){
                    $("#" + id).replaceWith(data);
                }
            });
        }
        return false;
    });

    $('#doZone div.blockMcommun a,#seeZone div.blockMcommun a').live('click', function() {
        var href = $(this).attr("href");
        if (href.indexOf("#") > -1) {
            href = href.substring(href.indexOf("#"), href.length);
        }
        var id = $(this).parents("div.blockMcommun").attr("id");
        if (id === href.replace("#", "")) {
            var height = $("#" + id).height();
            $("#" + id).children().each(function() {
                if(!$(this).hasClass("btmcorner")) {
                    $(this).remove();
                }
            });
            $("#" + id).find(".btmcorner").before("<div class='loading' style='height:"+ height + "px;'>chargement</div>");
            $.ajax({
                url: "/fr/components/ajax/ajaxDestinationTabs.jsp?action=open&code=" + id,
                success: function(data){
                    $("#" + id).replaceWith(data);
                }
            });
        }
        return false;
    });

    $("#doZone h2 a").live('click', function() {
        var href = $(this).attr("href");
        if (href.indexOf("#") > -1) {
            href = href.substring(href.indexOf("#"), href.length);
        }
        var regexp = new RegExp("^#desti=([a-zA-Z0-9._-]+)&code=([a-zA-Z0-9._-]+)$", "g");
        var result = regexp.exec(href);
        if (href.match(regexp) && result.length == 3) {
            var desti = result[1];
            var code = result[2];
            var categoryDiv = $("#" + code);
            if(categoryDiv.length > 0) {
                var height = categoryDiv.height();
                categoryDiv.html("<div class='loading' style='height:" + height + "px;'>chargement</div>");
                $.ajax({
                    url: "/fr/components/ajax/ajaxToMakeAll.jsp?code=" + code + "&desti=" + desti,
                    success: function(data){
                        categoryDiv.replaceWith(data);
                    }
                });
            }
        }
        return false;
    });

    $("#commentZone p.pagination a").live('click', function() {
        var href = $(this).attr("href");
        if (href.indexOf("#") > -1) {
            href = href.substring(href.indexOf("#"), href.length);
        }
        var regexp = new RegExp("^#(.*)$","g");
        var result = regexp.exec(href);
        if (href.match(regexp) && result.length == 2) {
            $.ajax({
                url: "/fr/components/ajax/ajaxCommentZone.jsp?" + result[1],
                success: function(data){
                    $("#commentZone").html(data);
                }
            });
        }
        return false;
    });
    $("#seeZone p.pagination a").live('click', function() {
        var href = $(this).attr("href");
        if (href.indexOf("#") > -1) {
            href = href.substring(href.indexOf("#"), href.length);
        }
        var regexp = new RegExp("^#(.*)$","g");
        var result = regexp.exec(href);
        if (href.match(regexp) && result.length == 2) {
            $.ajax({
                url: "/fr/components/ajax/ajaxSeeZone.jsp?" + result[1],
                success: function(data){
                    $("#seeZone").html(data);
                }
            });
        }
        return false;
    });
    if (typeof(hasBrowsing) !== 'undefined' && hasBrowsing && contentType !== null && (contentType === "dossier" || contentType === "news")) {
        var browsingParameters;
        var href = document.location.href;
        var regexp = new RegExp("^.+html#(.+)$","g");
        var result = regexp.exec(href);
        if (href.match(regexp) && result.length == 2) {
            browsingParameters = result[1] + "&contentType=" + contentType;
            $.ajax({
                url: "/fr/components/ajax/contentBrowsing.jsp?" + browsingParameters,
                success: function(data){
                    $("p.pagination").html(data);
                }
            });
        }
    }

}

function initEarlyBooking(){
	var earlyBookingValue = $("#disponibility option:selected").attr("title");
	if(earlyBookingValue !== "" && earlyBookingValue !== undefined){
		$("#reductionCode").val(earlyBookingValue);
	}
}

function changeDispo(){
    $("#disponibility").change(function(){
        var codeReductionLabel = "";
        $("#disponibility option:selected").each(function () {
            codeReductionLabel += $(this).attr("title");
            $("#reductionCode").val(codeReductionLabel);
        });
        return false;
    });
}

function selectExperts(){
    $("#search_expert input").click(function(){
        var container = $(this).parents("#search_expert");
        var expertRef = "";
        expertRef = container.find("#searchExpert").val();
        var params = "?critereMaux=";
        var url  = window.location.pathname;
        if(expertRef != ""){
            url = url + params + expertRef;
        }
        window.location.href = url;
        return false;
    });
}
function searchEngineMagazine(){
  $('#searchEngineMagazine input').click(function(){
    var container = $(this).parents('#searchEngineMagazine');
    var maux = '';
    maux = container.find('#selectMagazine').val();
    var params = '?critereMaux=';
    var url  = '/fr/magazine-resultats.html';
    if(maux != ''){
      url = url + params + maux;
    }
    window.location.href = url;
    return false;
  });
}
function selectExpertDetail(){
  $("#search_article input").click(function(){
    var container = $(this).parents("#search_article");
    var articleRef = "";
    articleRef = container.find("#searchArticle").val();
    var url = "/fr/experts-bien-etre/";
    if(articleRef != ""){
      url = url + articleRef + ".html";
    }
    window.location.href = url;
    return false;
  });
}

function abonnement(){
    $(".newsForm #pays").change(function(){
        var container = $(this).parents(".newsForm");
        var countryCode = container.find("#pays").val();
        if(countryCode == "AU" || countryCode == "BR" || countryCode == "CA" || countryCode == "MX" || countryCode == "US"){
            $("#etatLabel").removeClass("desabled");
            $("#etat").removeClass("desabled");
            $("#etat").removeAttr("disabled");
            $('#centerNewsletter span').each(function(){
                $('#centerNewsletter span').attr('style', 'display:none;')
            });
            $('#'+ countryCode).removeAttr("style");
        }else{
            $("#etatLabel").removeClass("desabled");
            $("#etat").removeClass("desabled");
            $("#etat").removeAttr("disabled");
            $("#etatLabel").addClass("desabled");
            $("#etat").addClass("desabled");
            $("#etat").attr('disabled', 'disabled');
            $('#centerNewsletter span').each(function(){
                $('#centerNewsletter span').attr('style', 'display:none;')
            });
            $('#etatHome').attr('style', '');
        }
        return false;
    });
//	$(".newsForm form").submit(function() {
//		var civilite = $("#civiliteSelect").val();
//		var country = $("#pays").val();
//		var state = "";
//		if(country == "AU" || country == "BR" || country == "CA" || country == "MX" || country == "US"){
//			state = $("#"+country + " select").val();
//		}
//
//		var lan = $("#langue").val();
//		$("#civilite").val(civilite);
//		$("#country").val(country);
//		$("#state").val(state);
//		$("#language").val(lan);
//
//	});
}
function loadBackGround(){
  var currentLanguage = $("#currentLanguage").val();
  if (currentLanguage) {
    var currentLanguage = currentLanguage.toLowerCase();
    var randomnumber=Math.floor(Math.random()*4) + 1;
    var imgClass = "img" + randomnumber;
    var url = location.pathname;
    if(url == "/fr" || url == "/fr/" || url == "/en" || url == "/en/" || url == "/it" || url == "/it/"){
        $("#content").addClass("home "+imgClass);
    }
    var edito = currentLanguage + "_edito" + randomnumber;
    if(randomnumber == 2 || randomnumber == 3 || randomnumber == 4){
        $(".heure").css({
            color: "rgb(16, 54, 87)"
        });
        $("div.savoirPlus").css({
            color: "rgb(16, 54, 87)"
        });
    }
    $("#"+edito).show();
  }
}
function getBienreunirPdf(){
    $('.btn_download_fh').click(function(){
        var cityName = $('#download_fh_selecet').val();
        window.open("/csvweb/fr/pdf/" + cityName + ".pdf");
       return false;
    });
}
function changeSoinAZ(){
  $('div.alpha a').click(function(){
    var pageName = $(this).attr('id');
    var container = $('div.alpha a#' + pageName).parent('div');
    container.append(pageName);
    $('div.alpha a#' + pageName).remove();
    var chooseName = $('div.choose').text();
    chooseName = chooseName.charAt(0);
    $('.choose').text('');
    $('.choose').append('<a href=\"#\" id=\"'+ chooseName + '\">'+ chooseName +'</a>');
    $('.choose').bind('mouseup', function() {
     changeSoinAZ();
    });
    $('.choose').removeClass('choose');

    container.addClass('choose');
    $.ajax({
        url: "/csvweb/fr/static-zone/soin/" + pageName + ".html",
        type: "GET",
        dataType: "text",
        success: function(msg){
        $('div#ajaxUpdate').html(msg);
     }
    });
    if (pageName == 'b') {
      $(".blockThalassa").height(1089);
    }else if(pageName == 'c' || pageName == 'f'|| pageName == 'g'|| pageName == 'i'|| pageName == 'j'|| pageName == 'k'|| pageName == 'l'|| pageName == 'n'|| pageName == 'o'|| pageName == 'q'||pageName == 's'|| pageName == 't'||pageName == 'u'|| pageName == 'v'|| pageName == 'w'|| pageName == 'x'|| pageName == 'y'|| pageName == 'z'){
      $(".blockThalassa").height(1048);
    }else if( pageName == 'h'){
      $(".blockThalassa").height(1195);
    }else if(pageName == 'p'){
      $(".blockThalassa").height(1072);
    }else if(pageName == 'd'){
      $(".blockThalassa").height(1315);
    }else if(pageName == 'e'){
      $(".blockThalassa").height(1460);
    }else if(pageName == 'm'){
      $(".blockThalassa").height(1172);
    }else if(pageName == 'r'){
      $(".blockThalassa").height(1195);
    }else if(pageName == 'a'){
      $(".blockThalassa").height(1235);
    }
    return false;
  });
}
/******/
function setEventMain(){
  $('.sousMenu ul li a').each(function(i,obj){
    $(obj).unbind();
    $(obj).bind('click',function(){
      $('.sousMenu ul li').removeClass("select");
      $('.items>div').hide();
      $(obj).parent().addClass("select");
      $('.items .item'+(i+1)).show();
      call_xt_click(this.className);
      return false;
    });
  });

  $("div.blockLangue a").click(function() {
    var language = $(this).attr("class");
    var link = $(this).attr("href");
    writeCookie("THALASSA_LANGUAGE", language, 30);
    window.location=link;
    return false;
  });

  $("a#addFavoris").click(function() {
    var url = window.location.href;
    if (document.all){
       window.external.addFavorite(url,'Thalassa sea & spa');
    }else if (window.sidebar){
       window.sidebar.addPanel('Thalassa sea & spa', url, "");
    }
    return false;
  });

}
function selectSousMenu(){
  $("#main #content #center .listeDestination .contentQuiberon .sousMenuMagasine ul li").removeClass("selected");
  $("#main #content #center .listeDestination .contentQuiberon .sousMenuMagasine ul li a").unbind();
  $("#main #content #center .listeDestination .contentQuiberon .sousMenuMagasine ul li a").bind('mouseover', function(){
      $(this).parent().addClass("selected");
      if($(this).parent().hasClass("selected")){
        $(this).parent().stop().animate({opacity : "1"},1000);
      }

  }).bind("mouseout",function(){
    if($(this).parent().hasClass("selected")){
      $(this).parent().stop().animate({opacity : "0"},1000);
      $(this).parent().css("opacity","0");
    }
    $("#main #content #center .listeDestination .contentQuiberon .sousMenuMagasine ul li").removeClass("selected");
    if(!$(this).parent().hasClass("selected")){
      $(this).parent().stop().animate({opacity : "1"},1000);
    }
  });
}
function activeMenu(){
  $("#main #header .partMenu ul li a").removeClass("active");
  $("#main #header .partMenu ul li a").unbind();
  $("#main #header .partMenu ul li a").bind('mouseover', function(){

      $(this).addClass("active");
      if($(this).hasClass("active")){
        $(this).stop().animate({opacity : "1"},1000);
      }

  }).bind("mouseout",function(){
    if($(this).hasClass("active")){
      $(this).stop().animate({opacity : "0"},1000);
      $(this).css("opacity","0");
    }
    $("#main #header .partMenu ul li a").removeClass("active");
    if(!$(this).hasClass("active")){
      $(this).stop().animate({opacity : "1"},1000);
    }
  });
}
function showFenetre(){
  $(".visuels ul li").find(".descToltip").hide();
  $("#main .destinationHp .listeDestination .resultList .visuels ul li a").unbind();
  $("#main .destinationHp .listeDestination .resultList .visuels ul li a").hover(function(){
        if($(".price")) $(".price").css("z-index", 9999999)
        $(this).css("height",$(this).height());
    $(this).find(".titleToltip").hide();
    //alert("---"+$(this).parent().lenght());
    var cheminPhoto=$(this).find("img").attr("src");
    var description=$(this).find(".descToltip").text();
    var titre=$(this).find(".titleToltip").text();
    var aLink=$(this).attr("href");
        $(this).children(".visu").children("img").attr("title",titre);
        $(this).children(".visu").children("img").attr("alt",titre);
        var balise="<a class='fenetre' href='"+aLink+"'><span><strong>"+titre+"</strong>"+description+" ...</span></a>";
    //alert("left :"+(e.pageX+20)+"top :"+(e.pageY+20));
    $(this).parent().css("position","relative");
    $(this).prepend(balise);
    $(".fenetre").animate({ top: "0px" }, 300 );
        if($(this).height()<125) $(".fenetre").css("height", 96);
        else $(".fenetre").css("height", 96);

    var url = $(this).attr("href");
    var urlNew = url.replace(/\'/g, "");
    $(this).attr("href", urlNew);
  },function(){
    $(".fenetre").remove();
    $(".titleToltip").show();
  });
}
function deleteFenetre(obj){
  $(obj).find(".titleToltip").show();
  $(obj).remove();
}


/***fontioon savoir position souris***/
function position (evt) {
      if(!evt) evt = window.event;
      x = evt.clientX;
      y = evt.clientY;
      //return[x,y];;
      alert("---"+x+"----"+y);
}

function writeCookie(nom, valeur, nombreJours) {
    var expiration = new Date();
    expiration.setTime(expiration.getTime() + (nombreJours * 24 * 3600 * 1000));
    document.cookie = nom + "=" + escape(valeur) + ";path=/;expires=" + expiration.toGMTString();
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin === -1) {
      begin = dc.indexOf(prefix);
      if (begin !== 0) {
          return null;
      }
  } else {
      begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end === -1) {
      end = dc.length;
  }
  return dc.substring(begin + prefix.length, end);
}

/********/

/********************************************************/
// Init des popins
/********************************************************/
function initPopins(){
  var dim = getPageSize();
  $('#newsletter').submit(function() {

        var parent = $(this).parent('#newsletter');
        var emailVal = $('#newsletter').find("input[name='emailNewsLetter']").val();
        var newsletterType =$('#newsletter').find("input[name='type']").val();

        loadPopin("popinError");

        /* expression régulière pour l'email */
        var regle = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
        if(!emailVal.match(regle)){
          var message = $("div.blockSearch").find("#emailErrorMsg").val()
          var data = "<div id=\"popinError\" class=\"popin\"><p>" + message
          showPopin(data,"popinError");
          return false;
        }
        var params = "email=" + emailVal + "&type=" + newsletterType;
        var url = "/abonnementNewsletter?" + params;
        $.ajax({
          type: "GET",
          url: url,
          success: function(data){
            try{
              showPopin(data,"popinError");
            }catch(e){}
          }
        });
      return false;
    });
  $('.linkPopin').bind('click',function(){
    var _this = this;

    var parent = $(this).parent('form');
    var emailVal = parent.find("input[name='emailNewsLetter']").val();
    var newsletterType = parent.find("input[name='type']").val();

    loadPopin("popinError");
    /* expression régulière pour l'email */
    var regle = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if(!emailVal.match(regle)){
      var message = $("div.blockSearch").find("#emailErrorMsg").val();
      var data = "<div id=\"popinError\" class=\"popin\"><p>" + message
      showPopin(data,"popinError");
      return false;
    }
    var params = "email=" + emailVal + "&type=" + newsletterType;
    var url = "/abonnementNewsletter?" + params;
    $.ajax({
      type: "GET",
      url: url,
      success: function(data){
        try{
          showPopin(data,"popinError");
        }catch(e){}
      }
    });
    return false;
  });
  $('.linkPopinForm').bind('click',function(){
      $('html, body').animate({scrollTop:0}, 'slow');
      //return false;
      var _this = this;
      var language = $('#linkPopinForm').attr('name');
      loadPopin("popinConseiller");//$(_this).attr('rel')
      $.ajax({
        type: "GET",
        url: "/"+language+"/components/ajax/helpForm.jsp",//$(_this).attr('href'),
        dataType: "html",
        success: function(data){
          try{
            showPopin(data,"popinConseiller"/*$(_this).attr('rel')*/);
          }catch(e){}
        }
      });
      return false;

    });
  $('.btn_news').click(function(){
      var civilite = $("#civiliteSelect").val();
      var country = $("#pays").val();
      var state = "";
      if(country == "AU" || country == "BR" || country == "CA" || country == "MX" || country == "US"){
         state = $("#"+country + " select").val();
     }

      var lan = $("#langue").val();
      $("#civilite").val(civilite);
      $("#country").val(country);
      $("#state").val(state);
      $("#language").val(lan);
      var url = $('#centerNewsletter').attr('action') + "?" + $('#centerNewsletter').serialize();
      loadPopin("popinError");
      $.ajax({
          type: "GET",
          url: url,
          success: function(data){
            try{
              showPopin(data,"popinError");
              $('.closeBox').click(function(){
                  $("#popinTemp").remove();
                  $("#popinOverlay").remove();
                  return false;
              });
            }catch(e){}
          }
      });
        return false;
  });

  $("#detailArea").live("keyup", function(e) {
      var text = $("#detailArea").val();
      if (text.length > 50) {
          $("#detailArea").val(text.substring(0,50));
      }
  });
  $('.btn_brochure').click(function(){
      var civilite = $("#civiliteSelect").val();
      var country = $("#pays").val();
      var state = "";
      var detail = $("#detailArea").val();
      if (detail.length > 50) {
        loadPopin("popinError");
        var selectedLanguage = getCookie("THALASSA_LANGUAGE");
        $.ajax({
              type: "GET",
              url: "/" + selectedLanguage + "/components/ajax/popinMessage.jsp?key=popin.detail.50max",
              success: function(data){
                  try {
                      showPopin(data, "popinError");
                      $('.closeBox').click(function(){
                          $("#popinTemp").remove();
                          $("#popinOverlay").remove();
                          return false;
                      });
                  }
                  catch (e) {
                  }
              }
          });
      } else {
          if (country == "AU" || country == "BR" || country == "CA" || country == "MX" || country == "US") {
              state = $("#" + country + " select").val();
          }

          var lan = $("#langue").val();
          $("#civilite").val(civilite);
          $("#country").val(country);
          $("#state").val(state);
          $("#language").val(lan);
          $("#detail").val(detail);
          var url = $('#centerNewsletter').attr('action') + "?" + $('#centerNewsletter').serialize();
          loadPopin("popinError");
          $.ajax({
              type: "GET",
              url: url,
              success: function(data){
                  try {
                      showPopin(data, "popinError");
                      $('.closeBox').click(function(){
                          $("#popinTemp").remove();
                          $("#popinOverlay").remove();
                          return false;
                      });
                  }
                  catch (e) {
                  }
              }
          });
      }
        return false;
  });

    $(".blockReservation .linkReserver").click(function(){
        $(".blockReservation .linkReserver").hide();
        $(".blockReservation .loader").show();
        return true;
    });

}

function resizeOverlayForPopin(){
  $(window).bind('resize',function(){
    resizaOverlay();
  });

  $(window).bind('scroll',function(){
    resizaOverlay();
  });
}

function resizaOverlay(cond){
  var overlay = $('#popinOverlay');
  var scroll = getPageScroll();
  //alert(hi);
  if(cond){
    overlay.css({
      opacity: 0.7,
      display: 'block'
    }).fadeIn('slow',function(){
      var hi = getHeight() + scroll[1];
      overlay.height(hi);
    });
  }else{
    var hi = getHeight() + scroll[1];
    overlay.height(hi);
  }
}
/********************************************************/
// Affichage des popins
/********************************************************/
function showPopin(data,id){
  $('#popinTemp').html(data);
  $('#popinTemp').removeAttr('style');
  $('#popinTemp').show();
  setEventSelectLayers();
  setPopinPosition(id);
  //alert("---");
  if($("#popinOverlay").length){
    $("#popinOverlay").unbind();
    $("#popinOverlay").bind('click',function(){

        $("#popinOverlay").fadeOut();
        $("#popinTemp").fadeOut();
        setTimeout("deletePopin()",300);
        clearTimeout();

     });
  }
}
function deletePopin(){
  $("#popinTemp").remove();
        $("#popinOverlay").remove();
}
function getHeight(){
  if(window.innerHeight || window.innerWidth)
    return window.innerHeight ;
  return document.documentElement.clientHeight ;
}

function refreshPositionPopin(popin){


  $(window).bind('resize',function(){
    var dim = getPageSize();
      popin.css({
      left: (dim[2]-popin.width())/2
    })
  });


}

function setPopinPosition(id){
  var dim = getPageSize();
  var scroll = getPageScroll();
  var overlay = $('#popinOverlay');
  var popin = $('#'+id);
  resizaOverlay(1);
  popin.css({
    top: '40%', //scroll[1] + (dim[3] / 10) - 50
    left: (dim[2]-$(popin).width())/2,
    opacity: 1,
    display: 'block'
  }).fadeIn();
  refreshPositionPopin(popin);

  popin.find('p.close a').bind('click', function(){
    overlay.fadeOut();
    popin.fadeOut();
    return false;
  });
}

function loadPopin(id){
  if(!$('#popinOverlay').length)
    $('#main').before('<div id="popinOverlay"></div>');

  if(!$('#popinTemp').length)
    $('#main').before('<div id="popinTemp"></div>');
  $('#popinTemp').html("<div style='position:absolute;' id='"+id+"' >Loading..</div>");
  setPopinPosition("popinTemp");
}
/*************************************************/
// Fonctions g�n�rales
/*************************************************/

// Renvoie les dimensions de la page
function getPageSize() {
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
    xScroll = window.innerWidth + window.scrollMaxX;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) {	// all except Explorer
    if(document.documentElement.clientWidth){
      windowWidth = document.documentElement.clientWidth;
    } else {
      windowWidth = self.innerWidth;
    }
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
    pageHeight = windowHeight;
  } else {
    pageHeight = yScroll;
  }
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){
    pageWidth = xScroll;
  } else {
    pageWidth = windowWidth;
  }

  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
  return arrayPageSize;
};

function getPageScroll() {
  var xScroll, yScroll;
  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
    xScroll = self.pageXOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
    yScroll = document.documentElement.scrollTop;
    xScroll = document.documentElement.scrollLeft;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
    xScroll = document.body.scrollLeft;
  }
  arrayPageScroll = new Array(xScroll,yScroll);
  return arrayPageScroll;
}
function setEventSelectLayers(){
  $('.cmb div.select').unbind('click');
  $('.cmb div.select').bind('click',function(){
      var etat = $(this).next().css('display').toLowerCase();
      if(etat == "none")
        $(this).next().show();
      else
        $(this).next().hide();
      return false;
    });

  $('.layer ul li a').unbind();
  $('.layer ul li a').bind('click',function(){
    var idBloc = $(this).attr('class');

    var label = $(this).html();
    var select = $(this).parent().parent().parent().prev();
    $('p span',select).html(label);
    select.next().hide();


    if(idBloc && $('#'+idBloc).length){
      $('#popinContact .blocC').hide();
      $('#'+idBloc).show();
      $('.msgError').hide();
      $('p.error').removeClass('error');
    }

    return false;
  });
}
function showselectEnfant(){
  $('#nbEnfant').unbind();
  $('#nbEnfant').bind('change',function(){
    $(".blockReservation .nbrePerso .choix .enfants").hide();
    if(parseInt($(this).val())==0){
      $(".blockReservation .nbrePerso .choix .enfants").hide();
    }else if(parseInt($(this).val())==1){
      $(this).next().show();
    }else if(parseInt($(this).val())==2){
      $(this).next().show();
      $(this).next().next().show();
    }else if(parseInt($(this).val())==3){
      $(this).next().show();
      $(this).next().next().show();
      $(this).next().next().next().show();
    }else if(parseInt($(this).val())==4){
      $(this).next().show();
      $(this).next().next().show();
      $(this).next().next().next().show();
      $(this).next().next().next().next().show();
    }
  });
}
function initLoaderBP() {
    $(".blockReservation .linkReserver").after("<div class='loader'></div>");
}

function call_xt_click(class_name) {
    if (class_name != null) {
        if (class_name == 'site') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.site, ts_click_data.action );
        } else if (class_name == 'institut') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.institut, ts_click_data.action );
        } else if (class_name == 'culture') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.culture, ts_click_data.action );
        } else if (class_name == 'soinProgram') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.soinProgram, ts_click_data.action );
        } else if (class_name == 'soins') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.soins, ts_click_data.action );
        } else if (class_name == 'soinsPhares') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.soinsPhares, ts_click_data.action );
        } else if (class_name == 'hebergement') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.hebergement, ts_click_data.action );
        } else if (class_name == 'restauration') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.restauration, ts_click_data.action );
        } else if (class_name == 'pratique') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.pratique, ts_click_data.action );
        } else if (class_name == 'product') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.product, ts_click_data.action );
        } else if (class_name == 'destination') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.destination, ts_click_data.action );
        } else if (class_name == 'treatment') {
            xt_click(this, 'C', xtn2, ts_click_data.click_labels.treatment, ts_click_data.action );
        }
    }
}
/*************************************************/
/**        Agenda des offres exclusives         **/
/*************************************************/

/**
 * monthAgenda.
 */
function monthAgenda() {
  // Set variables
  var today = new Date(),
      cpt = 0,
      monthTab = [];

  today = today.getMonth();

  if ($("html").attr("xml:lang")== "fr") {
    monthTab = ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"];
  } else {
    monthTab = ["january","februayr","march","april","may","june","july","august","september","october","november","december"];
  }

  $(".month li").each(function(){

    if (cpt > 5) {
      cpt = 0;
    }

    myMonth = today + cpt;

    if (myMonth > 11) {
      myMonth = myMonth - 12;
    }

    $(this).text(monthTab[myMonth]);

    cpt++;
  });
}

/**
 * offersAgenda.
 */
function offersAgenda() {
  // Set variables
  var today = new Date(),
      monthNewYear;

  today = today.getMonth() + 1;
  monthNewYear = (today + 5 > 12) ? (today + 5) - 12 : 0;

  $(".promo li a").each(function() {
    // Set variables
    var link = $(this),
        datePromo,
        dayStart, dayEnd,
        monthStart, monthEnd,
        monthStartRC, monthEndRC,
        duration, sizeBloc, positionBloc;

    datePromo = link.attr("class").split("-");
    dayStart = parseInt(datePromo[0], 10);
    dayEnd = (parseInt(datePromo[2], 10) > 30) ? 30 : parseInt(datePromo[2], 10);
    monthStart  = parseInt(datePromo[1], 10);
    monthEnd = parseInt(datePromo[3], 10);

    if (monthStart > today + 5){
      monthStartRC = monthStart - 12;
    } else if ( monthNewYear > 0 && monthStart <= monthNewYear){
      monthStartRC = monthStart + 12;
    } else {
      monthStartRC = monthStart;
    }

    dayStartRC = dayStart * 1.8;
    dayEndRC = (30 - dayEnd + 1) * 1.8;
    monthEndRC = (monthEnd < monthStart) ? (monthEnd + 12) : monthEnd;

    duration = (monthEndRC - monthStart) +1;
    sizeBloc = ((56 * duration +1)) - dayEndRC - dayStartRC;
    positionBloc = ((monthStartRC - today) * 56) + dayStartRC;
    sizeBloc = ((sizeBloc+positionBloc) > 335) ? 335 - positionBloc : sizeBloc;

    if (positionBloc < 0){
      sizeBloc = sizeBloc + positionBloc;
      positionBloc = 0;
    }

    link.css("width", sizeBloc + "px");
    link.css("left", positionBloc + "px");
  });
}

/**
 * popinAgenda.
 */
function popinAgenda() {

  $(".promo li").hover(
    function(){
      $(this).css('z-index', 10);
    },
    function(){
      $(this).css('z-index', 1);
    }
  );

  $(".promo li a").hover(
    function(){
      var popin = $(".popinAgenda", $(this));
      popin.css("margin-top", -((popin.height() / 2) + 3) + 'px')
           .show();
    },
    function(){
      $(".popinAgenda", $(this)).hide();
    }
  );
}


