/*
University of Pittsburgh
Graduate School of Public Health
Site-wide JavaScript include
Created: 22 Aug 2007 by Pat Collins <pat@walltowall.com>
Wall-to-Wall Studios, Inc.
*/

var preload = Array(
"images/load.gif",
"images/search-x.gif"
);

var peopleSearchInterval;

$(function(){
	// preload images
	$.each(preload,function(i,n){
		var img = new Image();
		img.src = n;
	});
	
	// ===================
	// = First menu item =
	// ===================
	$("#menu").children("li:first").addClass("first").end().children("li:last").addClass("last");
	
	// ========================
	// = Submenus first items =
	// ========================
	$(".dropmenu ul").each(function(){
		$(this).children("li:first").addClass("first");
	});
	
	var totalMenus = $("#menu").children("li").children("a").length;
	
	$("#menu").children("li").children("a").hover(function(){
		// link mouseover
		var id = this.id;
		var menu_id = '#menu'+id.split('nav')[1];
		// if(!($(this).parent().get(0).className.indexOf('first') > -1 && $(this).get(0).className.indexOf('current') > -1)){
			$(this).add($(this).parent().get(0)).addClass("hover");
			if($.browser.msie) {
				$("select").css("visibility", "hidden");
			}
			$(menu_id).show();
		// }
	},function(){
		// link mouseout
		var id = this.id;
		var menu_id = '#menu'+id.split('nav')[1];
		// if(!($(this).parent().get(0).className.indexOf('first') > -1 && $(this).get(0).className.indexOf('current') > -1)){
			$(this).add($(this).parent().get(0)).removeClass("hover");
			if($.browser.msie) {
				$("select").css("visibility", "visible");
			}
			$(menu_id).hide();
		// }
	}).each(function(menuIndex){
		// alert(index);
		var id = this.id;
		var menu_id = '#menu'+id.split('nav')[1];
		// taking the id of the links, finding the divs, and attaching behavior.
		$(menu_id).hover(function(){
			$('#'+id).add($('#'+id).get(0)).addClass("hover");
			if($.browser.msie) {
				$("select").css("visibility", "hidden");
			}
			$(this).show();
		},function(){
			$('#'+id).add($('#'+id).get(0)).removeClass("hover");
			if($.browser.msie) {
				$("select").css("visibility", "visible");
			}
			$(this).hide();
		}).mousemove(function(){
			$('#'+id).add($('#'+id).get(0)).addClass("hover");
			if($.browser.msie) {
				$("select").css("visibility", "hidden");
			}
			$(this).show();
		}).each(function(){
			// set the absolute left position for each dropdown submenu.
			// console.log(id + ' ' + this.id);
			// var id = this.id.split('_submenu')[0];
			$(this).css("left", $('#'+id).position().left+'px');
			if(menuIndex == totalMenus-1) {
				var offset = 215 - $("#"+id).outerWidth() + 1;
				$(this).css("left", ($('#'+id).position().left - offset)+'px');
			}
		});
	});
	
	$("#sectionnav").each(function(){
		$("div", $(this)).filter(function(){
			return $(this).children("a").length == 0;
		}).addClass("current").end().filter(".firstlevel").filter(function(){
			return $("div.current", $(this)).length != 0;
		}).addClass("currentSection");
	});
	
	textBoxLabelFromValue($("#site_search_input, #people_search_input, #inline_search_box"));
	
	detectFirstHeader($("#content"));
	
	$("#container_wrapper, #container, #content").append('<div class="clear"></div>');
	
	$("#content div.event").after('<hr>');
	
	if($.browser.safari) { // commented out b/c safari 3.0 fixes these.
		// $("#site_search_input").each(function(){
		// 	$(this).height(29).width(200).css({
		// 		color: '#bbb',
		// 		fontSize: '20px'
		// 	});
		// });
		// $("#people_search_input").each(function(){
		// 	$(this).height(29).width(250).css({
		// 		color: '#bbb',
		// 		fontSize: '20px'
		// 	});
		// });
	}
	
	$("tr:last", $("#people_search_results")).addClass("last");
	
	
	// Replace all horizontal rules with a custom HR div, maintaining the classes set on them.
	$("hr").wrap('<div class="hr"></div>').each(function(){
		var tmpCls = this.className.split(' ');
		var theDiv = $(this).parent();
		$(tmpCls).each(function(index){
			theDiv.addClass(tmpCls[index]);
		});
	}).remove();
	
	$("img[@align=right]").css({
		'float': 'right'
	});
	
	$('#events_dropdown').change(function(){
		window.location = 'events.php?month='+escape($(this).children('option:selected').text());
	});
	
	$("#for_you li a, #side_gsph_events a, #side_gsph_news a, #side_faculty_search a").hover(function(){
		$(this).fadeTo(150, 0.5);
	},function(){
		$(this).fadeTo(150, 1);
	});
	
	$("#footer .contact.email").hover(function(){
		$(this).fadeTo(150, 0.7);
	},function(){
		$(this).fadeTo(150, 1);
	});
	
	$(".fadelink50").hover(function(){
		$(this).children("img").fadeTo(150, 0.5);
	},function(){
		$(this).children("img").fadeTo(150, 1);
	});
	
	$(".fadelink70").hover(function(){
		$(this).children("img").fadeTo(150, 0.7);
	},function(){
		$(this).children("img").fadeTo(150, 1);
	});
});


