var jsReady = false;
var movie = null;
var currentAccordionHeaderIsCarnet = false;
var xmlForLieu = "";
var domain = window.location.href;
domain = domain.replace("http://", "");
domain = domain.substring(0, domain.indexOf("/"));
var carnetvoyage = new Array();
var currentRegion="";
var grabOk=false;
var qs = new Querystring();

function Lieu(id, nom, vignette){
    this.Id = id;
    this.Nom = nom;
    this.Vignette = vignette
}

function initUIPageCarte(){

    var qs = new Querystring();

    if(qs.get("viah")==null) {ecrireCookie("viah", "false");}
    else{ecrireCookie("viah", "true");}

    if(qs.get("region")==null) {currentRegion=regiontv;}
    else {currentRegion=qs.get("region");}

    var flashContent = document.getElementById("flashContent");
    flashContent.innerHTML = "<img src='/assets/templates/default/images/ajax-loader-gris.gif'/>";
    var screenW = parseInt(document.body.clientWidth);
    var screenH = parseInt(jQuery(document).height());  if (screenH < 750) {screenH = 650}

    //Gestion du slide
    jQuery("#grab").click(function() {
	if(grabOk)
	{
		jQuery("#windowThemes").css("top","160px");
		jQuery("#windowLocalisation").css("top","160px");

		jQuery("#global_carto").slideDown(400);
		jQuery("#grab img").attr("src","/assets/templates/default/images/grab2.png");
		grabOk=false;
	}
	else {
		jQuery("#windowThemes").css("top","50px");
		jQuery("#windowLocalisation").css("top","50px");


		jQuery("#global_carto").slideUp(400);
		jQuery("#grab img").attr("src","/assets/templates/default/images/grab.png");
		grabOk=true;
	}
	return false;
    });

    var lang="fr";
    if (lireCookie("newlang") != null) {
        lang = lireCookie("newlang");
    }

    var hotel = -1;
    if (qs.get("hotelid") != null) {hotel = qs.get("hotelid");}

    var html = "";
    html += "<object id=\"flashCarte\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"100%\" height=\"" + screenH + "\">";
    html += "<param name=\"movie\" value=\"/assets/flash/carte_globale.swf\" />";
    html += "<param name=\"wmode\" value=\"transparent\" />";
    html += "<param name=\"allowScriptAccess\" value=\"always\" />";
    html += "<param name=\"salign\" value=\"t\" />";
    html += "<param name=\"menu\" value=\"false\" />";
    html += "<param name=\"scale\" value=\"border\" />";
    html += "<param name=\"align\" value=\"top\" />";
    html += "<param name=\"quality\" value=\"high\" />";
	html += "<param name=\"flashvars\" value=\"backoffice=false&defaultmap="+currentRegion+"&langue="+lang+"&hotel="+hotel+"\" />";		
    html += "<embed name=\"flashCarte\" flashvars=\"backoffice=false&defaultmap="+currentRegion+"&langue="+lang+"&hotel="+hotel+"\" src=\"/assets/flash/carte_globale.swf\" wmode=\"transparent\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"100%\" height=\"" + screenH + "\"></embed></object>";

    flashContent.innerHTML = html;
    var th = jQuery("#windowThemes");
    th.draggable({
        handle: '.windowTitre-title',
        containment: 'window'
    });
    th.accordion({
        collapsible: true,
        autoHeight: false,
        header: '.windowTitre-img',
        change: function(event, ui){
            if (ui.newContent[0]) {
                currentAccordionHeaderIsCarnet = (ui.newContent[0].outerText.indexOf("Carnets") > -1)
            }
        }
    });
    th.css("top", "50px");
    if (screenW > 1280) {th.css("left", "130px")}
    else {th.css("left", "5px")}
    th.fadeIn("slow");

    jsReady = true;

    initCarnets();
    if (lireCookie("newlang") != null) {
        if (typeof(google) != "undefined") {
            startTraduction("carto", "fr", lireCookie("newlang"))
        }
    }

    Custom.init();

    setTimeout(slideUpHeader,1000);
}

function slideUpHeader()
{
jQuery("#global_carto").slideUp(1000); grabOk=true;
}

function setCurrentRegion(region){
    currentRegion = region;
}

