/* 
 * Filename - map.js
 * Author   - R. Zupko II
 *  
 * Purpose  - 
 */
   
// The main map that is created for use by the page
var map;

// Geocoder that is used to preform searches
var geocoder;

// addLenderMarker - Add a marker to the map for a lender with the message 
// 	provided at the point indicated.
// message         - The message string to add.
// point           - The location to put the lender's information at.
function addLenderMarker(message, point) {
	// Prepare the icon for the marker
	var iconImage = new GIcon(G_DEFAULT_ICON);
	iconImage.image = iconLeader;
	// Prepare the marker
	var marker = new GMarker(point, { icon:iconImage })			
	marker.value = message;	
	// Set the event for the marker
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(marker.value);});
	// Set an event to clear the events for the marker when it is destoryed
	GEvent.addListener(marker, "remove", function() {
		GEvent.clearListeners(marker);});
	// Show it on the map
	map.addOverlay(marker);		
}

// addLenders - Process the XML provided and add the lenders to the map, 
//	grouped by their location.
// xml        - An XML document containing the lenders grouped by location.
function addLenders(xml) {
	$(xml).find("location").each(
		function() {
			// Prepare the lender whereabouts for the geocoder search
			var whereabouts = this.getAttribute("whereabouts");
			var country = this.getAttribute("country");			
			// Prepare the beginning of the message
			var message = "<em>" + whereabouts + ", " + country + "</em><hr />" +
						  "<ul style=\"text-align: left;\">";
			// Process all of the lenders			
			$(this).find("lender").each(
				function() {
					var name = $(this).find("name").text();
					var id = $(this).find("uid").text();
					message += 
						"<li>" + 
						"<a href=\"" + $(this).find("link").text() + "\" title=\"" + name + "\" target=\"_blank\">" + name  + "</a> " +
						"<a href=\"#\" title=\"View Loans\" onclick=\"searchLender('" + id + "')\">[Loans]</a>" +
						"</li>";
					status = $(this).find("status").text();
				});
			message += "</ul>";
			// If whereabouts where not proivded, just directly to trying for the country
			if (whereabouts === null) {
				whereabouts = "country:" + country;
			}
			// Don't show unknown, i.e. anonymous, lenders at this time
			if (country !== "UNKNOWN") {
				// Preform the search on the whereabouts
				geocoder.getLatLng(whereabouts,
					function(point) {
						if (!point) {
							geocoder.getLatLng("country:" + country,
								function(point) {
									if (point) {
										addLenderMarker(message, point);
									}
								});
						} else {
							addLenderMarker(message, point);
						}
					});
			}
		});		
}

// addLoans - Process the XML provided and add the loans to the map grouped
//	by their location.
// xml      - An XML document containing the loans grouped by location.
function addLoans(xml) {
	$(xml).find("location").each(
		function() {
			// This variable will be used for the maker icon
			var status;
			// On rare occasions, the whereabouts will have a leading comma, remove it if it is there
			var whereabouts = this.getAttribute("whereabouts");
			if (whereabouts.indexOf(",") == 0) {
				whereabouts = whereabouts.substring(1);
			}
			// Prepare the beginning of the message
			var message = "<em>" + whereabouts + "</em><hr />" +
						  "<div style=\"color: black; text-align: left;\">";
			// Process all of the loans			
			$(this).find("loan").each(
				function() {
					var name = $(this).find("name").text();
					var id = $(this).find("id").text();
					message += 
						"<a href=\"" + $(this).find("link").text() + "\" title=\"" + name + "\" target=\"_blank\">" + name  + "</a> " +
						"<a href=\"#\" title=\"View Lenders\" onclick=\"searchLendee('" + id + "')\">[Lenders]</a>" +
						" - " + $(this).find("status").text() + "<br />" +
						$(this).find("activity").text() + " - " +
						$(this).find("use").text() + "<br /><br />";
					status = $(this).find("status").text();
				});
			// Finish off the message
			message += "</div>";
			// Prepare the icon for the marker
			var iconImage = new GIcon(G_DEFAULT_ICON);
			iconImage.image = getLoanIcon(status);
			// Prepare the marker
			var point = new GLatLng(this.getAttribute("lat"), this.getAttribute("long"));
			var marker = new GMarker(point, { icon:iconImage })			
			marker.value = message;
			// Set the event for the marker
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(marker.value);});
			// Set an event to clear the events for the marker when it is destoryed
			GEvent.addListener(marker, "remove", function() {
				GEvent.clearListeners(marker);});
			// Show it on the map
			map.addOverlay(marker);	
		});
}

// getLoanIcon - Return the correct icon type based upon the loan status.
// status      - The current status of the loan.
// Returns     - The URL of the icon to to use.
function getLoanIcon(status) {
	switch (status) {
		case "fundraising": return iconFundrasing;
		case "defaulted": return iconDefaulted;
		case "refunded": return iconRefunded;
	}
	return iconLoan;
}

// getNewestLoans - Make an AJAX call to the server to get the newest Kiva loans.
function getNewestLoans() {
	// Show the waiting icon
	document.getElementById("working").style.display = "inline";		
	// Make the call of the newest loans
	$.ajax({
		url: kivaServer + newestLoans,
		success: onNewestLoans,
		error: onError});
}

// getRecentActions - Make an AJAX call to the server to get the most recent 
//	Kiva actions
function getRecentActions() {
 	// Show the waiting icon
	document.getElementById("working").style.display = "inline";		
	// Make the call of the newest loans
	$.ajax({
		url: kivaServer + recentActions,
		success: onRecentActions,
		error: onError});
}

