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["note"]      = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_note_musique.png");
/*
gicons["bleu"]      = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_bleu.png");
gicons["bordeaux"]  = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_bordeaux.png");
gicons["gris"]      = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_gris.png");
gicons["jaune"]     = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_jaune.png");
gicons["marron"]    = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_marron.png");
gicons["orange"]    = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_orange.png");
gicons["parme"]     = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_parme.png");
gicons["rose"]      = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_rose.png");
gicons["vert"]      = new GIcon(G_DEFAULT_ICON, "/mod-map/images/gicon_vert.png");
*/

function modMapInitialize() {
  if (GBrowserIsCompatible()) {
    
    if( gmapVersion < 3 ){
      map = new GMap2(document.getElementById("mod-map"));
      map.addControl(new GLargeMapControl); // zoom, directions
      map.addControl(new GMapTypeControl()); // vues "plan", "satellite","mixte"

      //map.setCenter(new GLatLng(48.23055,-3.36310), 8);
      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 = "/mod-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();
    }
    else{
      var latlng = new google.maps.LatLng(0, 0);
				//objet contenant des propriétés avec des identificateurs prédéfinis dans Google Maps permettant
				//de définir des options d'affichage de notre carte
      var options = {
        center: latlng,
        zoom: 19,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("mod-map"), options);
    }

  }
}

// ----------------------------------------------
// 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 marker = new GMarker(point, gicons['note']);

  //-----------------------------------------
  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 iti">'+html+'</div>');

  var tabItiHtml  = 'Vous pouvez calculer un itinéraire';
  // 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 += ' entre ce festival et une adresse comme destination ou point de départ.<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/>(préciser le code postal et/ou l\'adresse pour un meilleur calcul).<br/> <br/><label for="gAddrIsDest">Par défaut cette adresse est votre point de départ,<br/> cocher cette case si c\'est votre destination</label> <input type="checkbox" name="gAddrIsDest" id="gAddrIsDest" value="true" /> ';
  tabItiHtml += '<input type="button" name="gBtnGetIti" id="gBtnGetIti" value="Calculer" 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);
      //setTimeout("init_view_fiche();",3000);
    }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(8);
  }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()
  $("#secteursContainer").css("visibility","hidden");
  $("#gInfoWinContent").css("visibility","hidden");
  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.hide();

}
function closeItineraire() {
  if( 'undefined' != typeof(gdir) ){
    gdir.clear();
  }
  $("#itiContainer").hide();
  $("#secteursContainer").css("visibility","visible");
}
//-----------------------------------------------------------
function ajax_create_fest_markers( iSsectId, sChkType ){
  $.ajax({
    type: "GET",
    dataType: "json",
    url: "http://"+location.host+"/mod-map/rest-mod-map.php" ,
    //data: "function=mod_map_get_adh_from_sous_secteur&argument='"+iSsectId+"|"+sChkType+"'",
    data: "function=mod_map_get_all_festivals",
    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);
        $("#une").css("visibility","hidden");
        $("#mod-map-container").css("visibility","visible");
      }
    },
    error: function(msg){/*alert("ERROR : "+msg);*/}
  });
}

function mod_map_get_all_festivals(){

}



// ----------------------------------------------
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(){
      $("#mod-map-container").css("visibility","hidden");
      $("#une").css("visibility","visible");
    }
  );
}
// ----------------------------------------------
function ajax_get_adh( id, sLinkType ){
  $.ajax({
		   
    type: "GET",
    dataType: "json",
    url: "http://"+location.host+"/mod-map/rest-mod-map.php" ,
    data: "function=mod_map_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);
    },
    error: function(msg){/*alert("ERROR : "+msg);*/}
  });
  $("#une").css("visibility","hidden");
  $("#mod-map-container").css("visibility","visible");
  	  
}

// ----------------------------------------------

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(){
    modMapInitialize();
    //show_hide_sous_secteurs();
    //init_sous_secteurs_actions();
    init_map_links();
    
    $("input.ssect-check").attr("checked", "checked");//On coche la case
  //ajax_create_sssect_markers( 84, 'adh' );//on lance l'action de création des points de sous secteurs
    
  }
  );
  

//============================================================================
// ----------------------------------------------
/*
function ajax_create_fest_en_cours( iSsectId, sChkType ){
  $.ajax({
    type: "GET",
    dataType: "json",
    url: "http://"+location.host+"/mod-map/rest-mod-map.php" ,
    data: "function=mod_map_get_fest_en_cours&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);
        $("#une").css("visibility","hidden");
        $("#mod-map-container").css("visibility","visible");
      }
    },
    error: function(msg){/*alert("ERROR : "+msg);* /}
  });
}*/
/*
 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") ){
        alert('ajax_create_sssect_markers');
        ajax_create_sssect_markers( iSsectId, sChkType );
      }
      else{
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "http://"+location.host+"/mod-map/rest-mod-map.php" ,
          data: "function=mod_map_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 ajax_create_sssect_markers( iSsectId, sChkType ){
  $.ajax({
    type: "GET",
    dataType: "json",
    url: "http://"+location.host+"/mod-map/rest-mod-map.php" ,
    data: "function=mod_map_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);* /}
  });
}*/
// ----------------------------------------------
