//JS file for NAU

//Variable for Global Nav --------------------------------------------------------------------------------

var navConfig = {
	interval: 50, // number = milliseconds delay before onMouseOver
	over: dropDown, // function = onMouseOver callback (REQUIRED)    
	timeout: 100, // number = milliseconds delay before onMouseOut    
	out: pullUp // function = onMouseOut callback (REQUIRED)    
};

//Variables for Page Banner --------------------------------------------------------------------------------

//var for total number of li's in the pageBanner slideshow
var pageBannerNum;
//var for number of images that have 'checked in' loaded
var imageCounter = 0;
//var for counting through the slideshow
var i = 0;
//translock to ensure actions don't overlap each other
var translock = false;
//set modal lock to ensure that modal actions don't overlap
var modlock = false;
//set var to count where user is in a modal window photo gallery
var modalCount = 1;
//and another var to globalize the gallery length
var modalLength = 0;
//var to standardize the amount of time slides take (in milliseconds)
var timeInterval = 5000;
//set timeout var
var t;
//set var to store ajax URL
var ajaxString;
//media lock
var medialock = false;
//inline gallery lock
var inlineLock = false;

//Prep the doc
$(document).ready(function(){

//Collapsable Content --------------------------------------------------------------------------------------

$('div.collapse').addClass('jshide');
//on a.toggle click...
$('a.toggle').click(function() {
	//check to see if still accessibly hidden
	if($(this).hasClass('fired')) {
		//toggle the hidden content
		$(this).next().slideToggle(250);
		//change the arrow
		if($(this).hasClass("toggled")) {
			$(this).removeClass("toggled");
		}
		else {
			$(this).addClass("toggled");
		}
	}
	else {
		//accessible hide has been fired once
		$(this).addClass('fired');
		//hide the content
		$(this).next().hide();
		//remove the jshide class
		$(this).next().removeClass('jshide');
		//toggle the hidden content
		$(this).next().slideToggle(250);
		//change the arrow
		if($(this).hasClass("toggled")) {
			$(this).removeClass("toggled");
		}
		else {
			$(this).addClass("toggled");
		}
	}
	
});

//Global Nav --------------------------------------------------------------------------------------

$("nav#nauNav > ul > li").stop();
//when the global links are hovered over
$("nav#nauNav > ul > li").not('.home').hoverIntent( navConfig );

//Page Banner --------------------------------------------------------------------------------------

if ($('div#pageBanner').length>0) {
	//if so, check to see if there is more than one
	if ($('div#pageBanner ul li').length>1) {
		//show the loading gif
		$('div#pageBanner img#loader').show();
		//randomize li's if classed correctly
		if ($('div#pageBanner').hasClass('randomize')) {
			$('div#pageBanner ul').randomize('li');
		}
		//count the li's (if they haven't been already)
		if (pageBannerNum == null) {
			//set the pageBannerNum var
			pageBannerNum = $('div#pageBanner ul li figure').length;
		}
		//create the thumbnails
		var thumbs = 1;
		while (thumbs <= pageBannerNum) {
			//if this isn't the last time
			if (thumbs == 1) {
				//write the thumb
				$('div#pageBanner nav').prepend('<a class="active 1" onClick="alterShow(1);"></a>')
			}
			else {
				//write thumb
				$('div#pageBanner nav').prepend('<a class="' + thumbs + '" onClick="alterShow(' + thumbs + ');"></a>');
			}
			//add one to thumbs
			thumbs++;
		}
	}
	//or else just show the first li
	else {
		$('div#pageBanner ul li').show();
		translock = true;
	}
}

//Modal Windows --------------------------------------------------------------------------------------

/*
 * SimpleModal Basic Modal Dialog
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2010 Eric Martin - http://ericmmartin.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Revision: $Id: basic.js 254 2010-07-23 05:14:44Z emartin24 $
 */
 	
 	$('.videoModalTrigger').click(function (e) {
 		//first remove the modalActive class in case there was a gallery already open
 		$('div.modalContent').removeClass('modalActive');
 		//add class 'activate' to the current modal gallery to specify movements etc
 		$(this).next('.modalContent').addClass('modalActive');
 		//fire the modal window
 		$(this).next('.modalContent').modal({
 			opacity: 85,
 			position: ["100px", null]
 		});
 	});
 	

	$('.modalTrigger').click(function (e) {
		//first remove the modalActive class in case there was a gallery already open
		$('div.modalContent').removeClass('modalActive');
		//add class 'activate' to the current modal gallery to specify movements etc
		$(this).next('.modalContent').addClass('modalActive');
		//fire the modal window
		$(this).next('.modalContent').modal({
			opacity: 85,
			position: ["100px", null]
		});
		
		//ashx test   https://cmsdev.nau.edu/gallery.ashx?id=652
		//my test page    http://cmsassets.nau.edu/dev/nau/testModal.html
		
		//grab the url and change it to the ajax content page
		ajaxString = $(this).prev('a').attr('href').replace('.aspx','.ashx');
		
		//ajax in content
		$.get(ajaxString, function(content){
			//place the ajaxed content into the document
			$('.modalActive').prepend(content).show(0, function(){
				//modal image size adjustments
				$('div.modalActive ul li img').each(function(){
					//check to see if img is too short
					if ($(this).height() < 475) {
						//set the height to a var
						var hgt = ((475 - $(this).height()) / 2);
						//set the padding accordingly
						$(this).css({'padding-top' : hgt, 'padding-bottom' : hgt});
					}
					if ($(this).width() < 720) {
						//set the height to a var
						var hgt = ((720 - $(this).width()) / 2);
						//set the padding accordingly
						$(this).css({'padding-left' : hgt, 'padding-right' : hgt});
					}
				});
			});
			//count the number of images in the gallery
			modalLength = $('div.modalActive ul li').length;
			//write the counter content to the dom
			$('div.modalActive span').html(modalCount + ' / ' + modalLength);
		});
		return false;
	});

	//on modal close...
	$('a.simplemodal-close').click(function(){
		modalGalClose();
	});	
	
	
	//on gallery arrow click
	$('div.modalContent div.nav .modalRight').click(function(){
		modalGalRight();
	});

	$('div.modalContent div.nav .modalLeft').click(function(){
		modalGalLeft();
	});
	
	//on gallery arrow strike
	$(document).keydown(function(e){
	    if (e.keyCode == 37) { 
	       modalGalLeft();
	       return false;
	    }
	    else if (e.keyCode == 39) { 
	       modalGalRight();
	       return false;
	    }
	    else if (e.keyCode == 27) { 
	       modalGalClose();
	       return false;
	    }
	});
	
//Tabbing interface actions for global nav	----------------------------------------------
	$("nav#nauNav > ul > li").focusin(function() {
		$('a', this).animate({ color: "#FFF" }, 0);
	$('ul.dropdown, ul.dropdownRight', this).fadeIn(0);
	});
	
	$("nav#nauNav > ul > li").focusout(function() {
		if ($(this).hasClass('quickLinks')) {
			$('a', this).animate({ color: "#618F80" }, 0);
			$('ul.dropdown, ul.dropdownRight', this).fadeOut(0);
		}
		else {
			$('a', this).animate({ color: "#8c8c8c" }, 0);
			$('ul.dropdown, ul.dropdownRight', this).fadeOut(0);
		}
	});
	
//Media Ribbon Functionality
	if ($('section#mediaRibbon ul li').length > 4) {
		//There are more than 4 items in the Ribbon
		$("<div id=\"mediaNavigation\"><a id=\"prevMedia\"></a><a id=\"nextMedia\"></a></div>").insertBefore('section#mediaRibbon');
	}
	else {
		//There are less than 4 items in the Ribbon
		$("<div id=\"mediaNavigation\"></div>").insertBefore('section#mediaRibbon');
	}
	
	//The Action
	$('a#prevMedia').click(function(){
		if (medialock == true) {
			return;
		}
		else {
			medialock = true;
			//send the last li to the front
			$('section#mediaRibbon ul li:first-child').before($('section#mediaRibbon ul li:last-child'));
			//reset the ul position
			$('section#mediaRibbon ul').animate({ left: -183 }, 0, function(){
				//move the li
				$('section#mediaRibbon ul').animate({ left: 0 }, 400, function(){
					//unlock
					medialock = false;	
				});
			});
		}
	});
	$('a#nextMedia').click(function(){
		if (medialock == true) {
			return;
		}
		else {
			medialock = true;
			//move the ul position
			$('section#mediaRibbon ul').animate({ left: -183 }, 400, function(){
				//send the first li to the back
				$('section#mediaRibbon ul li:last-child').after($('section#mediaRibbon ul li:first-child'));
				//reset the position simultaneously
				$('section#mediaRibbon ul').animate({ left: 0 }, 0);
				//unlock
				medialock = false;	
			});
			
		}
	});		
	
	
//Inline Gallery slider functionality

	$('div.inlineGallery a.right').click(function(){
		//if animation is already under way...
		if (inlineLock==true) {
			return;
		}
		inlineLock=true;
		$('div.inlineGallery div ul').animate({'left' : -240},{queue:false, duration: 500, complete: function(){
			$('div.inlineGallery div ul li:last-child').after($('div.inlineGallery div ul li:first-child')); 	
			$('div.inlineGallery div ul').css({'left' : '0px'});
			inlineLock = false;
		}
		});
	});
	
	$('div.inlineGallery a.left').click(function(){
		//if animation is already under way...
		if (inlineLock==true) {
			return;
		}
		inlineLock=true;
		$('div.inlineGallery div ul li:first-child').before($('div.inlineGallery div ul li:last-child')); 	
		$('div.inlineGallery div ul').animate({'left' : '-240px'}, {queue:false, duration: 0, complete: function(){
			$('div.inlineGallery div ul').animate({'left' : 0},{queue:false, duration: 500, complete: function(){
				inlineLock = false;
			}
			});
		}
		});
	});
	
	
	
	
	
//close doc.ready	
});

