//AddThis Helper
//Creates add this buttons on the appropriate paragraphs
function addthisHelper(){
	var addThisLinks = $$('p.addThis');
	
	var buttonContainer = []
	var button = [];
	
	addThisLinks.each(function(addThisLink, index){

		buttonContainer[index] = new Element('p');
		buttonContainer[index].addClassName('addthis');
		addThisLink.insert({ after: buttonContainer[index] });
		button[index] = new Element('a');
		button[index].addClassName('addthis_button_compact');
		button[index].update('Share This Page');
		buttonContainer[index].insert({ bottom: button[index] });

		var addthis_config = {
			
		};
		var addthis_share = {
			url: addThisLink.down('a').href,
			title: addThisLink.down('a').innerHTML
		};
		addthis.button(button[index], addthis_config, addthis_share);
		
		addThisLink.remove();

	});

}

//Home Page Secondary Nav Height Fix for IE6
//Adjusts the height of the secondary nav to at least the height of the carousel + 1px to keep 
//items floating correctly.
function homeNavHelper(){
	var carousel = $('highlightCarousel'); 
	var secondaryNav = $('supportNav');
	
	if(!carousel) return false;
	
	carouselHeight = carousel.getHeight();
	
	secondaryHeight = carouselHeight - 10;
	secondaryNav.setStyle({
		height: secondaryHeight + 'px'
	});
	
}

//Other Option Reveal
//Disables and Hides or Re-enables and Shows an input field on click or on the choice of other
//within a corresponding dropdown list.
//Prototype Driven
function selectOverride(){
	var overrideLabels = $$('label.selectOverride');
	
	overrideLabels.each(function(overrideLabel, index){
		//console.log(overrideLabel);
		
		var overrideClasses = [];
		overrideLabel.readAttribute('class').scan(/\w+/, function(match){
			overrideClasses.push(match[0]);
		});
		
		//console.log('Classes are: ');
		//console.log(overrideClasses);
		
		var selectName;
		
		overrideClasses.each(function(overrideClass){
			//console.log(overrideClass);
			
			if(overrideClass.include('Override') && !overrideClass.include('select')){
				selectName = overrideClass.sub('Override', '');
				
				//console.log('Select name is: ' + selectName);
			}
		});
		//console.log('Building select statement, with: ' + selectName);
		//console.log('select[name="' + selectName + '"]');
		
		var pageSelects = $$('select');
		var overrideSelect;
		
		pageSelects.each(function(pageSelect){
			if(pageSelect.readAttribute('id').include(selectName)){
				overrideSelect = pageSelect;
			}
		});
		
		//var overrideSelect = $$('#' + selectName)[0];
		//console.log(overrideSelect);
		
		overrideSelectOptions = overrideSelect.select('option');
		
		overrideSelect.observe('change', function(event){
			var selectedValue = '';
			var revealValue = overrideSelectOptions[overrideSelectOptions.size() - 1].value;
			
			//console.log('Select value has been updated.');
			//console.log('Value of the select is: ' + overrideSelect.getValue());
			//console.log('Reveal value is: ' + revealValue);
			
			if(overrideSelect.getValue() == revealValue){
				//console.log('Select Override Event Fired with toggleState = true');
				overrideLabel.fire('parkplace:selectOverride', { labelToToggle: overrideLabel, toggleState: true });
			}
			else {
				//console.log('Select Override Event Fired with toggleState = false');
				overrideLabel.fire('parkplace:selectOverride', { labelToToggle: overrideLabel, toggleState: false });
				
			}
		});
		
		overrideLabel.next('p.instruction').observe('click', function(event){
			//console.log('Label has been clicked');
			//console.log(overrideLabel.down('input'));
			overrideLabel.next('p.instruction').hide();
			overrideLabel.fire('parkplace:selectOverride', { labelToToggle: overrideLabel, toggleState: true });
		});
		
		overrideLabel.down('input').observe('blur', function(event){
			if(overrideLabel.down('input').value.empty()){
				overrideLabel.next('p.instruction').show();
				overrideSelectOptions[0].selected = 1;
				overrideLabel.fire('parkplace:selectOverride', { labelToToggle: overrideLabel, toggleState: false });
			}
		});
	});
	
	//previousListingAnchor.fire('parkplace:updateNews', { labelToToggle: object, toggleState: true });
	document.observe('parkplace:selectOverride', function(event){
		//console.log('Select Override Event Caught');
		
		var labelToToggle = event.memo.labelToToggle;
		var toggleState = event.memo.toggleState;
		var overrideInput = labelToToggle.down('input');
		//console.log('Value of labelToToggle:');
		//console.log(labelToToggle);
		//console.log('Value of toggleState: ' + toggleState);
		
		
		if(toggleState){
			//console.log('Making the Input Active');
			overrideSelectOptions[overrideSelectOptions.size() - 1].selected = 1;
			labelToToggle.removeClassName('inactive');
			labelToToggle.next('p.instruction').hide();
			overrideInput.enable();
			overrideInput.activate();
		}
		else {
			//console.log('Making the Input Inactive');
			labelToToggle.addClassName('inactive');
			labelToToggle.next('p.instruction').show();
			overrideInput.clear();
			overrideInput.disable();
		}
	});
}