// initialize - This function is called when the page is done loading and loads
//	the basic map to be displayed. 
function initialize() {
    if (GBrowserIsCompatible()) {
		// Resize the map div
		resize();
		// Load the map
		map = new GMap2(document.getElementById("map"));
		// Load the geocoder
		geocoder = new GClientGeocoder();
		// Set the center
        map.setCenter(new GLatLng(42, 0), 2);
	    map.setUIToDefault();
		// Add the legend control
		map.addControl(new KivaLegend());
		// Get the newest loans
		getNewestLoans();
	}
}

// onError  - Called by jQuery when an error occures.
// response - An XML document with error information.
function onError(response) {
	alert("An expected error occured while preforming the operation: \n" + 
		  "Response Text: " + response.responseText + "\n" +
		  "Message: " + response.Message);
}

// onLendeeDetail - Called when we get detail information back from the server,
//	display the loans and details for the lender provided.
// response        - An XML document with a lender's details and loans.
function onLendeeDetail(response) {
	// Did we get any results back?
	if ($(response).find("lender").text() === "") {
		alert("The server failed to return results for the search string.");
		// Clear the waiting icon
		document.getElementById("working").style.display = "none";	
		return;
	}
	// Clear any makers already on the map
	map.clearOverlays();
	// Add the loan marker to the map, note that it takes the same from
	// a list of loans
	addLoans($(response).find("loans"));
	// Add the lender markers to the map
	addLenders($(response).find("lenders"));	
	// Clear the waiting icon
	document.getElementById("working").style.display = "none";	
}

// onLenderDetail - Process the information returned by the server for the 
//	lender's details.
// response       - An XML document containing the lenders detailed information.
function onLenderDetail(response) {
	// Did we get any results back?
	if ($(response).find("lender").text() === "") {
		alert("The server failed to return results for the search string.");
		// Clear the waiting icon
		document.getElementById("working").style.display = "none";	
		return;
	}	
	// Clear any makers already on the map
	map.clearOverlays();
	// Prepare the lender whereabouts for the geocoder search
	var whereabouts = $(response).find("whereabouts").text();
	var country = $($(response).find("lender")).find("country").text();
	// Prepare the lender message
	var name = $($(response).find("lender")).find("name").text();
	var message = "<a href=\"" + kivaLenderUrl + $($(response).find("lender")).find("uid").text() + 
		"\" text=\"" + name + "\" target=\"_blank\">" + name + "</a>" + 
		"<hr /><div style=\"color: black; text-align: left;\">";
	if (whereabouts !== "") {
		message += "Whereabouts: " + whereabouts + "<br />";
	}
	message += "Country: " + country + "<br />";
	var joined = $($(response).find("lender")).find("joined").text();
	message += "Joined: " + joined.substr(0, joined.indexOf("T")) + "<br />";
	message += "Total Loans: " + $($(response).find("lender")).find("totalLoans").text() + "<br />";
	// Preform the search
	geocoder.getLatLng(whereabouts,
		function(point) {
			if (!point) {
				geocoder.getLatLng("country:" + country,
					function(point) {
						if (point) {
							addLenderMarker(message, point);
						}
					});
			} else {
				addLenderMarker(message, point);
			}
		});
	// Add the loan makers to the map
	addLoans($(response).find("loans"));
	// Clear the waiting icon
	document.getElementById("working").style.display = "none";	
}

// onNewestLoans - Process the information returned by the server for the newest 
//	Kiva loans.
// response      - An XML document containing the newest loans detail.
function onNewestLoans(response) {
	// Clear any markers already on the map
	map.clearOverlays();
	// Add the markers to the map
	addLoans(response, null);
	// Clear the waiting icon
	document.getElementById("working").style.display = "none";	
}

// onRecentActions - Called when we get the recent loan information back from 
// 	the server, display the loans and lenders on the map.
// response        - An XML document with loans and lenders.
function onRecentActions(response) {
	// Clear any makers already on the map
	map.clearOverlays();
	// Add the loan markers
	addLoans($(response).find("loans"));
	// Add the lender markers to the map
	addLenders($(response).find("lenders"));	
	// Clear the waiting icon
	document.getElementById("working").style.display = "none"
}

// resize - Resize the map to ensure it properly fills the page.
function resize() {
	var search = document.getElementById("search");
	var div = document.getElementById("map");
	// Expand the size of the map
	div.style.height = 
		(document.body.clientHeight - search.clientHeight - 32) + "px";
}

// searchLender - Make sure the lender id makes sense and call the server if it does.
// lender       - The lender id string provided by the user.
function searchLender(lender) {
	// Where we given something to work with?
	if (lender === "") {
		alert("You must enter a lender's id.");
	} else {
		// Show the waiting icon
		document.getElementById("working").style.display = "inline";		
		// Make the call ot the server
		$.ajax({
			url: kivaServer + lenderDetail + "&id=" + lender,
			success: onLenderDetail,
			error: onError});
	}
}

// searchLendee - Make sure the lendee id makes sense and call the server if it does.
// lender       - The lendee id string provided by the user.
function searchLendee(lendee) {
	// Where we given something to work with?
	if (lendee === "") {
		alert("You must enter a lendee's id.");
	} else {
		// Show the waiting icon
		document.getElementById("working").style.display = "inline";		
		// Make the call ot the server
		$.ajax({
			url: kivaServer + lendeeDetail + "&id=" + lendee,
			success: onLendeeDetail,
			error: onError});
	}
}
