/*
University of Pittsburgh
Graduate School of Public Health
People Directory Search JavaScript include
Created: 29 Aug 2007 by Pat Collins <pat@walltowall.com>
Wall-to-Wall Studios, Inc.
*/


// =============
// = Variables =
// =============

// initialize letterCount array with lowercase letters a-z as the keys, zero as the values.
var letterCount = Array();
var otherCount = 0;

var initCount = function(){
	for(var i=97; i<=122; i++) {
		letterCount[ String.fromCharCode(i) ] = 0;
	}
	otherCount = 0;
};
initCount();


var typeThenSearchPause = 600;

$(function(){
	var searchForm = $("#people_search_form");
	
	searchForm.submit(function(){
		$("#people_search_index, #people_search_results, #people_show_all, #people_search_intro").hide();
		$("#people_search_load").html('Searching').show();
		$("#people_search_clear").show();
		$("#people_search_result_title").text('Searching...');
		$.ajax({
			dataType: 'json',
			type: $(this).attr("method").toUpperCase(),
			url: $(this).attr("action"),
			data: $(this).formSerialize(),
			beforeSend: function(obj){ // obj == XMLHttpRequest object.
			},
			error: function(obj, msg, exception){  
				if(obj.status != 200) {
					$("#people_search_load").hide();
					$("#people_search_result_title").text(obj.statusText.toUpperCase() + ' -- Please try again.');
				}
			},
			success: function(data){
				initCount();
				// alert(data);
				// console.log(data);
				$("#people_search_index, #people_search_results, #people_show_all").show();
				$("#people_search_load").hide();
				$("#people_search_result_title").text(data.message);
				$("#people_search_results tr:gt(0)").remove();
				var headerRow = $("#people_search_results tr:last");
				$.each(data.results, function(index, person){
					var letter = person.lastName.charAt(0).toLowerCase();
					var charCode = letter.charCodeAt(0);
					var letterClass = '';
					if(charCode >= 97 && charCode <= 122) {
						letterCount[ letter ]++;
						letterClass = letter;
					}
					else {
						otherCount++;
						letterClass = 'other';
					}
					headerRow.after('<tr class="' + letterClass + '"><td class="name">' + person.lastName + ', ' + person.firstName + '</td><td class="dept">' + person.dept + '</td><td>' + person.phone + '</td><td class="location">' + person.location + '</td><td class="contact email"><a href="mailto:' + person.email + '">email</a></td></tr>');
					headerRow = $("#people_search_results tr:last");
				});

				// other
				if(otherCount > 0) {
					$("#label_0-9").children("a").addClass("enabled");
				}

				// letters
				$("#people_search_index").children("li:gt(2)").children("a").removeClass("enabled").end().each(function(){
					if(typeof($(this).attr("id")) != 'undefined'){
						var letter = this.id.split('_')[1].toLowerCase();
						if(parseInt(letterCount[letter]) > 0) {
							$(this).children("a").addClass("enabled");
						}
					}
				});
			},
			timeout: 10000 // ten seconds
		});
		return false; // don't actually submit the form synchronously.
	});
	
	$("#people_search_input").each(function(){
		$("#people_search_index").children("li").children("a").click(function(){
			var nodeInfo = highlightIndex(this);
			if(nodeInfo.isEnabled) {
				var letter = $(this).parent().get(0).id.split('_')[1].toLowerCase();
				// alert(letter);
				$("#people_search_results tr:gt(0)").hide().filter("." + letter).show();
			}
			return false;
		}).end().filter("#label_ALL").children("a").click(function(){
			var nodeInfo = highlightIndex(this);
			$("#people_search_results tr:gt(0)").show();
			return false;
		}).end().end().filter("#label_0-9").children("a").click(function(){
			var nodeInfo = highlightIndex(this);
			if(nodeInfo.isEnabled) {
				$("#people_search_results tr:gt(0)").hide().filter(".other").show();
			}
			return false;
		}).end().end().end().prepend('<li><a class="first" href="#">&nbsp;</a></li>').append('<li><a class="last" href="#">&nbsp;</a></li>');
		
		$("#people_search_result_title").each(function(){
			$(this).attr("title", $(this).text());
		})

		$("#people_search_clear").click(function(){
			peopleSearchClear(false);
			$("#people_search_input").val('').focus();
			return false;
		});
		
		// hide all search-result-related fields initially, using override.
		// necessary for safari table rendering.
		peopleSearchClear(true);
		
	}).keypress(function(e){
		var arrow = $("#people_search_arrow");
		if(arrow.css("display") != "none"){
			setTimeout(function(){
				arrow.hide();
			}, 150);
		}
		clearInterval(peopleSearchInterval);
		peopleSearchInterval = setInterval(peopleSearchIntervalFunction, typeThenSearchPause);
	}).focus();
	
	$("#people_show_all").children("a").click(function(){
		peopleSearchClear(true);
		$("#people_search_arrow").hide();
		$("#people_search_form").append('<input type="hidden" id="show_all" name="show_all" value="true">').submit();
		$("#show_all").remove();
		return false;
	});
});


// ==========================
// = AJAX success function. =
// ==========================
// function showResponse(responseText, statusText) {
// 
// 
// }


// ============================
// = People search functions. =
// ============================

function peopleSearchIntervalFunction(){
	var input = $("#people_search_input");
	var form = $("#people_search_form");
	// var output = $("#people_search_output");
	var title = input.attr("title");
	var last = input.attr("alt");
	var val = $.trim(input.val());
	var query = '';
	if(title != val && val != '' && (val != last || $("#people_search_result_title").text() == $("#people_search_result_title").attr("title"))) {
		input.attr("alt", val);
		query = val;
	}
	else if(val == '' || title == val) {
		peopleSearchClear(false);
	}
	if(query != '') {
		// do ajax search
		form.submit();
	}
}

function peopleSearchClear(override){
	$("#people_search_result_title").each(function(){
		if(($(this).text() != $(this).attr("title")) || override) {
			$("#people_search_index, #people_search_results, #people_show_all, #people_search_load, #people_search_clear").hide();
			$("#people_search_arrow, #people_search_intro").show();
			$("#people_search_index").children("li").children("a").removeClass("current").filter(function(){
				return $(this).parent().get(0).id == "label_ALL";
			}).addClass("current");
			$("#people_search_results tr:gt(0)").remove();
			$(this).text($(this).attr("title"));
		}
	});
}

function highlightIndex(node) {
	var enabled;
	var current;
	$(node).each(function(){
		var classes = node.className.split(" ");
		enabled = ($.grep(classes, function(n,i){ return n=="enabled"; }).length > 0);
		current = ($.grep(classes, function(n,i){ return n=="current"; }).length > 0);
		// alert(enabled)
		if(enabled && !current) {
			$("#people_search_index").children("li").children("a").removeClass("current");
			$(node).addClass("current");
		}
	});
	return {
		isEnabled: enabled,
		isCurrent: current
		};
}
