var churches;

// Start function when DOM has completely loaded 
$(document).ready(function(){ 
	
	$("div.popup_card").hide();
	initData();
	
});

function initData() {
	$.getJSON("churches.js",
		function(json) {
			churches = json.churches;
			$.each(churches, function (i, item) {
				// make sure that if a certain element in the each listing isn't defined to set it to ""
				item.meetingaddress.line1 = item.meetingaddress.line1 || "";
				item.meetingaddress.line2 = item.meetingaddress.line2 || "";
				item.meetingaddress.city = item.meetingaddress.city || "";
				item.meetingaddress.state = item.meetingaddress.state || "";
				item.meetingaddress.zip = item.meetingaddress.zip || "";
				item.meetingaddress.country = item.meetingaddress.country || "";
				item.mailingaddress.line1 = item.mailingaddress.line1 || "";
				item.mailingaddress.line2 = item.mailingaddress.line2 || "";
				item.mailingaddress.city = item.mailingaddress.city || "";
				item.mailingaddress.state = item.mailingaddress.state || "";
				item.mailingaddress.zip = item.mailingaddress.zip || "";
				item.mailingaddress.country = item.mailingaddress.country || "";
				item.phone = item.phone || "";
				item.fax = item.fax || "";
				item.email = item.email || "";
				item.site = item.site || "";
				item.pastors = item.pastors || [];
				item.latlng = item.latlng || [0,0];
			});
			initBinding();
	});
}

function filterChurches(searchString, confString, stateString) {
	
	// first make all lowercase for ease of comparison and to avoid case sensitivity
	searchString = searchString.toLowerCase();
	confString = confString.toLowerCase();
	stateString = stateString.toLowerCase();
	var churchCount = 0;
	var searchSetting = 0;
			
	if (searchString != "" && confString == "" && stateString == "") {
		// just search box has data
		searchSetting = 0;
	} else if (searchString != "" && confString != "" && stateString == "") {
		// both search field and conference string have data, but no state
		searchSetting = 1;
	} else if (searchString == "" && confString == "" && stateString == "") {
		// search, conference, and state are blank, return all churches
		searchSetting = 2;
	} else if (searchString == "" && confString != ""  && stateString == "") {
		// just conference has data
		searchSetting = 3;
	} else if (searchString == "" && confString == ""  && stateString != "") {
		// just state has data
		searchSetting = 4;
	} else if (searchString == "" && confString != ""  && stateString != "") {
		// just conference and state has data, but no search
		searchSetting = 5;
	} else if (searchString != "" && confString == ""  && stateString != "") {
		// just search and state has data, but no conference
		searchSetting = 6;
	} else if (searchString != "" && confString != ""  && stateString != "") {
		// search, conference, and state all have data
		searchSetting = 7;
	}
			
			
	$.each(churches, function(i, item) {
				
		var churchName = item.name;
		var churchConf = item.conf;
		var churchLoc = item.meetingaddress.city;
		var churchState = item.meetingaddress.state;
		var churchPostal = item.mailingaddress.state;
		
		
		switch(searchSetting) {
			
		case 0:
			if (churchName.toLowerCase().indexOf(searchString) != -1) {
				$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );
				churchCount++;
			}
			break;
		
		case 1:
			if (churchName.toLowerCase().indexOf(searchString) != -1 && churchConf.toLowerCase() == confString) {
				$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );
				churchCount++;
			}
			break;
		
		case 2:
			$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );
			churchCount++;
			break;
		
		case 3:
			if (churchConf.toLowerCase() == confString) {
				$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );
				churchCount++;
			}
			break;
		
		case 4:					
			if (churchPostal.toLowerCase() == stateString) {
				$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );	
				churchCount++;
			}
			break;
		
		case 5:		
			if (churchConf.toLowerCase() == confString && churchPostal.toLowerCase() == stateString) {
				$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );	
				churchCount++;
			}
			break;
		
		case 6:
			if (churchName.toLowerCase().indexOf(searchString) != -1 && churchPostal.toLowerCase() == stateString) {
				$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );	
				churchCount++;
			}
			break;
		
		case 7:
			if (churchName.toLowerCase().indexOf(searchString) != -1 && churchConf.toLowerCase() == confString && churchPostal.toLowerCase() == stateString) {
				$("#listings").append( BuildChurchHTML(i, churchName, churchLoc, churchState) );	
				churchCount++;
			}
			break;
		}
		
	
	});
			
	if ($("#listings").is(":empty")) {
		$("#listings").append('<li class="no_results">No results</li>');
	}
	
	$("input[name='church_search']").removeClass("loading");
		
	$("li.church_listing").click(function() {
		var idNum = $(this).attr("id");
		BuildFullCard(idNum);
		$("div.popup_card").fadeIn("fast");
		
		var popup_top = 75 + $(window).scrollTop();    // places the popup 75 px from the top		
		$('div.popup_inner').css({'top':popup_top});
	} );
	
	return churchCount;
}
 
 
function BuildChurchHTML(churchID, churchName, churchLoc, churchState){
	output = '';
	output += '<li class="church_listing" id=' + churchID + '><a href="#" onClick="return false;">';
	output += churchName + ' ';
	output += '</a><span class="listing_location">' + churchLoc + ', ';
	output += churchState + '</span>';
	output += '</li>';
	return output;
}

