window.addEvent('load', function()
{		
	mapLoad();
	
	initClubs();
	
	$(document.body).addEvent('unload', function()
	{
		GUnload();
	});

});

var clubs = new Array();
var map;
var clubDetails;
var myInput;
var searchListParent;
var searchListHeader;
var sameCountyList;
var sameCountyListHeader;


/*
	Builds html to show club details and inserts it into the clubDetails Div
*/
function showDetails(item) {
	clubDetails.removeClass('hidden');
	while (clubDetails.firstChild) {
		clubDetails.removeChild(clubDetails.firstChild);
	}

	html = '<h3>'+item.name+'</h3>';
	html += '<dl><dt>Address</dt>';
	html += '<dd><address>' + 
		item.address1 + '<br />' +
		item.address2 + '<br />' +
		item.town + '<br />' +
		item.county + '<br />' +
		item.postCode ;
	html += '</address></dd>';
	html += '<dt>Secretary</dt><dd>' + item.secretary + '</dd>';
	html += '';
	html += '<dt>Phone</dt><dd>' + item.phone + '</dd>';
	if(item.email) {
		html += '<dt>Email</dt><dd><a href="mailto:' + item.email + '">send email</a></dd>';
	} else {
		html += '<dt>Email</dt><dd>&mdash;</dd>';
	}
	if(item.web) {
		html += '<dt>Website</dt><dd><a href="http://' + item.web + '" onclick="goPopup(\'http://' + item.web + '\'); return false;">launch website</a></dd>';
	} else {
		html += '<dt>Website</dt><dd>&mdash;</dd>';
	}
	html += '<dt>Category</dt><dd>' + item.groundType + '</dd>';
	html += '<dt>Grid Ref.</dt><dd>' + item.gridReference + '</dd>';
	html += '<dt>Disciplines</dt><dd>' + item.disciplineStr + '</dd>';
	
	if (item.description!=="") {
		html += '<dt>Details</dt><dd>' + item.description + '<dd>';
	}
	html += '</dl>';

	clubDetails.set('html', html);
	searchListParent.addClass('hidden');
	searchListHeader.addClass('hidden');
	
	for(i=0;i<$('county').length;i++) {
		if($('county')[i].value.toLowerCase() == item.county.toLowerCase()) {
			$('county')[i].selected=true;
			break;
		}
	}
	
	//$('county').value = item.county;
	var matchedClubs = clubs.filter(compareCounty);
	
	// Empty the search results box
	while (sameCountyList.firstChild) {
		sameCountyList.removeChild(sameCountyList.firstChild);
	}
	if(matchedClubs.length < 1) {
		sameCountyList.set('html', '<li>No results to show</li>');
	}
	
	matchedClubs.each(function(item, index)
	{
		var clubList = new Element('li');
		var clubLink = new Element( 'a', {
			'href': '#',
			'html': item.name,
			'events': {
				'click': function(e) { 
					e.stop();
					if(item.lat != 0 && item.lng != 0) {
						map.setZoom(10);
						map.panTo(new GLatLng(item.lat, item.lng));
					} else {
						map.setZoom(5);
						map.panTo(new GLatLng(53.981935, -2.900391));
					}
					showDetails(item);
				}
			}
		});
		clubLink.inject(clubList);
		clubList.inject(sameCountyList);
	});
	sameCountyList.removeClass('hidden');
	sameCountyListHeader.removeClass('hidden');
	sameCountyListHeader.set('html', 'All clubs in ' + item.county);
	//clubDetails.addClass('hidden');
	
}

/*
 * Creates a google maps marker object and adds the required event
 * listeners to it.  Icon styles are also defined here.
 */
function createMarker(point, clubObject)
{
	// Create custom marker icon
	var customIcon = new GIcon();
	//customIcon.image = "http://www.cpsa.co.uk/images/CPSA.png";
	customIcon.image="http://www.cpsa.co.uk/images/CPSA-new.png";
	customIcon.iconSize = new GSize(26, 26);
	customIcon.iconAnchor = new GPoint(6, 20);
	customIcon.infoWindowAnchor = new GPoint(5, 1);
	
	// Create the marker and add the click event
	markerOptions = { icon:customIcon };
	
	var marker = new GMarker(point, markerOptions);
	
	//var html = "<b>" + clubObject.name + "</b> <br/>" + clubObject.postCode;
	GEvent.addListener(marker, 'click', function()
	{
		//marker.openInfoWindowHtml(html);
		if(clubObject.lat != 0 && clubObject.lng != 0) {
			map.setZoom(10);
			map.panTo(new GLatLng(clubObject.lat, clubObject.lng));
		} else {
			map.setZoom(5);
			map.panTo(new GLatLng(53.981935, -2.900391));
		}
		showDetails(clubObject);
	});
	
	return marker;
}

function Club(){}

function mapLoad()
{
	if(GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(53.981935, -2.900391), 5);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());

		// Load the XML file containing the clubs data
		GDownloadUrl("/find-a-club/getClubs", loadClubData);
	}
}

function initClubs()
{
	clubDetails = $('clubDetails');
	myInput = $('clubName');
	searchListParent = $('searchList');
	searchListHeader = searchListParent.getPrevious();
	sameCountyList = $('sameCountyList');
	sameCountyListHeader = sameCountyList.getPrevious();
	myInput.addEvent('keyup', function(e)
	{
		e.stop();
		if(myInput.value.length > 2) {
			var tempArray = clubs.filter(compareName);
			populateClubListHTML(tempArray);
		}
	});
	
	$('county').addEvent('change', function(e){
		countyChange();
	});
}

