//Newsletter Signup Helper
function newsletterHelp() {
	var emailInputs = $$('input.emailSignup');
	
	emailInputs.each(function(emailInput) {
		emailInput.observe('keypress', function(event){
			if(event.keyCode == Event.KEY_RETURN) {
				console.log('test');
				window.location('http://safeguardbeta.optiemstaging.com/News_and_Events/Email_Sign_Up.aspx');
				event.stop();
				return false;
			} else {
			}	
		});	
	});

}


//Sort by Year Drop Down Helper
//Finds the list item without a link and puts it at the top of the list indicating current selection.
function sortHelper() {
	var sortLists = $$('ul.yearPagination');
	
	if(!sortLists[0]) return false;
	
	
	sortLists.each(function(sortList) {
		var listItems = sortList.select('li');
		
		
		listItems.each(function(listItem) {
			
			
			if(!listItem.down('a')){
				copy = new Element('li').update(listItem.firstChild.nodeValue);
				sortList.insert({ top: copy });
			}
			
		});
	});
}
//Utility Drop Down Hover Fix
//Note: Prototype Driven

function sortDropDown() {
	var sortDropDown = $$('ul.yearPagination');
	
	sortDropDown.each(function(DropDownLink){
		DropDownLink.observe('mouseenter', function(event){
			DropDownLink.addClassName('hover');
		});
		DropDownLink.observe('mouseleave', function(event){
			DropDownLink.removeClassName('hover');
		});
	});
}

//Upcoming Events Rotator
//Note: Prototype Framework
function upcomingEventCarousel() {
	var upcomingEvents = $$('ul.events li');
	
	if(!upcomingEvents[0]) return false;
	
	
	var upcomingEventQueue = Effect.Queues.get('eventQueue');
	
		upcomingEvents.each(function(upcomingEvent, index) {
		if(upcomingEvent.empty()){
			upcomingEvent.remove();
		}
	});
	
	var upcomingEvents = $$('ul.events li');
	
	var eventContainer = upcomingEvents[0].up('div');
	var currentHighlight = 0;
	var previousHighlight = upcomingEvents.size();
	var highlightIndex = upcomingEvents.size();
	
	var upcomingEventsNavigation = new Element('ol');
	upcomingEventsNavigation.addClassName('navUpcomingEvents');
	
	previousHighlightButton = new Element('li');
	previousHighlightButton.addClassName('previous');
	previousHighlightAnchor = new Element('a', { href: "#"}).update("Previous");
	
	previousHighlightButton.insert({ bottom: previousHighlightAnchor });
	upcomingEventsNavigation.insert({ top: previousHighlightButton });
	
	navigationDescription = new Element('li').update("click arrows to scroll");
	navigationDescription.addClassName('navDescription');
	
	previousHighlightButton.insert({ after: navigationDescription });
	
	nextHighlightButton = new Element('li');
	nextHighlightButton.addClassName('next');
	nextHighlightAnchor = new Element('a', { href: "#"}).update("Next");

	nextHighlightButton.insert({ bottom: nextHighlightAnchor });
	upcomingEventsNavigation.insert({ bottom: nextHighlightButton });

	eventContainer.down('p').insert({ after: upcomingEventsNavigation });
	
document.observe('safe:updateEvent', function(event){
		if (upcomingEventQueue.effects.size() == 0) {
			
			var highlightMove = event.memo.indexMove;
			
			previousHighlight = currentHighlight;
			currentHighlight = (upcomingEvents.size() + ((currentHighlight - highlightMove) % upcomingEvents.size())) % upcomingEvents.size();

			upcomingEvents[currentHighlight].setStyle({
				left: -(highlightMove*upcomingEvents[previousHighlight].getWidth()) + 'px'
			});
			

	new Effect.Parallel([new Effect.Move(upcomingEvents[previousHighlight], {
				sync: true,
				x: highlightMove*upcomingEvents[previousHighlight].getWidth(),
				y: 0,
				mode: 'absolute'
			}), new Effect.Move(upcomingEvents[currentHighlight], {
				sync: true,
				x: 0,
				y: 0,
				mode: 'absolute'
			})], {
				upcomingEventQueue: {
					position: 'end',
					scope: 'eventQueue',
					limit: 3
				}
		});
	};
	
	});	
	carousel = new PeriodicalExecuter(function(){
		nextHighlightButton.fire('safe:updateEvent', { indexMove: -1 });
	}, 10);
	
	previousHighlightButton.observe('click', function(event){
		previousHighlightButton.fire('safe:updateEvent', { indexMove: 1 });
		carousel.stop();
		event.stop();
	});
	
	nextHighlightButton.observe('click', function(event){
		nextHighlightButton.fire('safe:updateEvent', { indexMove: -1 });
		carousel.stop();
		event.stop();
	});
}

