var geocoder = new GClientGeocoder();
geocoder.setBaseCountryCode('uk');

var unitedKingdom  = new GLatLng(55.541064956111036, -3.427734375);
var landsEnd       = new GLatLng(50.068611, -5.716111);
var shetland       = new GLatLng(60.183892, -1.427812);
var leeds          = new GLatLng(53.799637, -1.54911);
var preston        = new GLatLng(53.757729, -2.70344);

var latlngbounds = new GLatLngBounds(landsEnd, shetland);

geocoder.setViewport(latlngbounds);

var map;

var markers = [];

var urlVars;

$(document).ready(function() {
	urlVars = $.getUrlVars();

	map_init();

	$('a.show-marker').click(function() {
		var id = parseInt(this.id.substring(5));
		highlight_school(id);
		return false;
	});
});


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
$.extend({
	getUrlVars: function() {
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

		for (var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}

		return vars;
	},

	getUrlVar: function(name) {
		return $.getUrlVars()[name];
	}
});


//------------------------------------------------------------------------------
// Given its identifier, highlight a specific school by a) centering the map
// (and zooming) and b) opening an info window for that school
//------------------------------------------------------------------------------
function highlight_school(id)
{
//	if (window.console) console.log('highlight_school');
	var school, gll;

	for (s in schools)
	{
		school = schools[s];

		if (school.id == id)
		{
			break;
		}
	}

//	if (window.console) console.log(school);

	if (school && markers[id])
	{
//		if (window.console) console.log('highlight: found');
//		console.log(markers[id]);
		var gll = markers[id].getLatLng();

		map.setCenter(gll, 9);
		var infoWindowOptions = { maxWidth: 300 };
		markers[id].openInfoWindowHtml(get_info_window(school), infoWindowOptions);
	}

	return gll;
}


//------------------------------------------------------------------------------
// Given a school object, display its info window
//------------------------------------------------------------------------------
function get_info_window(school)
{
	var out = "";

	out += "<h2 style='margin-top: 0; margin-right: 12px;'>" + school.name + "</h2>";

	if (school.when == 'undecided')
	{
		school.when = '';
	}

	if (school.what && school.what != 'Undecided')
	{
		out += "<p>";

		if (school.when && school.when != 'undecided')
		{
			out += "In " + school.when + ", we plan to ";
		}
		else
		{
			out += "We plan to ";
		}

		if (school.what == 'Crafty Creations' || school.what == 'Pop-up shop'
			|| school.what == 'Money Magic' || school.what == 'Playtime')
		{
			out += "do the &lsquo;" + school.what + "&rsquo; fundraising challenge";
		}
		else
		{
			out += school.what;
		}

		out += ".</p>";
	}
	else if (school.when)
	{
		out += "<p>We are taking part in " + school.when + "</p>";
	}

	return out;
}


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
function show_address(map, address, showOthers, centerOnPoint) {
	geocoder.getLocations(
		address,
		function(response) {
			if (response.Status.code == '200')
			{
				var closest = -1;
				var closestPoint = null;

				for (p in response.Placemark)
				{
					var pl = response.Placemark[p];

					var gll = new GLatLng(pl.Point.coordinates[1], pl.Point.coordinates[0]);
					var dist = gll.distanceFrom(unitedKingdom);

					if (closest < 0 || dist < closest)
					{
						closest = dist;
						closestPoint = pl;
					}

//					add_point(map, pl, address, address);
				}

				if (showOthers)
				{
					$('#others ul').html('');

					var num = 1;

					for (p in response.Placemark)
					{
						var pl = response.Placemark[p];

						if (pl != closestPoint)
						{
							$('#others ul').append('<li id="' + num + '"><a href="">' + pl.address + '</a></li>');

							$('#others ul li#' + num).data("point", pl);

							$('#others ul li#' + num).click(function() {
								var point = $(this).data("point");
								add_point(map, point, point.address, point.address);
								setCenterAndZoom(point);
								return false;
							});

							num++;
						}
						else
						{
//							console.log("pl is closest");
						}
					}

					$('#others').show();
				}

				add_point(map, closestPoint, closestPoint.address, address);

				if (centerOnPoint)
				{
					setCenterAndZoom(closestPoint);
				}
			}
		}
	);
}


//------------------------------------------------------------------------------
// Look up a school's address via Google GeoCoder, and add it to the map.
//------------------------------------------------------------------------------
function add_single_address(id, map, title, address, text)
{
//	if (window.console) console.log("Looking up address [" + address + "] with google");

	geocoder.getLatLng(
		address,
		function(gll) {
			var type = urlVars['show'] == id ? 'custom' : 'default';

			if (gll)
			{
//				if (window.console) console.log("adding " + id + " to markers");
				markers[id] = add_marker(map, gll, title, text, type);

				$.post('/assets/php/coords.php', { address: address, lat: gll.lat(), lng: gll.lng() });
			}
			else
			{
				// Couldn't locate this school
				// if (window.console) console.log("ERROR HERE");
			}

			focus_school(id, gll);
		}
	);
}