var togglePatrimoine = false;
var toggleNature = false;
function toggleCoche(type){
    if (type == "patrimoine") {
        var couche;
        var h;
        if (togglePatrimoine == false) {
            togglePatrimoine = true;
            h = checkboxHeight * 3 + "px";
            jQuery("#allcheckboxPatrimoine").html("tout d&eacute;cocher")
        }
        else {
            togglePatrimoine = false;
            h = "0px";
            jQuery("#allcheckboxPatrimoine").html("tout cocher")
        }
        couche = jQuery("#clip_concerts_theatres");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('concerts_theatres', togglePatrimoine);

        couche = jQuery("#clip_patrimoine_unesco");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('patrimoine_unesco', togglePatrimoine);

        couche = jQuery("#clip_jardins_remarquables");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('jardins_remarquables', togglePatrimoine);

        couche = jQuery("#clip_sites_remarquables");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('sites_remarquables', togglePatrimoine);

        couche = jQuery("#clip_lieux_culturels");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('lieux_culturels', togglePatrimoine);

        couche = jQuery("#clip_thermalisme");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('thermalisme', togglePatrimoine);

        couche = jQuery("#clip_monuments");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('monuments', togglePatrimoine);

        couche = jQuery("#clip_tourisme_fluvial");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('tourisme_fluvial', togglePatrimoine);
        couche = jQuery("#clip_musees");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('musees', togglePatrimoine);
        couche = jQuery("#clip_vins_oenologie");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('vins_oenologie', togglePatrimoine);
        couche = jQuery("#clip_parcs_sites_naturels");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('parcs_sites_naturels', togglePatrimoine);
        couche = jQuery("#clip_visites_commentees");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('visites_commentees', togglePatrimoine);
        couche = jQuery("#clip_patrimoine_industriel");
        couche.attr("checked", togglePatrimoine);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('patrimoine_industriel', togglePatrimoine)
    }
    else {
        if (toggleNature == false) {
            toggleNature = true;
            h = checkboxHeight * 3 + "px";
            jQuery("#allcheckboxNature").html("tout d&eacute;cocher")
        }
        else {
            toggleNature = false;
            h = "0px";
            jQuery("#allcheckboxNature").html("tout cocher")
        }
        couche = jQuery("#clip_aeroclubs");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('aeroclubs', toggleNature);

        couche = jQuery("#clip_montgolfiere");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('montgolfiere', toggleNature);

        couche = jQuery("#clip_casinos");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('casinos', toggleNature);
        couche = jQuery("#clip_peche");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('peche', toggleNature);
        couche = jQuery("#clip_chasse");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('chasse', toggleNature);
        couche = jQuery("#clip_randonnees");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('randonnees', toggleNature);
        couche = jQuery("#clip_equitation");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('equitation', toggleNature);
        couche = jQuery("#clip_sport_automobile");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('sport_automobile', toggleNature);
        couche = jQuery("#clip_fetes_manifestation");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('fetes_manifestation', toggleNature);
        couche = jQuery("#clip_sports_hiver");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('sports_hiver', toggleNature);
        couche = jQuery("#clip_golf");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('golf', toggleNature);
        couche = jQuery("#clip_parapente");
        couche.attr("checked", toggleNature);
        couche.prev().attr("style", "background-position:0 -" + h);
        showTheme('parapente', toggleNature)
    }
}

function clickFond(){
}

function isReady(){
    return jsReady
}

function flashComplete(){
    if (qs.get("villeid") != null) {
        localisationInit(qs.get("villeid"), "ville", "")
    }
    if (qs.get("lieuid") != null) {
        var id = qs.get("lieuid");
        localisationInit(id, "lieu", "");
        setTimeout("activeLieu("+id+", 'lieu', '','');",1000);
    }
}

