//Media Viewport
//Creates and fills the media viewport
//via an AJAX call to the supplied URL
function mediaViewport(mediaURL) {
	var container = $('contentMain');
	var mediaPortal = null;
	var mediaPortals = $$('#contentMain div.mediaPortal');
	
	if (!mediaPortals[0]) {
		mediaPortal = new Element('div');
		mediaPortal.identify();
		mediaPortal.addClassName('mediaPortal');
		
		container.insert({
			top: mediaPortal
		});
	}
	else {
		mediaPortal = mediaPortals[0];
	}
	
	mediaPortal.setStyle({
		height: '0px',
		overflow: 'hidden'
	});
	
	mediaPortal.setOpacity(0);
	mediaPortal.hide();
	
	new Ajax.Updater({ success: mediaPortal	}, mediaURL, {
		method: 'get',
		parameters: { json: true },
		onSuccess: function(transport) {
			//console.log('success');
		},
		onComplete: function() {
			portalInitialize();
			portalTransition(true);
			videoAssist();
			mediaAssist();
			slideCarousel(mediaPortal);
		}
	});
	
	function portalInitialize(){
		var portalClose = mediaPortal.down('ul.controlsMediaPortal').down('li.close');
		
		portalClose.observe('click', function(event){
			document.fire('optiem:pauseVideos');
			portalTransition(false);
		});
	}
	
	function portalTransition(direction) {
		
		if(direction) {
		
			var scrollEffect = new Effect.ScrollTo($('header'), { 
				duration: 1,
				offset: 196,
				afterFinish: function(element){
					mediaPortal.show();
				},
				queue: {
					position: 'end',
					scope: 'portalQueue'
					}
			});

			/*new Effect.Tween(window, 0, 1, {
				sync: false,
				duration: 1,
				afterFinish: function(element){
					mediaPortal.show();
				},
				queue: {
					position: 'end',
					scope: 'portalQueue'
					}
				}, function(value){
					window.scrollBy(0,100*value);
				}
			);*/
			
			new Effect.Tween(mediaPortal, 0, 1, {
				sync: false,
				duration: 1,
				afterFinish: function(element){
					mediaPortal.setStyle({
						overflow: 'visible'
					});
					document.fire('optiem:playVideos');
				},
				queue: {
					position: 'end',
					scope: 'portalQueue'
					}
				}, function(value){
					this.setOpacity(value);
					this.setStyle({
						height: 522 * value + 'px'
					});
				}
			);
		}
		else {
			mediaPortal.setStyle({
				overflow: 'hidden'
			});
			new Effect.Tween(mediaPortal, 1, 0, {
				sync: false,
				duration: 1,
				afterFinish: function(element){
					mediaPortal.remove();
				},
				queue: {
					position: 'end',
					scope: 'portalQueue'
					}
				}, function(value){
					this.setOpacity(value);
					this.setStyle({
						height: 522 * value + 'px'
					});
				}
			);
		}
	}

}

//Image Assistant
//Adjusts styling on media meta data
function mediaAssist(){
	var viewportElements = $$('.mediaPortal ul.carousel li');
	
	viewportElements.each(function(viewportElement){
		if(viewportElement.down('div.meta')){
			viewportElement.down('div.meta').setOpacity(.8);
			viewportElement.down('div.meta').down('p').setOpacity(.75);
		}
	});
}

