var directionsWindow = null;
var gmarkers = [];
var gicons = [];
var imageDirectory = '/images/google_markers/';
var googleMap = null;
var coords = {
	centre: {
		lat: 53.21662116165011,
		lng: -0.13260841369628906
	},
	home: {
		lat: 53.21662116165011,
		lng: -0.13260841369628906
	}
};
var zoomLevel = 10;
var homeMarker = null;
var homeMarkerHtml = '';




// A function to create the marker and set up the event window
function createMarker(point,name,html,category,description,url) {
	var marker = new GMarker(point,gicons[category]);
	// === Store the category and name info as a marker properties ===
	marker.mycategory = category;
	marker.myname = name;
	marker.mydescription = description;
	marker.myurl = url;
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	gmarkers.push(marker);
	return marker;
}

function isHidden(category){
	return !$('a#'+category).hasClass('selected');
}

// A function to create the marker and set up the event window
function createMarker(point,name,html,category,description,url) {
	var marker = new GMarker(point, gicons[category]);

	// === Store the category and name info as a marker properties ===
	marker.mycategory = category;
	marker.myname = name;
	marker.mydescription = description;
	marker.myurl = url;
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	gmarkers.push(marker);

	return marker;
}


// == hides all markers of a particular category, and set hidden value ==
function hideCategory(category) {
	for (var i=0; i<gmarkers.length; i++) {
		if (gmarkers[i].mycategory == category) {
			gmarkers[i].hide();
		}
	}

	// == clear the checkbox ==
	if($('#'+category).hasClass('selected')) {
		$('#'+category).removeClass('selected');
	}
	if($('#allAttractions').hasClass('selected')) {
		$('#allAttractions').removeClass('selected');
	}

	// == close the info window, in case its open on a marker that we just hid
	googleMap.closeInfoWindow();
}


// == shows all markers of a particular category, and ensures the checkbox is checked ==
function showCategory(category) {
	for (var i=0; i<gmarkers.length; i++) {
		if (gmarkers[i].mycategory == category) {
			gmarkers[i].show();
		}
	}

	// == check the checkbox ==
	if(!$('#'+category).hasClass('selected')) {
		$('#'+category).addClass('selected');
	}

	if($('#subMenu a.selected').length == categories.length) {
		$('#allAttractions').addClass('selected');
	}
}


function getDirectionsFromPostCode(lat, lng) {
	addressEle = document.getElementById('address_home');

	if(addressEle.value == '') {
		alert('Please enter your Postcode');
		return false;
	}
	url = 'http://maps.google.co.uk/maps?saddr='+escape(addressEle.value)+'&daddr='+lat+','+lng;

	return getDirections(url);
}

function getDirectionsFromHome(lat, lng) { // Home being the customer's marker
	addressEle = document.getElementById('address_home');

	url = 'http://maps.google.co.uk/maps?saddr='+coords.home.lat+','+coords.home.lng+'&daddr='+lat+','+lng;

	return getDirections(url);
}

function getDirections(url) {
	if(directionsWindow!=null && !directionsWindow.closed && directionsWindow.location) {
		directionsWindow.location.href = url;
	} else {
		directionsWindow = window.open(url, 'directions');
		if(!directionsWindow.opener) {
			directionsWindow.opener = self;
		}
	}

	if(window.focus) {
		directionsWindow.focus();
	}

	return false;
}




