var mapOptions;

var map;
var markers = [];
var openedWindow;
var bounds;

var daysLetter = new Array(lang.day_1, lang.day_2, lang.day_3, lang.day_4, lang.day_5, lang.day_6, lang.day_7);
var list;

/**
 * Initialise les textes d'affichage des points relais contenus dans la
 * liste passée en parametre.
 */
function initTextDisplays(l, type) {
  inputCallBackName =  ptrelInputCallBack;
  for(var i=0; i<l.length; i++) {
    var point = l[i];
    point.rightcoltext = getRightColText(point, i);
    point.markertext = getMarkerText(point, i);
  }
}

/**
 * Fonction d'affichage des informations d'un relais dans le div de la page choix.
 * Les parametres sont
 * - index : l'index du relais dans le tableau des relais
 * - selected : un booleen qui indique si le relais est affiche en temps que relais
 *                          le plus proche ou le relais sélectionné.
 */
function displayRelayInfo(index, selected) {
  var point = list[index];

  // affichage des horaires.
  var horaires ="<div>";
  for(var k in point.schedule){
    if(point.schedule[k].open_am !== "" && point.schedule[k].open_pm !== ""){
      point.schedule[k].open_am = hhmm(point.schedule[k].open_am);
      point.schedule[k].open_pm = hhmm(point.schedule[k].open_pm);
      if(point.schedule[k].close_am != point.schedule[k].open_pm){
          point.schedule[k].close_am = hhmm(point.schedule[k].close_am);
          point.schedule[k].close_pm = hhmm(point.schedule[k].close_pm);
          horaires += "<span class='day'>"+daysLetter[k]+"</span><span class='db fr'>"+ point.schedule[k].open_am+" - "+ point.schedule[k].close_am+", "+ point.schedule[k].open_pm+" - "+ point.schedule[k].close_pm+"</span><br />";
    } else {
          point.schedule[k].close_pm = hhmm(point.schedule[k].close_pm);
          horaires += "<span class='day'>"+daysLetter[k]+"</span><span class='db fr'>"+ point.schedule[k].open_am+" - "+ point.schedule[k].close_pm+"</span><br />";
      }
    } else if(point.schedule[k].open_am !== ""){
      point.schedule[k].open_am = hhmm(point.schedule[k].open_am);
      point.schedule[k].close_am = hhmm(point.schedule[k].close_am);
      horaires += "<span class='day'>"+daysLetter[k]+"</span><span class='db fr'>"+point.schedule[k].open_am+" - "+point.schedule[k].close_am+"</span><br />";
    }
  }
  horaires += "</div>";

  var infos = "<p><strong>"+point.name+"</strong><br />" +
                              point.address+"<br />" +
                              point.zipcode+" "+point.city+"<br />" +
                              lang['Opening hours'] +
                              '<a class="popover-hour pointer" data-placement="top" data-toggle="popover" type="button" data-original-title="'+horaires+'" >' +
                              "<img class='pl5 pb2' src='/img/ico-question.png'>" +
                              "</a><br/>" +
                              (selected ? "": "<a class='choice pointer button' rel='"+point.id+"' onClick='choicePtrel("+index+")'>JE S&Eacute;LECTIONNE</a>") +
                              "</p>";

  jQuery("#show").html(infos);
  // activation tooltip horaires
  jQuery('.popover-hour').popover({ trigger :"hover", html : true });
}

/**
 * Fonction de creation de l'affichage des informations du point relais dans la colonne de droite
 */
function getRightColText(point, index) {
  var nbImg = index+1;
  var parcelPointSelect = "";
  if( inputCallBackName !== '' && inputCallBackName != 'undefined' ){
    parcelPointSelect = "<a class='btn btn-info btn-xs' style='width:100%;' onClick='chooseParcelPoint(\""+point.code.split("-")[1]+"\")' ><b>"+lang['Choose this ']+ relayName +"</b></a>";
  }
  var txt = "<tr class='mt20' id='infos-pr-"+nbImg+"' class='point-relais-right-col'>" +
                  "<td><img src='"+pluginUrl+"/assets/img/marker-number-"+nbImg+".png' class='emcMarker' />" +
                  "<div class='emcPointTitle'><a class='showInfo"+point.code+" pointer'>"+point.name+"</a></div><br />" +
                  point.address+"<br />"+point.zipcode+" "+point.city+"<br />" +
                  lang['Code of']+" <strong>"+point.code.split("-")[1]+"</strong><br/>" +
                   parcelPointSelect +
                  "</td></tr>";
  return txt;
}

