/*
 * Load GMap2
 */
google.load("maps", "2.x");

/*
 * Initialise our SoakMaps object
 */
SoakMaps = {};


/**
 * load function
 * Defines global variables, Checks for browser compatibility 
 * Loads Map object and applies it to "#map" in the markup
 * Lists for click of map to draw new markers
 *
 * - destination: Used to center the map to a location
 * - zoomLevel: Used to define what level zoom will be applied
 */ 
SoakMaps.load = function() {

	// define global variables
	SoakMaps.directions = false;
	SoakMaps.waypoints = new Array();
	SoakMaps.waypointMarkers = new Array();
	SoakMaps.poly = false;
	SoakMaps.map = false;
	SoakMaps.clickTimeOut = false;
	SoakMaps.mapPin = false;
	SoakMaps.geoCoder = new GClientGeocoder();
	SoakMaps.geoCoder.setBaseCountryCode('uk');

	// Set up an array for comverting (string) map types to google map types
	SoakMaps.mapViews = { 'Map': G_NORMAL_MAP, 'Hybrid': G_HYBRID_MAP, 'Satellite': G_SATELLITE_MAP, 'Terrain': G_PHYSICAL_MAP };

	// Set up an array for comverting (string) map types to google map types
	var mapRouteTypes = { 'driving': G_TRAVEL_MODE_DRIVING, 'walking': G_TRAVEL_MODE_WALKING } ;

	// Get various defaults from the page hidden fields, if not present use sensible defaults
	SoakMaps.mapRouteType = mapRouteTypes['driving'];
	var mapView = SoakMaps.mapViews['Terrain'];
	var mapLat = 45;
	var mapLong = 35;
	var zoomLevel = 1;
	
	// check compatibility
	if (GBrowserIsCompatible()) {

	// Create our custom marker icon
	customIcon = new GIcon();
	customIcon.image = '/assets/images/marker.png';
	customIcon.shadow = '/assets/images/marker-shadow.png';
	customIcon.shadowSize = new GSize(38, 34);
	customIcon.iconSize = new GSize(21.0, 34.0);
	customIcon.iconAnchor = new GPoint(10.5, 34.0);
	markerOptions = {
		icon: customIcon
	};

		// assign map object to variable and define peramamters
		SoakMaps.map = new google.maps.Map2(document.getElementById('map-canvas'));
		SoakMaps.map.setCenter(new GLatLng(mapLat, mapLong), zoomLevel, mapView);
		SoakMaps.map.addControl(new GLargeMapControl3D());

		// add event listener on when map finishes moving
		GEvent.addListener(SoakMaps.map, 'moveend' , SoakMaps.mapMoveEnd);
		
		for (i=0; i<yourCoords.length; i++) {
			SoakMaps.createMarker(yourCoords[i].latitude, yourCoords[i].longitude);
		}
	}
	
	
}
		
SoakMaps.createMarker = function (lat,lng) {
	marker = new GMarker( new GLatLng(lat, lng), markerOptions);
	SoakMaps.map.addOverlay(marker);
	GEvent.addListener(marker, 'click', function() {
		SoakMaps.map.setCenter((new GLatLng(lat, lng)), 9, G_NORMAL_MAP);
		$('#map-controls li').removeClass('active');
		$('#map-controls .map').parent('li').toggleClass('active');
	});
}

SoakMaps.showLocationSearch = function (address) {
	if (SoakMaps.geoCoder) {
		SoakMaps.geoCoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				if(address == 'Where would you like to look?')
				{
					alert("Please enter a place name or location");
				}
				else
				{
					alert(address + " not found, Please check the spelling and try again");
				}
			} else {
				SoakMaps.map.setCenter(point, 13);
			}
		});
	}
}


SoakMaps.initDirections = function() {
	// assign direcitons object to variable
	SoakMaps.directions = new GDirections(false);
	
	// add event listener on load of directions object (also called on loadFromWaypoints)
	GEvent.addListener(SoakMaps.directions, "load", function() {
		
		// if polygon exists remove it
		if(SoakMaps.poly) {
			SoakMaps.map.removeOverlay(SoakMaps.poly);
		}
		
		// define new polygon
		SoakMaps.poly = SoakMaps.directions.getPolyline();
		
		// The directions object will snap markers to closest physically accessible point
		// on the map. (e.g. if you click in a field it will snap to the nearest road)
		
		// count number of markers
		var markerCount = 1;
		
		// get the latest added "directions object" marker
		var last = SoakMaps.directions.getMarker(markerCount);
		
		// get the coords for this marker
		var refinedLatLng = last.getLatLng();
		
		// adjust the users visable marker position to match the directions object marker
		SoakMaps.waypointMarkers[markerCount].setLatLng(refinedLatLng);
		
		// re-add the polygon for all markers so far.
		SoakMaps.map.addOverlay(SoakMaps.poly);

		// If we've now added two waypoints, re-centre the map on them
		if(!SoakMaps.startup) {
			SoakMaps.map.setCenter(SoakMaps.directions.getBounds().getCenter());
			SoakMaps.map.setZoom(SoakMaps.map.getBoundsZoomLevel(SoakMaps.directions.getBounds())); 
			SoakMaps.startup = true;
		}

	}); 
		
}