function thisMovie(movieName){
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

function showTheme(theme, checked){
    var swf = thisMovie("flashCarte");
    swf.setVisibleLayer(theme, checked, true, true);
}

function selectCarte(carte){
    var swf = thisMovie("flashCarte");
    swf.selectCarte(carte);
}

function traductionFromFlash(type, startLang, destLang, text){
    google.language.translate(text, startLang, destLang, function(result){
        if (result.translation) {
            var swf = thisMovie("flashCarte");
            swf.traductionToFlash(type, result.translation)
        }
    })
}

function hideLocalisation(){
    jQuery("#windowLocalisation").fadeOut("slow");
    jQuery("#localisationVille-NomVille").html("");
    jQuery("#localisationLieux").html("");
    jQuery("#localisationHotels").html("")
}

var firstInit=true;
function localisationInit(modxId, type){
    var wl = jQuery("#windowLocalisation");
    wl.draggable({
        handle: '.windowTitre-title',
        containment: 'window'
    });
    wl.accordion({
        collapsible: true,
        autoHeight: false,
        header: '.windowTitre-img'
    });
   
    if(firstInit)
    {
        var screenW = parseInt(document.body.clientWidth);
        if (screenW > 1280) {
            var flashW = jQuery("#flashContent").width();
            wl.css("left", flashW - 215)
        }
        else {
            wl.css("left", screenW - 215)
        }
	firstInit=false;
    wl.css("top", "100px");
    }
    wl.fadeIn("slow");
    var wsUrl = "";
    if (type == "lieu") {wsUrl = "http://" + domain + "/webservices/getinfoslocalisation?pageID=" + modxId + "&withMeteo=true"}
    else {wsUrl = "http://" + domain + "/webservices/getinfoslocalisation?villeID=" + modxId + "&withMeteo=true"}

    jQuery.ajax({
        type: "GET",
        url: wsUrl,
        dataType: "xml",
        error: function(xhr, err, e){
            alert("Error: " + err)
        },
        success: function(xml){
            xmlForLieu = xml;
            var ville = jQuery(xml).find("parentVille");
            var region = ville.next();
            var meteoTempF = region.next();
            var meteoTempC = meteoTempF.next();
            var meteoIcon = meteoTempC.next();
            var meteoCondition = meteoIcon.next();

            var liensUtiles = meteoCondition.next();
            ville = "<span class='green'>[</span>" + ville.text() + "<span class='green'>]</span>";
            region = region.text();
            meteoTempF = meteoTempF.text();
            meteoTempC = meteoTempC.text();
            meteoIcon = meteoIcon.text();
            meteoCondition = meteoCondition.text();
            liensUtiles = liensUtiles.text();
            jQuery("#localisationVille-NomVille").html(ville);
            if (liensUtiles == "  ") {
                jQuery("#localisationLiensUtiles").css("display", "none")
            }
            else {
                jQuery("#localisationLiensUtiles").css("display", "block");
                jQuery("#localisationLiensUtiles").html(liensUtiles)
            }
            if (meteoTempC == "") {
                jQuery("#localisationVille-Meteo").html("")
            }
            else {
                if (meteoIcon == "http://www.google.com") {
                    jQuery("#localisationVille-Meteo").html(meteoTempC + "&deg;C")
                }
                else {
                    jQuery("#localisationVille-Meteo").html("<img alt='" + meteoCondition + "' title='" + meteoCondition + "' src='" + meteoIcon + "' />" + meteoTempC + "&deg;C")
                }
            }

            var html = "";
            jQuery(xmlForLieu).find("lieu").each(function(){
                var curLieu = jQuery(this);
                var titre = curLieu.find('pageTitre').text();
                var img = curLieu.find('pageVignette').text();
                var id = curLieu.attr('id');
                img = img.replace(" ", "");
                if (img == "") {
                    img = "/assets/templates/default/images/pasphoto.png"
                };
                html += "<div class=\"localisationLieux-item\">";
                html += "  <div class=\"localisationLieux-item-image\">";
                html += "    <a href=\"#\" onclick=\"activeLieu('" + id + "','lieu','',''); return false;\"><img src=\"/" + img + "\" /></a>";
                html += "  </div>";
                html += "  <div class=\"localisationLieux-item-titre\">";
                html += "    <a href=\"#\" onclick=\"activeLieu('" + id + "','lieu','',''); return false;\">" + titre + "</a>";
                html += "  </div>";
                html += "</div>";
            });
            jQuery("#localisationLieux").html(html);


            var html = "";
	     var hotel = "";
	     var ok = false;
	     if (qs.get("hotelid") != null) {hotel = qs.get("hotelid");}
            jQuery(xmlForLieu).find("hotel").each(function(){
                var curHotel = jQuery(this);
             	  var id = curHotel.attr('id');		  
		  ok = false;
		  if(hotel == "") {
			ok=true;
		  }
		  else {
			ok=(hotel==id);
		  }

	 	  if (ok) {
                	var titre = curHotel.find('pageTitre').text();
		  	var reg = new RegExp("'", "gi");
		  	var titre2 = titre.replace(reg,"\\'" );

                	var img = curHotel.find('pageVignette').text();
                	var siteweb = curHotel.find('pageUrl').text();
                	img = img.replace(" ", "");
                	if (img == "") {img = "/assets/templates/default/images/pasphoto.png"};
                	html += "<div class='localisationHotels-item'>";
                	html += "  <div class='localisationHotels-item-image'>";
                	html += "    <a href='#' onclick=\"activeLieu('" + id + "','hotel','" + siteweb + "','" + titre2 + "'); return false;\"><img src='/" + img + "' alt='" + titre + "' /></a>";
                	html += "  </div>";
                	html += "  <div class='localisationHotels-item-titre'>";
                	html += "    <a href='#' onclick=\"activeLieu('" + id + "','hotel','" + siteweb + "','" + titre2 + "'); return false;\">" + titre + "</a>";
                	html += "  </div>";
                	html += "</div>";
		  }
            });
            jQuery("#localisationHotels").html(html+"<br/><br/><br/><br/>");
            jQuery("#localisationInfos").jScrollPane();
        }
    });
    return false;
}

function activeLieu(modxId, type, web, nom){
	    	if (popupGoogle == 1) {
       		setMarkerActive(modxId, type)
		}
		else {
			if (type == "hotel") {
				addToCarnet(modxId, nom, true);
    				var qs = new Querystring();
    				if(qs.get("viah")==null)
				{
					ecrireCookie("viah", "false");
					document.location=web;
				}
    				else {
					ecrireCookie("viah", "true");
					document.location=web+"?viah=1";
				}
			}
			else {
				var swf = thisMovie("flashCarte");
  	     			var couche=swf.setVisibleLieu(modxId);
           			if (couche != "") {
					couche="#clip_"+couche;
                			jQuery(couche).attr("checked", "true");
			              jQuery(couche).prev().attr("style", "background-position:0 -" + checkboxHeight * 3 + "px")
            			}
			}
		}
	return false;
}

function initCarnets(){
    var wsUrl = "http://" + domain + "/webservices/admincarnetsvoyages?action=GetListeCarnets&rd=" + (Math.random() * 10);
    var html = "";
    var htmlListe = "";
    jQuery.ajax({
        type: "GET",
        url: wsUrl,
        dataType: "xml",
        error: function(xhr, err, e){
            alert("Error: " + err + e)
        },
        success: function(xml){
            var sel = document.getElementById("carnetsVoyages-liste");
            jQuery(xml).find("carnet").each(function(){
                var curCarnet = jQuery(this);
                var id = curCarnet.attr('id');
                var nom = curCarnet.attr('nom');
                htmlListe += "<option value='" + id + "'>" + nom + "</option>"
            });
            if (htmlListe != "") {
                html += "<div class='windowContent-rubrique'>Carnets enregistr&eacute;s</div>";
                html += "  <div id='carnetsVoyages-existants-liste'>";
                html += "    Liste de vos Carnets de voyages enregistr&eacute;s : <br/>";
                html += "    <table cellspacing='0' cellpadding='0' style='margin-top:5px'>";
                html += "      <tr>";
                html += "        <td><select id='carnetsVoyages-liste' onchange='loadSavedCarnet()'><option value='-1'>Nouveau Carnet...</option>" + htmlListe + "</select></td>";
                html += "        <td style='padding-left:5px'><a id='link-delete' href='#' onclick='deleteCarnet(); return false;' style='display:none'>Supprimer ce Carnet</a></td>";
                html += "      </tr>";
                html += "    </table>";
                html += "  </div>"
            }
            else {
                html += ""
            }
            jQuery("#carnetsVoyages-existants").html(html);
            jQuery("#carnetsVoyages-courant").html("Votre carnet de voyage est actuellement vide.<br/><br/><i>Pour ajouter un lieu dans votre carnet de voyage, s&eacute;lectionnez un lieu et cliquez sur le bouton 'Ajouter au carnet de voyage'.</i>");
            document.getElementById("carnetsVoyages-courant-save").style.display = "none";
            document.getElementById("carnetsVoyages-courant-saveCmd").style.display = "block";
            document.getElementById("carnetsVoyages-courant-saveConfirm").style.display = "none";
            document.getElementById("carnetNom").value = "";
            carnetvoyage = new Array()
        }
    })
}

function reloadCarnet(){
    var html = "";
    document.getElementById("carnetsVoyages-courant").innerHTML = "<img src='/assets/templates/default/images/ajax-loader-gris.gif'/>";
    for (var i = 0; i < carnetvoyage.length; i++) {
        var wsUrl = "http://" + domain + "/webservices/getinfoslocalisation?pageID=" + carnetvoyage[i].Id + "&rd=" + (Math.random() * 10);
        jQuery.ajax({
            type: "GET",
            async: false,
            url: wsUrl,
            dataType: "xml",
            error: function(xhr, err, e){
                alert("Error: " + err + e)
            },
            success: function(xml){
                var curLieu = jQuery(xml).find("lieuCourant");
                var titre = curLieu.find('pageTitre').text();
                var template = curLieu.find('pageTemplate').text();
                var url = curLieu.find('pageUrl').text(); //curLieu.find('pageSiteWeb').text();
                var img = curLieu.find('pageVignette').text();
                img = img.replace(" ", "");
                if (img == "") {
                    img = "/assets/templates/default/images/pasphoto.png"
                };
                carnetvoyage[i].Nom = titre;
                carnetvoyage[i].Vignette = img;
                html += "<div class=\"localisationLieux-item\">";
                html += "  <div class=\"localisationLieux-item-image\">";
                html += "    <img src=\"/" + img + "\" alt=\"" + titre + "\" />";
                html += "  </div>";
                html += "  <div class=\"localisationLieux-item-titre\">";
                if (template == 9) {
                    html += "    <a class=\"localisationLieux-item-titreOpen\" href=\"#\" onclick=\"activeLieu('" + carnetvoyage[i].Id+ "','hotel','" + url + "',''); return false;\">" + titre + "</a>"
                }
                else {
                    html += "    <a class=\"localisationLieux-item-titreOpen\" href=\"#\" onclick=\"activeLieu('" + carnetvoyage[i].Id + "','lieu','',''); return false;\">" + titre + "</a>"
                }
                html += "     <br/><a class=\"localisationLieux-item-titreDelete\" href=\"#\" onclick=\"deleteLieu('" + carnetvoyage[i].Id + "'); return false;\">Retirer</a>";
                html += "  </div>";
                html += "</div>"
            }
        })
    }
    if (html == "") {
        document.getElementById("carnetsVoyages-courant").innerHTML = "Votre carnet de voyage est actuellement vide.<br/><br/><i>Pour ajouter un lieu dans votre carnet de voyage, s&eacute;lectionnez un lieu et cliquez sur le bouton 'Ajouter au carnet de voyage'.</i>"
    }
    else {
        document.getElementById("carnetsVoyages-courant").innerHTML = html
    }
    if (carnetvoyage.length > 0) {
        document.getElementById("carnetsVoyages-courant-save").style.display = "block"
    }
    else {
        document.getElementById("carnetsVoyages-courant-save").style.display = "none"
    }
    if (popupGoogle == 0) {
        if (currentAccordionHeaderIsCarnet == false) {
            jQuery("#windowThemes").accordion('activate', 1)
        }
    }
}

function addToCarnet(modxId, nom, withoutmsg){
    var finded = false;
    for (var i = 0; i < carnetvoyage.length; i++) {
        if (carnetvoyage[i].Id == modxId) {
            finded = true
        }
    }
    if (finded == false) {
        var liste = document.getElementById("carnetsVoyages-liste");
        var carnetId = -1;
        if (liste) {
            carnetId = document.getElementById("carnetsVoyages-liste").value
        }
        if (carnetId != -1) {
            var wsUrl = "http://" + domain + "/webservices/admincarnetsvoyages?action=AddItemToCarnet&carnetId=" + carnetId + "&idPageModx=" + modxId + "&nom=" + nom;
            var rep = jQuery.ajax({
                type: "GET",
                sync: false,
                url: wsUrl,
                dataType: "xml"
            })
        }
        carnetvoyage.push(new Lieu(modxId, "", ""));
        if (withoutmsg == undefined) 
            alert('Le lieu a bien \351t\351 ajout\351 dans votre Carnet de Voyage');
        reloadCarnet()
    }
    else {
        if (withoutmsg == undefined) 
            alert("Ce lieu est d\351j\340 pr\351sent dans votre Carnet de Voyage")
    }
}

function saveCarnet(){
    var nom = document.getElementById("carnetNom").value;
    if (nom == "") {
        alert("Vous devez sp\351cifier un nom pour sauvegarder ce Carnet de Voyage")
    }
    else {
        var wsUrl = "http://" + domain + "/webservices/admincarnetsvoyages?action=AddCarnetVoyages&nom=" + nom + "&rd=" + (Math.random() * 10);
        jQuery.ajax({
            type: "GET",
            url: wsUrl,
            dataType: "xml",
            error: function(xhr, err, e){
                alert("Error: " + err + e)
            },
            success: function(xml){
                var idCarnet = jQuery(xml).find("carnets").text();
                if (idCarnet == "not logged") {
                    var html = "<iframe src='http://" + domain + "/fr/iframe-login' border='none' width='550px' height='400px'></iframe>";
                    showPopup("Merci de vous identifier", html, 550, 400)
                }
                else {
                    for (var i = 0; i < carnetvoyage.length; i++) {
                        var wsUrl = "http://" + domain + "/webservices/admincarnetsvoyages?action=AddItemToCarnet";
                        wsUrl += "&carnetId=" + idCarnet + "&idPageModx=" + carnetvoyage[i].Id + "&nom=" + carnetvoyage[i].Nom;
                        var rep = jQuery.ajax({
                            type: "GET",
                            sync: false,
                            url: wsUrl,
                            dataType: "xml"
                        })
                    }
                    alert("Votre Carnet de voyage est sauvegard\351 sous le nom '" + nom + "'");
                    initCarnets()
                }
            }
        })
    }
}

function loadSavedCarnet(){
    var carnetId = document.getElementById("carnetsVoyages-liste").value;
    if (carnetId == -1) {
        initCarnets()
    }
    else {
        document.getElementById("carnetsVoyages-courant").innerHTML = "<img src='/assets/templates/default/images/ajax-loader-gris.gif'/>";
        document.getElementById("link-delete").style.display = 'block';
        var wsUrl = "http://" + domain + "/webservices/admincarnetsvoyages?action=GetListeItemsForCarnet&carnetId=" + carnetId + "&rd=" + (Math.random() * 10);
        jQuery.ajax({
            type: "GET",
            url: wsUrl,
            dataType: "xml",
            error: function(xhr, err, e){
                alert("Error: " + err + e)
            },
            success: function(xml){
                carnetvoyage = new Array();
                jQuery(xml).find("item").each(function(){
                    var curItem = jQuery(this);
                    var id = curItem.attr('id');
                    carnetvoyage.push(new Lieu(id, "", ""))
                });
                reloadCarnet()
            }
        })
    }
}

function deleteCarnet(){
    var carnetId = document.getElementById("carnetsVoyages-liste").value;
    var wsUrl = "http://" + domain + "/webservices/admincarnetsvoyages?action=DeleteCarnetVoyages&carnetId=" + carnetId;
    jQuery.ajax({
        type: "GET",
        url: wsUrl,
        dataType: "xml",
        error: function(xhr, err, e){
            alert("Error: " + err + e)
        },
        success: function(xml){
            alert("Le Carnet de voyage est supprim\351.");
            initCarnets()
        }
    })
}

function deleteLieu(id){
    var liste = document.getElementById("carnetsVoyages-liste");
    var carnetId = -1;
    if (liste) {
        carnetId = document.getElementById("carnetsVoyages-liste").value
    }
    var newTab = new Array();
    if (carnetId == -1) {
        for (var i = 0; i < carnetvoyage.length; i++) {
            if (carnetvoyage[i].Id != id) {
                newTab.push(carnetvoyage[i])
            }
        }
        carnetvoyage = newTab;
        newTab = null;
        reloadCarnet()
    }
    else {
        var wsUrl = "http://" + domain + "/webservices/admincarnetsvoyages?action=DeleteItemForCarnet&carnetId=" + carnetId + "&itemId=" + id;
        jQuery.ajax({
            type: "GET",
            url: wsUrl,
            dataType: "xml",
            error: function(xhr, err, e){
                alert("Error: " + err + e)
            },
            success: function(xml){
                alert("Le lieu est supprim\351.");
                loadSavedCarnet()
            }
        })
    }
}

var map;
var geocoder;
var markers;
var markershtmls;
var gdir;
var popupGoogle = 0;
function openGoogleMap(currentModxId, gps){
    var wt = jQuery("#windowThemes");
    wt.accordion('activate', false);
    wt.fadeOut("slow");
    var wgm = jQuery("#windowGoogleMap");
    var w = parseInt(document.body.clientWidth);
    var leftGm = ((w / 2) - (700 / 2) - 130);
    wgm.css("top", "70px");
    wgm.css("left", leftGm);
    wgm.fadeIn("slow");
    jQuery("#backgroundPopup").css({
        opacity: "0.7"
    });
    jQuery("#backgroundPopup").fadeIn("slow");
    var wl = jQuery("#windowLocalisation");
    var leftLoc = (leftGm + 720);
    wl.css('z-index', '500');
    wl.animate({
        top: "110px",
        left: leftLoc
    }, 600);
    var coords = gps.split(",");
    var lat = coords[0];
    var lng = coords[1];
    map = new GMap2(document.getElementById("windowGoogleMap-content"));
    map.setCenter(new GLatLng(lat, lng), 10, G_NORMAL_MAP);
    map.setUIToDefault();
    geocoder = new GClientGeocoder();
    initShowAllLieuxAndHotels(currentModxId);
    popupGoogle = 1;
    return false
}

function initShowAllLieuxAndHotels(currentModxId){
    markers = new Array();
    markershtmls = new Array();
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "/assets/templates/default/images/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    var hotelIcon = new GIcon(baseIcon);
    hotelIcon.image = "/assets/templates/default/images/markerH.png";
    var hotel = "";
    if (qs.get("hotelid") != null) {hotel = qs.get("hotelid");}

    jQuery(xmlForLieu).find("lieu").each(function(){
        try {
            var id = jQuery(this).attr('id');
            var gps = jQuery(this).find('pageGps').text();
            if (gps != "") {
                var coords = gps.split(",");
                var lat = coords[0];
                var lng = coords[1];
                var marker = new GMarker(new GLatLng(lat, lng));
                map.addOverlay(marker);
                var titre = jQuery(this).find('pageTitre').text();
                var intro = jQuery(this).find('pageIntro').text();
                var img = jQuery(this).find('pageImage').text();
                var siteweb = jQuery(this).find('pageSiteWeb').text();
                var html = "<div style='width:290px'>";

                html += "<div class='lieuTitre'>" + titre + "</div>";
                html += "<table style='margin-top:5px;width:100%' cellspacing='0' cellpadding='0'>";
                html += " <tr>";
                html += "   <td style='vertical-align:top; width:100px;'>";
                html += "    <img class='lieuPhoto' style='width:65px; height:29px' src='" + img + "'/>";
                html += "  </td>";
                html += "  <td style='vertical-align:top; padding-left:5px'>";
                html += "    <a class='lieuSite' href='" + siteweb + "' target='_blank'>Voir le site internet</a>";
                html += "    <a class='lieuItineraire' href='#' onclick=\"showItineraire('" + id + "','" + gps + "'); return false;\">S'y rendre</a>";
                html += "    <a class='lieuAddCarnet' href='#' onclick=\"addToCarnet('" + id + "'); return false;\">Ajouter au Carnet de Voyage</a>";
                html += "  </td>";
                html += " </tr>";
                html += "</table>";
                if ((lireCookie("newlang") != null) && (typeof(google) != "undefined") && (lireCookie("newlang") != "fr")) {
                    google.language.translate(intro, "fr", lireCookie("newlang"), function(result){
                        if (result.translation) {
                            var html2;
                            html2 = html + "<div id='mapinfo_" + id + "' class='lieuIntro'>" + result.translation + "</div>";
                            html2 += "</div>";
                            markershtmls[id] = html2;
                            if (currentModxId == id) {
                                marker.openInfoWindowHtml(html2)
                            }
                            GEvent.addListener(marker, "click", function(){
                                marker.openInfoWindowHtml(html2)
                            })
                        }
                        else {
                            var html2;
                            html2 = html + "<div id='mapinfo_" + id + "' class='lieuIntro'>" + intro + "</div>";
                            html2 += "</div>";
                            markershtmls[id] = html2;
                            if (currentModxId == id) {
                                marker.openInfoWindowHtml(html2)
                            }
                            GEvent.addListener(marker, "click", function(){
                                marker.openInfoWindowHtml(html2)
                            })
                        }
                    })
                }
                else {
                    var html2;
                    html2 = html + "<div id='mapinfo_" + id + "' class='lieuIntro'>" + intro + "</div>";
                    html2 += "</div>";
                    markershtmls[id] = html2;
                    if (currentModxId == id) {
                        marker.openInfoWindowHtml(html2)
                    }
                    GEvent.addListener(marker, "click", function(){
                        marker.openInfoWindowHtml(html2)
                    })
                }
                markers[id] = marker
            }
        } 
        catch (e) {
        }
    });
    jQuery(xmlForLieu).find("hotel").each(function(){
        try {
            var id = jQuery(this).attr('id');

            var ok = false;
	     ok = false;
	     if(hotel == "") {
		ok=true;
	     }
	     else {
		ok=(hotel==id);
	     }
	     if (ok) {
            var gps = jQuery(this).find('pageGps').text();
            if (gps != "") {
                var coords = gps.split(",");
                var lat = coords[0];
                var lng = coords[1];
                var marker = new GMarker(new GLatLng(lat, lng), {
                    icon: hotelIcon
                });
                map.addOverlay(marker);
                var titre = jQuery(this).find('pageTitre').text();
                var intro = jQuery(this).find('pageIntro').text();
                var img = jQuery(this).find('pageImage').text();
                var siteweb = jQuery(this).find('pageUrl').text();
                var html = "<div style='width:290px'>";

                html += "<div class='lieuTitre'>" + titre + "</div>";
                html += "<table style='margin-top:5px;width:100%' cellspacing='0' cellpadding='0'>";
                html += " <tr>";
                html += "   <td style='vertical-align:top; width:100px;'>";
                html += "    <img class='lieuPhoto' style='width:65px; height:29px' src='" + img + "'/>";
                html += "  </td>";
                html += "  <td style='vertical-align:top; padding-left:5px'>";
                html += "    <a class='lieuSite' href='" + siteweb + "' target='_blank'>Voir la fiche h&ocirc;tel</a>";
                html += "    <a class='lieuItineraire' href='#' onclick=\"showItineraire('" + id + "','" + gps + "'); return false;\">S'y rendre</a>";
                html += "    <a class='lieuAddCarnet' href='#' onclick=\"addToCarnet('" + id + "'); return false;\">Ajouter au Carnet de Voyage</a>";
                html += "  </td>";
                html += " </tr>";
                html += "</table>";
                if ((lireCookie("newlang") != null) && (typeof(google) != "undefined") && (lireCookie("newlang") != "fr")) {
                    google.language.translate(intro, "fr", lireCookie("newlang"), function(result){
                        if (result.translation) {
                            var html2;
                            html2 = html + "<div id='mapinfo_" + id + "' class='lieuIntro'>" + result.translation + "</div>";
                            html2 += "</div>";
                            markershtmls[id] = html2;
                            if (currentModxId == id) {
                                marker.openInfoWindowHtml(html2)
                            }
                            GEvent.addListener(marker, "click", function(){
                                marker.openInfoWindowHtml(html2)
                            })
                        }
                        else {
                            var html2;
                            html2 = html + "<div id='mapinfo_" + id + "' class='lieuIntro'>" + intro + "</div>";
                            html2 += "</div>";
                            markershtmls[id] = html2;
                            if (currentModxId == id) {
                                marker.openInfoWindowHtml(html2)
                            }
                            GEvent.addListener(marker, "click", function(){
                                marker.openInfoWindowHtml(html2)
                            })
                        }
                    })
                }
                else {
                    var html2;
                    html2 = html + "<div id='mapinfo_" + id + "' class='lieuIntro'>" + intro + "</div>";
                    html2 += "</div>";
                    markershtmls[id] = html2;
                    if (currentModxId == id) {
                        marker.openInfoWindowHtml(html2)
                    }
                    GEvent.addListener(marker, "click", function(){
                        marker.openInfoWindowHtml(html2)
                    })
                }
                markers[id] = marker
            }
	     }
        } 
        catch (e) {
        }
    })
}

function setMarkerActive(modxId, type){
    if (markers[modxId] != null) {
        if (type == "lieu") {
            jQuery(xmlForLieu).find("lieu[id='" + modxId + "']").each(function(){
                markers[modxId].openInfoWindowHtml(markershtmls[modxId])
            })
        }
        else {
            jQuery(xmlForLieu).find("hotel[id='" + modxId + "']").each(function(){
                markers[modxId].openInfoWindowHtml(markershtmls[modxId])
            })
        }
    }
}

function showItineraire(id, gps){
    var ct = jQuery("#windowGoogleMap-content");
    ct.css("width", "500px").css("margin-left", "250px");
    jQuery("#windowGoogleMap-itineraire").css("display", "inline");
    document.getElementById("windowGoogleMap-itineraire-to-input").value = gps;
    document.getElementById("windowGoogleMap-itineraire-from-input").value = "";
    jQuery("#windowGoogleMap-itineraire-from-route").innerHTML = "";
    map.checkResize();
    return false
}

function hideItineraire(){
    var ct = jQuery("#windowGoogleMap-content");
    ct.css("width", "750px").css("margin-left", "0px");
    jQuery("#windowGoogleMap-itineraire").css("display", "none");
    map.checkResize();
    if (gdir != null) 
        gdir.clear();
    map.clearOverlays();
    return false
}

function calculItineraire(){
    document.getElementById("windowGoogleMap-itineraire-route").innerHTML = "";
    gdir = new GDirections(map, document.getElementById("windowGoogleMap-itineraire-route"));
    GEvent.addListener(gdir, "load", gdir_Load);
    GEvent.addListener(gdir, "error", gdir_Error);
    GEvent.addListener(gdir, "addoverlay", gdir_Addoverlay);
    var from = document.getElementById("windowGoogleMap-itineraire-from-input").value;
    var to = document.getElementById("windowGoogleMap-itineraire-to-input").value;
    var mode = document.getElementById("windowGoogleMap-itineraire-mode");
    gdir.load("from: " + from + " to: " + to, {
        locale: "fr",
        travelMode: mode,
        preserveViewport: false
    });
    return false
}

function gdir_Load(){
}

function gdir_Addoverlay(){
}

function gdir_Error(){
    var msg = document.getElementById("windowGoogleMap-itineraire-route");
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
        msg.innerHTML = "Aucune correspondance n'a &eacute;t&eacute; trouv&eacute;e pour une des adresses saisies.<br/>Cela peut arriver si l'adresse est r&eacute;cente ou incorrecte."
    }
    else 
        if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
            msg.innerHTML = "Un probl&egrave;me de g&eacute;ocodage vient de survenir. Aucune erreur pr&eacute;cise n'est disponible."
        }
        else 
            if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
                msg.innerHTML = "Aucune correspondance n'a &eacute;t&eacute; trouv&eacute;e pour une des adresses saisies.<br/>Cela peut arriver si l'adresse est r&eacute;cente ou incorrecte."
            }
            else 
                if (gdir.getStatus().code == G_GEO_BAD_KEY) {
                    msg.innerHTML = "La clef Google est invalide"
                }
                else 
                    if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
                        msg.innerHTML = "Aucune correspondance n'a &eacute;t&eacute; trouv&eacute;e pour une des adresses saisies.<br/>Cela peut arriver si l'adresse est r&eacute;cente ou incorrecte."
                    }
                    else {
                        msg.innerHTML = "Un probl&egrave;me de g&eacute;ocodage vient de survenir. Aucune erreur pr&eacute;cise n'est disponible."
                    }
}