function BuildFullCard(idNum) {
	
	var fullHTML = '';
	$("div.popup_inner div.popup_top").html("");
			
	var googleMapLink = 'http://maps.google.com/?q=' + churches[idNum].name.split(' ').join('+') +'@'+churches[idNum].latlng[0]+'+'+churches[idNum].latlng[1];
					
	fullHTML += '<h1>' + churches[idNum].name + '</h1>';
	fullHTML += '<span class="conference">' + churches[idNum].conf + ' Conference</span>';
	fullHTML += '<div class="card_section">';
	if (churches[idNum].latlng[0] != 0) { fullHTML += '<h2 class="meeting-h2"><a href="'+googleMapLink+'" class="google_link"><img src="google_pin.png" /> View on map</a>Meeting Place</h2>'; } else { fullHTML += '<h2>Meeting Place</h2>'; }
	fullHTML += churches[idNum].meetingaddress.line1;
	if (churches[idNum].meetingaddress.line2 != "") { fullHTML += '<br />' + churches[idNum].meetingaddress.line2; }
	fullHTML += '<br />' + churches[idNum].meetingaddress.city + ', ' + churches[idNum].meetingaddress.state + ' ' + churches[idNum].meetingaddress.zip;
	if (churches[idNum].meetingaddress.country != "") { fullHTML += '<br />' + churches[idNum].meetingaddress.country + '</div>'; } else { fullHTML += '</div>'; }
	fullHTML += '<div class="card_section"><h2>Mailing Address</h2>';
	fullHTML += churches[idNum].mailingaddress.line1;
	if (churches[idNum].mailingaddress.line2 != "") { fullHTML += '<br />' + churches[idNum].mailingaddress.line2; }
	fullHTML += ' <br />' + churches[idNum].mailingaddress.city + ', ' + churches[idNum].mailingaddress.state + ' ' + churches[idNum].mailingaddress.zip;
	if (churches[idNum].mailingaddress.country != "") { fullHTML += '<br />' + churches[idNum].mailingaddress.country + '</div>'; } else { fullHTML += '</div>'; }
	fullHTML += '<div class="card_separator"></div>';
	fullHTML += '<div class="card_section short"><h2>Phone</h2>' + churches[idNum].phone + '</div>';
	fullHTML += '<div class="card_section short"><h2>Fax</h2>' + churches[idNum].fax + '</div>';
	fullHTML += '<div class="card_section short"><h2>Email</h2><a href="mailto:' + churches[idNum].email + '">' + churches[idNum].email + '</a></div>';
	fullHTML += '<div class="card_section short"><h2>Website</h2><a href="http://' + churches[idNum].site + '">' + churches[idNum].site + '</a></div>';
	fullHTML += '<div class="card_section pastors"><h2>Church Leadership</h2>';
	for (i=0; i<churches[idNum].pastors.length;i++) {
		fullHTML += churches[idNum].pastors[i].name + ', <em>' + churches[idNum].pastors[i].title + '</em><br />';	
	}
	fullHTML += '</div>';
	fullHTML += '<div id="close"><a id="closebutton" href="#"> </a></div>';
	
	$("div.popup_inner div.popup_top").append(fullHTML);
	
	var maskHeight = 0;
	var maskWidth = 0;
	
	maskHeight = $(document).height();
	maskWidth = $(document).width();
	
	$("div.closemask").css({'width':maskWidth, 'height':maskHeight, 'opacity':0, 'display':'block'});
	
	$("div.closemask").fadeTo(350, 0.25);
	
	$("#closebutton").click(function() {
		$(".popup_card").fadeOut("fast");
		$(".closemask").fadeTo(350, 0, function() {
			$(".closemask").css({'display':'none'});
		});
		return false;
	});
				
	$("#closebutton").click(function() {
		$("div.popup_card").fadeOut("fast");
		$("div.closemask").fadeTo(350, 0);
		return false;
	} );
}

