var map;
var gmarkers = [];
var htmls = [];
var i = 0;
var bGetDirections = false;
var aFromPoint = {'lat':'','lng':''};
var gdir;
var bounds;
// === Create an associative array of GIcons() ===
var gicons = [];
    gicons["bleu"]      = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_bleu.png");
    gicons["bordeaux"]  = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_bordeaux.png");
    gicons["gris"]      = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_gris.png");
    gicons["jaune"]     = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_jaune.png");
    gicons["marron"]    = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_marron.png");
    gicons["orange"]    = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_orange.png");
    gicons["parme"]     = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_parme.png");
    gicons["rose"]      = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_rose.png");
    gicons["vert"]      = new GIcon(G_DEFAULT_ICON, "/otd-map/images/gicon_vert.png");

function odtMapInitialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("otd-map"));
    map.addControl(new GLargeMapControl); // zoom, directions
    map.addControl(new GMapTypeControl()); // vues "plan", "satellite","mixte"

    // map.setCenter(new GLatLng(48.6305506,-2.0631084), 14);
    map.setCenter(new GLatLng(0,0),0);

    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "/otd-map/images/gicon_shadow.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);

    bounds = new GLatLngBounds();

  }
}

// ----------------------------------------------
// A function to create the marker and set up the event window
function createMarker(lat,lng,label,html,id,idSecteur,bClear,bLoc) {

  if(bClear == true){
    map.clearOverlays();
  }
  var point = new GLatLng(lat,lng);
  switch(idSecteur){
    case '15'   : gicontype = 'bleu'; break;
    case '6'    : gicontype = 'bordeaux'; break;
    case '7'    : gicontype = 'jaune'; break;
    case '14'   : gicontype = 'marron'; break;
    case '9'    : gicontype = 'orange'; break;
    case '11'   : gicontype = 'parme'; break;
    case '1'    : gicontype = 'rose'; break;
    case '16'   : gicontype = 'vert'; break;
    default     : gicontype = 'gris'; break;
  }
  var marker = new GMarker(point, gicons[gicontype]);

  //-----------------------------------------
  var infoWinOptions = { maxWidth : 300, selectedTab : 0, height : 180 };
  // Fenêtre avec 3 onglets
  if(bLoc == true){
    label += "<br/><br/>";
    label += "<a href=\"javascript:popup('locations/bien_loc_t.php?cle_bien="+id+"&rub="+idSecteur+"&etab=')\">";
    label += "+ d'infos</a>";
  }
 // var onglet1 = new GInfoWindowTab ("Infos", '<div class="gInfoWinContent">'+label+'</div>');
 var onglet1 = new GInfoWindowTab ("Infos", '<div class="gInfoWinContent">'+html+'</div>');

 var tabItiHtml  = 'Vous pouvez calculer 2 types d\'itinéraire : <br/><br/>';
     tabItiHtml += ' - <strong>Entre 2 repères sur cette carte</strong><br/>';
     tabItiHtml += ' Cliquez sur <a href="#null" onclick="initGetItineraire('+lat+','+lng+','+id+')">ce lien</a> pour sélectionner ';
     tabItiHtml += ' le point de départ puis sur un repère pour votre destination.<br/><br/>';
     tabItiHtml += ' - <strong>Entre ce repère et une destination ou point de départ</strong><br/>';
     tabItiHtml += ' <label for="gAddr">Adresse : </label><input type="text" size="30" name="gAddr" id="gAddr" value=""/>';
     tabItiHtml += ' <br/><input type="checkbox" name="gAddrIsDest" id="gAddrIsDest" value="true" /><label for="gAddrIsDest"> L\'adresse saisie est votre destination</label>';
     tabItiHtml += '<br/><input type="button" name="gBtnGetIti" id="gBtnGetIti" value="Go" onclick="getLargeItineraire('+lat+','+lng+','+id+')" />';

  var onglet2 = new GInfoWindowTab ("Itinéraire", '<div class="gInfoWinContent">'+tabItiHtml+'</div>');
  //-----------------------------------------
  // Event Click : open the pop-up
  GEvent.addListener(marker, "click", function() {
    if(bGetDirections == false){
	   marker.openInfoWindowTabsHtml([onglet1,onglet2], infoWinOptions);
    }else{
      var aDirectionTo = {'lat':lat , 'lng':lng };
      getDirections( aFromPoint, aDirectionTo);
      bGetDirections = false;
      var oInfoWin = map.getInfoWindow();
          oInfoWin.show();
    }
  });
  gmarkers[id] = marker;
  //htmls[id] = html;
  map.addOverlay(marker);
  
  // Event Load, if the action comes from the list : open the pop-up
  if(bClear == true){
    marker.openInfoWindowTabsHtml([onglet1,onglet2], infoWinOptions);
  }
  // ==== Each time a point is found, extent the bounds ato include it =====
   bounds.extend(point);
  // ===== determine the zoom level from the bounds =====
  if(bClear == true){
    map.setZoom(14);
  }else{
    map.setZoom(map.getBoundsZoomLevel(bounds));
  }
  // ===== determine the centre from the bounds ======
  map.setCenter(bounds.getCenter());

}

// Cette fonction sera complétée pour terminer le calcul
// d'itinéraire à partir d'une/ vers une adresse...
function getLargeItineraire( lat, lng, id ){
  closeItineraire()
  var addr = $("#gAddr").val();
  if( addr == "" ){
    alert("Merci de saisir une adresse valide.");
    return false;
  }else{
    aDirFrom  = addr;
    aDirTo    = {'lat':lat,'lng':lng};
    if(  $("#gAddrIsDest").is(":checked") ){
      aDirFrom  = {'lat':lat,'lng':lng};
      aDirTo    = addr;
    }
    getDirections( aDirFrom, aDirTo);
    return true;
  }
}