function focus_school(id, gll)
{
	if (urlVars['show'] == id)
	{
//		if (window.console) console.log(urlVars, id, 'found');

		if (!gll)
		{
			$('#error').html("We could not find your school using the address details you supplied. We will check the details and contact you if necessary.");
		}
		else
		{
			//$('#error').html("We've highlighted your school on the map; this is how it will appear once we've approved it.");
		}

		var gll = highlight_school(id);

		if (gll)
		{
			var txt = '';

			for (s in schools)
			{
				if (schools[s].id != id)
				{
//					if (window.console) console.log(markers, schools[s].id);

					if (markers[schools[s].id])
					{
						var dist = gll.distanceFrom(markers[schools[s].id].getLatLng());
						dist = Math.round(dist);

						if (dist <= 25000)
						{
							txt += '<li><a class="show-marker" id="view-' + schools[s].id + '" href="google-map.php#show-' + schools[s].id + '">' + schools[s].name + '</a></li>';
						}
					}
				}
			}

			if (txt)
			{
				$('#recent-signups').after('<h2>Groups near you</h2><ul id="nearby-schools"></ul>');
				$('#nearby-schools').append(txt);

				$('a.show-marker').click(function() {
					var id = parseInt(this.id.substring(5));
					highlight_school(id);
					return false;
				});
			}
		}
	}
}

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
function setCenterAndZoom(point)
{
	var gll = new GLatLng(point.Point.coordinates[1], point.Point.coordinates[0]);
	var accuracy = point.AddressDetails.Accuracy;

	switch (accuracy)
	{
		case 2:	// e.g. scotland
			map.setCenter(gll, 6);
			break;

		case 3:
			map.setCenter(gll, 7);
			break;

		case 4: // e.g. london
			map.setCenter(gll, 8);
			break;

		case 5:
			map.setCenter(gll, 10);
			break;

		case 6:
			map.setCenter(gll, 12);
			break;

		case 9:
			map.setCenter(gll, 14);
			break;

		default:
//			alert(accuracy);
//			alert(point.address);
			map.setCenter(gll, 9);
			break;
	}
}


var mapType = G_HYBRID_MAP;

var mapZoom = 6;
var mapContinuousZoom = 1;
var mapScrollWheelZoom = 0;
var mapSmallZoom = 1;
var mapFixed = 0;
var mapMinZoom = 2;
var mapMaxZoom = 14;


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
function map_init()
{
    if (!GBrowserIsCompatible())
    {
        return;
    }

    var geocoder = new GClientGeocoder();

    if (mapMinZoom) { G_HYBRID_MAP.getMinimumResolution = function() { return mapMinZoom; }; }
    if (mapMaxZoom) { G_HYBRID_MAP.getMaximumResolution = function() { return mapMaxZoom; }; }

    // Create and Center a Map
    map = new GMap2(document.getElementById("map"));

    map.setMapType(mapType);

    if (mapContinuousZoom)  { map.enableContinuousZoom();  }
    if (mapScrollWheelZoom) { map.enableScrollWheelZoom(); }
    if (mapFixed)           { map.disableDragging();       }

    var center = preston;
    map.setCenter(center, mapZoom);


    if (mapSmallZoom)
    {
        map.addControl(new GSmallZoomControl3D());
    }

	for (s in schools)
	{
		var add = schools[s].address ? schools[s].address : schools[s].name;

		if (coords && coords[schools[s].address])
		{
			var c = coords[schools[s].address];
			var gll = new GLatLng(c[0], c[1]);

			//var type = urlVars['show'] == id ? 'custom' : 'default';
			var type = 'default';
			var id = schools[s].id;

//			if (window.console) console.log("adding " + id + " to markers");

			markers[id] = add_marker(map, gll, schools[s].name, get_info_window(schools[s]), type);

			focus_school(id, gll);
		}
		else
		{
			add_single_address(schools[s].id, map, schools[s].name, add, get_info_window(schools[s]));
		}
	}
}


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
function add_point(map, point, title, text)
{
	var gll = new GLatLng(point.Point.coordinates[1], point.Point.coordinates[0]);
	add_marker(map, gll, title, text, 'default');
}


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
function add_marker(map, gll, title, text, type)
{
	var icon = new GIcon(G_DEFAULT_ICON);

	//icon.image = '/assets/images/' + icons[type];

	switch (type)
	{
		case 'custom':
			icon.image = '/assets/images/pin-yellow-20x34.png';
			break;

		case 'default':
		default:
			icon.image = '/assets/images/pin-orange-20x34.png';
			break;
	}

    var infoWindowOptions = { maxWidth: 300 };
	var markerOptions = { title: title, icon: icon };
	var marker = new GMarker(gll, markerOptions);

	marker.bindInfoWindowHtml(text, infoWindowOptions);
	map.addOverlay(marker);
	return marker;
}