//Randomization function for page banner
(function($) {

$.fn.randomize = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);
      
      elems.sort(function() { return (Math.round(Math.random())-0.5); });  

      $this.empty();  

      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);      

  });    
}
})(jQuery);


//Functions for Global Nav -----------------------------------------------------------------------------------
function dropDown() {
	$('a', this).animate({ color: "#FFF" }, 100);
	$('ul.dropdown, ul.dropdownRight', this).fadeIn(100);
}

function pullUp() {
	if ($(this).hasClass('quickLinks')) {
		$('a', this).animate({ color: "#618F80" }, 100);
		$('ul.dropdown, ul.dropdownRight', this).fadeOut(100);
	}
	else {
		$('a', this).animate({ color: "#8c8c8c" }, 100);
		$('ul.dropdown, ul.dropdownRight', this).fadeOut(100);
	}
}

//Functions for Page Banner -----------------------------------------------------------------------------------

//functions for modal gallery navigation
function modalGalRight() {
	//check for modalLock
	if (modlock == true) {
		return;
	}
	else {
		modlock = true;
		//move the li
		$('div.modalActive ul').animate({ left: -720 }, 400, function() {
			//send the first li to the back
			$('div.modalActive ul li:last-child').after($('div.modalActive ul li:first-child'));
			//reset the ul position
			$('div.modalActive ul').css("left", "0px");
			//see if this is the last image in the gallery
			if (modalCount == modalLength) {
				//if so set the modalCount back to one
				modalCount = 1;
			}
			else {
				//if not add one
				modalCount++;
			}
			//write the counter content to the dom
			$('div.modalActive span').html(modalCount + ' / ' + modalLength);
			//release lock
			modlock = false;
		});
	}
}

