/* Variables */
var baseIcon, recomendedIcon, esperaIcon, hostelsclubIcon;
// Variables para personalizar los iconos numerales.
var baseNumeralIcon = '';
var secondaryIcon = '';
var extensionNumeralIcon = '';

var urlIcon;
var marker = new Array();
var html = new Array();
var map;
var gg_layer = "map";
var lat, lon, zoom;
var typeControl = true;
var largeMapControl = true;
var smallMapControl = false;
var scaleControl = true;
var is_map_loaded = false;
var centerMarker = null;
var radiusMarker = null;
var circleLine = null;
var geocoder = null;
//---bug:14095
var varMarker=null;
//------------

/* Metodos */
function MapLoad()
{
    if (GBrowserIsCompatible())
    {
        baseIcon = new GIcon();
        baseIcon.image = "http://www.google.com/mapfiles/marker.png";
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(11, 26);
        baseIcon.infoWindowAnchor = new GPoint(18, 0);

        secondaryIcon = new GIcon();
        secondaryIcon.image = "http://labs.google.com/ridefinder/images/mm_20_gray.png";
        secondaryIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        secondaryIcon.iconSize = new GSize(12, 20);
        secondaryIcon.shadowSize = new GSize(22, 20);
        secondaryIcon.iconAnchor = new GPoint(11, 26);
        secondaryIcon.infoWindowAnchor = new GPoint(18, 0);

        esperaIcon = new GIcon();
        esperaIcon.image = "http://www.atrapalo.com/images_new/restaurantes/cargando.gif";
        esperaIcon.iconSize = new GSize(32, 32);
        esperaIcon.iconAnchor = new GPoint(11, 26);
        esperaIcon.infoWindowAnchor = new GPoint(18, 0);

        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(41.394952289339166,2.1503591537475586),14);

        map.enableDoubleClickZoom();
        map.enableContinuousZoom();
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
        map.addControl(new GMapTypeControl());

        geocoder = new GClientGeocoder();
    }
}

// Creates a marker at the given point with the given number label
function createMarker(point, icon, html, titulo, onmover)
{
    var mark = new GMarker(point, icon);
    GEvent.addListener(mark, "click", function() {
        mark.openInfoWindowHtml(html);
    });
    if(onmover!='')
    {
        GEvent.addListener(mark, "mouseover", function() {
           if(map.getZoom()>=14) mark.openInfoWindowHtml(html);
        });
        GEvent.addListener(mark, "mouseout", function() {
        });
    }
    return mark;
}

function showAddress(address)
{
    if (geocoder)
    {
        geocoder.getLocations(address,
        function(result)
        {
            if (result.Status.code != G_GEO_SUCCESS)
            {
                errores.push(new Error('12', '000', '000', address + " Direccion desconocida"));
                errores.show();
            }
            else
            {
                if (result.Placemark.length > 1)
                {
                    $("quiso_decir").innerHTML = "Quiso decir:";
                    for (var i = 0; i < result.Placemark.length; i++)
                    {
                        var p = result.Placemark[i].Point.coordinates;
                        $("quiso_decir").innerHTML += "<li><a href='#' onclick='place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"</a></li>";
                    }
                }
                else
                {

                    var p = result.Placemark[0].Point.coordinates;
                    place(p[1], p[0]);
                }
            }
        }
        );
    }
}

//-- bug:14095
function elimina(lat, lng)
{
	map.removeOverlay(varMarker);
	$("quiso_decir").innerHTML = "";
}
//--------------

function place(lat, lng)
{
    // -- bug:14095
    if(varMarker!=null) elimina(varMarker);
    var point = new GLatLng(lat, lng);
    map.setCenter(point, 15);
    varMarker=new GMarker(point);
    map.addOverlay(varMarker);
    $("quiso_decir").innerHTML = "";
}

