// JavaScript Document
/* -- allows reverse function on string prototype  -- */
String.prototype.reverse = function () {
	return this.split('').reverse().join('');
};

/* function appends a javascript file into the header of the page’s DOM
* Instead of an arbitrary and lengthy timeout to ensure the script’s functions will be 
* ready, we can use the completed upload event to trigger
*/
var filesadded = "";
function includeJs(filename,callback){
	/* test to see if the script's already been loaded and skip to the callback if true */
	if (filesadded.indexOf("["+filename+"]") == -1){
	  //get the page’s head object
	  var head = document.getElementsByTagName('head')[0];
	  //create an build the new scripting object to be injected
	  var script = document.createElement('script');
	  
	  script.type = 'text/javascript';
	  script.src = filename;
	  //if we’re dealing with IE
	  if (script.readyState){
		  //check the status of the script looking for a completed load
		  script.onreadystatechange= function () { 
			  //check to see if the state has changed to indicate a successful load
			  if (script.readyState == "loaded" || script.readyState == "complete"){ 
				  //some scripts don’t need a callback as they’re self executing so avoid a callback if it’s not already defined
				  if (callback != null){
					  //the callback is the collection of operations waiting for the script to be uploaded.
					  callback();
				  }
			  }
		  }
	  } else {
		  //Mozilla based browsers use the onload event for upload completion
		  script.onload = function () { if (callback != null){ callback(); }}
	  }
	  //List of files added in the form "[filename1],[filename2],etc"
	  filesadded+="["+filename+"]"; 
	  //attach/upload the js file to the document head
	  head.appendChild(script);
	}else{
		if (callback != null){
			//the callback is the collection of operations waiting for the script to be uploaded.
			callback();
	  	}
	}
}