function modalGalLeft() {
	//check for modalLock
	if (modlock == true) {
		return;
	}
	else {
		modlock = true;
		//send the first li to the back
		$('div.modalActive ul li:first-child').before($('div.modalActive ul li:last-child'));
		//reset the ul position
		$('div.modalActive ul').animate({ left: -720 }, 0, function(){
			//move the li
			$('div.modalActive ul').animate({ left: 0 }, 400, function(){
				//see if this is the last image in the gallery
				if (modalCount == 1) {
					//if so set the modalCount back to one
					modalCount = modalLength;
				}
				else {
					//if not add one
					modalCount--;
				}
				//write the counter content to the dom
				$('div.modalActive span').html(modalCount + ' / ' + modalLength);
				//release lock
				modlock = false;	
			});
		});
	}
}

function modalGalClose() {
	//remove the ajaxed content from the doc
	$('.modalActive h3, .modalActive ul').remove();
	//reset modalCount
	modalCount = 1;
}

//waiting for images to load
function upImgCount() {
	//if for some reason the img's load before the doc.ready fires
	if (pageBannerNum == null) {
		//set the pageBannerNum var
		pageBannerNum = $('div#pageBanner ul li figure').length;
	}
	//add one to images loaded
	imageCounter++;
	//test to see if they all are loaded
	if (imageCounter == pageBannerNum) {
		slideshow();
	}
	else {
		return;
	}
} 

function slideshow() {
	//check translock
	if (translock == true) {
		return;
	}
	else {
		translock = true;
		//if this is the first time through
		if (i == 0) {
			//fade Out the loader gif
			$('img#loader').delay(1000).fadeOut(500, function(){
				//fade in the nav
				$('div#pageBanner nav').fadeIn(500);
				//fade in the li's
				$('div#pageBanner ul li:first-child').fadeIn(500, function(){
					//i equals 1 to start
					i = 1;
					//set timeout
					t=setTimeout(slideshow, timeInterval);
					//turn off lock
					translock = false;
				});
			});
		}
		//repeat time through
		else if (i < pageBannerNum) {
			//fadeout the active thumb
			$('div#pageBanner nav a.active').fadeTo(500, 1);
			//fadeout the current slide
			$('div#pageBanner ul li:nth-child(' + i + ')').fadeOut(500, function(){
				//add one to i
				i++;
				//swap the 'active' thumbnail
				$('div#pageBanner nav a.active').removeClass('active');
				//fade in the li
				$('div#pageBanner ul li:nth-child(' + i + ')').fadeIn(500);
				//and fadeIn the new thumb active
				$('div#pageBanner nav a.' + i).fadeTo(500, 0.6, function(){
					//add the active class
					$(this).addClass('active');
					//setTimeout for the slideshow again
					t=setTimeout(slideshow, timeInterval);
					//turn off lock
					translock = false;
				});
			});
		}
		else if (i == pageBannerNum) {
			//fadeout the active thumb
			$('div#pageBanner nav a.active').fadeTo(500, 1);
			//fadeout the current slide
			$('div#pageBanner ul li:nth-child(' + i + ')').fadeOut(500, function(){
				//swap the 'active' thumbnail
				$('div#pageBanner nav a.active').removeClass('active');
				//fade in the li
				$('div#pageBanner ul li:first-child').fadeIn(500);
				//and fadeIn the new thumb active
				$('div#pageBanner nav a.1').fadeTo(500, 0.6, function(){
					//add the active class
					$(this).addClass('active');
					//set i to 1
					i = 1;
					//setTimeout for the slideshow again
					t=setTimeout(slideshow, timeInterval);
					//turn off lock
					translock = false;
				});
			});
		
		}
	}
}