/**
 * mapTypeChange function
 * Fired on change of map type, updates the hidden form field with the new map type
 * 
 */ 
SoakMaps.mapTypeChange = function() { 

	var mapView = SoakMaps.map.getCurrentMapType();
}


/**
 * changeType function
 * If a user changes the map type (area, pin, route) we clear any existing routes
 * and add a pin if appropriate
 */ 
SoakMaps.changeType = function(type) {
		// and clear the pin if it exists
		if (SoakMaps.mapPin) {
			SoakMaps.map.removeOverlay( SoakMaps.mapPin );
		}

		SoakMaps.mapPin = false;

		$('.route-type').hide();
		$('#map-details').hide();
}


/**
 * mapMoveEnd function
 * Fired on drag of map, updates the hidden form field with the new centre lat and long
 * and the location (country name via call to webservice).
 * 
 */ 
SoakMaps.mapMoveEnd = function() { 
	
	$('#notice-drag').fadeOut();
	var centreSplit = SoakMaps.map.getCenter().toString().split(', ', 2);
	var lat = Math.round(centreSplit[0].replace('(', '') * 1000000)/1000000;
	var lng = Math.round(centreSplit[1].replace(')', '') * 1000000)/1000000;
		
	$('#centre_lat').val(lat);
	$('#centre_long').val(lng);
	
	/* TEMP disable offers for IE */
    if (!jQuery.browser.msie) {
		$.getJSON(
			'http://ws.geonames.org/findNearbyJSON',
			{lat:lat, lng:lng},
			function(data) {
				if(data.geonames[0])
				{
					countryName = data.geonames[0].countryName;
				}
				else
				{
					countryName = '';
				}
				$('#location').val(countryName);
				SoakMaps.postState({action:'dragMap', latitude:lat, longitude:lng, location:countryName});
			}
		);
	}
}
// Post state data via the state.php object.
SoakMaps.postState = function(stateData) {
	$.post(
		'http://treasurehunt.imaginative-traveller.com/includes/lib/helper.state.php',
		stateData,
		function(data) {
			$('#locationHasChanged').val(Boolean(data.response));
			if(Boolean(data.newOffers))
			{
				$('#latest-offers').replaceWith(data.newOffers);	
			}
		}, "json"
	);
}

/**
 * zoomToLocation function
 * If a user clicks the goto location button this function is called
 * We use google geocoder object to convert an address
 */ 
SoakMaps.zoomToLocation = function(address) {

	SoakMaps.geoCoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + ' not found');
			}
			else {
				SoakMaps.map.setCenter(point, 8);
			}
		}
	);

}


/**
 * On page load we use jQuery to fire the relevent events and bind 
 * any events that are required in the page
 */ 
$(function(){

	// Initialise the soak maps object
	SoakMaps.load();
	SoakMaps.map.disableScrollWheelZoom();
	SoakMaps.map.enableContinuousZoom();
	
	$('#map-canvas').prepend('<ul id="map-controls"><li><a class="map" href="#none">MAP</a></li><li><a class="satellite" href="#none">SAT</a></li><li><a class="terrain" href="#none">TER</a></li></ul>');
	
	if ($('#view').val() == 'Map') $('#map-controls .map').parent('li').addClass('active');
	
	$('#map-controls .map').live('click', function(){
		SoakMaps.map.setMapType(SoakMaps.mapViews['Map']);
		$('#map-controls li').removeClass('active');
		$(this).parent('li').toggleClass('active');
		return false;
	});
	
	if ($('#view').val() == 'Satellite') $('#map-controls .satellite').parent('li').addClass('active');
	
	$('#map-controls .satellite').live('click', function(){
		SoakMaps.map.setMapType(SoakMaps.mapViews['Satellite']);
		$('#map-controls li').removeClass('active');
		$(this).parent('li').toggleClass('active');
		return false;
	});
	
	if ($('#view').val() == 'Terrain' || $('#view').val() == '' || $('#view').length == 0) $('#map-controls .terrain').parent('li').addClass('active');
	
	$('#map-controls .terrain').live('click', function(){
		SoakMaps.map.setMapType(SoakMaps.mapViews['Terrain']);
		$('#map-controls li').removeClass('active');
		$(this).parent('li').toggleClass('active');
		return false;
	});

	// To prevent memory leaks in IE tidy up after ourselves
	$('body').unload( function () {
		GUnload();
	});
	
	$('#frm-search').live('submit',function() {
		SoakMaps.showLocationSearch($('#frm-search-location').val());
		return false;
	});

});

