google.load("maps", "3",{'other_params':'sensor=false'});

var mapSubPageDisplay = {
	init:  function( options ){  
   		 
		var latLng = new google.maps.LatLng(options.latitude,options.longitude);

	    var mapOptions = {
    	    zoom: parseInt( options.zoom ),
        	center:  latLng,
	        mapTypeId: google.maps.MapTypeId.ROADMAP
    	}

		//Show the Map
		//this.data('googleMap', new google.maps.Map( document.getElementById( this.attr('id')), mapOptions ) );
		var map = new google.maps.Map( document.getElementById( this.attr('id')), mapOptions );
		this.data('googleMap', map );
	
		// Add the loading text
		var div = $('<div id="mapControlLoading" class="mapLoading">Loading Points</div>');
		$(this).data("googleMap").controls[google.maps.ControlPosition.TOP_CENTER].push(div.get(0));
		
		//Add teh reload code
		this.mapSubPageDisplayPlugin('showReload');

		//Until the view port is fully loaded we can not get the bounds to 
		//find the marker points, so we must wait.
		var parent = this;	
		google.maps.event.addListenerOnce( map, 'tilesloaded', function(){
			// Select appropriate tab after load
			if ( tabText = getQueryStringParameter('tab') ){
    	   	options = 	$( ".tab:contains('"+ tabText +"')").click().data();
	   		 }

			$(parent).mapSubPageDisplayPlugin('showPoints',options);
			$("#mapControlLoading").hide();
		
		});


		var infoWindow = new google.maps.InfoWindow( {content: ""} );
		this.data('infoWindow', infoWindow );
		this.data('markersSaved', new Array() );

	
	},
	getMapBusinessIcons: function(marker){
			var data = $(marker).data();
			var div = $("<div class='mapBusinessIcons'></div>");

			if ( typeof(data.urlWebsite) != 'undefined' ){
				var url = $("<a />").append( 
				$("<img />").attr('height','20').attr('align','middle').attr('width','75').attr('src','http://g3.worldweb.com/button-map-web.gif')
				);
				$(url).attr('href', data.urlWebsite);
				$(url).attr('target', '_blank');
				$(div).append(url);
				$(div).append( document.createTextNode("  ") ) ;
			}

			if ( typeof(data.urlBookNow) !== 'undefined' ){
				var url = $("<a />").append( 
				$("<img />").attr('height','20').attr('align','middle').attr('width','50').attr('src','http://g3.worldweb.com/button-map-book.gif')
				);
				$(url).attr('href', data.urlBookNow);
				$(url).attr('target', '_blank');
				$(div).append(url);
				$(div).append( document.createTextNode("  ") ) ;
			}
					
			var a2 = $("<a class='mapBusinessSave' />").append( $("<img />").attr('height','20').attr('align','middle').attr('width','50').attr('src','http://g3.worldweb.com/button-map-save.gif') );
			$(div).append(a2);

		return div;
	},


	setBusinessList: function(){
		var parent = this;


		$("#businessList").html( "" );	

		var olElement = $("<ol></ol>");
		$("#businessList").append( olElement );
		var listItems = new Array();
		$.each( this.data('markers'), function( index, value){
			var elm = $("<li><span class='mapBusiness'>" + value.title + "</span></li>");
			$(elm).find(".mapBusiness").data('index', index);

			// Get the look of the marker icons
			var div = $(this).mapSubPageDisplayPlugin('getMapBusinessIcons', value);

			// Add them to the display
			$(elm).append(div);
			$(olElement).append( elm );
		});


		//Sort the Map Points		
		parent.mapSubPageDisplayPlugin('sortBusinessList');	



		// Each Business added to the businesslist will use the 
		// mapBusiness class. 
		$(".mapBusiness").click( function(e) {
			google.maps.event.trigger( $(parent).data('markers')[$(this).data('index')], 'mouseover' );
		});
		
		// Add the ability to save the point
		$(".mapBusinessSave").click( function(e) {
			var markerToSave = $(parent).data('markers')[$(this).closest('li').find('.mapBusiness').data('index')];
			var markers = $(parent).data('markersSaved');
			markers.push( markerToSave );
			$(parent).data('markersSaved', markers);
			$(this).hide();
			$(parent).mapSubPageDisplayPlugin('showPointsSaved');
		});



		if ( this.data('markers').length == 0 ){
			$("#businessList").html( $("<h3>No Points Found</h3>") );	
		}


	},
	
	sortBusinessList: function(){
		var parent = this;

		if ($("#mapSort input:checked").val() == 'sortMember' ){
			$("#businessList li").sort( function(a,b){

				var dataA = $(parent).data('markers')[ $(a).find(".mapBusiness").data("index") ];
				var dataB = $(parent).data('markers')[ $(b).find(".mapBusiness").data("index") ];

				return parseInt( $(dataB).data('priority') ) -  parseInt( $(dataA).data('priority') );
			}).appendTo( $("#businessList ol")  );
		}else{
			$("#businessList li").sort( function(a,b){

				var dataA = $(a).find(".mapBusiness").data("index");
				var dataB = $(b).find(".mapBusiness").data("index");

				return parseInt( dataA ) -  parseInt( dataB );
			}).appendTo( $("#businessList ol")  );
		}
	},


	setMarkers: function(options){		
		var thisMap = this.data("googleMap");	
		var parent = this;

		$("#mapControlLoading").text("Loading Points for " + options.text ).show();

		var swBounds = this.data("googleMap").getBounds().getSouthWest();
		var neBounds = thisMap.getBounds().getNorthEast();
		
		var port = window.location.href.indexOf("8001") > 0 ? ":8001" : '';

		var url= "http://services.worldweb.com"+port+"/record-json.html?mode=jsonMapPoints" + 
			 "&neLng=" + neBounds.lng() +
			 "&neLat=" + neBounds.lat() +
			 "&swLng=" + swBounds.lng() +
			 "&swLat=" + swBounds.lat() + 
			 "&catLevel=" + options['catLevel'] + 
			 "&catID=" + options['catID'] + 
			 "&swLat=" + swBounds.lat() ; 

		url += "&jsoncallback=?";

		$.getJSON( url ,	function(json){ 
			var markers = new Array();
			$.each(json.records, function(index, value){
				var latLng = new google.maps.LatLng( value.map_latitude, value.map_longitude);
				var map = parent.data('googleMap');

				// Create a marker but don't put it on the map
				var marker = new google.maps.Marker({
					position: latLng,
					title: value.title,
					map: map
				});

				// Move all the key, value pairs to the marker
				$(marker).data(value);
	
				// Add a marker listener for a click to show the infoWindow
				google.maps.event.addListener(marker,'mouseover', function(){
					var data = $(marker).data();
					
					var div = $("<div class='mmap-box'>"+data.title+"</div>");
					if (typeof(data.urlSubPage) != 'undefined'){
						div = $("<div class='mmap-box'><a class='t-11b' href='"+data.urlSubPage+"'>"+data.title+"</a></div>");
					}



					$(div).append( $(parent).mapSubPageDisplayPlugin('getMapBusinessIcons', marker) );
					if ( 'reviewRating' in marker ){
						$(div).append( $("<div>" + data.reviewRating+"</div>"));
					}
					$(div).append( $("<div>" + data.address+"</div>"));
					if ( $(".mapBusiness").parent(':eq('+index+')').find('.mapBusinessSave:hidden').length > 0 ){
						$(div).find(".mapBusinessSave").hide();
					}
		
		
					// Add the ability to save the point
					$(div).find(" .mapBusinessSave").click( function(e) {
							var markerToSave = marker;
							var markers = $(parent).data('markersSaved');
							markers.push( markerToSave );
							$(parent).data('markersSaved', markers);
							$(this).hide();
							$(parent).mapSubPageDisplayPlugin('showPointsSaved');
							$(".mapBusiness").parent(':eq('+index+')').find('.mapBusinessSave').hide();

					});
									    
					$(parent).data('infoWindow').setContent( div.get(0) );
					
					$(parent).data('infoWindow').open( $(parent).data('googleMap'), marker );
				});
				

				// Add the marker onto the stack
				markers.push( marker );
			});

			// If there are no points then show the infoWindow and give feeback
			if( markers.length == 0 ){
				$("#mapControlLoading").text("No Points for " + options.text ).show();
			}else{
				$("#mapControlLoading").hide();
			}

			// Store the markers on the map element
			parent.data("markers", markers );
			//Show the Business List
			parent.mapSubPageDisplayPlugin('setBusinessList');	
		});
		
	},
	
	showPoints: function(options){
		if ( this.data('markers') ){
			this.mapSubPageDisplayPlugin('removePoints', this.data('markers'));
		}

		//Set the default for hotels & motels category
		function defaults() {
			return {
				'catLevel': 0,
				'catID': 17,
				'pointsLoaded': 0,
				'text': 'Hotels',

			};
		};
		options = jQuery.extend(defaults(), options);

		
		this.mapSubPageDisplayPlugin('setMarkers',options);
		this.mapSubPageDisplayPlugin('showPointsSaved');

	},
	
	showPointsSaved: function(){
		var parent = this;
		if ( this.data('markersSaved') ){
			this.mapSubPageDisplayPlugin("removePoints", this.data("markersSaved"));
		}

		var olElement = $("<ol></ol>");
		$("#businessListSaved").html( olElement.get(0) );
		$.each( this.data('markersSaved') , function(index,value){
			var elm = $("<li><span class='mapBusiness'>" + value.title + "</span></li>");
			$(elm).find(".mapBusiness").data('index', index);

			var div = $("<div class='mapBusinessIcons'></div>");
			if ( value.urlWebsite !== undefined ){
				var url = $("<a />").append( 
				$("<img />").attr('height','20').attr('align','middle').attr('width','75').attr('src','http://g3.worldweb.com/button-map-web.gif')
				);
				$(url).attr('href', value.urlWebsite);
				$(url).attr('target', '_blank');
				$(div).append(url);
				$(div).append( document.createTextNode("  ") ) ;
			}

			if ( value.urlBookNow !== undefined ){
				var url = $("<a />").append( 
				$("<img />").attr('height','20').attr('align','middle').attr('width','50').attr('src','http://g3.worldweb.com/button-map-book.gif')
				);
				$(url).attr('href', value.urlBookNow);
				$(url).attr('target', '_blank');
				$(div).append(url);
				$(div).append( document.createTextNode("  ") ) ;
			}
					
			var a2 = $("<a class='mapBusinessSaveRemove' />").append( $("<img />").attr('height','20').attr('align','middle').attr('width','50').attr('src','http://g3.worldweb.com/button-map-delete.gif') );
			$(div).append(a2);

			$(elm).append(div);

			$(olElement).append( elm );
			value.setMap( parent.data("googleMap") );
		
			// Each Business added to the businesslist will use the 
			// mapBusiness class. 
			$("#businessListSaved .mapBusiness").click( function(e) {
				google.maps.event.trigger( $(parent).data('markersSaved')[$(this).data('index')], 'mouseover' );
			});
		
		
			// Add the ability to save the point
			$(".mapBusinessSaveRemove").click( function(e) {
				var markerToSave = $(parent).data('markersSaved')[$(this).closest('li').find('.mapBusiness').data('index')];
				if (markerToSave){
					markerToSave.setMap(null);
		
					// Find any markers shown with the same Title and add show the "save" button aga
					$.each( $("#businessList li"), function( index, element){
						var dataElement = $(element).find(".mapBusiness");
						if ( $(dataElement).text() == markerToSave.title ){
							$(element).find("a").show();

							var marker = $(parent).data('markers')[ $(dataElement).data("index") ];
							marker.setMap( $(parent).data("googleMap")  );
						}
					});

			
				// Remove the element from teh saved markers
				var removeIndex =  $(this).closest('li').find('.mapBusiness').data('index');
				$(parent).data('markersSaved').splice(removeIndex,1 );
				$(parent).mapSubPageDisplayPlugin('showPointsSaved');
				}
			
				

			});
		});	

	},
	showReload: function(){
		var parent = this;

		// Add the page reload to each category tab
		$.each( $(".tab"), function (index, value){
			if ($(value).data('catID')){
				$(value).click( function(event){
					var options = new Object();
					options.catLevel =  $(value).data('catLevel');
					options.catID =  $(value).data('catID');
					options.text =  $(value).text();
					
					parent.mapSubPageDisplayPlugin('showPoints',options);
					$(".mapReload").data( 'options', options );
					$(".mapReload").hide();

					// Change the text above the subheader
					$("#categorySelected").text( $(value).text() );
				});
			}
		});

		 var div = $('<div id="mapControl" class="mapReload hideBlock">Reload Map Points</div>');
		 $(this).data("googleMap").controls[google.maps.ControlPosition.TOP_RIGHT].push(div.get(0));

		$(div).click( function(event){
			parent.mapSubPageDisplayPlugin('showPoints', $(this).data('options') );
			$(this).hide();
		});
			
		google.maps.event.addListener( $(this).data("googleMap"), 'bounds_changed', function(){
			if ( $(div).data('show') == 1  ){
				$(div).show();
			}else{
				$(div).data('show',1);
			}
		});
	

	},

	// To remove points we have to remove each marker one by one.
	removePoints: function(markers){
		$.each( markers, function(index,value){
				value.setMap(null);
		});	
	}



}

jQuery.fn.sort = function() {
        return this.pushStack( jQuery.makeArray( [].sort.apply( this, arguments ) ) );
}; 
	
$.fn.mapSubPageDisplayPlugin = function( method ) {

    // Method calling logic
    if ( mapSubPageDisplay[method] ) {
      return mapSubPageDisplay[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return mapSubPageDisplay.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.wwtjmap' );
    }    
  
};


