/**
 * Cross browser event attachment
 */
function AttachEvent(target,eventName,handlerName) {
	if(jQuery) {
		jQuery(target).bind(eventName,handlerName);
	}else{
		if (target.addEventListener)
			target.addEventListener(eventName, handlerName, false);
		else if (target.attachEvent) {
			target.attachEvent("on" + eventName, handlerName);
		}else
			target["on"+eventName] = handlerName;
	}
}

/**
 * Makes an input so the value clears when focused and reset
 * when blurred if it is the default/empty
 */
function defaultInput(elm,def) {
	AttachEvent(elm,'focus',function(){if(elm.value==def)elm.value='';});
	AttachEvent(elm,'blur',function(){if(elm.value=='')elm.value=def;});
}

/**
 * Onload
 */
 function qAction(callback)
 {
	jQuery("body").bind("introComplete", callback);	
 }
function siteloaded() {
	// Set up default input values
	jQuery(".hideUntilReady").removeClass("hideUntilReady");
	var un = document.getElementById('username');
	if(un) defaultInput(un,'username');
	var pw = document.getElementById('password');
	if(pw) defaultInput(pw,'password');
	var st = document.getElementById('searchinput');
	if(st) defaultInput(st,'Search');

	//DropShadow.init(document.getElementById("wrapper"));
	autoRollOver.setup();
	animateIntro();
	newNav.init();

	// do accordions
	setupAccordions();
	externalLinks();
	jQuery("#search_term").focus();
}
function isIE(n)
{
	if (!n)
		return jQuery.browser.msie;
	else
	 return jQuery.browser.msie && parseInt(jQuery.browser.version.substr(0,1))==n;
}
function isPage(page)
{
	return jQuery("body.page_" + page).length;
}
function animateIntro()
{
	var atHome = isPage("home");//jQuery("body.page_home").length;
	//var isContact = isPage("contact");//jQuery("body.page_contact_us").length;
	if (atHome)
		doHomeAnim();
	if (!atHome)
		doNormalAnim();
	
}
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}
function introComplete()
{
	jQuery("body").trigger("introComplete");
}
function doNormalAnim()
{
	if (!isIE())
	{
		jQuery("#media").hide();
		jQuery("#media").fadeIn(1000, introComplete);
	}
	else
		introComplete();
}
function doHomeAnim()
{
	var ie6 = isIE(6);
	var ie = isIE();
	if (!ie6)
	{
		
		if (!ie)
		{
			var capitol = jQuery("#home_capitol");
			capitol.hide();
			setTimeout(function(){capitol.show()}, 350);
			
			/*
			var loginForm = jQuery("#user_login");
			loginForm.hide();
			setTimeout(function(){loginForm.show(200)}, 300);
			*/
			
			var mediaMessage = jQuery(".media_message");
			mediaMessage.hide();
			setTimeout(function(){mediaMessage.fadeIn(200)}, 900);
			
			
			var news = jQuery("#news, #news_icon");
			news.hide();
			setTimeout(function(){news.fadeIn(200);}, 1100); 
			
			
			var logo = jQuery("#logo");
			logo.hide();
			logo.fadeIn(500);
		}
		setTimeout(introComplete,1800);
		moveMap();
	}
	else		
		setTimeout(introComplete,1800);
}
var mapMoveDur = 500; // amount of time it takes for one pixel to move
function moveMapOnce()
{
	xpos = 0;
	ypos = 0;
	var orig = jQuery(".home_media.orig");
	var clone = jQuery(".home_media.clone");
	var pos = orig.css("backgroundPosition");
	if (pos)
	{
		pos = pos.split(" ");		
		xpos = parseInt(pos[0]);
		ypos = parseInt(pos[1]);
	}
	xpos--;
	var newpos = xpos + "px" + " "  + ypos + "px";
	var newpos2 = (xpos-1) + "px" + " "  + ypos + "px";
	orig.css("backgroundPosition", newpos);
	clone.css("backgroundPosition", newpos2);
	clone.stop(true,true);
	clone.hide();
	clone.fadeIn(mapMoveDur, "linear");

}
function moveMap()
{
	window.mapInterval = setInterval(moveMapOnce, mapMoveDur);
	var media = jQuery("#media");
	var node = jQuery(".home_media");
	node.addClass("orig");
	media.prepend('<div class="home_media clone" style="background-position: 0px 0px;	position:absolute; top:0; left:0;"></div>');
}
jQuery(siteloaded);
//AttachEvent(window,'load',siteloaded);

/**************************************************************
 * Quick Jump
 **************************************************************/
