

//First and Last LI Selector
//Note: Prototype Driven
function liFirstLast() {
	var firstLIs =	$$('ul > li:first-child');
	var lastLIs = $$('ul > li:last-child, dl > dd: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 = $$('#header 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 externalLinks(){
	var externalLinks = $$('a[rel=external]');
	
	externalLinks.windowWidth = 300;
	externalLinks.windowHeight = 300;
	
	externalLinks.each(function(externaLink){
		externalLink.observe('click', function(event){
			// window.open code
			event.stop(); //capital E?  Can't recall
		});
	});
}

// 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; 
}

// Breakout Helper
// Adjusts opacity, etc. for the breakout
function breakoutHelper() {
	var breakoutLinks = $$('#breakout p.more a');
	
	breakoutLinks.each(function(breakoutLink){
		breakoutLink.setOpacity(.80);
	});
}

// Highlight Helper
// Evens out heights across all highlights
function highlightHelper() {
	var siteFooter = $('footer');
	var mainHighlights = $$('#contentMain div.highlight');
	var mainSections = $$('#contentMain #contentRelated div.section');
	var footerHighlights = $$('#footer div.highlight');

	
	mainHighlights.each(function(mainHighlight, index){
		switch(index){
			case 0:
				mainHighlight.addClassName('firstHighlight');
				break;
			case 1:
				mainHighlight.addClassName('secondHighlight');
				break;
			case 3:
				mainHighlight.addClassName('lastHighlight');
				break;
			default:
				break;
		}

		var mainMaxHeight = mainHighlights.max(function(mainHighlight){
			return mainHighlight.getHeight();
		});
		
		mainHighlight.setStyle({
			height: mainMaxHeight - 120 + 'px'
		});
	});
	
	mainSections.each(function(mainSection, index){
		switch(index){
			case 0:
				mainSection.addClassName('firstSection');
				break;
			case 1:
				mainSection.addClassName('secondSection');
				break;
			case 3:
				mainSection.addClassName('lastSection');
				break;
			default:
				break;
		}
	
		var mainMaxHeight = mainHighlights.max(function(mainHighlight){
			return mainHighlight.getHeight();
		});
	});
	
	footerHighlights.each(function(footerHighlight, index){
		switch(index){
			case 0:
				footerHighlight.addClassName('firstHighlight');
				break;
			case 1:
				footerHighlight.addClassName('secondHighlight');
				break;
			case 3:
				footerHighlight.addClassName('lastHighlight');
				break;
			default:
				break;
		}
	
		var footerMaxHeight = footerHighlights.max(function(footerHighlight){
			return footerHighlight.getHeight();
		});
		
		footerHighlight.setStyle({
			height: footerMaxHeight + 'px'
		});
		siteFooter.setStyle({
			backgroundPosition: 'center ' + footerMaxHeight + 'px'
		});
	});
}

// Breakout Flash Helper
// Sets up an array of all available Flash SWFs for breakout
// Randomizes the results and handles the SWF Object Replacement
// of the various Flash breakout headers
function breakoutHelper(){
	var breakoutSection = $('breakout');
	var backpage = $$('.backpage');
	
	if(!breakoutSection){
		return false;
	}
	
	if(backpage[0]){
		
	}
	else {
	
		var breakoutSWFs = [["/flash/HylandHeader.swf"], ["/flash/KeyGPS.swf"], ["/flash/CCF-Header2.swf"]]  // List of SWF header files
		
	    var randomNumber = Math.floor(Math.random()*(breakoutSWFs.length))  //Randomization math based on the amount of SWFs
				
		var flashvars = {
			
		}
		var params = {
			wmode: 'transparent'
		}
		var attributes = {
			
		}
		
		swfobject.embedSWF(breakoutSWFs[randomNumber], "breakoutImage", "1094", "460", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes); 
	
	}

}