//Video Assistant
//Turn HTML5 video into SWF Video Player
//when playing in IE
function videoAssist(){
	var videoPlayers = $$('video');
	var flowPlayers = [];
	
	// display seconds in hh:mm:ss format
	function toTime(sec) {
		var h = Math.floor(sec / 3600);
		var min = Math.floor(sec / 60);
		sec = sec - (min * 60);
		
		if (h >= 1) {
			min -= h * 60;
			return pad(h) + ":" + pad(min) + ":" + pad(sec);
		}
		
		return pad(min) + ":" + pad(sec);
	}
	
	// prefix integer with zero when nessessary 
	function pad(val) {
		val = parseInt(val, 10);
		return val >= 10 ? val : "0" + val;
	}
	videoPlayers.each(function(videoPlayer, index){
		var videoControls;
		
		if ($('hasIE')) {
			if (videoPlayer.next('div.controlsVideoPlayer')) {
				videoPlayer.next('div.controlsVideoPlayer').remove();
			}
			
			videoControls = new Element('div');
			videoControls.addClassName('controlsVideoPlayer');
			videoPlayer.insert({
				after: videoControls
			});
			
			//alert('test');
			//alert(videoPlayer.readAttribute('href'));
			var videoSource = videoPlayer.readAttribute('href');
			videoPlayer.update('');
			
			
			flowPlayers[index] = flowplayer(videoPlayer, {
				width: '934',
				height: '522',
				wmode: 'transparent',
				src: "/scripts/flowplayer/flowplayer-3.1.5.swf",
				version: [9, 115]
			}, {
				clip: {
					url: videoSource,
					autoPlay: true,
					autoBuffering: true
				},
				plugins: {
					controls: null
				}
			}).controls(videoControls, {duration: 25});
			
			
		}
		else {
			
			videoControls = videoPlayer.next('div.controlsVideoPlayer');
			
			videoControls.down('a.play').observe('click', function(event){
				if (this.hasClassName('play')) {
					videoPlayer.play();
					this.removeClassName('play');
					this.addClassName('pause');
				}
				else {
					videoPlayer.pause();
					this.removeClassName('pause');
					this.addClassName('play');
				}
			});
			
			videoControls.down('a.mute').observe('click', function(event){
				if (this.hasClassName('mute')) {
					videoPlayer.muted = !videoPlayer.muted;
					this.removeClassName('mute');
					this.addClassName('unmute');
				}
				else {
					videoPlayer.muted = !videoPlayer.muted;
					this.removeClassName('unmute');
					this.addClassName('mute');
				}
			});
			
			var videoDuration = videoControls.down('div.time').down('strong');
			var videoCurrentTime = videoControls.down('div.time').down('span');
			var videoTrack = videoControls.down('div.track');
			var videoBuffer = videoTrack.down('div.buffer');
			var videoProgress = videoTrack.down('div.progress');
			var videoPlayHead = videoTrack.down('div.playhead');
			
			videoDuration.update(toTime(videoPlayer.duration));
			videoCurrentTime.update(toTime(videoPlayer.currentTime));
			
			var videoLengthRatio = videoTrack.getWidth() / videoPlayer.duration;
			
			var videoUpdater = new PeriodicalExecuter(function(pe) {
				
				videoLengthRatio = videoTrack.getWidth() / videoPlayer.duration;
				
				videoCurrentTime.update(toTime(videoPlayer.currentTime));
				
				if (videoPlayer.buffered) {
					var lastBuffered = videoPlayer.buffered.end(videoPlayer.buffered.length - 1);
					videoBuffer.setStyle({
						width: videoLengthRatio * lastBuffered + 'px'
					});
				}
				
				videoDuration.update(toTime(videoPlayer.duration));
				
				videoProgress.setStyle({
					width: videoLengthRatio * videoPlayer.currentTime + 'px'
				});
				
				videoPlayHead.setStyle({
					left: videoLengthRatio * videoPlayer.currentTime + 'px'
				});

			}, 1);

		}
		
		new Effect.Fade(videoControls, {
			sync: false,
			from: 1,
			to: 0,
			transition: Effect.Transitions.sinoidal,
			duration: .5,
			queue: {
				position: 'end',
				scope: 'videoQueue'
				}
			}
		);
		
		//Common video player transitions between HTML5 and Flash
		videoPlayer.up('div').observe('mouseenter', function(event){
			new Effect.Appear(videoControls, {
				sync: false,
				from: 0,
				to: 1,
				transition: Effect.Transitions.sinoidal,
				duration: .5,
				queue: {
					position: 'end',
					scope: 'videoQueue'
					}
				}
			);
		});
		
		videoPlayer.up('div').observe('mouseleave', function(event){
			new Effect.Fade(videoControls, {
				sync: false,
				from: 1,
				to: 0,
				transition: Effect.Transitions.sinoidal,
				duration: .5,
				queue: {
					position: 'end',
					scope: 'videoQueue'
					}
				}
			);
		});
		
		
		document.observe('optiem:pauseVideos', function(event){
			videoPlayers.each(function(videoPlayer, index){
				if($('hasIE')){
					if (flowPlayers[index].isPlaying()) {
						flowPlayers[index].pause();
					}
					flowPlayers[index].unload();
				}
				else {
					if (!videoPlayer.paused) {
						videoControls = videoPlayer.next('div.controlsVideoPlayer');
						
						videoControls.down('a.play').addClassName('pause');
						videoControls.down('a.play').removeClassName('play');
						videoPlayer.pause();
					}
				}
			});
		});
		
		document.observe('optiem:playVideos', function(event){
			videoPlayers.each(function(videoPlayer, index){				
				if ($('hasIE')) {
					if (videoPlayer.up('div').visible()) {
						if (!flowPlayers[index].isPlaying()) {
							flowPlayers[index].play();
						}
					}
				}
				else {
					if (videoPlayer.up('li').visible()) {
						if (videoPlayer.paused) {
							videoControls = videoPlayer.next('div.controlsVideoPlayer');
							if (videoControls.down('a.play').hasClassName('play')) {
								videoControls.down('a.play').addClassName('pause');
								videoControls.down('a.play').removeClassName('play');
							}
							videoPlayer.play();
						}
					}	
				}
			});
		});
	
	});
		
	var bufferControls = $$('div.controlsVideoPlayer div.track div.buffer');
	var progressControls = $$('div.controlsVideoPlayer div.track div.progress');
	var playheadControls = $$('div.controlsVideoPlayer div.track div.playhead');
	
	bufferControls.each(function(bufferControl){
		bufferControl.setOpacity(.1);
	});
	
	progressControls.each(function(progressControl){
		progressControl.setOpacity(.25);
	});
	
	playheadControls.each(function(playheadControl){
		playheadControl.setOpacity(.5);
	});
}