//Site Highlight Rotator
//Creates navigation for Breakout Carousel
//Note: Prototype Framework
function breakoutCarousel() {
	var highlightModules = $$('#contentMain #siteModules div.highlight div.module');
	
	highlightModules.each(function(highlightModule, index){
		
		highlightModule.breakoutHighlights = highlightModule.down('ul.articles').childElements();
				
		highlightModule.numHighlights = highlightModule.breakoutHighlights.size();
		
		if(!highlightModule.breakoutHighlights[0]) return false;
		
		var queue = Effect.Queues.get('highlightQueue');
		
		highlightModule.breakoutHighlights.each(function(breakoutHighlight, index) {
			if(breakoutHighlight.empty()){
				breakoutHighlight.remove();
			}
		});
		
		highlightModule.breakoutHighlights = highlightModule.down('ul.articles').childElements();
		
		highlightModule.breakoutContainer = highlightModule.breakoutHighlights[0].up('div');
	
		highlightModule.currentHighlight = 0;
		highlightModule.previousHighlight = highlightModule.breakoutHighlights.size();
		highlightModule.highlightIndex = highlightModule.breakoutHighlights.size();
		
		highlightModule.breakoutNavigation = new Element('ul');
		highlightModule.breakoutNavigation.addClassName('navModule');
		
		highlightModule.previousHighlightButton = new Element('li');
		highlightModule.previousHighlightButton.addClassName('previous');
		highlightModule.previousHighlightAnchor = new Element('a', { href: "#"}).update("Previous");
		highlightModule.previousHighlightButton.insert({ bottom: highlightModule.previousHighlightAnchor });
		highlightModule.breakoutNavigation.insert({ top: highlightModule.previousHighlightButton });
		
		highlightModule.highlightPositionText = new Element('li').update(" (click arrows to scroll)");
		highlightModule.highlightPosition = new Element('strong').update("Story 1 of " + highlightModule.numHighlights);
		highlightModule.highlightPositionText.insert({ top: highlightModule.highlightPosition });
		highlightModule.breakoutNavigation.insert({ bottom: highlightModule.highlightPositionText });
		
		highlightModule.nextHighlightButton = new Element('li');
		highlightModule.nextHighlightButton.addClassName('next');
		highlightModule.nextHighlightAnchor = new Element('a', { href: "#"}).update("Next");
		highlightModule.nextHighlightButton.insert({ bottom: highlightModule.nextHighlightAnchor });
		highlightModule.breakoutNavigation.insert({ bottom: highlightModule.nextHighlightButton });
	
		highlightModule.breakoutContainer.insert({ top: highlightModule.breakoutNavigation });
		
		document.observe('SML:updateHighlight'+index, function(event){
				
				if (queue.effects.size() == 0) {
				
					highlightModule.highlightMove = event.memo.indexMove;
					
					highlightModule.previousHighlight = highlightModule.currentHighlight;
					highlightModule.currentHighlight = (highlightModule.breakoutHighlights.size() + ((highlightModule.currentHighlight - highlightModule.highlightMove) % highlightModule.breakoutHighlights.size())) % highlightModule.breakoutHighlights.size();
					
					highlightModule.highlightPosition.update("Story " + (highlightModule.currentHighlight + 1) +" of " + highlightModule.numHighlights);
					
					highlightModule.breakoutHighlights[highlightModule.currentHighlight].setStyle({
						left: -(highlightModule.highlightMove * highlightModule.breakoutHighlights[highlightModule.previousHighlight].getWidth()) + 'px'
					});
					
					new Effect.Parallel([new Effect.Move(highlightModule.breakoutHighlights[highlightModule.previousHighlight], {
						sync: true,
						x: highlightModule.highlightMove * highlightModule.breakoutHighlights[highlightModule.previousHighlight].getWidth(),
						y: 0,
						mode: 'absolute'
					}), new Effect.Move(highlightModule.breakoutHighlights[highlightModule.currentHighlight], {
						sync: true,
						x: 0,
						y: 0,
						mode: 'absolute'
					})], {
						queue: {
							position: 'end',
							scope: 'highlightQueue',
							limit: 1
						}
					});
				}
		});
		
		
		highlightModule.previousHighlightAnchor.observe('click', function(event){
			highlightModule.previousHighlightAnchor.fire('SML:updateHighlight'+index, { indexMove: 1 });
			event.stop();
		});
		
		highlightModule.nextHighlightAnchor.observe('click', function(event){
			highlightModule.nextHighlightAnchor.fire('SML:updateHighlight'+index, { indexMove: -1 });
			event.stop();
		});

	});
	
	
}

