var displayedSuggestionIds = [];

function goToMarker(event) {
	jQuery(this).parent().find(".address_id").each(function (index) {
		centerMapAroundMarker(userMap, venueMarkers[jQuery(this).attr('value')]);
	});	
}

function getMarkerForPostcode(map, postcode)
{
	var result;

	jQuery.ajax({
		url: "/session/location/ajax/location_of_town.php",
		async: false,
		type: "post",
		data: ({town: postcode}),
		dataType: "json",
		success:	function(data) {
						if (data.error == true) result = data;
						else result = markLocation(map, data.lat, data.lng, postcode, "blue");
					}
	});
	
	return result;
}

function markPostcode(map, postcode)
{
	var geocoder = new google.maps.Geocoder();

	geocoder.geocode( { 'address': postcode}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.panTo(results[0].geometry.location);
			map.setZoom(6);        
			var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
        });
		} else {
			
		}
	});
}

function markLocation(map, lat, lng, title, iconColour)
{
	var position = new google.maps.LatLng(lat, lng);

	// Create our "tiny" marker icon
	var image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/" + iconColour + "-dot.png";
	                
	var marker = new google.maps.Marker({
		map: map, 
		icon: image,
		position: position,
		title: title
	});

	return marker;
}


function centerMapAroundMarker(map, marker)
{
	map.setZoom(15);
	map.panTo(marker.getPosition(), true, true);
}

function initializeMap() 
{
	var latlng = new google.maps.LatLng(53.467, -2.233);
    var myOptions = {
      zoom: 6,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);


    return map;
}

function getMilesBetweenMarkers(marker1, marker2)
{
	var distance = google.maps.geometry.spherical.computeDistanceBetween(marker1.getPosition(), marker2.getPosition());
	return distance / 1600;
}

function filterVenuesWithinMileRadius(center, mileRadius, markers, distances)
{
	var distance;
	var filteredVenues = new Array();
	for (i = 0; i <= markers.length; i++) 
	{
		if (markers[i] instanceof google.maps.Marker)
		{
			distance = getMilesBetweenMarkers(center, markers[i]);
			if (distance <= mileRadius) {
				filteredVenues[i] = markers[i];
				distances[i] = distance; 
			}
		} 
	}

	return filteredVenues;
}

function hideMarkers(markers)
{
	for (i = 0; i <= markers.length; i++) {
		if (markers[i] instanceof google.maps.Marker) {
			markers[i].setMap(null);
		}
	} 
}

function showMarkersOnMap(map, markers)
{
	for (i = 0; i <= markers.length; i++) if (markers[i] instanceof google.maps.Marker) markers[i].setMap(map); 
}



function updateResultsTable(markers, distances)
{
	jQuery("#choir_list").html("");
	
	return appendToResultsTable(markers, distances);
}

function appendToResultsTable(markers, distances)
{
	var choirCount = 0;
	var sortedAddressIds = sortAddressIdsByDistances(distances);
	
	for (i = 0; i < sortedAddressIds.length; i++)
	{
		var resultLine = "";
		if (choirs[sortedAddressIds[i]] != undefined) 
		{ 
			for (j = 0; j <= choirs[sortedAddressIds[i]].length; j++)
			{
				if (choirs[sortedAddressIds[i]][j] != undefined)
				{
					choirCount++;
					
					var distance = (distances[sortedAddressIds[i]] > 10) ? 
							Math.round(distances[sortedAddressIds[i]] + 0.5) : 
								Math.round(distances[sortedAddressIds[i]] * 10) / 10;
					
					resultLine = "<div class=\"choir_name\">" + choirs[sortedAddressIds[i]][j].choir_name + " "
					+ choirs[sortedAddressIds[i]][j].choir_type_label + 
					(choirs[sortedAddressIds[i]][j].choir_type_description != "" ? "<br>(" + choirs[sortedAddressIds[i]][j].choir_type_description + ")" : "")
					+ "</div>"
						 
						+ "<div class=\"choir_distance\">" + distance + " miles </div>" 
						+ (choirs[sortedAddressIds[i]][j].incomplete == 't' ? "<div class=\"join_taster\"><div class=\"waiting_list\"><a href='#' class=\"waiting_list_button\">Join the waiting list for this choir</a></div></div>"
						: "<div class=\"join_taster\"><div class=\"join\"><a href='#' class=\"join_button\">Join</a></div><div class=\"taster\"><a href='#' class=\"taster_button\">Book taster</a></div></div>")
						+ (choirs[sortedAddressIds[i]][j].incomplete != 't' ? "<div class=\"choir_time\">" + choirs[sortedAddressIds[i]][j].defaultRehearsalDay + "<br/>"
                        + choirs[sortedAddressIds[i]][j].defaultRehearsalTime + "</div>" : "")
						+ (choirs[sortedAddressIds[i]][j].incomplete == 't' ? "<div class=\"choir_address\">" + choirs[sortedAddressIds[i]][j].tba_message + "</div>"
						: "<div class=\"choir_address\">" + address[sortedAddressIds[i]] + "</div>");
					
					jQuery("#choir_list").append("<div class=\"choir_item\"><input class=\"address_id\" type=\"hidden\" value=\"" + sortedAddressIds[i] + "\">" + 
							"<input class=\"choir_id\" type=\"hidden\" value=\"" + choirs[sortedAddressIds[i]][j].choir_id + "\" />" +
							resultLine + 
							"</div>");
				}
			}
		}
	}
	
	return choirCount;
}

