//addListener( window, 'load', findShopLink );

$(document).ready(function(){
  $("a.tab").live("click", function(e){
    e.preventDefault();
    switchTabs();
  });

  $(".find_store").submit(function(e){
    e.preventDefault();
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(
      $("#code_postal").val()+",France",
      function(point){
        if (!point) {
          alert("Ce code postal n\'a pas pu être localisé");
        } else {
          $("#lat").val(point.lat());
          $("#lng").val(point.lng());
          $("#code_postal_hidden").val($("#code_postal").val());
          $("#geolocate").submit();
        }
      });
  });

});

/* Google Maps */

var geocoder = null;
var gdir;

var streetFrom = '';
var cpFrom = '';
var cityFrom = '';

var storeSearchResultContent = '';

var baseIcon = new GIcon();
baseIcon.image="/pix/maps/unique.png";
baseIcon.shadow="/pix/maps/ombre.png";
baseIcon.iconSize = new GSize(24, 34);
baseIcon.shadowSize = new GSize(40, 34);
baseIcon.iconAnchor = new GPoint(12, 34);
baseIcon.infoWindowAnchor = new GPoint(12, 2);

function loadMap(){

  if (GBrowserIsCompatible()) {
    
    MaCarte.setCenter(new GLatLng(47.1949743, 1.9030469), 6);
    MaCarte.addControl(new GLargeMapControl());
    MaCarte.addMapType(G_PHYSICAL_MAP);
    var hierarchy = new GHierarchicalMapTypeControl();
    hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Afficher les noms", true);
    MaCarte.addControl(hierarchy);
    MaCarte.enableScrollWheelZoom();
    geocoder = new GClientGeocoder();

  }else{
    alert("Désolé, mais votre navigateur n'est pas compatible avec Google Maps");
  }

}

function loadMarkers(xml){
  var markersArray=[];

  if($.browser.msie){
    var data = xml;
    xml = new ActiveXObject( 'Microsoft.XMLDOM');
    xml.async = false;
    xml.loadXML(data);
  }
  
  var showResults = true;

  var fromcp = $(xml).find("fromcp").eq(0).text();

  if(fromcp!="" && fromcp.length==5){
    storeSearchResultContent = "";
    cpFrom = fromcp;
  }

  var $allmagasins = $(xml).find("magasin");

  if($.browser.msie){
    if($(xml).find("magasins").eq(0).attr("type")=="all") showResults=false;
  }else{
    if($(xml).attr("type")=="all") showResults=false;
  }

  var magasinsSize = $allmagasins.length;
  if(magasinsSize >0){
    for(var i=0; i<magasinsSize; i++){
      var $magasin = $allmagasins.eq(i);
      
      var point = new GLatLng($magasin.find("lat").text(),$magasin.find("lng").text());
      
      var marker = createMarker(point,$magasin);
      
      //hack pour éviter les erreurs javascript bloquant l'affichage'
      MaCarte.addOverlay(marker);
      MaCarte.removeOverlay(marker);
      markersArray.push(marker);

      if(magasinsSize == 1){
        GEvent.trigger(marker,"click");
      }

      // Ajout à la liste de résultats
      if(showResults){
        addStoreToResultList($magasin, marker);
      }
    }

    if(showResults){
     displayResults();
    }

    cluster=new ClusterMarker(MaCarte, { markers:markersArray } );
    cluster.clusterMarkerTitle='%count magasins';
    cluster.fitMapToMarkers();
    cluster.clusterMarkerClick=function(args) { MaCarte.setCenter(new GLatLng(args.clusterMarker.getLatLng().lat(), args.clusterMarker.getLatLng().lng()), MaCarte.getZoom()+3);return false;};

  }else{
    window.location = window.location;
    alert("Magasin introuvable\nIl se peut que le code postal recherché ne puisse pas être localisé.");
  }
}

/* Créé un marker */

