/*

  Copyright (c) 2009 August Lilleaas, http://august.lilleaas.net

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  

*/

/**
 * 19/08/2009 - Modificado por Intermark Tecnologías 
 *
 * Crea un mapa de google no intrusivo a partir de la imagen estática del mapa.
 * Se ha modificado este plugin para que admita una serie de propiedades que permiten
 * definir el icono y sombra a utilizar y los datos a mostrar en el bocadillo.
 *
 * @example	$('.google_map').unobtrusiveGoogleMaps();
 * @desc Ejemplo de uso básico
 *
 * @example	$('.google_map').unobtrusiveGoogleMaps({icon: 'images/icono.gif', shadow: 'images/sombra.gif', iconSize: [20, 32], shadowSize: [20, 32], iconAnchor: [0, 32]});
 * @desc Ejemplo de uso con propiedades:
 *
 * @param Object settings Objeto conteniendo pares clave/valor para proporcionar propiedades opcionales.
 * @option String icon Ruta completa de la imagen con el icono a utilizar. Por defecto null.
 * @option String shadow Ruta completa de la imagen con la sombra del icono a utilizar. Por defecto null.
 * @option Array iconSize Array de 2 dimensiones conteniendo el ancho, alto del icono. Por defecto [0,0].
 * @option Array shadowSize Array de 2 dimensiones conteniendo el ancho, alto de la sombra. Por defecto [0,0].
 * @option Array iconAnchor Array de 2 dimensiones conteniendo la posición x,y usada como anclaje del icono. Por defecto [0,0].
 * @option String pathInfoHtml xPath donde se encuentra la información que hay que mostrar en el bocadillo del icono. Por defecto null.
 * 
 * @type jQuery
 * 
 */
 
(function($){ 
  // Handles the loading of the Google Maps scripts
  var GoogleMapsScripts = {
    whenLoaded: function(callback){
      if (this.isLoaded) {
        callback.call()
      } else {
        // Without the callback, we get a nasty document.write which we don't want. Pick
        // any global function. parseInt works.
       	$.getScript("http://maps.google.com/maps/api/js?sensor=false&callback=parseInt");
        this.monitorScriptLoading(callback)
      }
    },
    
    // The reason that the google maps callback isn't used is that we want to persist our
    // own local callback from the UnobtrusiveGoogleMap instance.
    monitorScriptLoading: function(callback){
      if (window["google"] && window["google"]["maps"] && window["google"]["maps"]["LatLng"]) {
        this.isLoaded = true;
        callback();
      } else {
        setTimeout(function() { GoogleMapsScripts.monitorScriptLoading(callback) }, 100)
      }
    }
  }
  
  var UnobtrusiveGoogleMap = function(targetElement, settings){
    var self = this;
    
    this.targetElement = $(targetElement);
    this.targetElement.ready(function(){
      self.loadInteractiveMap(settings);     
      return false;
    });
   
  } 
    
  UnobtrusiveGoogleMap.prototype = {
    loadInteractiveMap: function(settings){
      var self = this;
      
      this.options = this.getOptionsFromQueryParameters(settings);
      GoogleMapsScripts.whenLoaded(function(){
        self.loadMap();
      })
    },
    
    getOptionsFromQueryParameters: function(settings){
      var src = this.targetElement.attr("src");
      settings = $.extend({
      	pathInfoHtml: null,
      	icon: null,
      	shadow: null,
      	iconSize: [0,0],
      	shadowSize: [0,0],
      	iconAnchor: [0,0]
      }, settings || {});
      var options = settings;
      var queryParameters = {};
      $.each(/\?(.+)/.exec(src)[1].split("&"), function(i, x) {
        var r = x.split("="); queryParameters[r[0]] = r[1];
      });
      
      options.zoom = parseInt(queryParameters["zoom"]);

      var sizes = queryParameters["size"].split("x");
      options.width = parseInt(sizes[0]);
      options.height = parseInt(sizes[1]);

      var latLong = queryParameters["center"].split(",");
      options.latitude = parseFloat(latLong[0]);
      options.longitude = parseFloat(latLong[1]);      
      
      return options;
    },
    
    loadMap: function(){
      var newTarget = $(document.createElement("div"));
      newTarget.css({width: this.options.width, height: this.options.height});
      this.targetElement.replaceWith(newTarget)
      
      var point = new google.maps.LatLng(this.options.latitude, this.options.longitude);
      var map = new google.maps.Map(newTarget[0], {
        zoom: this.options.zoom, center: point,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false
      });
      //Si tiene icono y/o sombra se crea el marcador con esa imagen
      var marker;
      if (this.options.icon) {      	
      	var imageIcon = new google.maps.MarkerImage(this.options.icon,
										      	new google.maps.Size(parseInt(this.options.iconSize[0]), parseInt(this.options.iconSize[1])),
										      	new google.maps.Point(0, 0),
										      	new google.maps.Point(parseInt(this.options.iconAnchor[0]), parseInt(this.options.iconAnchor[1])));
      	if (this.options.shadow) {      	
	      	var imageShadow = new google.maps.MarkerImage(this.options.shadow,
											      	new google.maps.Size(parseInt(this.options.shadowSize[0]), parseInt(this.options.shadowSize[1])),
											      	new google.maps.Point(0, 0),
											      	new google.maps.Point(parseInt(this.options.iconAnchor[0]), parseInt(this.options.iconAnchor[1])));
      		marker = new google.maps.Marker({position: point, map: map, icon: imageIcon, shadow: imageShadow });
		} else {
      		marker = new google.maps.Marker({position: point, map: map, icon: imageIcon });
      	}
      } else {
      	marker = new google.maps.Marker({position: point, map: map});
      }
      //Se obtiene la información para el globo de texto
      if (this.options.pathInfoHtml) {  
		  var contentString = "";	
		  $(this.options.pathInfoHtml).find("a").attr("target","_blank");
		  $(this.options.pathInfoHtml).find("a").attr("title", textoTitleVentanaNueva);   
		  $(this.options.pathInfoHtml).each(function() {
	         contentString += $(this).html().replace('mensaje', '') + "<br/>";
		  });
		  if (contentString != "") {
			  var infowindow = new google.maps.InfoWindow({
			  		content: contentString
			  });
			  google.maps.event.addListener(marker, 'click', function() {
			  		infowindow.open(map,marker);
			  });
		  }
	   }
    }
  }
  
  // Hooks the click event that loads a interactive map. The element(s)
  // you are refering to has to be the actual <img /> tags.
  // $("img.google_map").unobtrusiveGoogleMap();
  $.fn.unobtrusiveGoogleMaps = function(settings) {  	  
  	this.each(function(i, element) { new UnobtrusiveGoogleMap(element, settings) });
  }
})(jQuery);
