	$(document).ready(function(){
	
	$('#location_search').focus();
	
	$('#suggestion_email').val();
	
	/* Clear email suggest field on focus */
	
	var emailPrevious = '';

// clear input on focus
$('#suggestion_email').focus(function()
{
if($(this).val()==$(this).attr('title'))
{
emailPrevious = $(this).val();
$(this).val('');
}
});

// if field is empty afterward, add text again
$('#suggestion_email').blur(function()
{
if($(this).val()=='')
{
$(this).val(emailPrevious);
}
});
	
	var nynavconfig = {    
     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
     interval: 1, // number = milliseconds for onMouseOver polling interval    
     over: nynavOn, // function = onMouseOver callback (REQUIRED)    
     timeout: 1, // number = milliseconds delay before onMouseOut    
     out: nynavOff // function = onMouseOut callback (REQUIRED)    
};

	
			$("#subnav a.notyet").hoverIntent(nynavconfig);
			
			var nyconfig = {    
     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
     interval: 1, // number = milliseconds for onMouseOver polling interval    
     over: navOn, // function = onMouseOver callback (REQUIRED)    
     timeout: 1, // number = milliseconds delay before onMouseOut    
     out: navOff // function = onMouseOut callback (REQUIRED)    
};

			$("body.amabout #subnav li#phaseone").hoverIntent(nyconfig);
			
					
	$('#submitlink').click(
      function () {
		submitExpand();
			return false;
      }
	  );
	  
	  
		
	
		$('.location').hover(
      function () {
		$(this).children('a').blur();
      }
	  );
		


		
		}); // close document.ready

		
     function submitExpand() {
	  
	  	$('#submitbox').show();
		if (($('#resultslist').height()) >= 170) {
			$('#resultslist').animate({   height: "170px"  }, 100 );
			}
		$('#submitbox').slideDown();
		//theMarker.closeInfoWindow();
		
	
		return false;
      };
		
		
		var geomap = geomap || {};

