﻿(function($){

/* MAP BEHAVIOR */
	
	Behaviors.register("Map", "div.wp-map", {
    	reqScripts:[ SCRIPTS.GoogleMaps ]
    	,maxAutoZoomLevel: 13
	    //* methods:
	    ,isCompatible: function(){return GBrowserIsCompatible && GBrowserIsCompatible();}
	    ,init: function()
	    {
	        this.$ftrDiv = this.$el.next("div.wp-map-ftr");
	        if (this.$ftrDiv.length == 0)
	            this.$ftrDiv = null;
	    }
	    ,initLayout: function()
	    {
	        // handle ftr div
		    if (this.$ftrDiv)
		    {
		        this.$ftrDiv.link = this.$ftrDiv.children("a:first");
		        // create next link that will cycle through locations
	            this.$ftrDiv.next = $("<span title='Click to see next location on map.'>Next</span>").appendTo(this.$ftrDiv);
    	    }
    	    
    	    //* handle map
    	    // initialize the Google map elements
		    this.gmap = new GMap2(this.el, {
			    mapTypes: [G_NORMAL_MAP, G_HYBRID_MAP/*, G_SATELLITE_3D_MAP*/]
		    });
		    this.gmap.setCenter(new GLatLng(37.4419, -42.1419), this.isRail ? 1 : 2);
    		
    		if (this.options)
    		{	
		        if (this.options.xmlUrl)
		        {
			        this.geoXml = new GGeoXml(this.options.xmlUrl);
			        this.gmap.addOverlay(this.geoXml);
		        }
	            else if (this.options.addresses && this.options.addresses.length > 0)
	                this.loadAddresses(this.options.addresses);
	        }
    		
		    this.controls = $H({
			     zoom: this.isRail ? new GSmallZoomControl() : new GLargeMapControl()
			    ,overviewMap: new GOverviewMapControl()
			    ,buttons: this.isRail ? null : new GMapTypeControl()
		    })
    		
    		this.addControls(this.controls);
	        
	        if (this.isRail)
	            // this.controls.overviewMap.hide();
	            //  setTimeout (function(){this.controls.overviewMap.hide(true);}, 4000);
		    /*	setTimeout (function(){
					if (this.controls.overviewMap != null)
					{
					this.controls.overviewMap.hide(true);
					}
						}, 6000); */
			var xyz = 0;

   	    
   	    	this.hideTextOverrun();
		    /*this.gmap.getEarthInstance(function(object)
		    {
			    this.geInstance = object;
			    
    			
		    }.bind(this)); */   	        
	    }
	    ,initEvents: function()
	    {
	        if (this.$ftrDiv)
		        this.$ftrDiv.next.click(function()
		        {
			        if (++this.currentMarkerNdx == this.addressMarkers.length)
				        this.currentMarkerNdx = 0;
        				
			        this.centerOnCurrentMarker();
        			
		        }.bind(this));
		        
		    // these controls will be removed when in 3d mode since their layout doesnt cooperate very well in that mode.
		    var unfriendly3dControls = [
                this.controls.overviewMap
                ,this.controls.zoom
            ]
		    
		    GEvent.addListener(this.gmap, "maptypechanged", function(){
	            if (this.gmap.getCurrentMapType().getName() == "Earth")
	                this.removeControls(unfriendly3dControls);
	            else
                    this.addControls(unfriendly3dControls);   
	        }.bind(this));
	    }
	    ,centerOnCurrentMarker: function()
	    {
		    if (this.addressMarkers && this.addressMarkers.length > 0)
			    this.gmap.setCenter(new GLatLng(this.addressMarkers[this.currentMarkerNdx].point.coordinates[1], this.addressMarkers[this.currentMarkerNdx].point.coordinates[0]), this.maxAutoZoomLevel);
	    }
	    ,addControls: function(collection)
	    {
	        collection.each(function(c){
	        	
	            if (c && !c.isAdded)
	            {    
	                this.gmap.addControl(c);
	                c.isAdded = true;
	            }
	        }.bind(this));
	    }
	    ,removeControls: function(collection)
	    {
	        collection.each(function(c){ 
	            this.gmap.removeControl(c);
	            c.isAdded = false;
	        }, this);
	    }
	    ,clearMarkers: function()
	    {
	        this.gmap.clearOverlays();
	        this.addressMarkers = [];
	    }
	    ,loadAddresses: function(addresses, clear, cb)
	    {
	        if (clear)
	            this.clearMarkers();
	            
			this.asyncCount = 0;
			this.asyncCb = cb;	        
	            
            this.theAddresses = [];
	        for(var i=0;i<addresses.length;i++)
	        {
	        	
		        	this.asyncCount++;
		        	this.theAddresses.push(addresses[i]);
	        	
	        	
	        }

			this.geoDelay = 0;
			this.nextAddress = 0;
            this.getNext(this);
	    }
	    
	    ,getNext: function(owner) {
		    if (owner.nextAddress < owner.theAddresses.length) {
		          setTimeout(function() { owner.setAddressPoint(owner.theAddresses[owner.nextAddress], owner.getNext, owner); }, owner.geoDelay);
	        } 
	    }
	    ,setAddressPoint: function(address, next, owner)
	    {
		    // if the param is a string then convert it JSON format
		    if (Object.isString(address))
			    address = {location: address};
    		
		    if (!owner.geoCoder)
			    owner.geoCoder = new GClientGeocoder();

		    owner.geoCoder.getLocations(address.location, function(response)
		    {

			    if (response.Status.code == "200") {

					var point = response.Placemark[0].Point;
					//debugger;
			    	if (point != null) {
				    	owner.asyncCount--;
				    	
						// Create red flag icon
						var redFlag = new GIcon(G_DEFAULT_ICON);
						redFlag.image = "/Style%20Library/Images/Parsons/map-flag.png";
						redFlag.printImage = "/Style%20Library/Images/Parsons/map-flap.gif";
						redFlag.mozPrintImage = "/Style%20Library/Images/Parsons/map-flag.gif";
						//redFlag.transparent = "/Style%20Library/Images/Parsons/map-flag-transparent.png";
						redFlag.printShadow = "";
						//redFlag.iconSize = new GSize(10, 12);
						redFlag.iconSize = new GSize(13, 15);
						redFlag.shadow = "";
						redFlag.iconAnchor = new GPoint(0,13);
					    var marker = new GMarker(new GLatLng(point.coordinates[1], point.coordinates[0]), {
						    title: address.title || address.location
						    ,icon:redFlag
					    });
					    marker.data = address;
					    marker.point = point;

					    if (address.html)
					        marker.bindInfoWindowHtml(address.html);
					    else if (address.el)
					        marker.bindInfoWindow(address.el);

					    // if a link was provided with the address then make the marker clickable
					    if (address.href)
					    {
						    GEvent.addListener(marker, "click", function(){
							    window.location.href = marker.data.href;
						    });
					    }

					    // create the markers collection if it hasnt already been created
					    if (!owner.addressMarkers)
						    owner.addressMarkers = [];
		    				
					    // push the marker to the collection
					    owner.addressMarkers.push(marker);

					    // if the first point pushed then center around it
					    if (owner.addressMarkers.length == 1 && owner.isRail)
					    {
						    owner.currentMarkerNdx = 0;
						    owner.centerOnCurrentMarker();
					    }
					    // otherwise show the next button since there are multiple items on the map
					    else if (owner.$ftrDiv)
						    owner.$ftrDiv.next.show();	


					    // add the marker to the actual map
					    owner.gmap.addOverlay(marker);
					    if (!owner.isRail) {
				            var bounds = new GLatLngBounds();
					        owner.getAddressPoints().each(function(p){
					            bounds.extend(new GLatLng(p.coordinates[1], p.coordinates[0]));
					        }); 
					        var zoom = owner.gmap.getBoundsZoomLevel(bounds);
					        owner.gmap.setCenter(bounds.getCenter(), zoom > owner.maxAutoZoomLevel ? owner.maxAutoZoomLevel : zoom);
				        }
				             
						if (owner.asyncCount == 0 && owner.asyncCb)
							owner.asyncCb();


	    			}
    			}
    			else {
					if (response.Status.code == "620") {
						owner.geoDelay += 50;
						owner.nextAddress--;
					}
				}
                owner.nextAddress++;
				owner.getNext(owner);
		    }.bind(owner));
    		
	    }
	    ,centerAllMarkers: function(points)
	    {
	        var bounds = new GLatLngBounds();
	        (points || this.getAddressPoints()).each(function(p){
	            bounds.extend(p);
	        }); 
	        var zoom = this.gmap.getBoundsZoomLevel(bounds);
	        this.gmap.setCenter(bounds.getCenter(), zoom > this.maxAutoZoomLevel ? this.maxAutoZoomLevel : zoom);
	    }
	    ,getAddressPoints: function()
	    {
	        return this.addressMarkers.collect(function(m){
	            return m.point;
	        });
	    }
	    ,hideTextOverrun: function()
	    {
	        if (this.isRail)
		        $("div.gmnoprint span:first").hide();
	    }
    });
    
    Behaviors.Map.LINK_DIRECTIONS = "http://maps.google.com/maps?daddr={0}&hl=en&saddr=";


})(jQuery);