// all of the event bindings

function initBinding() {
	
	var lastsearchString = "";
	
	$("#conf_filter").change(function() {
		var state_filter = $("#state_filter option:selected").val();
		var conf_filter = $("#conf_filter option:selected").val();
		var search_filter = $("input[name='church_search']").val();
		
		// pass the search data to the handler
		handleSearch(search_filter, conf_filter, state_filter);
	});
	
	$("#state_filter").change(function() {
		var state_filter = $("#state_filter option:selected").val();
		var conf_filter = $("#conf_filter option:selected").val();
		var search_filter = $("input[name='church_search']").val();
		// pass the search data to the handler
		handleSearch(search_filter, conf_filter, state_filter);
	});
	
	$("input[name='church_search']").keyup(function() {
		var state_filter = $("#state_filter option:selected").val();
		var conf_filter = $("#conf_filter option:selected").val();
		var search_filter = $(this).val();
		
		// only do the search if the stuff in the box has changed
		if (lastsearchString != search_filter) {
			// pass the search data to the handler
			if (typeof t != 'undefined') clearTimeout(t);
			t = setTimeout(handleSearch(search_filter, conf_filter, state_filter), 500);		
		}
		
		lastsearchString = $(this).val();
	} );
	
	$("div.closemask").click(function() {
		$("div.popup_card").fadeOut("fast");
		$("div.closemask").fadeTo(350, 0);
	});
	
	// do some initialization and first search
	$("input[name='church_search']").val("");
	$("#conf_filter").val("Choose conference");
	$("#state_filter").val("Choose state/province");
	
	handleSearch("", "", "");
}



function clearSearch() {
	$("input[name='church_search']").val("");
	$("#search_filter_notice").fadeOut("slow");
	
	$("#listings").empty();
	
	var conf_filter = $("#conf_filter option:selected").val();
	var state_filter = $("#state_filter option:selected").val();
	
	handleSearch("", conf_filter, state_filter);
}



function clearConf() {
	$("#conf_filter").val("Choose conference");
	$("#conf_filter_notice").fadeOut("slow");
	
	$("#listings").empty();
	
	var search_filter = $("input[name='church_search']").val();
	var state_filter = $("#state_filter option:selected").val();

	handleSearch(search_filter, "", state_filter);
}



function clearState() {
	$("#state_filter").val("Choose state/province");
	$("#state_filter_notice").fadeOut("slow");
	
	$("#listings").empty();
	
	var search_filter = $("input[name='church_search']").val();
	var conf_filter = $("#conf_filter option:selected").val();

	handleSearch(search_filter, conf_filter, "");
}


