/*

Plugin name: UGMOCustomInfoWindow
For Ugmo version: 3.0

Description:
With this plugin you can create a custom info window

When this plugin is loaded, the normal infoWindow from Google is bypassed and a custom one is used.
This plugin attaches a div to the map at the right location on the map.

When no options are given. The html retrieved from the marker will be used as div.

If you want to generate the div yourself you can create a function for this and attach it to UGMOCustomInfoWindow.settings.generateInfoWindowFunction

example

var yourMap = new UGMO("yourMapDiv");

yourMap.UGMOCustomInfoWindow.settings.generateInfoWindowFunction = function(data){
    //generate you div
    var div = document.createElement("DIV");
    
    return div;
};

*/

(function(undefined){

//extension of UGMOMarker
if(typeof UGMOMarker !== "undefined"){
    
    //define a namespace for this plugin
    var UGMOCustomInfoWindow = {};
    
    //define settings
    UGMOCustomInfoWindow.settings = {
        //function to generate the infoWindow
        generateInfoWindowFunction: null,
		infoWindowCreated: function(infoWindowDiv){},
		handlePosition:'TOP_LEFT',
		panToFitWindow:true
    };
    
    //store the old showMarkerInfo
    UGMOCustomInfoWindow.oldShowMarkerInfo = UGMOMarker.fn.showMarkerInfo;
    
    //Define a new showMarkerInfo to attach controls to the shown infoWindow
    UGMOMarker.fn.showMarkerInfo = function(data){
		
        var marker_ = this;
		
		var markerIconWidth = (this.marker.icon && this.marker.icon.size) ? this.marker.icon.size.width : 0;
		var markerIconHeight = (this.marker.icon && this.marker.icon.size) ? this.marker.icon.size.height : 0;
		
        //define infoWindow options, difference is we also send data
        var infoWindowOptions = {
            marker: marker_,
			content: data.markerInfo.html,
			position: this.markerLatLon,
			iconSize: {width:markerIconWidth, height:markerIconHeight }
		};
		
		//if there already is an info window active, close it
		if(this.ugmo_.activeInfowindow !== null){
			this.ugmo_.activeInfowindow.close();
		}
		
		//don't use the google info window but our own
		this.infoWindow = this.ugmo_.activeInfowindow = new UGMOCustomInfoWindow.InfoWindow(infoWindowOptions);
		
		// check if we're in street view
		if(this.ugmo_.sv === null){
            this.ugmo_.sv = this.ugmo_.map.getStreetView();
        }
		
		//open the info window
		if(this.ugmo_.sv.getVisible()){
			this.infoWindow.open(this.ugmo_.sv);
		}else{
			this.infoWindow.open(this.ugmo_.map);
		}
		
    };
    
    /*
    We define our own infoWindow object
    */
    UGMOCustomInfoWindow.InfoWindow = function(infoWindowOptions){
        var infoWindow_ = this;
        
        //Figure out which div to use
        if(UGMOCustomInfoWindow.settings.generateInfoWindowFunction){
            var div = UGMOCustomInfoWindow.settings.generateInfoWindowFunction(infoWindowOptions.marker);
            if(!div || !div.nodeType){
                throw("Returned div is not a node in UGMOCustomInfoWindow!");
            }
        }else{
            if(typeof infoWindowOptions.content === "object"){
                var div = infoWindowOptions.content;
            }else{
                var div = document.createElement("DIV");
                div.innerHTML = infoWindowOptions.content;
            }
        }
        
        //make sure clicks don't propagate down to the map
        $(div).click(function(event){
          event.stopPropagation();
        });
		
		$(div).bind('mouseenter mouseleave mouseover mousemove', function(event){
          event.stopPropagation();
        });  
        
        $(div).mousedown(function(event){
          event.stopPropagation();
        });  
        
        // Now initialize all properties.
        this.position_ = infoWindowOptions.position;
        this.div_ = div;
		this.iconSize = infoWindowOptions.iconSize;
		
    };
   
    UGMOCustomInfoWindow.InfoWindow.prototype = new google.maps.OverlayView();
    
    UGMOCustomInfoWindow.InfoWindow.prototype.open = function(map){
        if(UGMOCustomInfoWindow.settings.closeInfoWindow){
            UGMOCustomInfoWindow.settings.closeInfoWindow();
        }
        this.setMap(map);
    };
	
	
    
    UGMOCustomInfoWindow.InfoWindow.prototype.close = function(){
        this.setMap(null);
    };
    
    UGMOCustomInfoWindow.InfoWindow.prototype.onAdd = function() {
          // Note: an overlay's receipt of onAdd() indicates that
          // the map's panes are now available for attaching
          // the overlay to the map via the DOM.

          // We add an overlay to a map via one of the map's panes.
          // We'll add this overlay to the overlayImage pane.
          var panes = this.getPanes();
          panes.floatPane.appendChild(this.div_);
		  UGMOCustomInfoWindow.settings.infoWindowCreated(this.div_);
    };  
    
    UGMOCustomInfoWindow.InfoWindow.prototype.draw = function() {
          // Size and position the overlay. We use a southwest and northeast
          // position of the overlay to peg it to the correct position and size.
          // We need to retrieve the projection from this overlay to do this.
     	  var overlayProjection = this.getProjection();
        
          // Retrieve the southwest and northeast coordinates of this overlay
          // in latlngs and convert them to pixels coordinates.
          // We'll use these coordinates to resize the DIV.
          var pos = overlayProjection.fromLatLngToDivPixel(this.position_);
        
          // Resize the image's DIV to fit the indicated dimensions.
          var div = this.div_;
		  var infoWinHeight = $(div).height();
          var infoWinWidth = $(div).width();
		  var offsetX, offsetY;
		  
		  // TODO: add other positons, and take iconAnchor into account!!!
		  switch(UGMOCustomInfoWindow.settings.handlePosition){
			case 'BOTTOM_CENTER':
				offsetX = (infoWinWidth / 2);
				offsetY = infoWinHeight + this.iconSize.height;
				break;
			case 'BOTTOM_LEFT':
				offsetX = 0;
				offsetY = infoWinHeight + this.iconSize.height;
				break;
			case 'BOTTOM_RIGHT':
				offsetX = infoWinWidth;
				offsetY = infoWinHeight + this.iconSize.height;
				break;
			case 'TOP_LEFT':
			  	offsetX = 0;
				offsetY = 0;
			  	break;
			
			default:
				throw('handlePosition \'' + UGMOCustomInfoWindow.settings.handlePosition + '\' not recognized!');
		  }
		  
		  div.style.left = pos.x - offsetX + 'px';
          div.style.top = pos.y - offsetY + 'px';
          div.parentNode.style.zIndex = 10000;
		  div.style.position = 'absolute';
		  div.className = 'infoWindow';
		  
		  
		  // if window doesn't fit within current viewport, scroll to make it fit, but only the first time
		  if(UGMOCustomInfoWindow.settings.panToFitWindow && !this.firstDrawExecuted){
			  var iwLeftBottomPix = new google.maps.Point(pos.x - offsetX, (pos.y - offsetY) + infoWinHeight);
			  var iwRightTopPix = new google.maps.Point((pos.x - offsetX) + infoWinWidth, pos.y - offsetY);
			  
			  var projection = this.getProjection();
			  
			  var iwLeftBottomLatLng = projection.fromDivPixelToLatLng(iwLeftBottomPix);
			  var iwRightTopLatLng = projection.fromDivPixelToLatLng(iwRightTopPix);
			  
			  var bounds = new google.maps.LatLngBounds();
			  bounds.extend(iwRightTopLatLng);
			  bounds.extend(iwLeftBottomLatLng);
				
			  // remove event handler
			  var originalBounds = this.map.getBounds();
				
			  if(!originalBounds.contains(iwRightTopLatLng) || !originalBounds.contains(iwLeftBottomLatLng)){
				  this.map.panTo(bounds.getCenter());
			  }
		  }
		  
		  this.firstDrawExecuted = true;
    };
    
    UGMOCustomInfoWindow.InfoWindow.prototype.onRemove = function() {
          this.div_.parentNode.removeChild(this.div_);
          this.div_ = null;
    };
   
    //attach this plugin to UGMO
    UGMO.fn.UGMOCustomInfoWindow = UGMOCustomInfoWindow;
}

}());