//siteHighlight rotator
//Creates navigation system to site highlights
//Note: Prototype Framework
function highlightCarousel() {
	var content = $('breakout');
	var highlights = $$('ol#siteHighlights li');
	
	if(!highlights[0]) {
		return false;
	}
	
	content.setStyle({
		position: 'static'
	});
	
	content.setStyle({
		position: 'absolute'
	});
	
	var currentHighlight = 0;
	
	var navigation = new Element('ol');
	navigation.addClassName('navHighlights');
	var navigationItems = [];
	
	highlights[currentHighlight].setStyle({
		position: 'absolute',
		top: '-999em',
		left: '-999em'
	});
	highlights[currentHighlight].setStyle({
		position: 'relative',
		top: 'auto',
		left: 'auto'
	});
	
	highlights.each(function(highlight, index){
		navigationItems[index] = new Element('li');
		var anchorTag = new Element('a', { href: "#"}).update(index+1);
		
		anchorTag.observe('click', function(event){
			highlights[currentHighlight].setStyle({
				position: 'absolute',
				top: '-999em',
				left: '-999em'
			})
			highlight.setStyle({
				position: 'relative',
				top: 'auto',
				left: 'auto'
			})
			currentHighlight = index;
		});
		
		navigationItems[index].insert({ bottom: anchorTag })
		navigation.insert({ bottom: navigationItems[index] });
	});
	
	content.insert({ top: navigation });
	
	var navigationLinks = navigation.childElements();
	navigationLinks[currentHighlight].down('a').toggleClassName('selected');
	
	carousel = new PeriodicalExecuter(function(){
		if(currentHighlight == highlights.size()-1) {
			highlights[currentHighlight].setStyle({
				position: 'absolute',
				top: '-999em',
				left: '-999em'
			});
			var lastHighlight = 0;
			highlights[lastHighlight].setStyle({
				position: 'relative',
				top: 'auto',
				left: 'auto'
			});
			navigationLinks[currentHighlight].down('a').toggleClassName('selected');
			currentHighlight = lastHighlight;
			navigationLinks[0].down('a').toggleClassName('selected');
		}
		else {
			highlights[currentHighlight].setStyle({
				position: 'absolute',
				top: '-999em',
				left: '-999em'
			});
			currentHighlight = currentHighlight + 1;
			highlights[currentHighlight].setStyle({
				position: 'relative',
				top: 'auto',
				left: 'auto'
			});
			navigationLinks[currentHighlight].down('a').toggleClassName('selected');
			navigationLinks[currentHighlight-1].down('a').toggleClassName('selected');
		}
	}, 5);

	navigationLinks.each(function(navLink, index){
		
		if(index){
			navLink.down('a').toggleClassName('carouselLink');
		}
		
		navLink.observe('click', function(event){
			navigationLinks.each(function(hiddenLink){
				hiddenLink.down('a').removeClassName('selected');
			});
			navigationLinks[currentHighlight].down('a').addClassName('selected');
			carousel.stop();
		});
	});
	
}

//Date Range Utility Show and Hide 
function dateUtility() {
	var dateUtilityButton = $('utilityButton');
	var dateUtilityShow = $$('fieldset.utility label');
	var utilityFieldset = $$('fieldset.utility')[0];
		
	if(!dateUtilityShow[0]) return false;	

	dateUtilityButton.observe('click', function(event){
		utilityFieldset.toggleClassName('utilityShow');
	});	
}
//Utility Drop Down Hover Fix
//Note: Prototype Driven