function closeGoogleMap(){
    hideItineraire();
    GUnload();
    jQuery("#windowGoogleMap").fadeOut("slow", function(){
        jQuery("#windowLocalisation").css('z-index', '200').fadeOut("slow", function(){
            jQuery("#backgroundPopup").fadeOut("slow", function(){
                var wt = jQuery("#windowThemes");
                wt.fadeIn("slow", function(){
                    wt.accordion('activate', 0)
                })
            })
        })
    });
    popupGoogle = 0;
    return false
}

jQuery.noConflict();
function Test(){
}

function AddCarnetVoyages(nom){
    jQuery.ajax({
        type: "POST",
        url: "[(site_url)]webservices/admincarnetsvoyages",
        data: "action=AddCarnetVoyages&nom=" + nom,
        success: function(obj){
            jQuery("#reponse").html(obj)
        },
        error: function(obj){
            jQuery("#reponse").html(obj)
        }
    })
}

function DeleteCarnetVoyages(carnetId){
    jQuery.ajax({
        type: "POST",
        url: "[(site_url)]webservices/admincarnetsvoyages",
        data: "action=DeleteCarnetVoyages&carnetId=" + carnetId,
        success: function(obj){
            jQuery("#reponse").html(obj)
        },
        error: function(obj){
            jQuery("#reponse").html(obj)
        }
    })
}