AttachEvent(window,'load', function() {
	var qjs = jQuery('.quickjump');
	var fadedur = 200;
	for(var i=0; i<qjs.length; i++) {
		var qj = qjs[i];
		var jls = jQuery(qj).children('.jumplead');
		var jl = jls && jls[0] ? jls[0] : null;
		var qjsitemaps = jQuery(qj).children('.qjsitemap');
		var qjsitemap = qjsitemaps && qjsitemaps[0] ? qjsitemaps[0] : null;
		if(jl && qjsitemap) {
			AttachEvent(document.body, 'click', function(){
				if(hasClass(qj,'quickjump-open')) {
					jQuery(qjsitemap).fadeOut(fadedur, function(){removeClass(qj,'quickjump-open');});
				}
				return true;
			});
			AttachEvent(jl, 'click', function(){
				if(hasClass(qj,'quickjump-open')) {
					jQuery(qjsitemap).fadeOut(fadedur, function(){removeClass(qj,'quickjump-open');});
				}else{
					jQuery(qjsitemap).fadeIn(fadedur);
					addClass(qj,'quickjump-open');
				}
				return false;
			});
		}
	}
});

/**************************************************************
 * LogoWidget
 **************************************************************/
AttachEvent(window,'load',function(){
	var lws = jQuery('.logowidget');
	var numtoshow = 4;	   // Number of icons to try showing
	var frequency = 8000;	// How frequently the fade occurs
	var fadeduration = 1000;  // Duration of fade animation
	for(var i=0; i<lws.length; i++) {
		var lw = lws[i];
		var logos = jQuery(lw).children('img');
			logos.hide();
		var doanimation = function(){
			var now = new Date();
			var seed = now.getSeconds();
			var c=0;
			var logostoshow=[];
			// Collect three random images
			while(logostoshow.length < numtoshow && c < 100) {
				var rn = Math.floor(Math.random(seed)*(logos.length-1));
				var inlist = false;
				for(var k=0; k<logostoshow.length; k++)
					if(logostoshow[k]==rn) inlist = true;
				if(!inlist) logostoshow.push(rn);
				c++;
			}

			var fadeoutc = 0;
			// Fade them out
			jQuery(logos).fadeOut(fadeduration, function(){
				var elms = [];
				for(var j=0; j<logostoshow.length; j++) {
					elms.push(logos[logostoshow[j]]);
				}
				fadeoutc++;
				if(fadeoutc>=logos.length) {
					var fadeinc = 0;
					// fade in appropriate elements
					jQuery(elms).fadeIn(fadeduration,function(){
						fadeinc++;
						if(fadeinc>=elms.length) // Make sure we're done with all of them, then queue the next anim
							setTimeout(doanimation, frequency);
					});
				}
			});
		}
		setTimeout(doanimation,0);
	}
});


/**************************************************************
 * Utility
 **************************************************************/
function addClass(elem, class_name){
	if(!hasClass(elem, class_name)) {
		elem.className += " " + class_name;
	}
}

function removeClass(elem, class_name){
	if(hasClass(elem, class_name)) {
		var regEx = new RegExp("\\b"+class_name+"\\b","g");
		elem.className = elem.className.replace(regEx, "");
	}
}

function hasClass(elem, class_name) {
	if(elem && elem.className) {
		var regEx = new RegExp("\\b"+class_name+"\\b");
		var m = elem.className.match(regEx);
		return (m && m.length>0)?true:false;
	}
	return false;
}

/**************************************************************
 * Focus Rectangle Configuration
 **************************************************************/
var followFocusSettings = {
	focusables: ".focuswrap input, .focuswrap textarea, .focuswrap button, .focuswrap select",	
	offset_tlx : -3,
	offset_tly : -3,
	offset_trx : 1,
	offset_try : -3,
	offset_blx : -3,
	offset_bly : 2,
	offset_brx : 1,
	offset_bry : 2
};

/**************************************************************
 * Validation
 **************************************************************/
var validation={
	presets:{
		not_empty:/^.+$/,
		email:/^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$|(\[?(\d{1,3}\.){3}\d{1,3}\]?)$/i,
		alpha:/^[a-z]+$/i,
		numeric:/^[0-9]+$/,
		resume_file:/\.(doc|docx|rtf|pdf)$/
	},
	exec:function(f,vo){
		var errors=[];
		for(var i in vo){
			var elm = f[i];
			if(!elm) continue;
			var value = elm.value;
			var errForElm = false;
			for(var j in vo[i]) {
				if(!value.match(vo[i][j].test)) {
					errors.push(i);
					errForElm=true;
				}
			}
			if(errForElm) addClass(elm,"error");
			else removeClass(elm,"error");
		}
		if(errors.length){
			alert("Please fill out the following fields: "+errors.join(", "));
			return false;
		}
		return true;
	},
	rulesets:{}
};

/** validation rules for contactform **/
validation.rulesets.contactform={
	name:[{test:validation.presets.not_empty,error:"Please enter your name"}],
	email:[{test:validation.presets.email,error:"Please enter a valid email"}]
};

/** validation rules for resume form **/
validation.rulesets.postresume={
	name:[{test:validation.presets.not_empty,error:"Please enter your name"}],
	address:[{test:validation.presets.not_empty,error:"Please enter your address"}]
};

/*****************************************************************
 * Auto image rollovers
 * - Add class "autorollover" to an image
 * - Make sure an image with <filename>_over.<ext> exists in the
 *   same directory.
 *   ie: /images/mybutton.png && /images/mybutton_over.png
 *****************************************************************/
