//the following functions listen for navigation tab clicks and load the appopriate section via AJAX

$(document).ready(function(){
		
function mapplication() {
	/////////// Initialize Map and set variables that control toggles , settings //////////////////////////////////////////

		var map = new google.maps.Map2(document.getElementById('map'));
		map.setMapType(G_NORMAL_MAP);
	    map.addControl(new google.maps.SmallZoomControl3D());
		var location = new google.maps.LatLng(52.451087,-1.715466);
		directionsPanel = document.getElementById("routetext");
		var directions = new google.maps.Directions(map);
		
		var baseIcon = new google.maps.Icon();
		          baseIcon.iconSize=new google.maps.Size(28,45);
		          baseIcon.shadowSize=new google.maps.Size(56,32);
		          baseIcon.iconAnchor=new google.maps.Point(14,45);
		          baseIcon.infoWindowAnchor=new google.maps.Point(16,0);

		      var hilton = new google.maps.Icon(baseIcon, rootUrl+"images/hilton_marker.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon27s.png");
	
		map.setCenter(location,13);
		var marker = new google.maps.Marker(location,hilton );
		map.addOverlay(marker);	
		
/////////////////////////////////////////// Listening Functions ////////////////////////////////////////////////////////	
		
		//these functions waits until the user clicks into the #location search box for the first time and deletes the content
		  var default_values = {};
		  jQuery('#location').each(function(i) {
		    var index = jQuery(this).attr('name');
		    var value = jQuery(this).val();
		    default_values[index] = value;
		  });

		  jQuery('#location').focus(function() {
		    if(jQuery(this).val() === default_values[jQuery(this).attr('name')]) {
		      jQuery(this).val('');
				$('#location').css({'color':'#000000'});
		    };
		  })
		
		
		
		
		
		//this function fires when a user clicks the '#reset' reset button
		$("#reset").click(function() {
		resetmap();
		});
		
		//this function fires when a user clicks the 'find route' button
		$("#submitLocation").click(function() {
			
			if($('#location').val() == ""){
			  return;
			}else{
			  searchlocation();
			}
			
			
		
		});
		
		//this function fires when a user hits enter in the 'location' search field
		$("#location").keypress(function(e){
		                if (e.which == 13) 
		                {
		                    if($('#location').val() == ""){
							  return;
							}else{
							  searchlocation();
							}
		                };
		            });
		
		// turns any div with class printPlaceHolder and <p> element into a print button
		var a = $('<input id="print" type="submit" value="Print" name="print"/>')
		$("#print").replaceWith(a);
		
		// creates new print button objects
		var myprint = new Adoro.PrintButton(a);
		
		
		
////////////////////////////////////////// Functions for performing map actions //////////////////////////////////////////////
// this function diplays the requested route on the map	///
		function displayroute(georesult,id) {
			var p = georesult.Placemark[id].Point.coordinates;
				var origin = new google.maps.LatLng(p[1],p[0]);
			//	var directions = new google.maps.Directions(map);
				directions.load("from:"+origin+" to: Hilton Birmingham Metropole@52.451087,-1.715466",{getSteps:true});
				// ============ custom direction panel ===============
			      function customPanel(map,mapname,dirn,div) {
			        var html = "";

			        // ===== local functions =====

			        // === waypoint banner ===
			        function waypoint(point, type, address) {
			          var target = '"' +mapname+".showMapBlowup(new google.maps.LatLng("+point.toUrlValue(6)+"))"  +'"';
			          html += '<table class="waypointtable">';
			          html += '  <tr>';
			          html += '    <td class="waypoint_numbers" style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
			          html += '      <img class="pngfix" src="'+rootUrl+'/images/'+type+'_marker.png">'
			          html += '    <\/td>';
			          html += '    <td style="vertical-align: middle; width: 100%;">';
			          html +=        address;
			          html += '    <\/td>';
			          html += '  <\/tr>';
			          html += '<\/table>';
			        }

			        // === route distance ===
			        function routeDistance(dist) {
			          html += '<div style="text-align: right; padding-bottom: 0.3em;">' + dist + '<\/div>';
			        }      

			        // === step detail ===
			        function detail(point, num, description, dist) {
			          var target = '"' + mapname+".showMapBlowup(new google.maps.LatLng("+point.toUrlValue(6)+"))"  +'"';
			          html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
			          html += '  <tr>';
			          html += '    <td style="border-top: 1px solid rgb(150, 125, 90); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
			      //    html += '      <a href="javascript:void(0)"> '+num+'. <\/a>';
			          html += '<span class="step_detail_num">'+num+'</span>';
			
			          html += '    <\/td>';
			          html += '    <td style="border-top: 1px solid rgb(150, 125, 90); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
			          html +=        description;
			          html += '    <\/td>';
			          html += '    <td style="border-top: 1px solid rgb(150, 125, 90); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
			          html +=        dist;
			          html += '    <\/td>';
			          html += '  <\/tr>';
			          html += '<\/table>';
			        }

			        // === Copyright tag ===
			        function copyright(text) {
			          html += '<div style="font-size: 0.86em;">' + text + "<\/div>";
			        }


			        // === read through the GRoutes and GSteps ===

			        for (var i=0; i<dirn.getNumRoutes(); i++) {
			          if (i==0) {
			            var type="play";
			          } else {
			            var type="pause";
			          }
			          var route = dirn.getRoute(i);
			          var geocode = route.getStartGeocode();
			          var point = route.getStep(0).getLatLng();
			          // === Waypoint at the start of each GRoute
			          waypoint(point, type, geocode.address);
			          routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");

			          for (var j=0; j<route.getNumSteps(); j++) {
			            var step = route.getStep(j);
			            // === detail lines for each step ===
			            detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
			          }
			        }

			        // === the final destination waypoint ===   
			        var geocode = route.getEndGeocode();
			        var point = route.getEndLatLng();
			        waypoint(point, "stop", geocode.address);

			        // === the copyright text ===
			        copyright(dirn.getCopyrightsHtml());

			        // === drop the whole thing into the target div
					document.getElementById("routetext").innerHTML = html;
			

			      } // ============ end of customPanel function ===========

			      // ========== launch the custom Panel creator a millisecond after the GDirections finishes loading ==========
			      // == The delay is required in case we rely on GDirections to perform the initial setCenter ==
			      google.maps.Event.addListener(directions,"load", function() {
					map.removeOverlay(marker); 
					directions.getMarker(1).getIcon().image = rootUrl+'/images/hilton_marker.png';
					directions.getMarker(1).getIcon().iconSize = new google.maps.Size(28,45);
		          	directions.getMarker(1).getIcon().shadowSize=new google.maps.Size(56,32);
		          	directions.getMarker(1).getIcon().iconAnchor=new google.maps.Point(14,45);
		          	directions.getMarker(1).getIcon().infoWindowAnchor=new google.maps.Point(16,0);
			
			        customPanel(map,"map",directions,document.getElementById("routetext"));
			      });
			 
				
				
				
				
				
				
				
				
		}
		
		// this function resets the map to its initial display
		function resetmap() {
			//reset map center
			map.setCenter(location);
			//reset map zoom
			map.setZoom(13);
			//wipe any added directions
			directions.clear();
			$("#routetext").empty();
			//set the map back to road view
			map.setMapType(G_NORMAL_MAP);
			map.addOverlay(marker);
			//hide the traffic overlay
	//		me.trafficInfo.hide();
		}
		
		
	// this function fires when user submits form - Checks results and then does one of three things
	// 1) displays route information     2) clarify user choice (did you mean? function)      3) tell user to try again

	function searchlocation() {
		//Create a Client Geocoder and initiate the cache (clears previous cache)
	      var geo = new google.maps.ClientGeocoder(new google.maps.GeocodeCache()); 
		//get location from form and check if its location is good.
			var search = document.getElementById("location").value;
		// Declare Error Messages Now
			var reasons=[];
		 reasons[G_GEO_SUCCESS]            = "Success";
		 reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
		 reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
		 reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
		 reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
		 reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
		 reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
	
		// ====== Perform the Geocoding ======        
        geo.getLocations(search, function (georesult) { 
			

            // If that was successful
            if (georesult.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
				// If only one then work out route and complete function 
				if (georesult.Placemark.length == 1) {
					
					//clear current directions / overlays
					directions.clear();
					$("#routetext").empty();
					// load route onto map
					displayroute(georesult,0);
					
					
				} else if (georesult.Placemark.length > 1) {
					
					//if more than one then echo choices into page and make user choose what location they want.
					document.getElementById("routetext").innerHTML = "<h3>Did you mean?</h3>";
					
				 	// Loop through the results
					for (var i=0; i<georesult.Placemark.length; i++) {
						var p = georesult.Placemark[i].Point.coordinates;
						directionsPanel.innerHTML += " <div class='didyoumean' id="+[i]+"><p>"+georesult.Placemark[i].address+"</p><\/div><\/a>";
					}
					// this event listener is triggered after the user chooses something after the "Did you mean?" Prompt
					$(".didyoumean").live("click", function() {	
						//get id of clicked element
						var clicked =  $(this).attr('id');
						//clear current directions / overlays
						directions.clear();
						$("#routetext").empty();
						//pass georesult data to displayroute function
						displayroute(georesult,clicked);
		      		});
				}	
            } else { //geocoding FAIL
			var reason="Code "+georesult.Status.code;
			if (reasons[georesult.Status.code]) {
			reason = reasons[georesult.Status.code];
			directionsPanel.innerHTML = "Address not found. We couldn't even provide you with a best guess. Please Try Again.";
			}
		}
        });	
	}; //END search location
	}

function loadMaps() {
  google.load("maps", "2", {"callback" :   mapplication})
				       
}

	//info
//	$("#travel_tabs #infoTab").click(function() {
//		$("#travelAjaxContainer").fadeOut(600,function(){
//				$("#travelAjaxContainer").hide().load(baseUrl+'location/info').fadeIn(600);
//			});
//		});
	
	
	
	//gmap
	$(".gmapTab").click(function() {
		$("#travel_container").height(600);
		$.scrollTo("#travel_container",{duration:1000});
				$("#travelAjaxContainer").fadeOut(600,function(){
						$("#travelAjaxContainer").hide().load(rootUrl+'location/gmap',function(){
							loadMaps();
							$(this).fadeIn();
						});
					});
		});
	
		//staticmap
		$(".staticmapTab").click(function() {
			$("#travel_container").height(600);
			$.scrollTo("#travel_container",{duration:1000});
					$("#travelAjaxContainer").fadeOut(600,function(){
							$("#travelAjaxContainer").hide().load(rootUrl+'location/staticmap',function(){
								$(this).fadeIn();
							});
						});
			});
	
	
	//rail
	$(".railTab").click(function() {
		$("#travel_container").height(400);
		$.scrollTo("#travel_container",{duration:1000});
		$("#travelAjaxContainer").fadeOut(600,function(){
				$("#travelAjaxContainer").hide().load(rootUrl+'location/rail',function(){
					$("#travelAjaxContainer").fadeIn(600);
				});
			});
	});
	
	
	$().ajaxSend(function(r,s){  
	$("#ajaxLoader").fadeIn(300);  
	});  
	  
	$().ajaxStop(function(r,s){  
	$("#ajaxLoader").fadeOut(300);  
	});

});

