/**
 * Clase de config del GMap. Tenemos dos versiones: cuando useGMap es true, se
 * comporta normalmente, creando los objetos de GMap, mostrando los marcadores,
 * etc. Cuando useGMap es false, es un objeto "fake", que no hace nada cuando se
 * invocan sus métodos.
 */
var GMapConfig = null;

if (MainApp.useGMap == true)
{
  /**
   * Alias de las clases de Google Map v3.x
   */
  var GMap = google.maps.Map;
  var GLatLng = google.maps.LatLng;
  var GMarker = google.maps.Marker;
  var GMarkerImage = google.maps.MarkerImage;
  var GInfoWindow = google.maps.InfoWindow;
  var GEvent = google.maps.event;
  
  /**
   * Alias de constantes.
   */
  var MAP_TYPE_TERRAIN = google.maps.MapTypeId.TERRAIN;

  GMapConfig = {
    /**
     * URL a la que le pedimos los metadatos de los mapas (los datos de las
     * estaciones y del clima). Para debuguear usamos una URL local, !!!EN
     * PRODUCCION DEBE SER LA URL DEL SITIO DE DATOS DEL CLIMA!!!
     */
    GMapURL: 'admin/lib/get_gmap_data.php',

    /**
     * Tipos de marcadores.
     */
    SIMPLE_MARKER: 1,
    WIND_MARKER: 2,
    TEMP_MARKER: 3,
    SNOW_MARKER: 4,
    PRECIPITATION_MARKER: 5,

    init: function()
    {
      this.initMarkers();

      this.map = this.createMap();
      this.downloadMapData();
    },

    initMarkers: function()
    {
      this.gmarkers = [];
      this.gmarkersTemp = [];
      this.gmarkersWind = [];
      this.gmarkersSnow = [];
      this.gmarkersPre = [];
      this.gicons = [];
    },

    downloadMapData: function( callback, scope)
    {
      $.ajax({
        url: this.GMapURL,
        success: function( data){
          this.onMapDataDownloaded( data);
          callback.call( scope);
        },        
        dataType: 'xml'
      });
    },

    onMapDataDownloaded: function( xmlDoc)
    {
      var self = GMapConfig;

      var markers = xmlDoc.documentElement.getElementsByTagName( "marker");

      for (var i = 0; i < markers.length; i++)
      {
        var marker = markers[i];
        var latitude = parseFloat( marker.getAttribute( "lat"));
        var longitude = parseFloat( marker.getAttribute( "lon"));

        var markerData = {
          position: new GLatLng( latitude, longitude),
          name: marker.getAttribute( "name"),
          temp: marker.getAttribute( "temp"),
          weather: marker.getAttribute( "weather"),
          wind: marker.getAttribute( "wind"),
          wind_km: marker.getAttribute( "wind_km"),
          visibility: marker.getAttribute( "visibility"),
          pressure: marker.getAttribute( "pressure"),
          snow: marker.getAttribute( "snow"),
          precipitation: marker.getAttribute( "precipitation"),
          date: marker.getAttribute( "date"),
          link: marker.getAttribute( "link"),
          type: marker.getAttribute( "type")
        };

        self.addMarkers( markerData);
      }

      self.showAllWeatherMarkers();
    },

    addMarkers: function( markerData)
    {
      this.createMarker( markerData, this.SIMPLE_MARKER);

      if (markerData.temp != "N/A")
      {
        this.createMarker( markerData, this.TEMP_MARKER);
      }

      if (markerData.wind != "N/A")
      {
        this.createMarker( markerData, this.WIND_MARKER);
      }

      if (markerData.snow != "N/A")
      {
        this.createMarker( markerData, this.SNOW_MARKER);
      }

      if (markerData.precipitation != "N/A")
      {
        this.createMarker( markerData, this.PRECIPITATION_MARKER);
      }
    },

    hideAllMarkers: function()
    {
      var count = this.gmarkers.length;

      for (var i = 0; i < count; i++)
      {
        this.gmarkers[i].setVisible( false);
      }
    },

    showMarkersByCategory: function( category)
    {
      this.hideAllMarkers();

      this.showMarkers( 1, category);
      this.showMarkers( 2, category);
      this.showMarkers( 3, category);
    },

    showAllWeatherMarkers: function()
    {
      this.showMarkersByCategory( 'weather');
    },

    createMap: function()
    {
      var result = new GMap( $('#map')[0], {
        zoom: 8,
        center: new GLatLng( 42.80, 25.10),
        mapTypeId: MAP_TYPE_TERRAIN
      });

      return result;
    },

    getMarkerIcon: function( data, type)
    {
      var result = null;

      switch (type)
      {
        case this.SIMPLE_MARKER:
          result = 'images/weather/' + data.weather;
          break;

        case this.TEMP_MARKER:
          result = 'admin/lib/text_marker.php?param=temp&text=' + data.temp + 'C';
          break;

        case this.WIND_MARKER:
          result = 'admin/lib/text_marker.php?param=wind&text=' + data.wind;
          break;

        case this.SNOW_MARKER:
          result = 'admin/lib/text_marker.php?param=snow&text=' + data.snow;
          break;

        case this.PRECIPITATION_MARKER:
          result = 'admin/lib/text_marker.php?param=pre&text=' + data.precipitation;
          break;

        default:
          throw new Error( 'Tipo de marcador desconocido: ' + type);
          break;
      }

      return result;
    },

    getMarkerSubtype: function( data, type)
    {
      var result = null;

      switch (type)
      {
        case this.SIMPLE_MARKER:
          result = 'weather';
          break;

        case this.TEMP_MARKER:
          result = 'temp';
          break;

        case this.WIND_MARKER:
          result = 'wind';
          break;

        case this.SNOW_MARKER:
          result = 'snow';
          break;

        case this.PRECIPITATION_MARKER:
          result = 'precipitation';
          break;

        default:
          throw new Error( 'Tipo de marcador desconocido: ' + type);
          break;
      }

      return result;
    },

    getMarkerHtml: function( type)
    {
      var result = '<b>{name}</b><br/>{date}<br/><b>Temp:</b>{temp} C<br/><b>Wind:</b>({wind_km} km/h)<br/>'
          + '<b>Visibility:</b>{visibility}<br/><b>Pressure:</b>{pressure}<br/><b>Snow:</b>{snow}<b>Precipitation:</b>'
          + '{precipitation}<br/><div align="right">';

      switch (type)
      {
        case this.SIMPLE_MARKER:
          result += '<a class="linkinfo"';
          break;

        case this.TEMP_MARKER:
        case this.WIND_MARKER:
        case this.SNOW_MARKER:
        case this.PRECIPITATION_MARKER:
          result += '<a rev="width: 900px; height: 450px; scrolling: yes; top:100px;" rel="lyteframe" class="link7"';
          break;

        default:
          throw new Error( 'Tipo de marcador desconocido: ' + type);
          break;
      }

      result += ' href="{link}">Station link</a></div>';

      return result;
    },

    createMarker: function( data, type)
    {
      var image = this.getMarkerIcon( data, type);
      var result = new GMarker({
        map: this.map,
        position: data.position,
        icon: new GMarkerImage( image, new google.maps.Size( 90, 32))
      });

      result.mytype = data.type;
      result.mysubtype = this.getMarkerSubtype( data, type);

      var html = Utils.format( this.getMarkerHtml( type), data);

      var infoWindow = new GInfoWindow({
        map: this.map,
        position: data.position,
        content: html,
        anchor: result
      });

      GEvent.addListener( result, 'click', function()
      {
        infoWindow.open( this.map, result);
      });

      this.gmarkers.push( result);

      switch (type)
      {
        case this.TEMP_MARKER:
          this.gmarkersTemp.push( result);
          break;

        case this.WIND_MARKER:
          this.gmarkersWind.push( result);
          break;

        case this.SNOWMARKER:
          this.gmarkersSnow.push( result);
          break;

        case this.PRECIPITATION_MARKER:
          this.gmarkersPre.push( result);
          break;
      }

      return result;
    },

    showMarkers: function( type, subtype)
    {
      for (var i = 0; i < this.gmarkers.length; i++)
      {
        var marker = this.gmarkers[i];

        if ((type == 3 || marker.mytype == type) && marker.mysubtype == subtype)
        {
          marker.setVisible( true);
        }
        else
        {
          marker.setVisible( false);
        }
      }
    }
  };
}
else
{
  GMapConfig = {
    init: function(){},
    showMarker: function(){},
    showMarkers: function(){},
    boxClick: function(){}
  };
}