function updateSuggestionsTable(markers)
{
	jQuery("#suggestion_list").html("");
	
	appendToSuggestionsTable(markers);
}

function appendToSuggestionsTable(markers)
{
	displayedSuggestionIds = [];
	for (i = 0; i < markers.length; i++) 
	{
		var resultLine = "";
		if (markers[i] != undefined)
		{
		    var telephone_number = suggestionsData[i].telephone;
		    if (telephone_number == "") {
		        telephone_number = "&nbsp;";
            }

			resultLine = "<div class=\"name\">" + suggestionsData[i].firstname + " " + suggestionsData[i].lastname + "</div>" 
				+ "<div class=\"under18\">" + (suggestionsData[i].under18 == "t" ? "Yes" : "No") + "</div>"
				+ "<div class=\"telephone\">" + telephone_number + "</div>"
				+ "<div class=\"town\">" + suggestionsData[i].town + "</div>" 
				+ "<div class=\"county\">" + suggestionsData[i].county + "</div>";
			
			jQuery("#suggestion_list").append("<div class=\"suggestion_item\">" + 
					resultLine + 
					"<div><input name=\"show[" + suggestionsData[i].choir_suggestions_id + "]\" checked=\"checked\" class=\"show\" type=\"checkbox\" value=\"" + i + "\" /></div>" +
					"<div><input name=\"remove[" + suggestionsData[i].choir_suggestions_id + "]\" class=\"delete\" type=\"checkbox\" value=\"" + i + "\" /></div>" +
					"<div class=\"email_value\">" + suggestionsData[i].email + "</div>" +
					"<div class=\"postcode\">" + suggestionsData[i].postcode + "</div>" +
					"</div>");
			jQuery(".suggestion_item:odd").addClass("suggestion_odd");
			
			displayedSuggestionIds[i] = suggestionsData[i].choir_suggestions_id;
		}
	}

	jQuery("#suggestion_list input.show").click(function (event) {
		if (jQuery(this).attr('checked') == true)
		{
			suggestions[jQuery(this).val()].setMap(userMap);
			displayedSuggestionIds[displayedSuggestionIds.length] = suggestionsData[jQuery(this).val()].choir_suggestions_id; 
		}
		else
		{
			suggestions[jQuery(this).val()].setMap(null);
			
			var i = 0;
			while(i < displayedSuggestionIds.length && displayedSuggestionIds[i] != suggestionsData[jQuery(this).val()].choir_suggestions_id) i++;
			if (i < displayedSuggestionIds.length)
			{
				displayedSuggestionIds.splice(i, 1);
			}
		}
	});
}

function sortAddressIdsByDistances(distancesToSort)
{
	var distances = distancesToSort.slice(0);
	var sortedKeys = new Array();
	var sortedKeysIndex = 0;

	do 
	{
		var minValuesKey = null;
		for (i = 0; i <= distances.length; i++)
		{
			if (distances[i] != undefined)
			{
				if (minValuesKey == null || distances[i] < distances[minValuesKey]) 
				{
					minValuesKey = i;
				}
			}
		} 
		if (minValuesKey != null) 
		{
			distances[minValuesKey] = undefined;
			sortedKeys[sortedKeysIndex++] = minValuesKey;
		}
	} while (minValuesKey != null);

	return sortedKeys;
}