//Site Highlight Rotator
//Creates navigation for Breakout Carousel
//Note: Prototype Framework
function breakoutCarousel() {
	var breakoutHighlights = $$('.carousel > li');
	
	if(!breakoutHighlights[0]) return false;
	
	var queue = Effect.Queues.get('highlightQueue');
	
	breakoutHighlights.each(function(breakoutHighlight, index) {
		if(breakoutHighlight.empty()){
			breakoutHighlight.remove();
		}
	});
	
	var breakoutHighlights = $$('.carousel > li');
	
	breakoutHighlights.each(function(breakoutHighlight){
		//console.log('Processing Highlight');
		var breakoutImages = breakoutHighlight.select('ol.portfolioMedia li');
		
		breakoutHighlight.setStyle ({
			backgroundImage: 'url(' + breakoutHighlight.down('img').src + ')',
			backgroundRepeat: 'no-repeat',
			backgroundPosition: '0 0'
		});
		
		breakoutHighlight.originalDimensions = new Hash({
			imageHeight: breakoutHighlight.down('img').getHeight(),
			definitionsHeight: breakoutHighlight.down('dl').getHeight(),
			portfolioHeight: 0
		});
		//console.log(breakoutHighlight.originalDimensions.get('imageHeight'));
		//console.log(breakoutHighlight.down('dl').getHeight());
			
		breakoutHighlight.down('img').remove();
		
		//console.log(breakoutImages);
		
		if(breakoutImages[0]) {
			var breakoutImagePreview = new Element('li');
			var breakoutImagesContainer = breakoutImages[0].up('ol');
			
			breakoutImagesContainer.insert({
				top: breakoutImagePreview
			});
			//console.log('Looping Breakout Images');
			breakoutImages.each(function(breakoutImage, index){
				if(index == 0){
					breakoutImagePreview.setStyle({
						position: 'absolute',
						left: '0px',
						top: '0px',
						width: '478px',
						height: '256px',
						backgroundImage: 'url(' + breakoutImage.down('img').src + ')',
						backgroundRepeat: 'no-repeat',
						backgroundPosition: 'center top',
						borderWidth: '0 0 4px 0',
						borderColor: '#A2C906'
					});
				}
				breakoutImage.setStyle({
					width: '100px',
					height: '100px',
					backgroundImage: 'url(' + breakoutImage.down('img').src + ')',
					backgroundRepeat: 'no-repeat',
					backgroundPosition: '-100px -60px'
				});
				
				breakoutImage.down('img').remove();
				
				breakoutImage.observe('click', function(event){
					new Effect.Tween(breakoutImagePreview, 100, 0, {
						duration: 1,
						afterFinish: function(item){
							breakoutImagePreview.setStyle({
								backgroundImage: breakoutImage.getStyle('backgroundImage')
							});
							new Effect.Tween(breakoutImagePreview, 0, 100, {
								duration: 1
							}, function(p){
								this.setOpacity(p/100)
							});
						}
					}, function(p){
						this.setOpacity(p/100)
					});
				});
			});
			breakoutHighlight.originalDimensions.set('portfolioHeight', breakoutImagesContainer.getHeight());
			//console.log('Processing Breakout Images: ' + breakoutImagesContainer.getHeight());
		}
		
		//console.log('Setting up Highlight Click Observe');
		breakoutHighlight.observe('click', function(event){
			if (!breakoutHighlight.hasClassName('open')) {
				breakoutHighlight.fire('optiem:displayHighlight', {
					transitionSpeed: 1
				});
				event.stop();
			}
		});
		
		breakoutHighlight.down('h3').observe('click', function(event){
			if (breakoutHighlight.hasClassName('open')) {
				breakoutHighlight.fire('optiem:displayHighlight', {
					transitionSpeed: 1
				});
				event.stop();
			}
		});
		
		//console.log('Setting up Highlight Fire Observe');
		breakoutHighlight.observe('optiem:displayHighlight', function(event){
			
			var transitionSpeed = event.memo.transitionSpeed;
			
			var highlightTweenOriginal = 300;
			var highlightListTweenOriginal = 300 + 40;
			var highlightDefinitionTweenOriginal = 224;
			var highlightTweenFinal = breakoutHighlight.originalDimensions.get('imageHeight') + breakoutHighlight.originalDimensions.get('definitionsHeight') + breakoutHighlight.originalDimensions.get('portfolioHeight');
			var highlightListTweenFinal = breakoutHighlight.originalDimensions.get('imageHeight') + breakoutHighlight.originalDimensions.get('definitionsHeight') + breakoutHighlight.originalDimensions.get('portfolioHeight') + 40;
			var highlightDefinitionTweenFinal = breakoutHighlight.originalDimensions.get('imageHeight') - 48;
			
			new Effect.ScrollTo( breakoutHighlight.up('ul'), 1000, {axis:'y'} );
			
			if (breakoutHighlight.hasClassName('open')) {
				
				new Effect.Parallel([
					new Effect.Tween(breakoutHighlight.down('h2'), highlightDefinitionTweenFinal, highlightDefinitionTweenOriginal, {
						duration: transitionSpeed
					}, function(p){
						this.setStyle({
							marginBottom: p + 'px'
						});
					}),
					new Effect.Tween(breakoutHighlight, highlightTweenFinal, highlightTweenOriginal, {
						duration: transitionSpeed
					}, function(p){
						this.setStyle({
							height: p + 'px'
						});
					})
				], {
					queue: {
						position: 'end',
						scope: 'highlightQueue',
						limit: 4
					}
				});
				
				new Effect.Tween(breakoutHighlight.up('ul'), highlightListTweenFinal, highlightListTweenOriginal, {
					duration: transitionSpeed,
					queue: {
						position: 'end',
						scope: 'highlightQueue',
						limit: 4
					}
				}, function(p){
					this.setStyle({
						height: p + 'px'
					});
				});
				
				new Effect.Morph(breakoutHighlight.up('ul'), {
					style: 'border-color: #3e3e3e;'
				});
				
			}
			else {
				
				new Effect.Tween(breakoutHighlight.up('ul'), highlightListTweenOriginal, highlightListTweenFinal, {
					duration: transitionSpeed,
					queue: {
						position: 'end',
						scope: 'highlightQueue',
						limit: 4
					}
				}, function(p){
					this.setStyle({
						height: p + 'px'
					});
				});
				
				new Effect.Morph(breakoutHighlight.up('ul'), {
					style: 'border-color: #ffffff;'
				});
				
				new Effect.Parallel([
					new Effect.Tween(breakoutHighlight.down('h2'), highlightDefinitionTweenOriginal, highlightDefinitionTweenFinal, {
						duration: transitionSpeed
					}, function(p){
						this.setStyle({
							marginBottom: p + 'px'
						});
					}),
					new Effect.Tween(breakoutHighlight, highlightTweenOriginal, highlightTweenFinal, {
						duration: transitionSpeed
					}, function(p){
						this.setStyle({
							height: p + 'px'
						});
					})
				], {
					queue: {
						position: 'end',
						scope: 'highlightQueue',
						limit: 4
					}
				});
			}
			
			breakoutHighlight.toggleClassName('open');
			if (breakoutHighlight.hasClassName('open')) {
				breakoutHighlight.setStyle({
					cursor: 'auto'
				});
			}
			else {
				breakoutHighlight.setStyle({
					cursor: 'pointer'
				});
			}
		});
	});
	
	var breakoutContainer = breakoutHighlights[0].up('ul');
	var currentHighlight = 0;
	var previousHighlight = breakoutHighlights.size();
	var highlightIndex = breakoutHighlights.size();
	
	(2).times(function(index){
		var breakoutNavigation = [];
		breakoutNavigation[index] = new Element('ol');
		breakoutNavigation[index].addClassName('navCarousel');
		
		previousHighlightButton = new Element('li');
		previousHighlightButton.addClassName('previous');
		previousHighlightAnchor = new Element('a', { href: "#"}).update("Backward");
		
		previousHighlightButton.insert({ bottom: previousHighlightAnchor });
		breakoutNavigation[index].insert({ top: previousHighlightButton });
		
		nextHighlightButton = new Element('li');
		nextHighlightButton.addClassName('next');
		nextHighlightAnchor = new Element('a', { href: "#"}).update("Forward");
	
		nextHighlightButton.insert({ bottom: nextHighlightAnchor });
		breakoutNavigation[index].insert({ bottom: nextHighlightButton });
		
		if(index == 0){
			breakoutContainer.insert({ before: breakoutNavigation[index] });
		}
		else {
			breakoutContainer.insert({ after: breakoutNavigation[index] });
		}
		
		previousHighlightAnchor.observe('click', function(event){
			previousHighlightAnchor.fire('optiem:updateHighlight', { indexMove: 1 });
			//carousel.stop();
			event.stop();
		});
		
		nextHighlightAnchor.observe('click', function(event){
			nextHighlightAnchor.fire('optiem:updateHighlight', { indexMove: -1 });
			//carousel.stop();
			event.stop();
		});
	});

	document.observe('optiem:updateHighlight', function(event){
		
		if (queue.effects.size() == 0) {
			
			if (breakoutHighlights[currentHighlight].hasClassName('open')) {
				breakoutHighlights[currentHighlight].fire('optiem:displayHighlight', {
					transitionSpeed: 1
				});
			}
			
			var highlightMove = event.memo.indexMove;
			
			previousHighlight = currentHighlight;
			currentHighlight = (breakoutHighlights.size() + ((currentHighlight - highlightMove) % breakoutHighlights.size())) % breakoutHighlights.size();

			breakoutHighlights[currentHighlight].setStyle({
				left: -(highlightMove*breakoutHighlights[previousHighlight].getWidth()) + 'px'
			});
			
			new Effect.Parallel([new Effect.Move(breakoutHighlights[previousHighlight], {
				sync: true,
				x: highlightMove*breakoutHighlights[previousHighlight].getWidth(),
				y: 0,
				mode: 'absolute'
			}), new Effect.Move(breakoutHighlights[currentHighlight], {
				sync: true,
				x: 0,
				y: 0,
				mode: 'absolute'
			})], {
				queue: {
					position: 'end',
					scope: 'highlightQueue',
					limit: 4
				}
			});
			
		}
	});
	
	/*carousel = new PeriodicalExecuter(function(){
		nextHighlightAnchor.fire('optiem:updateHighlight', { indexMove: -1 });
	}, 10);*/

}

