$(document).ready(function(){
	if($(".magazine")) $(".blockThalassa").height($(".listeDestination").height()+272);
	else $(".blockThalassa").height($(".listeDestination").height()+285);
  loadBackGround();
  showselectEnfant();
  initPopins();
  resizeOverlayForPopin();
  activeMenu();
  showFenetre();
  //document.getElementById("what").onmousemove = position;
  setEventMain();
  searchEngine();
  simpleReservation();
  selectSousMenu();
  abonnement();
  selectExperts();
  getBienreunirPdf();
  /***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 */
    });
  /*****/
});

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  = "/fr/experts-bien-etre.html";
		if(expertRef != ""){
			url = url + params + expertRef;
		}
		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/"){
    	$("#content").addClass("home "+imgClass);
    }
    var edito = currentLanguage + "_edito" + randomnumber;
    if(randomnumber == 2){
    	$(".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 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();
      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() {
    if (document.all){
       window.external.addFavorite('http://www.thalassa.com','Thalassa sea & spa');
      }else if (window.sidebar){
           window.sidebar.addPanel('Thalassa sea & spa', 'http://www.thalassa.com', "");
      }
    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 selectSousMenu(){
//	$('#main #content #center .listeDestination .contentQuiberon .sousMenuMagasine ul li a').each(function(i,obj){
//		$(obj).unbind();
//		$(obj).bind('click',function(){
//			$('#main #content #center .listeDestination .contentQuiberon .sousMenuMagasine ul li ').removeClass("select");
//			if(i==3){
//			$('div.mag').hide();
//			$('div.partRight').hide();
//			$(obj).parent().addClass("select");
//			//$('.items .item'+(i+1)).show();
//			return false;
//			}
//		});
//	});
//}
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();
}

/********/

/********************************************************/
// 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;
  });
  
  $('.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;
  });
  
  $('.btn_brochure').click(function(){
	  var civilite = $("#civiliteSelect").val();
	  var country = $("#pays").val();
	  var state = "";
	  var detail = $("#detailArea").val();
	  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;
  });
  
}

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();
    }
  });
}
