//Kiva.org plugin AJAX methods
//Daniel Posch
//Gumball Capital
//2009.2
//
//Dependencies: jQuery
//This AJAX code uses the Kiva API to dynamically fill in loan details for the
//loan views in Gumball's Kiva.org Wordpress plugin and Facebook application.
//It can load loan descriptions, Google maps (from geo data) and loan journal entries.

var PLUGIN_PATH = "http://gumballfund.org/site/wp-content/plugins/kivaorg-widget";
var KIVA_API_URL = PLUGIN_PATH + "/proxy.php?url=" + encodeURIComponent("http://api.kivaws.org/v1");
function loadLoanDescription(descDiv, loanId){
	//alert('desc: ' + descDiv + ', url' + KIVA_API_URL + "/loans/" + loanId + ".json");
	var res = $.ajax({
			type:'GET',
			url: KIVA_API_URL + "/loans/" + loanId + ".json",
			dataType: "json",
			success: function(res){
				var loan = res.loans[0];
				var html = "";
				for(var lang in loan.description.texts){ //lang is a language code like 'en', 'fr', etc
					var desc = loan.description.texts[lang]; //loan description
					html += "<div>" + desc + "</div>";
				}
				if($.trim(html).length == 0)
					html += '<div>No journal entries found</div>';
				$(descDiv).html(html);
				//closure on descDiv
			}
	}); 
	//alert(res);
}
function loadJournalEntries(journalDiv, loanId){
	//alert('journal: ' + journalDiv + ', id ' + loanId);
	 $.ajax({
			url: KIVA_API_URL + "/loans/" + loanId + "/journal_entries.json",
			dataType: "json",
			success: function(res){
				var entries = res.journal_entries;
				var html = "";
				for(var ix in entries){
					var entry = entries[ix];
					html += "<div style='font-weight:bold'>" + entry.subject + "</div>";
					html += "<div>" + entry.body + "</div>";
					html += "<div style='font-style:italic'>posted by " + entry.author + " on " + new Date().setISO8601(entry.date).toDateString() + "</div>";
				}
				if($.trim(html).length == 0)
					html += '<div>No journal entries found</div>';
				$(journalDiv).html(html);
				//closure on journalDiv
			}
	}); 
}
function loadGoogleMapInner(mapDiv, location, lat, lon){
	if (GBrowserIsCompatible()) {
		var zoom = 6;
		var map = new GMap2(mapDiv, { size: new GSize(640,480) });
		//map.setUIToDefault();
		var center = new GLatLng(lat, lon);
		map.setCenter(center, zoom);
		map.setMapType(G_HYBRID_MAP);
		map.addControl(new GSmallMapControl());

		//add info window and marker
		map.addOverlay(new GMarker(center));
		var bubble = document.createElement("div");
		bubble.innerHTML = "<h1 style='font-size:18px'>" + location + "</h1>";
		map.openInfoWindow(center, bubble);
	}
	else $(mapDiv).html("Sorry, your browser does not support Google Maps.");
}
//asynchronously loads a Google map, dynamically loading the google map javascript library first if this is the first time
function loadGoogleMap(mapDiv, location, lat, lon){
	//alert('map: ' + location + ' at coordinates ' + lat + ', ' + lon);
	//var apiKey = 'ABQIAAAAnjIM2UjeUNXIyJE5JVYdrhRYmFLZvnd1UIvyV5IXgGkXahwXeBRFIr60AEM6IYtQu8k-MPxgW4zgag';
	//if(typeof(GMap2) == "undefined") //google maps api is not loaded
	//{
	//	$.getScript("http://maps.google.com/maps?file=api&v=2&key=" + apiKey + "&sensor=false",
	//		function(){
	//			loadGoogleMapInner(mapDiv, location, lat, lon);
	//		});
	//}
	//else
		loadGoogleMapInner(mapDiv, location, lat, lon);
}
//(synchronously) inserts a Google map iframe into 'mapDiv'. 'coords' is a string in the form "lat long"
function loadGoogleMapFrame(mapDiv, location, lat, lon){
	//alert('map: ' + location + ' at coordinates ' + lat + ', ' + lon);
	var apiKey = 'ABQIAAAAnjIM2UjeUNXIyJE5JVYdrhRYmFLZvnd1UIvyV5IXgGkXahwXeBRFIr60AEM6IYtQu8k';
	var encodedMapUrl = "http://maps.google.com/maps?q=" + 
		encodeURIComponent(location) + "&amp;ll=" + 
		lat + "," + lon + "&amp;ie=UTF8&amp;z=5&amp;output=embed&amp;key=" + apiKey;
	var html =
		"<iframe width='425' height='350' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='" +
		encodedMapUrl + "'></iframe><br /><small><a href='" + 
		encodedMapUrl + "' style='color:#0000FF;text-align:left'>View Larger Map</a></small>";
	$(mapDiv).html(html);
}

$(document).ready(function(){
	$('.toggler').click(function(){
			var vessel = $(this).next();
			var parent = $(this).parent();
			if(vessel.hasClass('loaded') == 0){ //not loaded yet
				if($(this).hasClass('description'))
					loadLoanDescription(vessel[0], parent[0].attributes['loanId'].value);
				else if($(this).hasClass('journalEntries'))
					loadJournalEntries(vessel[0], parent[0].attributes['loanId'].value);
				else if($(this).hasClass('map'))
					loadGoogleMap(vessel[0], parent[0].attributes['location'].value, parent[0].attributes['lat'].value, parent[0].attributes['lon'].value);
				vessel.addClass('loaded');
				//vessel.stop(true); //stops the slideDown animation
			}
		});
	});