// Font Replacement
function cufonReplace() {
}

//Campaign Landing Page Background Chooser for Flash Campaigns
function backgroundClass() {
	var backgroundContainer = $('backgroundChoice');
	var pageBodies = $$('body');
	
	backgroundClass = backgroundContainer.innerHTML;
	
	pageBodies.each(function (pageBody, index){
		pageBody.addClassName(backgroundClass);
	});
	
	backgroundContainer.remove();
	
	return false;
}

//Add Query String to Impact Landing Pages
// ?utm_source=direct&utm_medium=postcard&utm_campaign=Impact1

function landingPageURLHandler() {
	var landingPages = $$('body.landing');
	if(!landingPages) return false;
	var pageLinks = $$('a');
	var backgroundContainer = $('backgroundChoice');
	
	if(!landingPages) return false;
	
	landingPages.each(function (landingPage){
		if(landingPage.hasClassName('greycreamgreen')){
			
			pageLinks.each(function (pageLink, index){
				var existingLink = pageLink.readAttribute("href");
				var queryString = '?utm_source=direct&utm_medium=postcard&utm_term=keybank&utm_campaign=impact3'
				var finalURL = existingLink + queryString
				pageLink.writeAttribute("href",  finalURL);
			});
			
		} else if(landingPage.hasClassName('lightblueblueorange')){
		
			pageLinks.each(function (pageLink, index){
				var existingLink = pageLink.readAttribute("href");
				var queryString = '?utm_source=direct&utm_medium=postcard&utm_term=hyland&utm_campaign=impact2'
				var finalURL = existingLink + queryString
				pageLink.writeAttribute("href",  finalURL);
			});
			
		} else if(landingPage.hasClassName('creambluegreen')){
			
			pageLinks.each(function (pageLink, index){
				var existingLink = pageLink.readAttribute("href");
				var queryString = '?utm_source=direct&utm_medium=postcard&utm_term=clinic&utm_campaign=impact1'
				var finalURL = existingLink + queryString
				pageLink.writeAttribute("href",  finalURL);
			});
		} else if(landingPage.hasClassName('none')){
			
			pageLinks.each(function (pageLink, index){
				var existingLink = pageLink.readAttribute("href");
				var queryString = '?utm_source=direct&utm_medium=postcard&utm_term=generic&utm_campaign=impactNone'
				var finalURL = existingLink + queryString
				pageLink.writeAttribute("href",  finalURL);
			});
		}
	
	});
	return false;
	event.stop();
}

