// JavaScript Document
$(document).ready(function() {
	eCheck();
	//$("#keywords").search();
	$("#keywords").focus(function() {
		if ($(this).val() == 'Search The College of Business') {
			$(this).val('');
		}
		return false;
	});
	$("#keywords").blur(function() {
		if ($(this).val() == '') {
			$(this).val('Search The College of Business');
		}
		return false;
	});	
	$("#FauKeywords").focus(function() {
		if ($(this).val() == 'FAU Web Search') {
			$(this).val('');
		}
		return false;
	});
	$("#FauKeywords").blur(function() {
		if ($(this).val() == '') {
			$(this).val('FAU Web Search');
		}
		return false;
	});	
	$("#uberSearchForm").validsearchFau();
	$("#searchForm").validsearch();
	//Dropdowns show/hide
	supaNavLoader("/undergraduate/dropdown/index.aspx","und",1);
	//$('#primaryNav li:has(div)').supaNav();//temporarily bind it this way until integration
	$('.resourceNav li:has(ul)').resourceDrops();
	$('#unterFooter li:has(div)').supaNav();//re-using the super nav function for the footer.
	//Emergency Notice Closer
	$('#eCloser').live('click', function(){
		$('#theHead').css('z-index','5').removeClass('emergency');
		$('#emergencyAlert').css('display','none');
		document.cookie = "eCookie=closed; path=/";
		return false;
	});
	$('#leftNav li.firstGrade:last').addClass('last');
	var leftNavTest = $('#leftNav').html();
	if (leftNavTest == null){
		leftNavTest = 'nothing';
	}
	if(leftNavTest.indexOf('LI') == -1 && leftNavTest.indexOf('li') == -1){
		$('#leftNav').remove();
	}
	var mastheadTest = $('.masthead').html();
	if (mastheadTest == null){
		mastheadTest = 'nothing';
	}
	if(mastheadTest.indexOf('IMG') == -1 && mastheadTest.indexOf('img') == -1){
		$('.masthead').remove();
	}
	/* JPG Fancybox opener for general content areas. If it's null, we will remove it. If it's not null, we'll make it more useful. */
	if ($('.contentImage img').attr('src') == null){
		$('.contentImage').remove();
	} else if ($('.contentImage img').attr('src') != null){
		$('.contentImage a:first').addClass('enlarge');
		$('.contentImage figcaption').addClass('caption');
		var contentImage = $('.content .enlarge img');
		var contentImageWidth = contentImage.width();
		var targetString = $('.contentImage img').attr('src');
		targetString = targetString.slice(0,targetString.indexOf('&')) + '&ext=.jpg';
		var contentImageCap = $('.contentImage .caption').text();
		$('.contentImage .enlarge').css('width',contentImageWidth+'px').attr('href',targetString).attr('title',contentImageCap).append('<span>enlarge</span>');
		$('.contentImage .caption').css('width',contentImageWidth+'px');
		$('.content .enlarge').fancybox({
			'zoomOpacity'			: true,
			'overlayShow'			: true,
			'zoomSpeedIn'			: 600,
			'zoomSpeedOut'			: 500,
			'easingIn'				: 'easeOutBack',
			'easingOut'				: 'easeInBack',
			'overlayOpacity'		: 0.9,
			'hideOnContentClick': false
		});
	}
	// Fancybox opener for Intelliworks Forms
	$('.iwforms').fancybox({
		'zoomOpacity'			: true,
		'overlayShow'       	: true,
		'zoomSpeedIn'       	: 600,
		'zoomSpeedOut'      	: 500,
		'easingIn'          	: 'easeOutBack',
		'easingOut'         	: 'easeInBack',
		'frameWidth'        	: 662,
		'frameHeight'       	: 580,
		'overlayOpacity'    	: 0.9,
		'hideOnContentClick'	: false
	});
	//Fancybox using the native gallery functionality
	$('.gallery').fancybox({
		'zoomOpacity'			: true,
		'overlayShow'			: true,
		'zoomSpeedIn'			: 600,
		'zoomSpeedOut'			: 500,
		'easingIn'				: 'easeOutBack',
		'easingOut'				: 'easeInBack',
		'overlayOpacity'		: 0.9,
		'hideOnContentClick': false
	});
	//JPG Fancybox opener for categorized image galleries, cloned from the right column script, but using a different class name
	$('.photoGalleryCat').fancybox({
		'zoomOpacity'			: true,
		'overlayShow'			: true,
		'zoomSpeedIn'			: 600,
		'zoomSpeedOut'			: 500,
		'easingIn'				: 'easeOutBack',
		'easingOut'				: 'easeInBack',
		'frameWidth'			: 662,
		'frameHeight'			: 580,
		'overlayOpacity'		: 0.9,
		'hideOnContentClick': false
	});
});
//Clear input box plugin.
$.fn.search=function(){return this.focus(function(){if(this.value==this.defaultValue){this.value=""}}).blur(function(){if(!this.value.length){this.value=this.defaultValue}})};
//validate FAU Search on submit
$.fn.validsearchFau=function(){return this.submit(function(){
if(this.elements['q'].value==''||this.elements['q'].value==this.elements['q'].defaultValue){$("p.tryagain2").html("Please enter a keyword before submitting").fadeIn(300);setTimeout('$("p.tryagain2").fadeOut()', 5000);return false}})};
//validate FAU School of Business Search on submit
$.fn.validsearch=function(){return this.submit(function(){
	if (this.elements['keywords'].value==''||this.elements['keywords'].value==this.elements['keywords'].defaultValue){
		$("p.tryagain").html("Please enter a keyword before submitting").fadeIn(300);
		setTimeout('$("p.tryagain").fadeOut()', 5000);
		return false;
	}
	var keyValString = $("#keywords").val();
	var keyValTest = $.trim(keyValString);
	$("#keywords").val(keyValTest);
  })
};
//validate email on submit
$.fn.validemail=function(){return this.submit(function(){
if(this.elements['email'].value==''||this.elements['email'].value==this.elements['email'].defaultValue||this.elements['email'].value.indexOf('@')==-1||this.elements['email'].value.indexOf('.',this.elements['email'].value.indexOf('@'))==-1){$("p.tryagain2").html("Please enter a valid email address").fadeIn(300);setTimeout('$("p.tryagain2").fadeOut()', 5000);return false}})};