function mostrar_datos_mapa(id_mapa, app, lista_ids_1, lista_ids_2, aux)
{
    load_url = '/mapas/index.php?pg=do_ajax';
    parameters = 'pg_action=geomapabusqueda&app='+app+'&ids1='+lista_ids_1+'&ids2='+lista_ids_2+'&'+aux;
    YAHOO.util.Connect.asyncRequest("post", load_url, {
          timeout: 75000,
          success: function(o)
          {
              map.clearOverlays();
              xmldata = o.responseXML;
              nodes = xmldata.getElementsByTagName('data')[0].getElementsByTagName('producto');
              bounds = new GLatLngBounds();
              // En caso de una pagina sin contenido con latitud, usaremos el centrado secundario que tiene en
              // cuenta todos los prodctos de la lista.
              secondaryBounds = new GLatLngBounds();
              num_principales = 0;
              num_secundarios = 0;
              for (i = 0; i < nodes.length; i++)
              {
                  // Obtener los datos del nodo:
                  lon = nodes[i].getAttribute("lon");
                  lat = nodes[i].getAttribute("lat");
                  tipo = nodes[i].getAttribute("tipo");
                  id = nodes[i].getAttribute("id");
                  nombre = nodes[i].getAttribute("nombre");
                  indice_marker = nodes[i].getAttribute("orden");
                  es_online = nodes[i].getAttribute("online");
                  if (is_ie)
                      contenido = nodes[i].text;
                  else
                      contenido = nodes[i].textContent;

                  // Si el restaurante tiene lat y lon, se puede markar sino, no.
                  if (lat != '' && lon != '')
                  {
                      // Crear el marcador.
                      point = new GLatLng(lat, lon);
                      if (tipo == 0)
                      {
                          if (baseNoNumeralIcon != '' && baseNoNumeralNoOnlineIcon != '')
                          {
                              // Es tipo secundario.
                              // Determinar el icono en base a si es con reserva online o no.
                              if (es_online == 1)
                                  secondaryIcon.image = baseNoNumeralIcon;
                              else
                                  secondaryIcon.image = baseNoNumeralNoOnlineIcon;
                          }
                          icono = secondaryIcon;
                          secondaryBounds.extend(point);
                          num_secundarios++;
                      }
                      else
                      {
                          // Es tipo normal.
                          if (baseNumeralIcon != '' && extensionNumeralIcon != '' && baseNumeralNoOnlineIcon != '')
                          {
                              // Determinar el icono en base a si es con reserva online o no.
                              if (es_online == 1)
                                  baseIcon.image = baseNumeralIcon+indice_marker+extensionNumeralIcon;
                              else
                                  baseIcon.image = baseNumeralNoOnlineIcon+indice_marker+extensionNumeralIcon;
                          }
                          icono = baseIcon;
                          // Como es un icono principal, ampliarlo.
                          bounds.extend(point);
                          num_principales++;
                      }
                      html[id] = contenido;
                      marker[id] = new createMarker(point, icono, html[id], nombre, false);
                      map.addOverlay(marker[id]);
                      if (document.getElementById('lat').value == lat &&
                          document.getElementById('lon').value == lon)
                      {
                          marker[id].openInfoWindowHtml(contenido);
                      }
                  }
              }
              if (bounds.isEmpty())
              {
                  map.setCenter(secondaryBounds.getCenter());
                  map.setZoom(map.getBoundsZoomLevel(secondaryBounds));
              }
              else
              {
                  if (num_principales == 1 && num_secundarios >= 1)
                  {
                      // Sólo hay un icono principal, mostrar los secundarios, que sino no se vera nada.
                      map.setCenter(secondaryBounds.getCenter());
                      map.setZoom(map.getBoundsZoomLevel(secondaryBounds));
                  }
                  else
                  {
                      map.setCenter(bounds.getCenter());
                      map.setZoom(map.getBoundsZoomLevel(bounds));
                  }
              }
          },
          failure: function() {
             return false;
          }
        }, parameters);
}

function mostrar_detalle_mapa(id)
{
    map.setZoom(16);
    marker[id].openInfoWindowHtml(html[id]);
    return false;
}

function mostrar_imagen_espera()
{
    point = new GLatLng(41.394952289339166,2.1503591537475586);
    // marker_espera = new createMarker(point, esperaIcon);
    marker_espera = new GMarker(point, esperaIcon);
    map.addOverlay(marker_espera);
}