//Fieldset Hint Helper 
//Hides and shows a paragraph with the class of 'hint' 
//adjacent to an input field, upon clicking the input.
//Prototype Driven

function formHints() {
	var inputFields = $$('#contentArticle fieldset p.hint');
	
	if(!inputFields[0]) return false;
	
	inputFields.each(function(inputField, index){
		
		inputField.previous('label').down('input').observe('focus', function(event){
			inputField.setStyle({
				display: 'inline'
			});
			
		});
		inputField.previous('label').down('input').observe('blur', function(event){
			inputField.setStyle({
				display: 'none'
			});
			
		});
	});
}


//News Rotation
// Created navigation for, and scrolls through list items
// in a specific newsAndPress div
//Prototype Driven
function newsRotation() {
	var newsContainer = $('newsAndPress');
	var newsListings = $$('div#newsAndPress ul.newsItems li');
	
	
	if(!newsListings[0]) return false;
	
	
	numListings = newsListings.size();  //determine how many listings there are
	
	var queueNews = Effect.Queues.get('newsQueue');	//setup the queue
	
	newsListings.each(function(newsListing, index){
		if(newsListing.empty()){ //check for empties and remove.
			newsListing.remove();
		}
	});
	
	//create the navigation which takes the number of items and lists them as such.
	currentListing = 0;
	previousListing = newsListings.size();
	listingIndex = newsListings.size();
	
	listingNavigation = new Element('ul');
	listingNavigation.addClassName('navModule');
	
	previousListingButton = new Element('li');
	previousListingButton.addClassName('previous');
	previousListingAnchor = new Element('a', { href: "#"}).update("Previous");
	previousListingButton.insert({ bottom: previousListingAnchor });
	listingNavigation.insert({ top: previousListingButton });
	
	listingPositionText = new Element('li').update(" ");
	listingPosition = new Element('strong').update("1 of " + numListings);
	listingPositionText.insert({ top: listingPosition });
	listingNavigation.insert({ bottom: listingPositionText });
	
	nextListingButton = new Element('li');
	nextListingButton.addClassName('next');
	nextListingAnchor = new Element('a', { href: "#"}).update("Next");
	nextListingButton.insert({ bottom: nextListingAnchor });
	listingNavigation.insert({ bottom: nextListingButton });

	newsContainer.insert({ top: listingNavigation });
	
	//start the queue of animation effects.
	document.observe('parkplace:updateNews', function(event){
			
		
		if (queueNews.effects.size() == 0) {
		
			listMove = event.memo.indexMove;
			
			previousListing = currentListing;
			currentListing = (newsListings.size() + ((currentListing - listMove) % newsListings.size())) % newsListings.size();
			
			listingPosition.update((currentListing + 1) +" of " + numListings);
			
			newsListings[currentListing].setStyle({
				left: -(listMove * newsListings[previousListing].getWidth()) + 'px'
			});
			
			new Effect.Parallel([new Effect.Move(newsListings[previousListing], {
				sync: true,
				x: listMove * newsListings[previousListing].getWidth(),
				y: 0,
				mode: 'absolute'
			}), new Effect.Move(newsListings[currentListing], {
				sync: true,
				x: 0,
				y: 0,
				mode: 'absolute'
			})], {
				queue: {
					position: 'end',
					scope: 'newsQueue',
					limit: 1
				}
			});
		}
	});	
	
	
	previousListingAnchor.observe('click', function(event){
		previousListingAnchor.fire('parkplace:updateNews', { indexMove: 1 });
		event.stop();
	});
	
	nextListingAnchor.observe('click', function(event){
		nextListingAnchor.fire('parkplace:updateNews', { indexMove: -1 });
		event.stop();
	});

	
	
}