/**
 * Fonction de creation du texte d'un marker google maps
 * Prend en parametre index car on en a besoin pour le lien de choix.
 */
function getMarkerText(point, index) {
  var horaires ="";
  var parcelPointSelect = "";
  if( inputCallBackName !== '' && inputCallBackName != 'undefined' ){
    parcelPointSelect = "<a class='btn btn-info btn-xs' onClick='chooseParcelPoint(\""+point.code.split("-")[1]+"\")' ><b>"+lang['Choose this ']+ relayName +"</b></a><br/>";
  }
  for(var k in point.schedule){
    if(point.schedule[k].open_am !== "" && point.schedule[k].open_pm !== ""){
      point.schedule[k].open_am = hhmm(point.schedule[k].open_am);
      point.schedule[k].open_pm = hhmm(point.schedule[k].open_pm);
      if(point.schedule[k].close_am != point.schedule[k].open_pm){
        point.schedule[k].close_am = hhmm(point.schedule[k].close_am);
        point.schedule[k].close_pm = hhmm(point.schedule[k].close_pm);
        horaires += "<span class='day'>"+daysLetter[k]+"</span><span class='fr' style='font-size:11px;'>"+ point.schedule[k].open_am+" - "+ point.schedule[k].close_am+", "+ point.schedule[k].open_pm+" - "+ point.schedule[k].close_pm+"</span><br />";
      }  else {
        point.schedule[k].close_pm = hhmm(point.schedule[k].close_pm);
        horaires += "<span class='day'>"+daysLetter[k]+"</span><span class='fr' style='font-size:11px;'>"+ point.schedule[k].open_am+" - "+ point.schedule[k].close_pm+"</span><br />";
      }
    } else if(point.schedule[k].open_am !== ""){
      point.schedule[k].open_am = hhmm(point.schedule[k].open_am);
      point.schedule[k].close_am = hhmm(point.schedule[k].close_am);
      horaires += "<span class='day'>"+daysLetter[k]+"</span><span class='fr' style='font-size:11px;'>"+point.schedule[k].open_am+" - "+point.schedule[k].close_am+"</span><br />";
    }
  }
  var txt = "<div style='width:250px'><b>"+point.name+"</b><br/>" +
                      parcelPointSelect +
                      point.address+"<br/>" +
                      point.zipcode+" "+point.city+"<br/>" +
                      "<b>"+lang['Opening hours']+"</b><br/>" +
                      "<div style='font-size:11px;'>"+horaires+"</div>" +
                      "</div>";
  return txt;
}

/**
 * Fonction qui permet de selectionner un point relais.
 * Les paramètres sont :
 * - type : exp ou dst
 * - index : index du point dans le tableau.
 */
var choicePtrel = function(index) {
  displayRelayInfo(index, true);
  jQuery("#map").addClass("hidden");
  jQuery("#relais_id").val(list[index].id);
  jQuery("#choice").removeClass("hidden");
};

/**
 * Mise à jour de la liste des relais en ajax.
 */
function updateListPoints(urlBase, cp, ville, pays, poids, ope_code, srv_code, collecte) {
  var list;

  jQuery.ajax({
    type: "GET",
    url: urlBase+"type=json&ville="+ville+"&cp="+cp+"&country="+pays+"&poids="+poids+"&ope="+ope_code+"&srv="+srv_code+"&collecte="+collecte,
    dataType: "json",
    async: false,
    success: function(data) {
        listByCarrier = data;
        list = listByCarrier[0].points;
    }
  });
  return list;
}

/**
 * Permet de reinitialiser ce qui doit l'etre
 * quand on raffraichit la carte
 */