$(document).ready(function(){
	if (GBrowserIsCompatible()) {

		// Initalise the map
		googleMap = new GMap2(document.getElementById("googleMap"));

		// Create the category icons
		for(var x=0; x<categories.length; x++) {
			gicons[categories[x]] = new GIcon(G_DEFAULT_ICON, imageDirectory+categories[x]+".png",'','','','','','');
			gicons[categories[x]].shadow = '';
			gicons[categories[x]].iconSize = new GSize(32, 32);
		}

		// Other Icons
		gicons['home'] = new GIcon(new GLatLng(coords.home.lat, coords.home.lng), imageDirectory+'home.png');
		gicons['home'].image = imageDirectory+'home.png';
		gicons['home'].iconSize = new GSize(32, 43);
		gicons['home'].shadow = imageDirectory+'home_shadow.png';
		gicons['home'].shadowSize = new GSize(48, 43);
		gicons['home'].iconAnchor = new GPoint(16, 43);
		gicons['home'].infoWindowAnchor = new GPoint(16, 43);

		// Add Map Controls
		googleMap.addControl(new GLargeMapControl());
		googleMap.addControl(new GOverviewMapControl());
		googleMap.addControl(new GMapTypeControl());
		googleMap.setCenter(new GLatLng(coords.centre.lat, coords.centre.lng), zoomLevel);

		// Create Marker for Crowders
		point = new GLatLng(coords.home.lat, coords.home.lng);
		homeMarkerHtml = '<strong>Crowders Garden Centre</strong>,<br />Lincoln Road,<br/>Horncastle,<br />Lincolnshire,<br />LN9 5LZ';
		homeMarkerHtml += '<p style="margin:0"><br/><strong>Directions to Crowders Garden Centre</strong><br/>Enter your Postcode:<br /><form onsubmit="return false;" style="padding: 0px; margin:0px;"><input type="text" size="30" name="address_home" id="address_home" /></form><a href="#" onclick="return getDirectionsFromPostCode('+coords.home.lat+','+coords.home.lng+')">Get Directions</a></p>';
		homeMarker = new GMarker(point, { icon: gicons['home'] });
		GEvent.addListener(homeMarker, "click", function() {
			homeMarker.openInfoWindowHtml(homeMarkerHtml);
			//this.openInfoWindowHtml("<b>Hello</b>");
		});
		googleMap.addOverlay(homeMarker);
		homeMarker.openInfoWindowHtml(homeMarkerHtml);

		// Import the attraction marker data
		GDownloadUrl("/location/local-attractions.xml", function(doc) {
	        var xmlDoc = GXml.parse(doc);
	        var markers = xmlDoc.documentElement.getElementsByTagName("marker");

	        // Loop through all the markers in the XML document
	        for (var i = 0; i < markers.length; i++) {

	          	// obtain the attribues of each marker
	          	var point = new GLatLng(
	          		parseFloat(markers[i].getAttribute("lat")),
	          		parseFloat(markers[i].getAttribute("lng"))
	          	);
		        var address = markers[i].getAttribute("address");
		        var name = markers[i].getAttribute("name");
		        var url = markers[i].getAttribute("url");
				var html =
	          		"<p style=\"margin-bottom:0\"><strong>"+name+"</strong></p>"
	          		+address
	          		+ "<a target='_blank' href='http://"+url+"'>"+name+"</a>"
	          		+ '<p><a href="#" onclick="return getDirectionsFromHome('+markers[i].getAttribute("lat")+','+markers[i].getAttribute("lng")+')">Get Directions</a></p>';
	          		;
	          	var category = markers[i].getAttribute("category");
			  	var description = markers[i].getAttribute("description");

	          	// create the marker
	          	var marker = createMarker(point, name, html, category, description, url);

	          	// Add marker to map
	          	googleMap.addOverlay(marker);
	        }

			//Set all isHidden values to true;
			for (i=0; i<categories.length;i++) {
				hideCategory(categories[i]);
			}

			// Show the first category in the list
			showCategory[categories[0]];
		});

		// Bind onclick event to category anchors
		$('#allAttractions').bind('click', function(){
			if($(this).hasClass('selected')) {
				for(var x=0;x<categories.length;x++) {
					hideCategory(categories[x]);
				}
			} else {
				for(var x=0;x<categories.length;x++) {
					showCategory(categories[x]);
				}
			}
			return false;
		});
		$('a.attractionCategory').bind('click', function() {
			if($(this).hasClass('selected')) {
				hideCategory(this.id);
			} else {
				showCategory(this.id);
			}
			return false;
		});
	}
});