function createMarker(point, xmlMagasin){
  
  var marker= new GMarker(point, {title:xmlMagasin.find("libelle").text(), icon:baseIcon});

  // Prepare content
  var htmlFirstTab = "<div class='html-window-info' style='margin-top: 15px; height: 180px; overflow: auto;'>"
  htmlFirstTab += "<img style='display:none' src=''/><p>";
  htmlFirstTab += "<strong>"+xmlMagasin.find("libelle").text()+"</strong>";
  htmlFirstTab += "<br/>";
  htmlFirstTab += xmlMagasin.find("adresse").text()+"<br/>"+xmlMagasin.find("cp").text()+" "+xmlMagasin.find("ville").text();
  htmlFirstTab += "<br/>Tel : "+xmlMagasin.find("tel").text()+"</p>";
  htmlFirstTab += "<br/><p class='block'><strong>Horaires :</strong><br/>";
  htmlFirstTab += xmlMagasin.find("horaires").text().replace(/mardi/i,"<br/>Mardi").replace(/mercredi/i,"<br/>Mercredi").replace(/jeudi/i,"<br/>Jeudi").replace(/vendredi/i,"<br/>Vendredi").replace(/samedi/i,"<br/>Samedi").replace(/dimanche/i,"<br/>Dimanche");
  htmlFirstTab += "</p></div>";

  var htmlSecondTab = "";
  htmlSecondTab += '<form id="directions" method="post" action="#" onsubmit="var ttype = (this.transportType1.checked)?this.transportType1.value:this.transportType2.value;setDirections( this.fromStreet.value, this.fromCp.value, this.fromCity.value, ttype, this.toLat.value, this.toLng.value );return false">';
  htmlSecondTab += '<center><table id="CommentSyRendreTable" border="0">';
  htmlSecondTab += '<tr>';
  htmlSecondTab += '<td align="right"><label for="fromStreet">Rue : </label></td>';
  htmlSecondTab += '<td align="left" colspan="3"><input type="text" size="25" id="fromStreet" name="fromStreet" value="%streetFrom%" class="inputs" /></td>';
  htmlSecondTab += '</tr>';
  htmlSecondTab += '<tr>';
  htmlSecondTab += '<td align="right"><label for="fromCp">Code postal : </label></td>';
  htmlSecondTab += '<td align="left"><input type="text" size="5" maxlength="5" id="fromCp" name="fromCp" value="%cpFrom%" class="inputs" /></td>';
  htmlSecondTab += '</tr>';
  htmlSecondTab += '<tr>';
  htmlSecondTab += '<td align="right"><label for="fromCity">Ville : </label></td>';
  htmlSecondTab += '<td align="left"><input type="text" size="25" id="fromCity" name="fromCity" value="%cityFrom%" class="inputs" /></td>';
  htmlSecondTab += '</tr>';
  htmlSecondTab += '<tr>';
  htmlSecondTab += '<td></td><td><input id="transportType1" name="transportType" type="radio" checked="checked" value="walking"/>&nbsp;&nbsp;<label for="transportType1">Itinéraire piéton</label><br/>\n\
                    <input id="transportType2" name="transportType" type="radio" value="driving"/>&nbsp;&nbsp;<label for="transportType2">Itinéraire véhicule</label></td>';
  htmlSecondTab += '</tr>';
  htmlSecondTab += '<tr>';
  htmlSecondTab += '<td></td><td align="left" colspan="3">';
  // latitude et longitude du marker que l'on vient d'afficher :
  htmlSecondTab += '<input type="hidden" id="toLat" name="toLat" value="' + point.lat() + '" />';
  htmlSecondTab += '<input type="hidden" id="toLng" name="toLng" value="' + point.lng() + '" />';
  htmlSecondTab += '<input name="submit" type="submit" value="Afficher l\'itin&#233;raire" class="submits" /></td>';
  htmlSecondTab += '</tr>';
  htmlSecondTab += '</table></center>';
  htmlSecondTab += '</form>';

  var htmlThirdTab = "<div id='pano"+marker.getLatLng().lat()+"' style='width:300px;height:200px;'></div>";
  
  // Add click event
  GEvent.addListener(marker, "click", function(){
    htmlSecondTab = htmlSecondTab.replace("%streetFrom%",streetFrom);
    htmlSecondTab = htmlSecondTab.replace("%cpFrom%",cpFrom);
    htmlSecondTab = htmlSecondTab.replace("%cityFrom%",cityFrom);
	
    marker.openInfoWindowTabsHtml( [ new GInfoWindowTab( 'Informations', htmlFirstTab ), 
                                    new GInfoWindowTab( 'S\'y rendre', htmlSecondTab ),
                                    new GInfoWindowTab( 'Panorama', htmlThirdTab )] );
	
									
	/*								
	marker.openInfoWindowTabsHtml( [ new GInfoWindowTab( 'Informations', htmlFirstTab ), 
                                    new GInfoWindowTab( 'S\'y rendre', htmlSecondTab ),
                                    new GInfoWindowTab( 'Panorama', htmlThirdTab )], {maxContent: htmlFirstTab, maxTitle: "Informations"} );
	*/
	
  });

  GEvent.addListener(marker, "infowindowopen", function(){
    // Créé un panorama
    var pano = new GStreetviewPanorama(document.getElementById("pano"+marker.getLatLng().lat()), { latlng:marker.getLatLng(), features:{userPhotos: false} });
    GEvent.addListener(pano, "error", handleNoFlash);
    // Vérifie si le panorama est disponible
    var svclient = new GStreetviewClient();
    svclient.getNearestPanorama(marker.getLatLng(),executeStreetView);
  });

  return marker;
}

/* Calcule l'itinéraire */

