
var points = [];
var liste = [];
var _xmlHttp = null;
var marker = [];
var markers = [];
var counter = 0;
var sidebar_html = "";
var marker_html = [];
var to_htmls = [];
var from_htmls = [];
var icon = [];
var map = null;
var paramCarte = [];
var draggablemarkers=[];
var idm=0;
var bds=null;


icon["drag"] = new GIcon();
icon["drag"].iconSize = new GSize(32,32);
icon["drag"].iconAnchor = new GPoint(16,16);
icon["drag"].infoWindowAnchor = new GPoint(16,16);


function getXMLHTTP(){var xhr=null;
if(window.XMLHttpRequest){xhr = new XMLHttpRequest();}else if(window.ActiveXObject){
   try {xhr = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {
      try {xhr = new ActiveXObject("Microsoft.XMLHTTP");} catch (e1) {xhr = null;}
}}else {location.href+=(location.href.indexOf("?")!=-1)?("&ajax=non"):("?ajax=non");}return xhr;}



function traiteXmlMap(xmlDoc){


   var iconListe=xmlDoc.getElementsByTagName("icone");


    for (var i=0; i < iconListe.length; ++i) {
         n=iconListe[i].getAttribute("id")
         icon[n] = new GIcon();
         icon[n].image = iconListe[i].getAttribute("icone");
         // si on gere plus tard les ombre
      // icon[n].shadow =  iconListe[i].getAttribute("icone");
      // icon[n].shadowSize = new GSize(20,20);

         icon[n].iconSize = new GSize(iconListe[i].getAttribute("iconew"),iconListe[i].getAttribute("iconeh"));
         icon[n].iconAnchor = new GPoint(iconListe[i].getAttribute("iconew")/2,iconListe[i].getAttribute("iconeh")*1);
         //icon[n].iconAnchor = new GPoint(0,0);
         icon[n].infoWindowAnchor = new GPoint(iconListe[i].getAttribute("iconew")/2,iconListe[i].getAttribute("iconeh")*1);
         //icon[n].infoWindowAnchor = new GPoint(0,0);
    }


   var markersXml=xmlDoc.getElementsByTagName("marker");
   var markersArray=[];

    for (var i=0; i < markersXml.length; ++i) {
         markersArray[i]=[];
         markersArray[i]['lat']=parseFloat(markersXml[i].getAttribute("lat"));
         markersArray[i]['lng']=parseFloat(markersXml[i].getAttribute("lng"));
         markersArray[i]['titre']=markersXml[i].getAttribute("titre");
         markersArray[i]['icon']=markersXml[i].getAttribute("icon");
         markersArray[i]['draggable']=markersXml[i].getAttribute("draggable");
         markersArray[i]['html']=markersXml[i].firstChild.data;
    }
      return(markersArray);
}




function onLoad() {
if (GBrowserIsCompatible()) {
   var mapObj = document.getElementById("map");



   if (mapObj != "undefined" && mapObj != null) {


   map = new GMap2(document.getElementById("map"));
   map.setCenter(new GLatLng(initCenter[0],initCenter[1]),initCenter[2],initCenter[3])


   paramCarte[0]=type=arguments[0];

  // alert(paramCarte[0])

   if(type){valeur=""
   for(i=1;i<arguments.length;i++){
   paramCarte[1]=valeur+=arguments[i]

  if(i<arguments.length-1)valeur+=",";

   }

   url=_adresseRecherche+"?"+type+"="+valeur;}
   else{url=_adresseRecherche;}


   if(_xmlHttp&&_xmlHttp.readyState!=0){_xmlHttp.abort()}
   _xmlHttp=getXMLHTTP();
   if(_xmlHttp){
      _xmlHttp.open("GET",url,true);
      _xmlHttp.onreadystatechange=function() {
         if(_xmlHttp.readyState==4&&_xmlHttp.responseXML) {


            listXml=_xmlHttp.responseXML
               liste = traiteXmlMap(listXml);
            if(liste.length==0)return;




            // on repositionne ici
            center=listXml.getElementsByTagName("center")[0];
            bounds=listXml.getElementsByTagName("bounds")[0];
            param=listXml.getElementsByTagName("param")[0];

            map.setCenter(new GLatLng(parseFloat(center.getAttribute("lat")), parseFloat(center.getAttribute("lng"))),6, eval(param.getAttribute('map_type')));
           if(liste.length==1){
            bds = new GLatLngBounds(new GLatLng(parseFloat(bounds.getAttribute("minlat")),parseFloat(bounds.getAttribute("minlng"))),new GLatLng(parseFloat(bounds.getAttribute("maxlat")),parseFloat(bounds.getAttribute("maxlng"))));
            map.setZoom(map.getBoundsZoomLevel(bds));
           }
            // on ajoute les parametre de base ici
            if(param.getAttribute('map_controls')==1){
            switch(param.getAttribute('control_size')){
               case "small":  map.addControl(new GSmallMapControl());break;
               case "large": map.addControl(new GLargeMapControl());break;
            }
            }

         if(param.getAttribute('type_controls')==1){
               map.addControl(new GMapTypeControl());
         }

         if(param.getAttribute('dragzoom')==1)
         {
            map.addControl(new DragZoomControl({}, {backButtonHTML:'Annuler Zoom',buttonZoomingHTML:'D&eacute;limiter la zone',backButtonEnabled: true}, {}),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(10,10)));
         }


            if(param.getAttribute('overview')!=""){
               taille=param.getAttribute('overview').split(",")
               map.addControl(new GOverviewMapControl(new GSize(taille[0],taille[1])));
            }

            // Gestion du zoom avec la molette
            if(param.getAttribute('zoomwheel')==1)map.enableScrollWheelZoom();else map.disableScrollWheelZoom();
            // Gestion du zoom avec double-clic
            if(param.getAttribute('dblclick_zoom')==1)map.enableDoubleClickZoom();
            // Gestion du zoom continu
            if(param.getAttribute('continuousZoom')==1)map.enableContinuousZoom();


              for (var i = 0; i < liste.length; i++) {
              if(liste[i]["titre"])
              {
                  point = new GLatLng(liste[i]["lat"],liste[i]["lng"]);


                  if(liste[i]['draggable']==1)
                  {
                    marker[i] = createMarker(point,liste[i]["titre"],liste[i]["html"],'drag', true);
                    GEvent.addListener(marker[i], "dragend"  , function() {var P=this.getPoint();document.formulaire.lon.value=P.x;document.formulaire.lat.value=P.y});
                    draggablemarkers[idm]=marker[i];
                    idm++;
                  }
                  else{

                     marker[i] = createMarker(point,liste[i]["titre"],liste[i]["html"],liste[i]["icon"], false);
                  }
                 map.addOverlay(marker[i]);
              }
              }

         }
      }
   _xmlHttp.send(null);
   }
}
}

}



