/*	LIVE FILTER JAVASCRIPT APPLICATION
 *	Update: March 29, 2009, granroth@gmail.com
 *	Live Filter UI pattern described at http://ui-patterns.com/pattern/LiveFilter
 *	
 *	
 */

// filterRanges requires jQuery

function filterRanges()
{
	var contentNodes = $("div.rangeInfo");
	var inputValue = $('#filterText').val();
	
	// If input field is empty, make sure each range is visible.
	if(inputValue.length == 0){
		contentNodes.each(
			function()
			{
				$(this).show();
			}
		);
	}else{
	// Otherwise, there is a value in the input field, so step through each range, 
	// get the content texts and compare it with the value from the input field.
		contentNodes.each(
			function()
			{
				testTarget = '';
				filterable = $(this).find('.filterable');
				for(i=0; i<filterable.length; i++){
					testTarget = testTarget + ' ' + filterable[i].innerHTML;	
				}
				if(filterTest(inputValue, testTarget)){
					$(this).show();
				}else{
					$(this).hide();
				}
			}
		);
	}
}



// testValue is the value of the form field
// testTarget is the string that testValue is compared against
function filterTest(testValue, testTarget)
{
	var testTarget = testTarget.toLowerCase();
	var testValue = testValue.toLowerCase();
	if(String(testTarget).indexOf(testValue) > -1){
		return true;
	}else{
		return false;
	}
}





// Count the current ranges showin and display after the input field
// Text: Showing n ranges.
function filterFeedback(){	
	// Count the number of TRs and create a message.
	var numRows = $("div.rangeInfo:visible").length - $("#feedbackRow:visible").length;
	var feedbackText = "Showing "+numRows+" ranges.";
	if(numRows == 1){
		feedbackText = "Showing "+numRows+" range.";
	}	
	$("#filterFeedback").text(feedbackText);

	// Add in a div when there are none to see. Could probably be a separate function.
	if($("#feedbackRow").length == 0){
		$("div#rangeList").append("<div class=\"rangeInfo mapped\" id=\"feedbackRow\"><h3></h3><div>No ranges match your search.<\/div><\/div>");
	}
	$("#feedbackRow").hide();
	if(numRows == 0){
		$("#feedbackRow").show();
	}	

}