function setDirections( fromStreet, fromCp, fromCity, transportType, toLat, toLng ) {

  // adresse de depart :
  var fromAdresse = fromStreet + ', ' + fromCp + ', ' + fromCity + ', France';
  // on garde l'adresse de depart pour ne pas la redemander :
  streetFrom = fromStreet;
  cityFrom = fromCity;
  // on geocode l'adresse de depart :
  geocoder.getLatLng( fromAdresse, function( fromLatLng ) {
    if ( !fromLatLng ) {
      alert( fromAdresse + ' inconnue' );
    } else {
      // si la "direction" existe, on la supprime
      if ( gdir ) {
        gdir.clear();
      }

      // creation d'une nouvelle direction ayant pour nom "gdir" :
      gdir = new GDirections( MaCarte, document.getElementById( "store-itinerary-list" ) );

      // gestionnaire d'erreur de la direction :
      GEvent.addListener( gdir, "error", erreurItineraire );

      // Chargement de l'itinéraire ( from: x1, y1 to: x2, y2) :
      var queryPoints = "from: " + fromLatLng.lat() + ", " + fromLatLng.lng() + " to: " + toLat + ", " + toLng;
      var ttype = (transportType=="walking")?G_TRAVEL_MODE_WALKING:G_TRAVEL_MODE_DRIVING;
      gdir.load( queryPoints,	{ "locale": 'fr', "travelMode":ttype });

      // Construction de la sidebar
      if($(".store-search-results:visible").length>0){
        makeTabs();
      }else{
        $(".store-itinerary-results").show();
      }
      
    }
  });

}

function erreurItineraire() {
  // Si l'adresse transmise à la direction "gdir" est inconnue ...
  if ( gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS ){
          alert( 'Aucun endroit geographique ne correspond. Code d\'erreur : ' + gdir.getStatus().code );
  } else {
          alert( 'Une erreur inconnue s\'est produite.' );
  }
}

function addStoreToResultList(xmlMagasin, marker){

  var html = "";
  var $distanceToStore = xmlMagasin.find("distance");
  if($distanceToStore.length>0){
    html += "<span class='list_distance'>"+$distanceToStore.text()+" km</span>";
  }

  html += "<h3>"+xmlMagasin.find("libelle").text()+"</h3>";
  html += "<p class='address'>"+xmlMagasin.find("adresse").text()+"<br/>"+xmlMagasin.find("cp").text()+" "+xmlMagasin.find("ville").text()+
          "<br/>Tel : "+xmlMagasin.find("tel").text()+"</p>";
  var li = document.createElement( 'li' );
  li.innerHTML = html;
  li.style.cursor = 'pointer';
  // quand un élément de la liste est cliqué, on simule un clic sur son marker associé
  GEvent.addDomListener( li, 'click', function() {
    GEvent.trigger( marker, 'click' );
  });
  GEvent.addDomListener( li, 'mouseover', function() {
    li.style.backgroundColor = '#EEEEEE';
  });
  GEvent.addDomListener( li, 'mouseout', function() {
    li.style.backgroundColor = '#FFFFFF';
  });
  $("#store-result-list").append(li);
}

function displayResults(){
  $(".store-search-results").show();
}

function makeTabs(){
  // sauvegarde les intitulés de bloc
  $(".store-itinerary-results").before("<input type='hidden' id='title_stores' value='"+$(".store-search-results h2").text()+"'/>");
  $(".store-itinerary-results").before("<input type='hidden' id='title_itinerary' value='"+$(".store-itinerary-results h2").text()+"'/>");
  // créé des fausses tabs
  $(".store-itinerary-results h2").html("<a class='tab' href='#'>"+$("#title_stores").val()+"</a><span class='separator'>|</span>"+$("#title_itinerary").val());
  $(".store-search-results").hide();
  $(".store-itinerary-results").show();
}

function switchTabs(){
  if($(".store-search-results:visible").length>0){
    $(".store-itinerary-results h2").html("<a class='tab' href='#'>"+$("#title_stores").val()+"</a><span class='separator'>|</span>"+$("#title_itinerary").val());
    $(".store-search-results").hide();
    $(".store-itinerary-results").show();
  }else{
    $(".store-search-results h2").html($("#title_stores").val()+"<span class='separator'>|</span><a class='tab' href='#'>"+$("#title_itinerary").val()+"</a>");
    $(".store-itinerary-results").hide();
    $(".store-search-results").show();
  }
}

function handleNoFlash(errorCode) {
  if (errorCode == "FLASH_UNAVAILABLE") {
    alert("Erreur: Flash ne semble pas être supporté par votre navigateur");
    return;
  }
}

function executeStreetView(svdata){
  if(svdata.location==undefined){
    var newTabs = new Array();
    newTabs.push(MaCarte.getInfoWindow().getTabs()[0]);
    newTabs.push(MaCarte.getInfoWindow().getTabs()[1]);
    MaCarte.updateInfoWindow(newTabs);
  }
}