window.onload = function(){
	//
	// $("#featured").each(function(){
	// 	var flashHeight 
	// });
	// $("#container_wrapper").height($("#featured").outerHeight()-20);
	// $("#side").height($("#featured").outerHeight()-180);
	
	// on the home page
	$("#home #content").each(function(){
		var side = parseInt($("#home #side").outerHeight());
		
		
		var heightFlash = parseInt($("#featured").outerHeight());
		
		var sideOffset = 55;
		
		var events = parseInt($("#home #events").outerHeight());
		var news = parseInt($("#home #news").outerHeight());
		var contentHeight = parseInt($(this).outerHeight());
		
		if((events + news + contentHeight) > (heightFlash - 75)) {
			$("#featured").height(events + news + contentHeight + 15);
		}
		$("#side").height($("#featured").outerHeight() - events - sideOffset);
		
	});
	
	
	//on the update info page
	$("#update_form_submit").click(function(){
			validateUpdateForm();
	});
	
	$("#update_form_reset").click(function(){
			resetUpdateForm();
	});
	
	//on the Open House page
	$("#open_house_form_submit").click(function(){
			validateOpenHouseForm();
	});
	
	$("#open_house_form_reset").click(function(){
			resetOpenHouseForm();
	});
	
	//on the Share News page
	$("#news_form_submit").click(function(){
			validateNewsForm();
	});
	
}




// =====================
// = Global functions. =
// =====================

function performWebSearch(json, node){
	json = eval("(" + json + ")");

	var url, preview, title, results;
	/*if(parseInt(json.GSP.RES.M) == 1){
		results = new Array(json.GSP.RES.R);
	}
	else{
		results = json.GSP.RES.R;": {"results
	}*/
	results = json.responseData.results;
	$.each(results, function(i, result){
	//$.each(json, function(i, result){
		url = (result.unescapedUrl != '' ? result.unescapedUrl : '');
		preview = (result.content != '' ? result.content : '');
		title = (result.title != '' ? result.title : '');
		node.append('<div class="web_search_result"><h3><a href="'+url+'">'+title+'</a></h3><p>'+preview+'<br><span class="green">'+url+'</span></p></div>');
	});
}

/*function performWebSearch(json, node){
	json = eval("(" + json + ")");
	var url, preview, title, results;
	if(parseInt(json.GSP.RES.M) == 1){
		results = new Array(json.GSP.RES.R);
	}
	else{
		results = json.GSP.RES.R;
	}
	$.each(results, function(i, result){
		url = (result.U != '' ? result.U : '');
		preview = (result.S != '' ? result.S : '');
		title = (result.T != '' ? result.T : '');
		node.append('<div class="web_search_result"><h3><a href="'+url+'">'+title+'</a></h3><p>'+preview+'<br><span class="green">'+url+'</span></p></div>');
	});
}*/

function highlightSection(vCurrSection) {
	$("#nav"+vCurrSection).each(function(){
		$(this).addClass("current");
	});
}

function textBoxLabelFromValue(jQueryNode) {
	jQueryNode.each(function(){
		if($(this).get(0).nodeName == "INPUT" && ($(this).attr("type") == "text") && $(this).val() != ""){
			var startText = $(this).val();
			$(this).focus(function(){
				$(this).addClass("focus");
				if($(this).val() == startText){
					$(this).val("");
				}
			}).blur(function(){
				if($(this).val() == ""){
					$(this).removeClass("focus");
					$(this).val(startText);
				}
			}).val(startText).attr("title", startText);
		}
		else {
			return false;
		}
	});
}

function detectFirstHeader(jQueryNode) {
	var children = jQueryNode.children();
	var headersFound = 0;
	children.each(function(){
		if(headersFound == 0) {
			if(isHeader(this.nodeName) && this.className.indexOf('topmargin') < 0) {
				$(this).addClass("top");
				headersFound++;
			}
		}
	});
}