(function () {

	// escapes strings for use in specifying IDs in jQuery expressions
	function escapeID(s) {
		return s.replace(/([\:\.\[\]])/g, '\\$1');
	}

	// creates a jQuery object for an id
	function jid(s) {
		return $('#' + escapeID(s));
	}

	/* Allows you to chain AJAX methods, mapping the output from one method to the input to the subsequent method. */
	// ajaxChain('service1', {a:1,b:2}).followedBy('service2',function (data) { return { c: data.a + data.b }; }).go(function (data) { /* side-effect */ });
	
	function ajaxChain(url, data, indicator) {
		var that = {};
		that.go = function (f) {
			$.ajax({
				url: url, 
				data: data, 
				dataType: 'json',
				success: f,
				beforeSend: function () { indicator.show(); },
				complete: function () { indicator.hide(); }
			});
		};
		that.followedBy = function (url, dataMapperFn) {
			var togo = {};
			togo.go = function (f) {
				that.go(function (data) {
					$.ajax({
						url: url, 
						data: dataMapperFn(data), 
						dataType: 'json',
						success: f,
						beforeSend: function () { indicator.show(); },
						complete: function () { indicator.hide(); }
					});
				});
			};
			return togo;
		};
		return that;
	};

	/* Allows you to use Google's geocoder service, with fallback options */
	// geocode(aGClientGeocoder, aLocation, zoom).orElse(secondaryLocation, zoom).orElse(tertiaryLocation, zoom).otherwise(defaultLatLong, zoom).go(function (aGLatLng, zoom) { /* side-effect */ });
	function geocode(geocoder, location, zoom) {
		var that = {};
		
		that.go = function (f) {
			geocoder.getLatLng(location, function (latlng) { f(latlng, zoom); } );
		};
		
		function orElseLink (location, zoom, link) {
			var togo = {};
			togo.go = function (f) {
				link.go(function (latlng, z) {
					if (latlng == null) {
						geocoder.getLatLng(location, function (latlng) { f(latlng, zoom); });
					} else {
						f(latlng, z);
					}
				});
			};
			togo.orElse = function (location, zoom) { return orElseLink(location, zoom, togo); }
			togo.otherwise = function (latlng, zoom) { return otherwiseLink(latlng, zoom, togo); }
			return togo;
		}
		
		that.orElse = function (location, zoom) { return orElseLink(location, zoom, that); }
		
		function otherwiseLink (default_latlng, zoom, link) {
			var togo = {};
			togo.go = function (f) {
				link.go(function (latlng, z) {
					if (latlng == null) {
						f(default_latlng, zoom);
					} else {
						f(latlng, z);
					}
				});
			};
			return togo;
		}
		
		that.otherwise = function (latlng, zoom) { return otherwiseLink(latlng, zoom, that); }
		
		return that;
	};
	
	/* Registration and dispatch functions for 2 messages: (1 "question") user has chosen a place to locate, and (2 "suggestion") user has dropped the marker on the map */
	var theQuestionObservers = [];
	function registerQuestionObserver(observer) {
		theQuestionObservers.push(observer);
	};
	
	function notifyQuestionObservers(question) {
		for (var i = 0; i < theQuestionObservers.length; ++ i) {
			theQuestionObservers[i](question);
		}
	};
	
	var theSuggestionObservers = [];
	function registerSuggestionObserver(observer) {
		theSuggestionObservers.push(observer);
	};
	
	function notifySuggestionObservers(suggestion) {
		for (var i = 0; i < theSuggestionObservers.length; ++ i) {
			theSuggestionObservers[i](suggestion);
		}
	};
	
	
     function onDrag() {
	  	if (($('#resultslist').height()) >= 170) {
			$('#resultslist').animate({   height: "170px"  }, 100 );
			}
  	$('#submitbox').slideDown();
      };
	  
	    function resetSubmit() {

	
		$('#thankyou').hide();					
		$('.emailinfo').show();	
		$('.submitintro').show();
		   };

	/*********** STEP ONE - SEARCHING *****************/
	
	geomap.bindSearch = function (theGeocoderURL, elementIDs) {

		function getSearchResultClickHandler(question_id) {
			return function () {
				ajaxChain(theGeocoderURL, { a: 'getOneLocation', id: question_id }, jid(elementIDs.gettingQuestion)).go(notifyQuestionObservers);
			
				 	$(this).children('a').blur();
							$('#resultslist a').removeClass('active');
							$(this).children('a').addClass('active');
							$('#submitbox').hide();
					resetSubmit();
				return false;
			};
		}

		function searchResultsHandler(data) {
		$('#location_results').hide();$('#submitbox').hide(); resetSubmit();
		
			jid(elementIDs.locationResults).empty();
			jid(elementIDs.locationResults).append('<h5><strong>2.</strong> Choose a location</h5><div id="resultslist"></div>');
				if (data.length == 0) {$('#nomatches').show();}
			for (var i = 0; i < data.length; ++ i) {
				var div = $('<div class="location"></div>');
				var a = div.append('<a id="location_result_' + i + '" href="">' + data[i].location + '</a>');
				a.click(getSearchResultClickHandler(data[i].question_id));
		
					$('#nomatches').hide();
				$('#location_results').show();
				$('#submitbox').hide();
					resetSubmit();
				$('#question_location').hide();		
				$('#resultslist').hide().append(div);
				$('#resultslist').slideDown();
				resetSubmit();
				
				
								
				if (i == (data.length - 1) && (data.length >= 140)) { $('#resultslist').append('<p id="refinealert">Your search term returned too many locations to show here. Please try refining it to a more specific area.</p>'); }
			}	
		}
		
		function submitSearch() {
			var location_search = jid(elementIDs.locationSearch).val();
			ajaxChain(theGeocoderURL, { a: 'getLocations', q: location_search, mr: '150', sc: 'location' }, jid(elementIDs.gettingLocations)).go(searchResultsHandler);
			// reset the marker and remove the submit box
			$('#submitbox').hide();
			return false;
		};
		
		
		jid(elementIDs.locationForm).submit(submitSearch);
		jid(elementIDs.locationSearch).keyup(function (ev) {
			if ((ev.keyCode >= 48 && ev.keyCode <= 57 || ev.keyCode >= 65 && ev.keyCode <= 90 || ev.keyCode == 8) 
				&& jid(elementIDs.locationSearch).val().length >= 3) {
				submitSearch();
			}
			return true;
		});

	};
	
	/**************** STEP TWO - LOCATING ***************/
	
	geomap.bindMap = function (theGeocoderURL, theMap, theGeocoder, questionLocationID) {
	
		registerQuestionObserver(function (question) {
			$('#locationconfirm').html(question.location);
			jid(questionLocationID).data('location', question);
			
			jid(questionLocationID).hide();
				$('#submitbox').hide();
				$('.infobox').slideUp();
	
	
		});
		
		var theMarker = null;
		var dragCount = 0;
		
		registerQuestionObserver(function (question) {
			var placeMarker = function (latlng, zoom) {
				if (theMap.getZoom() == zoom) {
					theMap.panTo(latlng);
				} else {
					theMap.setCenter(latlng, zoom);
				}
				if (theMarker == null) {
					theMarker = new GMarker(latlng, {draggable: true});
					theMap.addOverlay(theMarker);
					GEvent.addListener(theMarker, "dragend", notifySuggestionObservers);
				
				
				// Remove bubble if location search  in focus
				
				
				$('#location_search').click(
				  function () {
					theMarker.closeInfoWindow();
					$(this).val('');
				  }
				  );
				
				// Close info window when marker starts to move
				
				GEvent.addListener(theMarker, "dragstart", function () {	
					theMarker.closeInfoWindow();
					if (dragCount == 0) {onDrag(); dragCount = dragCount+1;}
					}
				);	
				
				
		GEvent.addListener(theMap.getInfoWindow(),"closeclick", function () {	
					submitExpand();
				});
					
				} else {
					theMarker.setLatLng(latlng);

				}
				notifySuggestionObservers(latlng);
				theMarker.openInfoWindowHtml('This marker is our best guess for<br/><strong>'+question.location+'</strong><br/><br/>Help Tate by refining the marker:<br/><br/>a) zoom and drag the marker to what you think is the right place<br/><br/>b) <a href="#" id="bubblelink" onclick="submitExpand();return false;">confirm it\'s already correct</a> then submit location in the left panel', {maxWidth:270});
				
				
				dragCount = 0;
		
				
			};
			
			geocode(theGeocoder, question.location, 13)
			.orElse(question.region + ', ' + question.country, 9)
			.otherwise(question.uk ? new GLatLng(54.5, -4.0) : new GLatLng(0, 0), question.uk ? 5 : 1)
			.go(placeMarker);
			
		});

	};
	
	/********** INITIALISE THE MAP (returns a GMap2) *************/

	geomap.initMap = function (mapID) {
		var theMap = new GMap2(document.getElementById(mapID));
		theMap.setCenter(new GLatLng(54.5, -4.0), 5);
		theMap.addControl(new GMapTypeControl());
		theMap.addControl(new GLargeMapControl());
		theMap.addControl(new GScaleControl());
		theMap.enableScrollWheelZoom();
		
		$(window).unload(function () { GUnload(); });

		return theMap;
	};
	
	/************** STEP 3 - SUBMIT SUGGESTION *****************/
	
	geomap.bindSuggestionForm = function (elementIDs) {
	
		registerQuestionObserver(function (question) {
			jid(elementIDs.question_id).val(question.question_id);
			jid(elementIDs.code).val(question.code);
			jid(elementIDs.lat).val('');
			jid(elementIDs['long']).val('');
		});
		
		registerSuggestionObserver(function (suggestion) {
			jid(elementIDs['lat']).val(suggestion.lat());
			jid(elementIDs['long']).val(suggestion.lng());
		});

		jid(elementIDs.form).submit(function () {
			$('#submitloaderinner').show();
				if (($('#suggestion_email').val() != 'Your email address') && ($('#suggestion_email').val() != '')) {$('.emailinput').hide();}
			if (jid(elementIDs['lat']).val() == '' || jid(elementIDs['long']).val() == '') {
				alert('Location not set!');
			} else {
				$(this).ajaxSubmit({ 
					dataType: 'json', 
					success: function (data) { 
					$('.active').remove();			
					$('#thankyou').show();					
				$('.emailinfo').hide();	
					$('.submitintro').hide();
				$('#submitloaderinner').fadeOut();
					} 
				});
			}
			return false;
		});
	};

})();

		
					
		function navOn(){ 
		$(this).animate({"top":17},100);
		};
		
		function navOff(){
		$(this).animate({"top":21},50);
		};
		
		function nynavOn(){ 
		$originaltext = $(this).html();
        $(this).html('Coming soon');
		};
		
		function nynavOff(){
        $(this).html($originaltext);
		};
		
	