function UpdateCarnetVoyages(carnetId){
    jQuery.ajax({
        type: "POST",
        url: "[(site_url)]webservices/admincarnetsvoyages",
        data: "action=UpdateCarnetVoyages&carnetId=" + carnetId,
        success: function(obj){
            jQuery("#reponse").html(obj)
        },
        error: function(obj){
            jQuery("#reponse").html(obj)
        }
    })
}

function AddItemToCarnet(carnetId, idPageModx, nom){
    jQuery.ajax({
        type: "POST",
        url: "[(site_url)]webservices/admincarnetsvoyages",
        data: "action=AddItemToCarnet&carnetId=" + carnetId + "&idPageModx=" + idPageModx + "&nom=" + nom,
        success: function(obj){
            jQuery("#reponse").html(obj)
        },
        error: function(obj){
            jQuery("#reponse").html(obj)
        }
    })
}

function RemoveItemFromCarnet(carnetId, idPageModx){
    jQuery.ajax({
        type: "POST",
        url: "[(site_url)]webservices/admincarnetsvoyages",
        data: "action=RemoveItemFromCarnet&carnetId=" + carnetId + "idPageModx=" + idPageModx,
        success: function(obj){
            jQuery("#reponse").html(obj)
        },
        error: function(obj){
            jQuery("#reponse").html(obj)
        }
    })
}