//Silly window shake script requested by Nuss and Ferguson.
//Flash file makes the call at specific point in animation.
function quake(){
		var quakeDuration=130; //time in milliseconds to perform quake.
		var quakeCounter=1;

		setTimeout("window.resizeTo(screen.width,screen.height); window.moveTo(0, 0);",1000);
		
		var deltaX=1;
		if (window.moveBy)
		{	
			for (quakeCounter=0; quakeCounter<quakeDuration; quakeCounter++)
			{
				if ((quakeCounter%4)==0)
				{
					window.moveBy(deltaX, 0);
				}
				else if ((quakeCounter%4)==2)
				{
					window.moveBy(-deltaX, 0);
				}
				if ((quakeCounter%30)==0)
				{
					if (quakeCounter<quakeDuration/2)
						deltaX++;
					else
						deltaX--;
				}
			}		
		}
		
		
		/* Alternate option for browser shaking...
		if (parent.moveBy) {
			for (i = 10; i > 0; i--) {
			for (j = 1; j > 0; j--) {
			parent.moveBy(0,i);
			parent.moveBy(i,0);
			parent.moveBy(0,-i);
			parent.moveBy(-i,0);

			}
			}
		}
		*/
		
		
	} 


//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
	//cufonReplace();
	breakoutCarousel();
	breakoutHelper();
	inputClear();
	highlightHelper();
	Cufon.refresh('div.highlight h2');
	backgroundClass();
	landingPageURLHandler();
});