//dropdown for absurdly impractical ultra mega primary navigation dropdowns
$.fn.supaNav=function(){
	return this
	.hoverIntent(
		function () {if ($(this).children('div')) {$(this).children('div').slideDown(300);}},
		function () {$(this).children('div').slideUp(300)});
};
$.fn.resourceDrops=function(){
	return this
	.hoverIntent(
		function () {if ($(this).children('ul')) {$(this).children('ul').slideDown(300);$('#theHead').css('z-index','33');}},
		function () {$(this).children('ul').slideUp(300);});
};
function supaNavLoader(sourcePage,targetDiv,sequence){
	//alert(sourcePage+' : '+targetDiv+' : '+sequence);
	if (sequence == 1 || sequence == 2 || sequence == 3 || sequence == 4 || sequence == 5 || sequence == 6){
		$.ajax({
		  url: sourcePage,
		  cache: true,
		  success: function(html){
			$("#"+targetDiv).html(html);
			if (sequence == 1){
				supaNavLoader("/masters-phd/dropdown/index.aspx","grad",2);
			} else if (sequence == 2) {
				supaNavLoader("/executive-education/dropdown/index.aspx","exec",3);
			} else if (sequence == 3) {
				supaNavLoader("/faculty-research/dropdown/index.aspx","faculty",4);
			} else if (sequence == 4) {
				supaNavLoader("/centers/dropdown/index.aspx","centers",5);
			} else if (sequence == 5) {
				supaNavLoader("/our-college/dropdown/index.aspx","college",6);
			} else if (sequence == 6){
				$('#primaryNav li:has(div)').supaNav();
			}
		  }
		});
	}
};
// hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+ <http://cherne.net/brian/resources/jquery.hoverIntent.html | author Brian Cherne <brian@cherne.net>
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:6000,interval:400,timeout:500};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

//Emergency Check
function eCheck(){
	var eMess;
	var eCookieTest = get_cookie("eCookie");
	if (eCookieTest == null){
		//alert('No Cookie Present Make the AJAX Call.');
		eMess = $("#emergencyAlert").text();
		if(eMess == '' || eMess == ' '){
			//alert('There was no cookie, but also there was no content. So we will remove the empty DIV. Test: '+eMess);
			$("#emergencyAlert").remove();
			document.cookie = "eCookie=closed; path=/";
		} else {
			//alert('There was no cookie, and there was content present. So we will display the emergency message. Test: '+eMess);
			$('#theHead').css('z-index','33').addClass('emergency');
			$('#emergencyAlert').slideDown();
		}
	}
	return false;
};

//Emergency Check Manual Version
function eCheckManual(){
	alert('This should not be called at all.');
	var eCookieTest = get_cookie("eCookie");
	if (eCookieTest == null){
		//No Cookie Present Make the test AJAX Call
		$.ajax({
		  url: "/emergency-on/index.aspx",
		  cache: false,
		  error: function(jqXHR,textStatus,errorThrown){
			//alert(jqXHR +" : "+ textStatus +" : "+ errorThrown);
			//The page is not there. So we remove the target div and write the cookie to prevent subsequent unnecessary AJAX calls
			$("#emergencyAlert").remove();
			document.cookie = "eCookie=closed; path=/";
		  },
		  success: function(html){
			  //The page is there. So we're going to display it.
			$("#emergencyAlert").html(html.slice(html.indexOf('body>')+5),html.indexOf('</body>'));
			$('#theHead').css('z-index','33').addClass('emergency');
			$('#emergencyAlert').slideDown();
		  }
		});
	}
};

// Cookie retrieval and deletion
function get_cookie(cookie_name) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
	if (results)
		return ( unescape ( results[2] ) );
	else
		return null;
};
function delete_cookie(cookie_name) {
	var cookie_date = new Date ( );  
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = cookie_name += "=; path=/; expires=" + cookie_date.toGMTString();
};

//automatic jQuery cookies if you don't feel like parsing them yourself - credit: Klaus Hartl (stilbuero.de)...Klaus is representin' DEUTSCHLAND!!!
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

