/* javascript for Parkway station mapping */

$(document).ready( function() {
	/* parkway map bits */
	directionsClicks();
});


//initialise clicks for large map
function directionsClicks() {
	//get directions
	$('#button-get-directions').click( function() {
		showDirections();
		
		return false;
	});
	
	//swap "to" and "from" fields
	$('#button-swap').click( function() {
		var tempText = $('#from-text').html();
		var tempValue = $('#txtDirections').val();
		$('#from-text').html( $('#to-text').html() );
		$('#to-text').html( tempText );
		$('#txtDirections').attr({ value: tempValue });
		
		showDirections();
		
		return false;
	});
}

function showDirections() {
	getPointFromAddress( $('#txtDirections').val(), directionsOutput );
}


function directionsOutput(point) {
	var p = point.toString().replace("(", "").replace(")", "");
	var parkway = "52.85795, -1.26435";
	//parkway = "Nottingham NG11 0EE";
	
	//only show direction if not "default" search result
	if ( p != "55.378051, -3.435973" ) {
		if ( $('#from-text input').val() == undefined ) {
			//input is "to" field
			directions.load( "from " + parkway + " to " + p );
		}
		else {
			//input is "from" field
			directions.load( "from " + p + " to " + parkway );
		}
	}
	
	//setTimeout( "checkDirectionsResults()", 10000 );
}


function checkDirectionsResults() {
	$('#map-directions:empty').append("<h2>Address not found</h2><p>Please check your search and try again.</p>");
}


//Use Google search to get more accurate address info
//See details at: http://www.tomanthony.co.uk/blog/geocoding-uk-postcodes-with-google-map-api/
function getPointFromAddress(address, callbackFunction) {
	localSearch.setSearchCompleteCallback(null, function() {
	
		if (localSearch.results[0]) {
			var resultLat = localSearch.results[0].lat;
			var resultLng = localSearch.results[0].lng;
			var point = new GLatLng(resultLat, resultLng);
			callbackFunction(point);
		}
	});
	
	localSearch.execute(address + ", UK");
}