//Portfolio Assistant
//Grab Portfolio Items based on linked AJAX Call
function portfolioAssistant(){
	var portfolioEntries = $$('.portfolio li');
	
	portfolioEntries.each(function(portfolioEntry, index){
		var entryURL = portfolioEntry.down('dl').down('dd.ajax').innerHTML;
		
		portfolioEntry.observe('click', function(event){
			mediaViewport(entryURL);
		});
		
		portfolioEntry.observe('mouseenter', function(event){
			portfolioEntry.addClassName('hover');
		});
		
		portfolioEntry.observe('mouseleave', function(event){
			portfolioEntry.removeClassName('hover');
		});
		
	});
}


//Slide Carousel
function slideCarousel(container) {
	var portalControls = container.down('ul.controlsMediaPortal');
	
	var navSlices = new Element('ul');
	navSlices.addClassName('navCarousel');
	
	var navSlicesItems = [];
	
	var queue = Effect.Queues.get('sliceQueue');
	
	var currentSlice = 0;
	var previousSlice = 0;
	
	var slices = $$('ul.carousel > li');
	
	var slideDeclaration = container.down('h2').down('em');
	slideDeclaration.update(currentSlice + 1 + ' / ' + slices.size());
	//Addition of detecting more than one slice.
	if(slices.size > 1){
		var nextButton = new Element('li');
		nextButton.addClassName('next');
		nextButton.update('Next Slide');
		portalControls.insert({
			top: nextButton
		});
		
		var previousButton = new Element('li');
		previousButton.addClassName('previous');
		previousButton.update('Previous Slide');
		portalControls.insert({
			top: previousButton
		});
		
		slices.each(function(slice, index){
			
			navSlicesItems[index] = new Element('li').update(index + 1);
			if(index == 0){
				navSlicesItems[index].addClassName('current');
			}
			else {
				slice.setOpacity(0);
				slice.hide();
			}
			
			navSlicesItems[index].observe('click', function(event){
				var sliceMove = index - currentSlice;
				navSlicesItems[index].fire('optiem:updateSlice', { indexMove: sliceMove, sliceSpeed: 1 });
			});
			
			navSlices.insert({ 
				bottom: navSlicesItems[index] 
			});
		});
	}
	container.insert({
		bottom: navSlices
	});
	
	function slideChange(sliceMove, slideSpeed) {
		var slideTime = slideSpeed ? slideSpeed : 1;
		
		document.fire('optiem:pauseVideos');
		
		previousSlice = currentSlice;
		
		currentSlice = (slices.size() + ((currentSlice + sliceMove) % slices.size())) % slices.size();
		
		navSlicesItems[previousSlice].removeClassName('current');
		navSlicesItems[currentSlice].addClassName('current');
		
		/*if(currentSlice == 0){
			previousButton.addClassName('disabled');
			if(currentSlice != (slices.size()-1)){
				nextButton.removeClassName('disabled');
			}
		}
		else if(currentSlice == (slices.size()-1)){
			nextButton.addClassName('disabled');
			if(currentSlice != 0){
				previousButton.removeClassName('disabled');
			}
		}
		else {
			previousButton.removeClassName('disabled');
			nextButton.removeClassName('disabled');
		}*/
		
		slideDeclaration.update(currentSlice + 1 + ' / ' + slices.size());
		
		new Effect.Fade(slices[previousSlice], {
			sync: false,
			from: 1,
			to: 0,
			transition: Effect.Transitions.sinoidal,
			duration: slideTime,
			queue: {
				position: 'end',
				scope: 'sliceQueue'
				}
			}
		);
		
		new Effect.Appear(slices[currentSlice], {
			sync: false,
			from: 0,
			to: 1,
			transition: Effect.Transitions.sinoidal,
			duration: slideTime,
			afterFinish: function(p){
				document.fire('optiem:playVideos');
			},
			queue: {
				position: 'end',
				scope: 'sliceQueue'
				}
			}
		);
	}
	
	document.observe('optiem:updateSlice', function(event) {
		var sliceMove = event.memo.indexMove;
		var sliceSpeed = event.memo.sliceSpeed;
		slideChange(sliceMove, sliceSpeed);
	});
	
	previousButton.observe('click', function(event){
		if(queue.effects.size() == 0){
			previousButton.fire('optiem:updateSlice', { indexMove: -1 });
			event.stop();
		}
	});
	
	nextButton.observe('click', function(event){
		if(queue.effects.size() == 0){
			nextButton.fire('optiem:updateSlice', { indexMove: 1 });
			event.stop();
		}
	});
}



//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');
	
	if(!breakoutLinks[0]) return false;
	
	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], "breakout", "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);

			}
			}
		}
		*/
		
		
	} 

function createVideoTag(videoURL,videoURLOgg){
	var viewport = $('viewport');
	
	videoTag = new Element('video', {width: '934', height: '522', preload: 'none', controls: 'controls'});
	videoSource = new Element('source', {src: videoURL, type: 'video/mp4'});
	videoSourceOgg = new Element('source', {src: videoURLOgg, type: 'video/ogg'});
	
	viewport.insert({
		top: videoTag
	});
	
	videoTag.insert({
		top: videoSourceOgg
	});	
	
	videoTag.insert({
		top: videoSource
	});	
	
	/*var agent=navigator.userAgent.toLowerCase();
	var is_ipad = ((agent.indexOf('ipad')!=-1));
	if (is_ipad) { alert('you are using an ipad')};
	*/
	new Effect.Opacity(videoTag, {from: 1, to: 0, duration: 1.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();
	breakoutHelper();
	breakoutCarousel();
	inputClear();
	highlightHelper();
	portfolioAssistant();
	Cufon.refresh('div.highlight h2');
	//backgroundClass();
	landingPageURLHandler();
});