function UtilDropDown() {
	var UtilityDropDown = $$('ul.utilityDropDown');
	
	UtilityDropDown.each(function(DropDownLink){
		DropDownLink.observe('mouseenter', function(event){
			DropDownLink.addClassName('hover');
		});
		DropDownLink.observe('mouseleave', function(event){
			DropDownLink.removeClassName('hover');
		});
	});
}


//First and Last LI Selector
//Note: Prototype Driven
function liFirstLast() {
	var firstLIs =	$$('ul > li:first-child');
	var lastLIs = $$('ul > li:last-child');
	
	firstLIs.each(function(liFirst) {
		liFirst.addClassName('first');
		});
		
	lastLIs.each(function(liLast) {
		liLast.addClassName('last');
	});
}

function navHelper(){
	var navigationLIs = $$('#navMain li');
	
	navigationLIs.each(function(navigationLI){
		navigationLI.observe('mouseenter', function(event){
			navigationLI.addClassName('hover');
		});
		navigationLI.observe('mouseleave', function(event){
			navigationLI.removeClassName('hover');
		});
	});
}

//Backups for complex selectors
function cssHelper() {
	var siblings = $$('#breakout + #contentMain, #contentMain div.highlight .module + .module');
	
	siblings.each(function(sibling){
		sibling.addClassName('sibling');
	});
}

//Home Page News Helper
//Navigates between news tabs and news items
function newsHelper() {
	var newsModules = $$('#contentMain #siteModules div.highlight div.module');
	
	currentNewsModule = 0;
	
	newsModules.each(function(newsModule, index){
		newsHeader = newsModule.down('h2');
		newsHeader.setStyle({
			cursor: 'pointer'
		});
		newsHeader.observe('click', function(event){
			if(index == 0){
				newsModules[currentNewsModule].removeClassName('active');
				newsModules[currentNewsModule].removeClassName('activeTwo');
				currentNewsModule = index;
				newsModules[currentNewsModule].addClassName('active');
				newsModules[currentNewsModule].addClassName('activeOne');
			}
			else {
				newsModules[currentNewsModule].removeClassName('active');
				newsModules[currentNewsModule].removeClassName('activeOne');
				currentNewsModule = index;
				newsModules[currentNewsModule].addClassName('active');
				newsModules[currentNewsModule].addClassName('activeTwo');
			}
		});
	});
}

//Header Helper
//Creates various hover classes for the header controls
function headerHelper() {
	var hoverLists = $$('#quickLinks, #loginPages');
	
	hoverLists.each(function(hoverList){
		hoverList.observe('mouseenter', function(event){
			hoverList.addClassName('hover');
		});
		hoverList.observe('mouseleave', function(event){
			hoverList.removeClassName('hover');
		});
	});
}

function sectionsHelper(){
	//Navigation between the various tabbed sections
	var faqTabs = $$('#contentMain #contentArticle ul.navSections li');
	var faqSections = $$('#contentMain #contentArticle div.section');
	
	if(!faqSections[0]){
		return false;
	}
	
	var currentSectionIndex = 0;
	faqTabs[currentSectionIndex].addClassName('activeSection');
	faqSections[currentSectionIndex].addClassName('activeSection');
	
	faqTabs.each(function(faqTab, index){
		faqTab.observe('click', function(event){
			faqTabs[currentSectionIndex].removeClassName('activeSection');
			faqSections[currentSectionIndex].removeClassName('activeSection');
			
			currentSectionIndex = index;
			
			faqTabs[index].addClassName('activeSection');
			faqSections[index].addClassName('activeSection');
		});
	});
}

