$(document).ready(
	function(){ 
		getChurchesByDenomination(null);
		var sortedByDenomination = true;
		
		$(".top").live("click", 
			function() {
				location.href = '#top';
			}
		);
		
		$(".denomination").click(
			function() {
				if (!sortedByDenomination) {
					getChurchesByDenomination($(this).attr("href"));
					sortedByDenomination = true;
				}
			}
		);		
		
		$(".city").click(
			function() {
				if (sortedByDenomination) {
					getChurchesByCity($(this).attr("href"));
					sortedByDenomination = false;
				}
			}
		);
		
		function getChurchesByCity(anchor) {
			$.getJSON("js/php/getChurchesByCity.php", 
				function(data) {
					showChurches(data, anchor);
				}
			);
		}		
		
		function getChurchesByDenomination(anchor) {
			$.getJSON("js/php/getChurchesByDenomination.php", 
				function(data) {
					showChurches(data, anchor);
				}
			);
		}
		
		function showChurches(data, anchor) {
			var html = "";
			$.each(data, function(){
				html += "<a name='" + this[0] + "'></a>";
				html += "<h3>" + this[0] + "</h3>";
				$.each(this[1], function() {
					html += "<strong>" + this.name + "</strong> (" + this.pastor + ")";
					if (this.address) html += "<br>" + this.address; 
					if (this.phone) html += " - " + this.phone;
					if (this.email) html += "<br><a href='mailto:>" + this.email + "'>" + this.email + "</a>";
					if (this.url) html += "<br><a href='" + this.url + "' target='_blank'>" + this.url + "</a>"
					html += "<br><br>";
				});
				html += "<a class=top href='#top'>- Back to Top -</a>";
			});
			$("div#content div").html(html);
			if (anchor) location.href = anchor;
		}
	}
);