function countyChange()
{
	var tempArray = clubs.filter(compareCounty);
	populateClubListHTML(tempArray);
	if($('county').value != '') {
		
		var county = $('county').value;
		
		switch (county) {
			case 'Eire': county = 'Ireland'; break;
			case 'Devon': county = 'Devonshire,United Kingdom'; break;
			case 'Avon': county = 'Bristol,United Kingdom'; break;
			default: county += ',United Kingdom'
		}
		
		var geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode('uk');
		
	/*	
		geocoder.getLocations(county, function(response) {
			if (!response || response.Status.code != 200) { 
				alert("Status Code:" + response.Status.code); 
			  } else { 
				place = response.Placemark[0]; 
				point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]); 
				alert('orig latlng:' + response.name + '\n' +  
					'latlng:' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '\n' + 
					'Status Code:' + response.Status.code + '\n' + 
					'Status Request:' + response.Status.request + '\n' + 
					'Address:' + place.address + '\n' + 
					'Accuracy:' + place.AddressDetails.Accuracy + '\n' + 
					'Country code: ' + place.AddressDetails.Country.CountryNameCode); 
			}
		});
	*/
		
		geocoder.getLatLng(county, function(point) 
		{
			if (!point) {
				//alert("Couldn't find county.");
				map.setZoom(1);
			} else {
				map.setZoom(8);
				map.panTo(point);
			}
		});
	} else {
		map.setZoom(5);
		map.panTo(new GLatLng(53.981935, -2.900391));
	}
}

function populateClubListHTML(matchedClubs){
	// Empty the search results box
	while (searchListParent.firstChild) {
		searchListParent.removeChild(searchListParent.firstChild);
	}
	if(matchedClubs.length < 1) {
		searchListParent.set('html', '<li>No results to show</li>');
	}
	
	matchedClubs.each(function(item, index)
	{
		var clubList = new Element('li');
		var clubLink = new Element( 'a', {
			'href': '#',
			'html': item.name,
			'events': {
				'click': function(e) { 
					e.stop();
					if(item.lat != 0 && item.lng != 0) {
						map.setZoom(10);
						map.panTo(new GLatLng(item.lat, item.lng));
					} else {
						map.setZoom(5);
						map.panTo(new GLatLng(53.981935, -2.900391));
					}
					showDetails(item);
				}
			}
		});
		clubLink.inject(clubList);
		clubList.inject(searchListParent);
	});
	searchListParent.removeClass('hidden');
	searchListHeader.removeClass('hidden');
	sameCountyList.addClass('hidden');
	sameCountyListHeader.addClass('hidden');
	clubDetails.addClass('hidden');
}

function compareName(element, index, array) {
	var re = new RegExp(myInput.value,'i');

	if (element.name.search(re) != -1 || element.address1.search(re) != -1) {
		return true;
	} else {
		return false;
	}
}

function compareCounty(element, index, array) {
	if (element.county.toLowerCase() == $('county').value.toLowerCase()) {
		return true;
	} else {
		return false;
	}
}

function compareId(element, index, array) {
	if (element.clubId == $('clubIdHid').value) {
		return true;
	} else {
		return false;
	}
}

function loadClubData(data)
{
	var xml = GXml.parse(data);
	var clubsXML = xml.documentElement.getElementsByTagName("club");
	for (var i = 0; i < clubsXML.length; i++) {
		club = new Club();
		club.clubId = clubsXML[i].getAttribute("clubId");
		club.name = clubsXML[i].getAttribute("name");
		club.address1 = clubsXML[i].getAttribute("address1");
		club.address2 = clubsXML[i].getAttribute("address2");
		club.town = clubsXML[i].getAttribute("town");
		club.county = clubsXML[i].getAttribute("county");
		club.postCode = clubsXML[i].getAttribute("postCode");
		club.phone = clubsXML[i].getAttribute("phone");
		club.email = clubsXML[i].getAttribute("email");
		club.web = clubsXML[i].getAttribute("website");
		club.type = clubsXML[i].getAttribute("type");
		club.groundType = clubsXML[i].getAttribute("groundType");
		club.gridReference = clubsXML[i].getAttribute("gridReference");
		club.secretary = clubsXML[i].getAttribute("secretary");
		club.disciplineStr = clubsXML[i].getAttribute("disciplineStr");
		club.lat = parseFloat(clubsXML[i].getAttribute("lat"));
		club.lng = parseFloat(clubsXML[i].getAttribute("lng"));
		club.description = clubsXML[i].getAttribute("description");
		var point = new GLatLng(club.lat, club.lng);
		var tempMarker = createMarker(point, club);
		club.marker = tempMarker;

		map.addOverlay(tempMarker);
		clubs.push(club);
	}
	if($('county').value!=''){
	countyChange();
	}
	if($('clubIdHid').value != '') {
		var tempArray = clubs.filter(compareId);
		showDetails(tempArray[0]);
		if(tempArray[0].lat != 0 && tempArray[0].lng != 0) {
			map.setZoom(10);
			map.panTo(new GLatLng(tempArray[0].lat, tempArray[0].lng));
		} else {
			map.setZoom(5);
			map.panTo(new GLatLng(53.981935, -2.900391));
		} 
	}
}