includeJs('/js/jquery.js',function(){	
	jQuery(document).ready( function () {
  
	/* -- if the global_navigation element is found, load the delayed hover file and implement the mega dropdown -- */
	if ($("ul#global_navigation").length){
		includeJs('/js/jquery.hoverIntent.minified.js',function(){
		  function addMega(){
			$(this).find("ul.drop_down").stop().fadeIn("fast");	  
		  }
		  
		  function removeMega(){
			$(this).find("ul.drop_down").stop().fadeOut("fast");
		  }
		  
		  var megaConfig = {
			interval: 200,
			sensitivity: 4,
			over: addMega,
			timeout: 200,
			out: removeMega
		  };
		  $("ul#global_navigation li ul.drop_down").hide();
		  $("#global_navigation > li").hoverIntent(megaConfig) ;
		});
	}
	
	/* -- kick in ie font smoothing fix.  It smooths out @font-face jaggies in ie -- */
	if(jQuery("#main div h1,#content h1,#content h2,#content h3:not(a),.cfn").length){
		includeJs('/js/IEffembedfix.jQuery.js',function(){
			jQuery("#main div h1,#content h1,#content h2,#content h3:not(a),.cfn").ieffembedfix();
		});
	}
	
	/* -- run google analytics on live servers after the page has loaded -- */
	if(!document.location.href.match(/(webtest|testgsb|gsbtest)/gi)){
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		var trackercode = (document.location.href.match(/gsb/gi))? 'UA-10389721-1' : 'UA-4487056-1' ;
		includeJs(gaJsHost + "google-analytics.com/ga.js",function(){
		  	setTimeout("{var pageTracker = _gat._getTracker('"+trackercode+"');	pageTracker._initData(); pageTracker._trackPageview();}",10);
		});
	}

	/* -- autoswap hyperlinks to flash files for clean flash insertion -- */
	$('a[href*="swf"][rel^="lightbox"]').each(function(e){
		var swf = $(this).attr("href");
		var title = $(this).attr("title");
		var rel = $(this).attr("rel");
		var w = rel.match(/\d+(?=;)/);
		var h = rel.substring(rel.indexOf("height=")+7,rel.length).match(/\d+/);
		
		var container = $(this).parent().prepend("<div></div>");
		includeJs('/js/jquery.flash.js',function(){
		  	container.flash({
			  	src: swf,
			  	swf: swf,
			  	width: w,
			  	height: h,
			  	callback: "/cbsMediaplayerStats.cfm",
				title: title
		  	});
			$("div.alt").remove();
		});
	});

	/* -- kick in form validation -- */
	if ($("form.validate_submit").length){
		includeJs('/js/jValidate.js',function(){
			includeJs('/js/form.validation.js');
		});
	}
	
	/* -- kick in datepicker architecture independent of any forms submission interception -- */
	$("form:not(.validate_submit) .date_picker").each(function(){
	  var o = this;
	  includeJs('/js/stevesDatePicker.js',function(){
		$(o).calendar(o);
	  });
	});
	
	/* -- auto implement rollover on images with class rollover -- */
	jQuery('img[class*=rollover]').each(function(){
		this.off = new Image();
		this.on = new Image();
		this.off = $(this).attr("src");
		this.on = $(this).attr("src").reverse().replace(/ffo(?=(-|_|\.))/g, '!ffo-ecalper!').reverse().replace(/!replace-off!(?=((-|_|\.)))/gi, "on");
		jQuery(this).hover(
			function(e){
				this.src = this.on;
			},function(e){
				this.src = this.off;
			}
		);
	});
	
	/*-- expansion code for accordion elements like the FAQs -- */
	jQuery("div.accordion h4 a").click(function(e) {
		var theDiv = jQuery(this).parent().parent().find("div.body");
		theDiv.css('display');
		theDiv.addClass("active");
		if (theDiv.css('display') == 'none'){
			theDiv.slideDown('slow').removeClass("active");
		}else{
			theDiv.slideUp('slow').removeClass("active");	
		}
		e.preventDefault();
		
	});
	
	/* -- trigger submission for staff profile research interests -- */
	jQuery(".search_interest").click(function(e){
		jQuery('#selSubCat').val(jQuery(this).attr('rel'));
		jQuery('#staffsearchfromprofile').trigger('submit');
		e.preventDefault();
	});
	
	/* -- auto rotator -- */
	$(".rotator").each(function(i){
		var img = $(this).find("IMG:first");
		img.addClass("active");
		$(this).addClass("active_"+i);
		$(this).animate({height:img.attr('height')+'px'},1000);
		$(this).animate({width:img.attr('width')+'px'},1000);
		includeJs('/js/rotator.js',function(){
			setInterval("triggerRotate('.active_"+i+"')", 5000 );
		});
	});

	/* -- fancybox triggered only if appropriate architecture and linking is found -- */
	if ($('a[href$=jpg],a[href$=gif],a[href$=png],a[href$=flv][rel^="lightbox"],a[href$=mp4][rel^="lightbox"],a[href$=xml][rel^="lightbox"]').length){
		includeJs('/js/jquery.flash.js',function(){
		includeJs('/js/jquery.easing.min.js',function(){ 
		includeJs('/js/jquery.fancybox.min.js',function(){
	$('a[href$=jpg] img,a[href$=gif] img,a[href$=png] img,a[href$=flv][rel^=lightbox] img,a[href$=mp4][rel^=lightbox] img,a[href$=xml][rel^=lightbox] img').parent().each(function(){
																																												   		var clickable = null;
		clickable = $(this); 
																																														
		clickable.each(function(){ var playButton = $('<img src="/images/img09-play-media-01.gif" alt="click to view" />'); $(this).css("position","relative"); playButton.css("position","absolute"); playButton.css("height","auto"); playButton.css("width","auto"); playButton.css("top",parseInt((parseInt(clickable.height(),10)-30)/2)+"px"); playButton.css("left",parseInt((parseInt(clickable.width(),10)-40)/2)+"px"); playButton.addClass("playButton"); playButton.fadeTo("fast", 0.3); $(this).append(playButton); }).hover(function(){$(this).find(".playButton").stop().fadeTo("slow",0.75);},function(){$(this).find(".playButton").stop().fadeTo("slow", 0.3);});
		$('a[href$=jpg],a[href$=gif],a[href$=png],a[href$=flv][rel^=lightbox],a[href$=mp4][rel^=lightbox],a[href$=xml][rel^=lightbox]').fancybox().click(function(e){e.preventDefault();});
				});
			});	
		});
	});
	}
  
  });
});