//AddThis Helper
//Creates add this buttons on the appropriate paragraphs
function addthisHelper(){
	var addThisLinks = $$('p.addThis');
	
	if(!addThisLinks[0]) return false; 
	
	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();

	});

}


function alertBox(){
	var alertBox = $('alert');
	var alertCloseButtons = $$('a.closeAlert');
	var viewport = $('viewport');
	var alertLinks = $$('#alert a');
	
	if(!alertBox) return false;
	
	if(readCookie('ppiAlert')){
		alertBox.remove();
	} 
	else {
		viewport.insert({
			top: alertBox
		});
		
		alertCloseButtons.each(function(alertCloseButton){
			alertCloseButton.observe('click', function(event){
				alertBox.blindUp({duration: .5});
				setCookie('ppiAlert', 1, 365);
				event.stop();
			});		
		});
		
		alertLinks.each(function(alertLink){
			alertLink.observe('click', function(event){
				setCookie('ppiAlert', 1, 365);
			});		
		});
		
	}	
}

//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');
	
	if(!overrideLabels[0]) return false;
	
	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();
	});	
}


function carousel() {
	var highlights = $$('ul.carouselItems li');
	var carouselContainer = $('highlightCarousel');
	var contentMain = $('contentMain');
	var speed = 20 //Carousel Pause Speed
	
	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.
	
	var navItems = []; //Setting up our variable for the array of navigation items that make up the menu.
	
	highlights.each(function(highlight, index) { //Lets strip out any accidental, empty LIs.
		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 currentHighlight = 0; //Right out of the gate, slide number 1 is the first. We'll keep track with this variable.
	var previousHighlight = highlights.size(); //The previous highlight at the start is the maximum number of slides, ie. 5 slides, slide #5 is the one before #1.
	
	//Check to see if is more than one - if not don't put the controls - it's unnecessary 
	highlightNavigation = new Element('ul').addClassName('highlightNav');//Making the controls for the carousel.
	
	contentMain.insert({
		top: highlightNavigation
	});
	
	highlights.each(function(highlight, index) {//For every carousel item, create a navigation control item.
		if(index > 0){
				highlight.setOpacity(0);
			} else {
				highlight.setOpacity(1);
				highlight.setStyle({
					zIndex: 1000
				});
			
			}
		
		navItems[index] = new Element('li').update((index + 1));
		
		if(index == 0){
			navItems[index].addClassName('currentPanel'); //Lets assign a class to keep track of the selected navItem
		}
		
		navItems[index].observe('click', function(event){
			if(queue.effects.size() == 0) {	
				var panelMove = currentHighlight - index;
				navItems[index].addClassName('currentPanel');
				carousel.stop();
				navItems[index].fire('parkplace:carouselUpdate', { indexMove: panelMove });	
				event.stop();
			}
		});
						
			highlightNavigation.insert({
				bottom: navItems[index]
			});		
	});
		
	nextHighlightButton = new Element('li');
	nextHighlightButton.addClassName('Next');
	nextHighlightAnchor = new Element('a', { href: "#"}).update("Next");
		
	nextHighlightButton.insert({ bottom: nextHighlightAnchor });
	highlightNavigation.insert({ bottom: nextHighlightButton });
	
	
	previousHighlightButton = new Element('li');
	previousHighlightButton.addClassName('Previous');
	previousHighlightAnchor = new Element('a', { href: "#"}).update("Previous");
	
	previousHighlightButton.insert({ bottom: previousHighlightAnchor });
	highlightNavigation.insert({ top: previousHighlightButton });
	
	previousHighlightButton.observe('click', function(event){
		document.fire('parkplace:carouselUpdate', { indexMove: 1 });	
	});
	
	nextHighlightButton.observe('click', function(event){
		document.fire('parkplace:carouselUpdate', { indexMove: -1 });		
	});
	
		
	if(highlights.size() < 1) {
		highlightNavigation.hide();
	}
	
	Cufon.replace('#contentMain #highlightCarousel ul.highlightNav li',{textShadow: '#fff 0px 1px'});
	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();
			
			var internalPreviousHighlight = previousHighlight;
			var internalCurrentHighlight = currentHighlight;
			
			navItems[internalPreviousHighlight].removeClassName('currentPanel');
			navItems[internalCurrentHighlight].addClassName('currentPanel');
			
			new Effect.Parallel([
				new Effect.Tween(highlights[previousHighlight], 1, 0, {sync: true}, function(value){
					this.setOpacity(value);
					this.setStyle({
						zIndex: 0 					
					});
				}),
				new Effect.Tween(highlights[currentHighlight], 0, 1, {sync: true}, function(value){
					this.setOpacity(value);
					this.setStyle({
						zIndex: 1000 					
					});
				})], {
				queue: {
					position: 'end',
					scope: 'highlightQueue',
					limit: 1
				}
			});	
		}
	});	
	
	carousel = new PeriodicalExecuter(function(){
		contentMain.fire('parkplace:carouselUpdate', { indexMove: -1 });
	}, speed);	
	
}

//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, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// 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();
	carousel();
	newsRotation();
	formHints();
	selectOverride();
	alertBox();
	addthisHelper();
});