//Highlight Carousel
//Prototype driven JS to cycle through highlighted list items
//And creates a carousel navigation to manually select each items
//Prototype and Scriptaculous Driven
function highlightCarousel() {
	var highlights = $$('ul.carouselItems li');  //declare variables for the items we'll fade in and out.
	var carouselControls = $$('ul.carouselNav li');
	
	
	if(!highlights[0]) return false; //lets be sure they exist, before we break anything
	
	var queue = Effect.Queues.get('highlightQueue'); // a queu's necessary for the overall animation.
	
	highlights.each(function(highlight, index) {
		if(highlight.empty()){
			highlight.remove();
		}
	});
	
	var highlights = $$('ul.carouselItems li');  //we've removed empties, now lets redefine the variable
	
	highlights.each(function(highlight){ //swap out the image inside the list items for their specific background
		highlight.setStyle ({
			backgroundImage: 'url(' + highlight.down('img').src + ')',
			backgroundRepeat: 'no-repeat',
			backgroundPosition: '0 0'
		});
			
		highlight.down('img').remove();
	});
	
	var breakoutContainer = highlights[0].up('div');
	var currentHighlight = 0;
	var previousHighlight = highlights.size();
		
	
	document.observe('parkplace:carouselUpdate', function(event){
		if(queue.effects.size() == 0) {
		
			var highlightMove = event.memo.indexMove;
			
			previousHighlight = currentHighlight;
			currentHighlight = (highlights.size() + ((currentHighlight - highlightMove) % highlights.size())) % highlights.size();

			if(previousHighlight == currentHighlight){
				return false;
			}
			
			new Effect.Parallel([new Effect.Opacity(highlights[previousHighlight], {
				from: 1,
				to: 0,
				duration: 1,
				afterFinish: function(){
								highlights[previousHighlight].setStyle({
									left: '-999em'
								});							
							}
			}), new Effect.Opacity(highlights[currentHighlight], {
				from: 0,
				to: 1,
				duration: 1,
				beforeStart: function(){
								highlights[currentHighlight].setStyle({
									left: '0'
								});	
				}
			})], {
				queue: {
					position: 'end',
					scope: 'highlightQueue',
					limit: 2
				}
			});
			
			/* carouselControls[currentHighlight].up('ul').setStyle({
				backgroundPosition: '1px '+ currentHighlight * 57 + 'px'
			});*/
			
			new Effect.Tween(carouselControls[currentHighlight].up('ul'), previousHighlight * 40 , currentHighlight * 40, { 
					duration: 1
				}, function(p){
				carouselControls[currentHighlight].up('ul').setStyle({
					backgroundPosition: '2px ' + p + 'px'
				});
			});			
		
		}
	});
	
	
	
	carousel = new PeriodicalExecuter(function(){
		carouselControls[currentHighlight].fire('parkplace:carouselUpdate', { indexMove: -1 });
	}, 20);
	
	carouselControls.each(function(carouselControl, index){
		carouselControl.observe('click', function(event){
			carouselControl.fire('parkplace:carouselUpdate', { indexMove: -(index - currentHighlight) });
			carousel.stop();
			event.stop();
		});
	});
	
	
}


//Live Chat
//Prototype and Scriptaculous
function liveChat() {
	var liveChatLinks = $$('div#liveChat h3'); //create variable for element that triggers function
	
	if(!liveChatLinks[0]) return false; //be sure it's there before continuing any further
	
	liveChatLinks.each(function(chatLink){ 
		chatLink.observe('click', function(event){ //listen for a click of said element
 		if(chatLink.up('div').hasClassName('closed')) { //determine if it's closed
				new Effect.Morph(chatLink.up('div'), { //scriptaculous effect to animate
					style: 'top: 0;',
					duration: 0.2
				});
				chatLink.up('div').removeClassName('closed'); //remove the closed class name
				chatLink.up('div').addClassName('open'); //add the open class name
				stop();
		} else { //if it's not closed, close it
				new Effect.Morph(chatLink.up('div'), { //another scriptaculous effect to animate, the reverse of what happened.
					style: 'top: -43px;',
					duration: 0.2
				});
				chatLink.up('div').removeClassName('open');
				chatLink.up('div').addClassName('closed');
				stop();
		}	
	});
});	
	
}

//Navigation Hovers
//Note: Prototype Driven
function navHover() {
	var navigationListItems = $$('#navigation ul li');
	
	navigationListItems.each(function(navigationListItem){
		navigationListItem.observe('mouseenter', function(event){
			navigationListItem.addClassName('hover');
		});
		navigationListItem.observe('mouseleave', function(event){
			navigationListItem.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');
	});
}

//Input Clear
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputClear() {
	var textInputs = $$('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; 
}

//External Links set to Target Blank
//Note: Prototype Driven
function externalLinks() {
	$$('a[rel="external"]').each(function(link){
		if (link.readAttribute('href') != '' && link.readAttribute('href') != '#') {
			link.writeAttribute('target', '_blank');
		}
	});
}

//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function() {
	//dynamicShadow('/images/global/shadow.png', 'page-container', 16, 0);
	liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	inputClear(); //Clears inputs of default values upon focus, restores on blur.
	externalLinks();
	liveChat();
	//homeNavHelper();
	navHover();
	highlightCarousel();
	newsRotation();
	formHints();
	selectOverride();
	addthisHelper();
});