function showInfoWindow(idx,html) {
map.centerAtLatLng(points[idx]);
markers[idx].openInfoWindowHtml(html);
}
function tohere(idx) {
markers[idx].openInfoWindowHtml(to_htmls[idx]);
}
function fromhere(idx) {
markers[idx].openInfoWindowHtml(from_htmls[idx]);
}

function createMarker(point, title, html, n,drag)
{
var marker = new GMarker(point, {icon:icon[n],draggable:drag});

  to_htmls[counter] = html + '<p /><form class="gmapDir" id="gmapDirTo" style="white-space: nowrap;" action="http://maps.google.com/maps" method="get" target="_blank">' +
                     '<span class="gmapDirHead" id="gmapDirHeadTo"><strong>Itineraire :</strong><br/> <strong>Vers ce lieu</strong> - <a href="javascript:fromhere(' + counter + ')">Depuis ce lieu</a></span>' +
                     '<p class="gmapDirItem" id="gmapDirItemTo"><label for="gmapDirSaddr" class="gmapDirLabel" id="gmapDirLabelTo">Adresse de depart<br /></label>' +
                     '<input type="text" size="40" maxlength="40" name="saddr" class="gmapTextBox" id="gmapDirSaddr" value="" onfocus="this.style.backgroundColor = \'#e0e0e0\';" onblur="this.style.backgroundColor = \'#ffffff\';" />' +
                     '<span class="gmapDirBtns" id="gmapDirBtnsTo"><input value="Obtenir" type="submit" class="gmapDirButton" id="gmapDirButtonTo" /></span></p>' +
                     '<input type="hidden" name="daddr" value="' +
                     point.y + ',' + point.x + "(" + title.replace(new RegExp(/"/g),'&quot;') + ")" + '" /></form>';

 from_htmls[counter] = html + '<p /><form class="gmapDir" id="gmapDirFrom" style="white-space: nowrap;" action="http://maps.google.com/maps" method="get" target="_blank">' +
                     '<span class="gmapDirHead" id="gmapDirHeadFrom"><strong>Itineraire :</strong><br/> <a href="javascript:tohere(' + counter + ')">Vers ce lieu</a> - <strong>Depuis ce lieu</strong></span>' +
                     '<p class="gmapDirItem" id="gmapDirItemFrom"><label for="gmapDirSaddr" class="gmapDirLabel" id="gmapDirLabelFrom">Adresse d arrivee<br /></label>' +
                     '<input type="text" size="40" maxlength="40" name="saddr" class="gmapTextBox" id="gmapDirSaddr" value="" onfocus="this.style.backgroundColor = \'#e0e0e0\';" onblur="this.style.backgroundColor = \'#ffffff\';" />' +
                     '<span class="gmapDirBtns" id="gmapDirBtnsFrom"><input value="Obtenir" type="submit" class="gmapDirButton" id="gmapDirButtonFrom" /></span></p' +
                     '<input type="hidden" name="daddr" value="' +
                     point.y + ',' + point.x + "(" + title.replace(new RegExp(/"/g),'&quot;') + ")" + '" /></form>';

html = html + '<p /><div id="gmapDirHead" class="gmapDir" style="white-space: nowrap;"><strong>Itineraire :</strong><br/> <a href="javascript:tohere(' + counter + ')">Vers ce lieu</a> - <a href="javascript:fromhere(' + counter + ')">Depuis ce lieu</a></div>';


GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); });
points[counter] = point;
markers[counter] = marker;
marker_html[counter] = html;
sidebar_html += '<li class="gmapSidebarItem" id="gmapSidebarItem_'+ counter +'"><a href="javascript:click_sidebar(' + counter + ')">' + title + '</a></li>';
counter++;
return marker;
}