function faqHelper() {
	//FAQ Categories and Questions
	var faqCategories = $$('ul.faqCategories li');
	var faqQuestionGroups = $$('ul.faqQuestions > li');
	var faqQuestions = $$('ul.faqQuestions li a');
	var faqAnswers = $$('ul.faqAnswers > li');
	
	if(!faqCategories[0]){
		
	}
	else {
		faqCategoriesContainer = faqCategories[0].up('ul');
		
		var currentCategoryIndex = 0;
		var currentCategory = new Element('li');
		currentCategory.update(faqCategories[currentCategoryIndex].innerHTML);
		
		faqCategoriesContainer.insert({top: currentCategory});
		
		faqQuestionGroups[currentCategoryIndex].addClassName('activeQuestionGroup');
		
		faqQuestionGroups.each(function(faqQuestionGroup){
			faqQuestionGroup.addClassName('faqQuestionGroup');
		});
	
		faqCategoriesContainer.observe('mouseenter', function(event){
			faqCategoriesContainer.addClassName('faqHover');
		});
		
		faqCategoriesContainer.observe('mouseleave', function(event){
			faqCategoriesContainer.removeClassName('faqHover');
		});
		
		faqCategories.each(function(faqCategory, index){
			faqCategory.observe('click', function(event){
				currentCategory.update(faqCategory.innerHTML);
				faqQuestionGroups[currentCategoryIndex].removeClassName('activeQuestionGroup');
				faqQuestionGroups[index].addClassName('activeQuestionGroup');
				currentCategoryIndex = index;
				
				event.stop();
			});
		});
	}
	
	if(!faqQuestions[0]){
		/*
console.log('No Questions');
*/
	}
	else {
		
		var currentQuestionIndex = 0;
		faqQuestions[currentQuestionIndex].up('li').addClassName('activeQuestion');
		faqAnswers[currentQuestionIndex].addClassName('activeQuestion');
		
		faqQuestions.each(function(faqQuestion, index){
			faqQuestion.up('li').observe('click', function(event){
				faqQuestions[currentQuestionIndex].up('li').removeClassName('activeQuestion');
				faqAnswers[currentQuestionIndex].removeClassName('activeQuestion');
				
				currentQuestionIndex = index;
				
				faqQuestions[index].up('li').addClassName('activeQuestion');
				faqAnswers[index].addClassName('activeQuestion');
				
				event.stop();
			});
		});
	}
	
	
}

//Input Clear
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputClear() {
	var textInputs = $$('#header fieldset input[type="text"]');
	
	textInputs.each(function(textInput){
		textInput.initialValue = textInput.value;
		textInput.observe('focus', function(event) {
			if(textInput.value == textInput.initialValue){
				textInput.clear();
			}
		});
		textInput.observe('blur', function(event){
			if(textInput.value.blank() == true) {
				textInput.value = textInput.initialValue;
			}
		});
	});
}
function clearText() {
	var textInputs = $$('div.highlight fieldset input[type="text"]');
	
	textInputs.each(function(textInput){
		textInput.initialValue = textInput.value;
		textInput.observe('focus', function(event) {
			if(textInput.value == textInput.initialValue){
				textInput.clear();
			}
		});
		textInput.observe('blur', function(event){
			if(textInput.value.blank() == true) {
				textInput.value = textInput.initialValue;
			}
		});
	});
}

// Cookie Functions
// Set the cookie 
function setCookie(name,value,days) { 
	if (days) { 
		var date = new Date(); 
		date.setTime(date.getTime()+(days*24*60*60*1000)); 
		var expires = ";expires="+date.toGMTString(); 
	} else { 
		expires = ""; 
	} 
	document.cookie = name+"="+value+expires+";"; 
}

// Read the cookie 
function readCookie(name) { 
	var needle = name + "="; 
	var cookieArray = document.cookie.split(';'); 
	for(var i=0;i < cookieArray.length;i++) { 
		var pair = cookieArray[i]; 
		while (pair.charAt(0)==' ') { 
			pair = pair.substring(1, pair.length); 
		} 
		if (pair.indexOf(needle) == 0) { 
			return pair.substring(needle.length, pair.length); 
		} 
	} 
	return null; 
}

//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function() {

	//dynamicShadow('/images/global/shadow.png', 'page-container', 16, 0);
	Cufon.replace('#navSecondary h2 a', {
	hover: true
});
	//Cufon.replace('#navMain li a');
	Cufon.replace('#contentRelated div.highlight h2');
	Cufon.replace('#contentMain #siteModules div.highlight h2');
	Cufon.replace('#breakout ol#siteHighlights li h2');
	Cufon.replace('#breakout ol#siteHighlights li h3');
	highlightCarousel();
	breakoutCarousel();
	inputClear();
	clearText();
	cssHelper();
	newsHelper();
	headerHelper();
	navHelper();
	sectionsHelper();
	sortHelper();
	faqHelper();
	dateUtility();
	UtilDropDown();
	upcomingEventCarousel();
	liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	sortDropDown();
	//newsletterHelp();
});