var autoRollOver = {
	over:"_over",
	setup:function(){
		var rolloverimgs = jQuery('img.autorollover');
		for(var i=0; i<rolloverimgs.length; i++) {
			var o = rolloverimgs[i];
			AttachEvent(o,'mouseover',autoRollOver.mouseover);
			AttachEvent(o,'mouseout',autoRollOver.mouseout);
		}
	},
	mouseover:function(e){
		if (!e) var e = window.event;
		var o = (e.target) ? e.target : e.srcElement ? e.srcElement : this;
		var lastDot = o.src.lastIndexOf('.');
		var firstChunk = o.src.substring(0,lastDot);
		var ext = o.src.substring(lastDot,o.src.length);
		o.src = firstChunk + autoRollOver.over + ext;
	},
	mouseout:function(e){
		if (!e) var e = window.event;
		var o = (e.target) ? e.target : e.srcElement ? e.srcElement : this;
		var lastDot = o.src.lastIndexOf('.');
		var firstChunk = o.src.substring(0,lastDot-autoRollOver.over.length);
		var ext = o.src.substring(lastDot,o.src.length);
		o.src = firstChunk + ext;
	}
}

/*****************************************************************
 * Sets up accordions
 *****************************************************************/
function setupAccordions() {
	var accs = jQuery('.accordion');
	for(var i=0; i<accs.length; i++) {
		var options = {autoHeight:false};
		var a = jQuery(accs[i]);

		// Open to the appropriate tab 
		if(a.children(window.location.hash).length) {
			var active = 0;
			var headers = a.children('h3');
			for(var j=0; j<headers.length; j++) {
				if('#'+headers[j].id == window.location.hash) {
					active = j;
					break;
				}
			}
			options.active=active;
		}
		jQuery(accs[i]).accordion(options);
	};
}

// **************************** NEW
var newNav = {
	overSubMenu:function(event)
	{
		var li = jQuery(event.data.node);
		if (event.data.node.timeout)
		{
			clearTimeout(event.data.node.timeout);
		}
		return true;
	},
	outSubMenu:function(event)
	{
		var li = jQuery(event.data.node);
		return true;
	},
	hideAll:function()
	{
		jQuery("#menu .links li").each(
			function (i){
				var li = jQuery(this);
				if (li.hasClass("hover"))
				{
					li.removeClass('hover');
					li.removeClass("animating");
					if (this.timeout)
						clearTimeout(this.timeout);
						
					li.addClass("animating");
					li.children('ul').stop(true,true);
					newNav.hideGlow(li);
					li.children('ul').slideUp(
						200,
						function(){
							li.removeClass("animating");
						}
					);
				}
			}
		);
	},
	overMenu:function(event)
	{
		var node = event.data.node.parentNode;
		var li = jQuery(node);
		if (!li.hasClass("hover"))
		{
			newNav.hideAll();
			li.removeClass("animating");
			if (node.timeout)
				clearTimeout(node.timeout);
			li.addClass("hover");
			li.addClass("animating");
			li.children('ul').stop(true,true);
			li.children('ul').hide();
			li.children('ul').slideDown(200,function(){li.removeClass("animating")});
			newNav.showGlow(li);
		}
		return true;
	},
	showGlow:function(node){
		if (!isIE())
		{
			node.children('.nav_glow').css("display","");
			node.children('.nav_glow').css("opacity",0.0);
			node.children('.nav_glow').stop(true,true);
			node.children('.nav_glow').animate({opacity:1},500);
		}
	},
	hideGlow:function(node){
		if (!isIE())
		{
			node.children('.nav_glow').stop(true,true);			
			node.children('.nav_glow').animate({opacity:0.0},250, function(){node.children('.nav_glow').css("display","none");});
		}
	},
	outMenu:function(event)
	{
		var node = jQuery(event.data.node);
		if (node.hasClass("hover"))
		{
			node.removeClass("animating");
			if (event.data.node.timeout)
				clearTimeout(event.data.node.timeout);
			event.data.node.timeout = setTimeout(
				function(){
				
					node.removeClass("hover");
					node.addClass("animating");
					newNav.hideGlow(node);
					node.children('ul').slideUp(200, function(){node.removeClass("animating");});
				},
				400
			);
		}
	},
	init:function()
	{
		if (!isIE())
		{
			jQuery(".nav_glow").addClass("js");
			jQuery(".nav_glow").css("opacity",0.0);
		}
		jQuery("#menu .links li a").each(
			function (i){
				if (!jQuery(this.parentNode.parentNode).hasClass('subnav')) {
					jQuery(this).bind("mouseover", {node:this}, newNav.overMenu);
					jQuery(this.parentNode).bind("mouseout", {node:this.parentNode}, newNav.outMenu);
				}
			}
		);
		jQuery("#menu .links li").each(
			function (i){
				if (!jQuery(this.parentNode).hasClass('subnav'))
				{
					jQuery(this).bind("mouseover", {node:this}, newNav.overSubMenu);
					jQuery(this).bind("mouseout", {node:this}, newNav.outSubMenu);
				}
			}
		);
		
	}
}

 