function alterShow(val) {
	//check to see if translock is on
	if (translock == true) {
		return;
	}
	else {
		if ($('div#pageBanner nav a.' + val).hasClass('active')) {
			return;
		}
		else {
			//activate lock
			translock = true;
			//clear timeout
			clearTimeout(t);
			//fadeout the active thumb
			$('div#pageBanner nav a.active').fadeTo(500, 1);
			//fadeout the current slide
			$('div#pageBanner ul li:nth-child(' + i + ')').fadeOut(500, function(){
				//change i
				i = val;
				//swap the 'active' thumbnail
				$('div#pageBanner nav a.active').removeClass('active');
				//fade in the li
				$('div#pageBanner ul li:nth-child(' + i + ')').fadeIn(500);
				//and fadeIn the new thumb active
				$('div#pageBanner nav a.' + i).fadeTo(500, 0.6, function(){
					//add the active class
					$(this).addClass('active');
					//setTimeout for the slideshow again
					t=setTimeout(slideshow, timeInterval);
					//turn off lock
					translock = false;
				});
			});
		}
	}
}








//Jquery Focus Plugin (allows tabbing between child elements with out losing focus on parent)
(function($) {

function sameOrChild(n1, n2) {
	// http://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html
	return n1 === n2 || (typeof(n1.contains) !== 'undefined' ? n1.contains(n2) : !!(n1.compareDocumentPosition(n2) & 16));
}

function focusHandler(event) {
	event = $.event.fix(event || window.event), $this = $(this), isFocused = $this.data('focus.isFocused');
	if (!isFocused) {
		$this.data('focus.isFocused', true);
		event.type = 'focusin';
		return $.event.handle.apply(this, [event]);
	}	
}

function blurHandler(event) {
	var args = [].slice.call(arguments, 1), $this = $(this);
	event = $.event.fix(event || window.event);

	window.setTimeout(function() {
		if (!sameOrChild($this.get(0), document.activeElement)) {
			$this.data('focus.isFocused', false);
			event.type = 'focusout';
			return $.event.handle.apply($this.get(0), [event]);
		}
	}, 0);
}

function setupEvents(elem) {
	var $elem = $(elem), ref = $elem.data('focus.handlerReferences') || 0;
	if (ref == 0) {
		if (elem.addEventListener) {
			elem.addEventListener('focus', focusHandler, true);
			elem.addEventListener('blur', blurHandler, true);
		}
		else {
			elem.onfocusin  = focusHandler;
			elem.onfocusout = blurHandler;
		}
	}
	$elem.data('focus.handlerReferences', ref + 1)
	$elem.data('focus.isFocused', sameOrChild(elem, document.activeElement));
}

function teardownEvents(elem) {
	var $elem = $(elem), ref = $elem.data('focus.handlerReferences') || 0;
	if (ref == 1) {
		if (elem.removeEventListener) {
			elem.removeEventListener('focus', focusHandler, true);
			elem.removeEventListener('blur', blurHandler, true);
		}
		else {
			elem.onfocusin  = null;
			elem.onfocusout = null;
		}
		$elem.removeData('focus.handlerReferences')
		$elem.removeData('focus.isFocused');
	}
	else {
		$elem.data('focus.handlerReferences', ref - 1);
	}
}

$.each(['focusin', 'focusout'], function(i, x) {
	$.event.special[x] = {
		setup: function() { setupEvents(this); },
		teardown: function() { teardownEvents(this); }
	};
});

$.fn.extend({
	focusin: function(fn) {
		return fn ? this.bind('focusin', fn) : this.trigger('focusin');
	},
	focusout: function(fn) {
		return fn ? this.bind('focusout', fn) : this.trigger('focusout');
	}
});

})(jQuery);