function clearAll() {
	$("#conf_filter").val("Choose conference");
	$("#state_filter").val("Choose state/province");
	$("input[name='church_search']").val("");
	
	$("#listings").empty();
	
	$("#search_filter_notice").fadeOut("slow");
	$("#conf_filter_notice").fadeOut("slow");
	$("#state_filter_notice").fadeOut("slow");
	
	handleSearch("", "", "");
}



function handleSearch(searchString, confString, stateString) {
	
	var filterHeaderToggle = false;
	var churchCount = 0;
	
	$("#listings").empty();
	
	//first, a little data scrub so we know what we're working with
	if (searchString == " ") searchString = "";
	
	if (confString == "Choose conference") confString = "";
	
	if (stateString == "Choose state/province") stateString = "";
	
	
	if (searchString != "") {
		// handle the filter notice for the search terms
		
		if ($("#search_filter_notice").length == 0) { 
			$("div.filters h4").after("<div class='filter_notice' id='search_filter_notice'>containing the term <strong></strong>.<br /> <a href='#' onClick='clearSearch(); return false;'>Clear this filter.</a></div>");
		} else if ($("#search_filter_notice:hidden").length > 0) {
			$("#search_filter_notice").toggle();
		}
		
		$("#search_filter_notice strong").empty();
		$("#search_filter_notice strong").append(searchString);
		$("input[name='church_search']").addClass("loading");
		$("#listings").empty();
		filterHeaderToggle = true;
		
	}
	
	if (confString != "") {
		// handle the filter notice for the conference drop down box
		
		if ($("#conf_filter_notice").length == 0) { 
			$("div.filters h4").after("<div class='filter_notice' id='conf_filter_notice'>in the <strong></strong>&nbsp;conference.<br /> <a href='#' onClick='clearConf(); return false;'>Clear this filter.</a></div>"); 
		} else if ($("#conf_filter_notice:hidden").length > 0) {
			$("#conf_filter_notice").toggle();
		}
		
		$("#conf_filter_notice strong").empty();
		$("#conf_filter_notice strong").append(confString);
		$("#listings").empty();
		filterHeaderToggle = true;
		
	}
	
	if (stateString != "") {
		// handle the filter notice for the state/province drop down box
		
		if ($("#state_filter_notice").length == 0) { 
			$("div.filters h4").after("<div class='filter_notice' id='state_filter_notice'>in <strong></strong>.<br /> <a href='#' onClick='clearState(); return false;'>Clear this filter.</a></div>"); 
		} else if ($("#state_filter_notice:hidden").length > 0) {
			$("#state_filter_notice").toggle();
		}
		
		$("#state_filter_notice strong").empty();
		$("#state_filter_notice strong").append(makeFullState(stateString));
		$("#listings").empty();
		filterHeaderToggle = true;
		
	}
		
			
	if (searchString=="") $("#search_filter_notice").remove();
	if (confString=="") $("#conf_filter_notice").remove();
	if (stateString=="") $("#state_filter_notice").remove();
		
	// send the cleaned up info to actually do the searching
	churchCount = filterChurches(searchString, confString, stateString);
	
	// change the header
	if (filterHeaderToggle) {
		if (churchCount != 1) {
			$("div.filters h4").html("Currently showing " + churchCount + " churches . . .");
		} else {
			$("div.filters h4").html("Currently showing 1 church . . .");
		}
		if ($("#filter_clear").length == 0) {
			$("div.filters div:last").after("<div class='filter_notice last_filter' id='filter_clear'><a href='#' onClick='clearAll(); return false;'>Clear all filters.</a></div>");
		}
	} else {
		$("div.filters h4").html("Currently showing all " + churchCount + " churches");
		$("#filter_clear").remove();
	}
			
}


function makeFullState(stateString) {
	var output = "";
	$("#state_filter option").each(function() {
		if ($(this).attr("value") == stateString) {
			output = $(this).text();
		}
	});
	return output;
}
	 