function isHeader(nodeName) {
	if(nodeName == "H1" || nodeName == "H2" || nodeName == "H3" || nodeName == "H4" || nodeName == "H5" || nodeName == "H6") {
		return true;
	}
	return false;
}

// =====================
// = Skrebs validate. =
// =====================

function validateEmail(str) {
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	if(!reg1.test(str) && reg2.test(str)) {
		return true;
	}
	return false;
}

function validateUpdateForm() {
	var form=document.getElementById("update_form");
	var errorMsg="<span class='errorTitle'>An error has occurred. Please make the following corrections:</span><br><br>";
	var doSubmit=true;
	
	if(form.firstname.value == "") {
		errorMsg += "- Please provide a first name. (First Name)<br>";
		doSubmit=false;
	}
	
	if(form.lastname.value == "") {
		errorMsg += "- Please provide a last name. (Last Name)<br>";
		doSubmit=false;
	}
	
	
	if (!validateEmail(form.email.value)) {
		errorMsg += "- Please provide a valid email address. (E-mail address)<br>";
		doSubmit=false;
	}
	
	
	if(!doSubmit) {
		$("#foundErrors").show().html(errorMsg);
		location.hash="foundErrors";
		//alert(errorMsg);
	} else {
		form.submit();
	}
}

function resetUpdateForm() {
	$("#foundErrors").hide();
	// location.hash="";
	// $("#contact_form :input").attr("value").empty();
}
// =====================

// =====================
//   MFulk Validate and date
// =====================
function todaysDate(){
	//Display the current date
	var Today = new Date();
	var Months = new Array("January","February","March","April","May","June", "July","August","September","October","November","December");
	var strDate = Months[Today.getMonth()] + " "+ Today.getDate() + ", " + Today.getFullYear();
	return strDate;
}

function validateOpenHouseForm() {
	var form=document.getElementById("openHouse");
	var errorMsg="<span class='errorTitle'>An error has occurred. Please make the following corrections:</span><br><br>";
	var doSubmit=true;
	
	if(form.fName.value == "") {
		errorMsg += "- Please provide a first name. (First Name)<br>";
		doSubmit=false;
	}
	
	if(form.lName.value == "") {
		errorMsg += "- Please provide a last name. (Last Name)<br>";
		doSubmit=false;
	}
	
	if(form.address.value == "") {
		errorMsg += "- Please provide an address. (Physical Address)<br>";
		doSubmit=false;
	}
	if(form.city.value == "") {
		errorMsg += "- Please provide a city. (City)<br>";
		doSubmit=false;
	}
	if(form.state.value == "") {
		errorMsg += "- Please provide an state/region. (State/Region)<br>";
		doSubmit=false;
	}
	if(form.zip.value == "") {
		errorMsg += "- Please provide an zip/postal code. (Zip/Postal Code)<br>";
		doSubmit=false;
	}

	if (!validateEmail(form.email.value)) {
		errorMsg += "- Please provide a valid email address. (E-mail address)<br>";
		doSubmit=false;
	}
	
	if(!doSubmit) {
		$("#foundErrors").show().html(errorMsg);
		location.hash="foundErrors";
		//alert(errorMsg);
	}
	else {
		form.submit();
	}
}
function resetOpenHouseForm() {
	$("#foundErrors").hide();
	// location.hash="";
	// $("#contact_form :input").attr("value").empty();
}

function validateNewsForm() {
	var form=document.getElementById("newsForm");
	var errorMsg="<span class='errorTitle'>An error has occurred. Please make the following corrections:</span><br><br>";
	var doSubmit=true;
	
	if(form.fName.value == "") {
		errorMsg += "- Please provide a first name. (First Name)<br>";
		doSubmit=false;
	}
	
	if(form.lName.value == "") {
		errorMsg += "- Please provide a last name. (Last Name)<br>";
		doSubmit=false;
	}
	
	if(form.degreeYear.value == "") {
		errorMsg += "- Please provide a Degree and Year earned. (Degree(s) and Year(s) Earned)<br>";
		doSubmit=false;
	}
	if(form.comments.value == "") {
		errorMsg += "- Please fill in your comments/questions. (Comments/Questions)<br>";
		doSubmit=false;
	}
	
	if(!doSubmit) {
		$("#foundErrors").show().html(errorMsg);
		location.hash="foundErrors";
		//alert(errorMsg);
	}
	else {
		form.submit();
	}
}
// =====================

