// before rendering the page...
$(document).ready( function() {

	// apply random background image on homepage intro
	if ($('body#home') != null) {
		var randomImages = [
			'section-bg-home1',
			'section-bg-home2',
			//'section-bg-home3',
			'section-bg-home4',
			//'section-bg-home5',
			'section-bg-home6',
			'section-bg-home7',
			//'section-bg-home8'
			];
		var rndNum = Math.floor(Math.random() * randomImages.length);
		$("#home-intro").css({ background: "url(/_includes/images/" + randomImages[rndNum] + ".jpg) 100% 100% no-repeat" });
	}
	
	// figure out server
	var server = window.location.protocol + "//" + window.location.host;
	
	// main menu highlighting
	$('#header ul a').each(function(){
		var href = $(this).attr('href');
		if( window.location.href.indexOf( server + href ) >= 0 && href.length > 1 ) {
			$(this).addClass("current");
		}
	});
	
	// section menu highlighting
	var $currentAnchor = null;
	$('#sections a').each(function(){
		var href = $(this).attr('href');
		if( window.location.href.indexOf( server + href ) >= 0 && href.length > 1 ) {
			$(this).addClass("current");
			if ($currentAnchor != null) {
				$currentAnchor.removeClass("current"); // remove top-level section highlight
			} else {
				$currentAnchor = $(this);	
			}
		}
	});
	
	// form handling
	initializeFocus();
	ifInstructs();
	
	//wrap forms with shadows
	$("#form-container")
		.before("<img id='top' alt='Horizontal separator' src='/_includes/images/form.top.png'/>")
		.after("<img id='bottom' alt='Horizontal separator' src='/_includes/images/form.bottom.png'/>")
		.css("margin-bottom","0");
});


function initializeFocus(){
	$("form ul li").contents().find(".field").each(function(){		
		if($(this)[0].type == 'radio' || $(this)[0].type == 'checkbox' || $(this)[0].type == 'file') {
			$(this)
				.click(function() {$(this).parents("li").addClass("selected")})
				.focus(function() {$(this).parents("li").addClass("focused")})
				.blur(function() {$(this).parents("li").removeClass("focused")});			
		} 
		else if($(this)[0].className.match('addr')){
			$(this)
				.focus(function() {$(this).parents("li").removeClass("focused")})
				.blur(function() {$(this).parents("li").removeClass("focused")});
		}
		else {
			$(this)
				.focus(function() {$(this).parents("li").addClass("focused")})
				.blur(function() {$(this).parents("li").removeClass("focused")});
		}
	});
}

function ifInstructs(){
	var container = $('#form-container');
	if(container.length > 0){
		container.removeClass('noI');
		var instructs = $(".instruct");
		if((container[0].offsetWidth <= 450) || (instructs == '')){
			container.addClass('noI');
		}
	}
}