function resetGlobals() {
  if(markers.length > 0) {
    for(var i=0; i<markers.length; i++) {
      if(markers[i]) markers[i].setVisible(false);
    }
  }
  markers = [];
}

/**
 * Affichage d'un marker sur la carte.
 */
function makeMarker(latlng, point, index) {

    var nbImg = index + 1;

    var emcMarker = {
        url: pluginUrl + "/assets/img/marker-number-"+nbImg+".png",
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(13, 37),
        scaledSize: new google.maps.Size(26, 37)
    };

    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: emcMarker
    });
    markers[index] = marker;
    bounds.extend(marker.getPosition());

    var infowindows = new google.maps.InfoWindow({
        'content'  : point.markertext
    });

    var added = false;
    for(var j = nbImg-1 ; j > 0 ; j--) {
        if(jQuery("#infos-pr-"+j).length > 0 && !added) {
            jQuery("#infos-pr-"+j).after(point.rightcoltext);
            added = true;
        }
    }
    if(!added) {
        jQuery("#rightcol-ptrel").prepend(point.rightcoltext);
    }

    google.maps.event.addListener(marker,"click",function() {
        if(typeof openedWindow != 'undefined' && openedWindow !== null) {
            openedWindow.close();
        }
        openedWindow = infowindows;
        infowindows.open(map, this);
    });

    //Trigger a click event to marker when the button is clicked.
    jQuery(".showInfo"+point.code).click(function(){
        if(typeof openedWindow != 'undefined' && openedWindow !== null) {
            openedWindow.close();
        }
        openedWindow = infowindows;
        infowindows.open(map,marker);
    });

    //chois du point relais
    jQuery("a.choice").click(function(){
        jQuery("#modal-parcel-point").modal("hide");
    });

}

jQuery(document).ready(function(){
  // initialisation des variables Google
  mapOptions = { zoom: 8,
                 zoomControlOptions : { style : google.maps.ZoomControlStyle.LARGE },
                 mapTypeId: google.maps.MapTypeId.ROADMAP,
                 streetViewControl: false };

  // premier init de la map
  list = updateListPoints(baseUrl, jQuery('#ptrel-cp').val(), jQuery('#ptrel-ville').val(), ptrelPays, ptrelPoids, ptrelOpe, ptrelSrv, ptrelCollecte);

  initTextDisplays(list);

  if(!map && jQuery('#map-canvas').length > 0) {
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  }
  bounds = new google.maps.LatLngBounds();

  jQuery("#rightcol-ptrel").html("");
  resetGlobals();

  for(var i=0;i<list.length; i++) {
      var latlng = new google.maps.LatLng(parseFloat(list[i].latitude),parseFloat(list[i].longitude));
      makeMarker(latlng, list[i], i);
  }

  map.fitBounds(bounds);

  /**
   * Soumission du pseudo formulaire de la popup.
   */
  jQuery('#submitNewMap').click(function() {
      list = updateListPoints(baseUrl, jQuery('#ptrel-cp').val(), jQuery('#ptrel-ville').val(), ptrelPays, ptrelPoids, ptrelOpe, ptrelSrv, ptrelCollecte);
      initTextDisplays(list);

      bounds = new google.maps.LatLngBounds();
      jQuery("#rightcol-ptrel").html("");
      resetGlobals();

      for(var i=0;i<list.length; i++) {
        var latlng = new google.maps.LatLng(parseFloat(list[i].latitude),parseFloat(list[i].longitude));
        makeMarker(latlng, list[i], i);
      }
      map.fitBounds(bounds);

      return false;
  });
});


/**
 * Choose Parcel Point and close modal
 */
function chooseParcelPoint(parcelPoint) {
    jQuery("input[name='"+inputCallBackName+"']", window.parent.document).val(parcelPoint);
    /* close colorbox in woocommerce */
    parent.jQuery.colorbox.close();
}

/**
 * Convert hours HH:mm:ss to HH:mm
 */
function hhmm(hhmmss){
  var data = hhmmss.split(':');
  var hours = data['0']+':'+ data['1'];
  return hours;
}