function initGetItineraire( lat, lng, id ){
  //var oMarker = gmarkers[id];
  var oInfoWin = map.getInfoWindow();
      oInfoWin.hide();
  aFromPoint = {'lat':lat , 'lng':lng };
  bGetDirections = true;
}

function getDirections( aDirFrom, aDirTo) {
  // ==== Set up the walk and avoid highways options ====
  var opts = {};
      opts.travelMode = G_TRAVEL_MODE_DRIVING;
      // opts.travelMode = G_TRAVEL_MODE_WALKING; // Beta !!!
      opts.avoidHighways = true;

  var divItineraire = document.getElementById("itineraire");

  gdir = new GDirections(map, divItineraire );

  if( 'string' != typeof(aDirFrom) && 'string' != typeof(aDirTo) ){
    gdir.load("from: "+aDirFrom['lat']+", "+aDirFrom['lng']+" to: "+aDirTo['lat']+", "+aDirTo['lng'], opts);
  }else{
    if( 'string' == typeof(aDirFrom) && 'string' != typeof(aDirTo) ){
      gdir.load("from: "+aDirFrom+" to: "+aDirTo['lat']+", "+aDirTo['lng'], opts);
    }
    else if('string' != typeof(aDirFrom) && 'string' == typeof(aDirTo) ){
      gdir.load("from: "+aDirFrom['lat']+", "+aDirFrom['lng']+" to: "+aDirTo, opts);
    }
  }

  
  var divItiContainer = document.getElementById("itiContainer");
      divItiContainer.style.display = "block";
  var oInfoWin = map.getInfoWindow();
      oInfoWin.show();

}
function closeItineraire() {
  if( 'undefined' != typeof(gdir) ){
    gdir.clear();
  }
  var divItiContainer = document.getElementById("itiContainer");
      divItiContainer.style.display = "none";
}
//============================================================================
function show_hide_sous_secteurs(){
  $(".li-secteurs > span").click(
    function(o){
      $(this).parent('li').find("ul").toggle('slow');
    }
  )
}
// ----------------------------------------------
function init_sous_secteurs_actions(){
  $(".li-sous-secteurs > input[@type=checkbox]").click(
    function(o){
      var iSsectId = $(this).val();
          iSsectId = iSsectId.replace("loc_","");
      var sChkType = ( /check-loc/.test($(this).attr("class")) )? 'loc' : 'adh';
      if( $(this).is(":checked") ){
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "http://"+location.host+"/otd-map/rest-otd-map.php" ,
          data: "function=otd_get_adh_from_sous_secteur&argument='"+iSsectId+"|"+sChkType+"'",
          success: function(msg){
            for( var j=0; j<msg.length;j++ ){
              var oAdh = msg[j];
              createMarker(oAdh['lat'], oAdh['lng'], oAdh['label'], oAdh['html'], oAdh['id'], oAdh['idSecteur'],false);
            }
          },
          error: function(msg){/*alert("ERROR : "+msg);*/}
        });
      }
      else{
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "http://"+location.host+"/otd-map/rest-otd-map.php" ,
          data: "function=otd_get_adh_from_sous_secteur&argument='"+iSsectId+"|"+sChkType+"'",
          success: function(msg){
            for( var j=0; j<msg.length;j++ ){
              var oAdh = msg[j];
              map.removeOverlay( gmarkers[oAdh['id']]);
            }
          },
          error: function(msg){/*alert("ERROR : "+msg);*/}
        });
      }
    }
  )
}

// ----------------------------------------------
function init_map_links(){
  $(".map-link").click(
    function(){
      var sLinkId = $(this).attr("id");
      var sLinkClass = $(this).attr("class");
      var sObjId =  sLinkId.replace("map-link-","");
      var sLinkType = ( /loc-link/.test( sLinkClass ) != false  )? 'loc' : 'adh';
      // -------------------------------------
      ajax_get_adh( sObjId, sLinkType );
      // -------------------------------------
      $("#close-map").click(
        function(){
          $("#otd-map-container").css("visibility","hidden");
          $("#D_In_2").css("visibility","visible");
        }
      )
    }
  );
}
// ----------------------------------------------
function ajax_get_adh( id, sLinkType ){
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "http://"+location.host+"/otd-map/rest-otd-map.php" ,
		data: "function=otd_get_marker_infos&argument='"+id+"|"+sLinkType+"'",
		success: function(msg){
      var bLoc = (sLinkType == 'loc')? true : false;
      createMarker(msg['lat'], msg['lng'], msg['label'], msg['html'], msg['id'], msg['idSecteur'],true,bLoc);
      $("input.ssect-check").attr("checked", "");
      $("#otd-map-container").css("visibility","visible");
      $("#D_In_2").css("visibility","hidden");
    },
		error: function(msg){/*alert("ERROR : "+msg);*/}
	});
}

// ----------------------------------------------
function getUrlParams( pName ) {
  pName = pName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+pName+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ){
    return "";
  }else{
    return results[1];
  }
}

// ----------------------------------------------
$(document).ready(
  function(){
    odtMapInitialize();

    show_hide_sous_secteurs();
    init_sous_secteurs_actions();
    init_map_links();

    var sect    = getUrlParams( 'secteur' );
    var rub     = getUrlParams( 'rub' );
    var parent  = getUrlParams( 'parent' );
    if( sect==31 && rub==34 && parent==31  ){
      $("#Inside_In").css("height","750px");
      $("#close-map").css("visibility","hidden");
      $("#otd-map-container").css("top","350px");
      $("#otd-map-container").css("visibility","visible");
      map.setCenter(new GLatLng(48.6305506,-2.0631084), 14);
    }
  }
);
  