var popupStatus = 0;
function showPopup(titre, contenu, largeur, hauteur){
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = hauteur;
    var popupWidth = largeur;
    jQuery("#windowPopupInfos").css({
        "position": "absolute",
        "width": largeur + "px",
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });
    jQuery("#backgroundPopup").css({
        "height": windowHeight
    });
    if (popupStatus == 0) {
        jQuery("#backgroundPopup").css({
            "opacity": "0.7"
        });
        jQuery("#backgroundPopup").fadeIn("slow");
        jQuery("#windowPopupInfos").fadeIn("slow");
        popupStatus = 1
    }
    jQuery("#popup-titre").html(titre);
    jQuery("#popup-contenu").html(contenu).css({
        "height": hauteur + "px",
        "width": largeur + "px"
    })
}

function disablePopup(){
    if (popupStatus == 1) {
        jQuery("#backgroundPopup").fadeOut("slow");
        jQuery("#windowPopupInfos").fadeOut("slow");
        popupStatus = 0
    }
}

var checkboxHeight = "19";
var radioHeight = "25";
var selectWidth = "190";
document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; }</style>');
var Custom = {
    init: function(){
        var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
        for (a = 0; a < inputs.length; a++) {
            if ((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
                span[a] = document.createElement("span");
                span[a].className = inputs[a].type;
                if (inputs[a].checked == true) {
                    if (inputs[a].type == "checkbox") {
                        position = "0 -" + (checkboxHeight * 2) + "px";
                        span[a].style.backgroundPosition = position
                    }
                    else {
                        position = "0 -" + (radioHeight * 2) + "px";
                        span[a].style.backgroundPosition = position
                    }
                }
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                inputs[a].onchange = Custom.clear;
                span[a].onmousedown = Custom.pushed;
                span[a].onmouseup = Custom.check;
                document.onmouseup = Custom.clear
            }
        }
        inputs = document.getElementsByTagName("select");
        for (a = 0; a < inputs.length; a++) {
            if (inputs[a].className == "styled") {
                option = inputs[a].getElementsByTagName("option");
                active = option[0].childNodes[0].nodeValue;
                textnode = document.createTextNode(active);
                for (b = 0; b < option.length; b++) {
                    if (option[b].selected == true) {
                        textnode = document.createTextNode(option[b].childNodes[0].nodeValue)
                    }
                }
                span[a] = document.createElement("span");
                span[a].className = "select";
                span[a].id = "select" + inputs[a].name;
                span[a].appendChild(textnode);
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                inputs[a].onchange = Custom.choose
            }
        }
    },
    pushed: function(){
        element = this.nextSibling;
        if (element.checked == true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 -" + checkboxHeight * 3 + "px"
        }
        else 
            if (element.checked == true && element.type == "radio") {
                this.style.backgroundPosition = "0 -" + radioHeight * 3 + "px"
            }
            else 
                if (element.checked != true && element.type == "checkbox") {
                    this.style.backgroundPosition = "0 -" + checkboxHeight + "px"
                }
                else {
                    this.style.backgroundPosition = "0 -" + radioHeight + "px"
                }
    },
    check: function(){
        element = this.nextSibling;
        if (element.checked == true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 0";
            element.checked = false
        }
        else {
            if (element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight * 2 + "px"
            }
            else {
                this.style.backgroundPosition = "0 -" + radioHeight * 2 + "px";
                group = this.nextSibling.name;
                inputs = document.getElementsByTagName("input");
                for (a = 0; a < inputs.length; a++) {
                    if (inputs[a].name == group && inputs[a] != this.nextSibling) {
                        inputs[a].previousSibling.style.backgroundPosition = "0 0"
                    }
                }
            }
            element.checked = true
        }
        showTheme(element.value, element.checked)
    },
    clear: function(){
        inputs = document.getElementsByTagName("input");
        for (var b = 0; b < inputs.length; b++) {
            if (inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight * 2 + "px"
            }
            else 
                if (inputs[b].type == "checkbox" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0"
                }
                else 
                    if (inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
                        inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight * 2 + "px"
                    }
                    else 
                        if (inputs[b].type == "radio" && inputs[b].className == "styled") {
                            inputs[b].previousSibling.style.backgroundPosition = "0 0"
                        }
        }
    },
    choose: function(){
        option = this.getElementsByTagName("option");
        for (d = 0; d < option.length; d++) {
            if (option[d].selected == true) {
                document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue
            }
        }
    }
}

