
//Height Matcher for Product Listings to fix any inconsistencies.
function heightClear() {
	var liInputs = $$('ul.productListing li');
	if(!liInputs) return false; //if there are no product list items, stop here.
	
	var maxHeight = liInputs.max(function(liInput){
		return liInput.getHeight();
	});
	
	liInputs.each(function(liInput, index){
		liInput.setStyle({
		  height: maxHeight+'px'
		});
	});
}
//Input Class Add
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputFocus() {
	var textInputs = $$('input[type="text"]');
	
	textInputs.each(function(textInput){
		textInput.observe('focus', function(event) {
			textInput.addClassName('focus');
		});
		textInput.observe('blur', function(event){
			textInput.removeClassName('focus');
		});
	});
}


//PartsList Helper
function partsListHelper(){
	var partRows = $$('ul.partsList tbody tr'); //Collect all the body table rows
	
	if(!partRows) return false; //if there are no rows, stop here.
	
	partRows.each(function (partRow){
		if(partRow.down('td:last-child').empty()|!partRow.down('td')){ //or takes care  of footer bit that includes link to product
			partRow.remove();
		}
	});
	
	var partRowsEvens = $$('ul.partsList tbody tr:nth-child(odd)'); //lets zebra strip this.
	
	partRowsEvens.each(function (tr){
		tr.addClassName('odd'); //every odd one, add this class.
	});
}

//Highlight Height Fix
function highlightFix() {
	var highlights = $$('div.highlight'); //grab the highlights make a variable
	var contentMain = $('contentMain'); //grab the container which will be the height of the tallest highlight.
	
	if(!highlights) return false;//if no highlights do nothing
	
	highlightHeight = contentMain.getHeight(); //grab that tallest height
	
	highlights.each(function(highlight){ //assign it to each highlight
		highlight.setStyle({
			height: highlightHeight + 'px'
		});
	});
}

//ResourceBox Checker
//Checks to see if the resource box contains items, if not it hides it.
function resourceBoxHelper() {
	var resourceBox = $('resourceBox');
	
	if(!resourceBox) return false;
	
	resourceBoxContents = $(resourceBox.down('a'));
	
	if(!resourceBoxContents){
		resourceBox.hide();
		return false;
	}
}

//Contact Listing Helper
function contactHelper(){
	var contactListItems = $$('ul.contactListing li');
	
	if(!contactListItems[0]) return false;
	
	var pageURL = window.location;
	
	contactListItems.each(function(contactListItem){
			
		//Finally, let's check for email links - if there are any, 
		//we'll create Email links to the contact form.
		
		if(contactListItem.down('dd.email')){
			emailLink = new Element('p');
			emailLink.addClassName('emailLink');
			emailAnchor = new Element('a', { href: "#"}).update("Email Us");
		
			emailLink.insert({
				top: emailAnchor
			});	
			
			contactListItem.insert({
				top: emailLink
			});	
			
			contactListItem.down('dd.email').remove();
		}
		
	});
}

//Navigation Hover
//Adds hover class to necessary objects
//Note: Prototype driven
function dropDownHovers() {
	var navHovers = $$('#header ul');
	
	navHovers.each(function(navHover){
		navHover.observe('mouseenter', function(event){
			navHover.addClassName('hover');
		});
		navHover.observe('mouseleave', function(event){
			navHover.removeClassName('hover');
		});
	});
}

//RegionTool Checker
//Checks to see if there are more than one region option available.
//If there isn't the regionTool list is hidden from the viewers site.
function regionToolHelper() {
	var regionTool = $('regionTool');
	var regions = $$('ul#regionTool li');
	
	if(!regionTool) return false;
	
	var regionQty = regions.size();
	
	if(regionQty < 4){
		regionTool.setStyle({
			position: 'absolute',
			left: '-999em'
		});
		
	}
}



//LanguageTool Checker
//Checks to see if there are more than one region option available.
//If there isn't the languageTool list is hidden from the viewers site.

function languageToolHelper() {
	var languageTool = $('languageTool');
	var languages = $$('ul#languageTool li');
	
	if(!languageTool) return false;
	
	var languageQty = languages.size();
	
	if(languageQty < 4){
		languageTool.setStyle({
			position: 'absolute',
			left: '-999em'
		});
		
	} 
	
}

//Internal Page Navigation Helper
function navProductHelper(viewAllKeyword,viewLessKeyword) {

	var prodLists = $$('ul.products');
	
	if(!prodLists) return false;
	
	prodLists.each(function(prodList, listIndex){

		var products = $$('ul.products li');
		
		var remainingApps = products.slice(2);
		
		prodshowMoreButton = new Element('li');
		prodshowMoreButton.addClassName('more');
		prodshowMoreAnchor = new Element('a', { href: "#"}).update(viewAllKeyword);
		
		
		prodList.insert({ bottom: prodshowMoreButton });
		prodshowMoreButton.insert({ bottom: prodshowMoreAnchor });
		
		remainingApps.each(function(remainingApp, index){
			remainingApp.addClassName('hidden');
			
			prodshowMoreButton.observe('click', function(event){
				remainingApp.toggleClassName('hidden');
				var hiddenApps = $$('ul.products li.hidden');
				if(hiddenApps.size() > 0){
					prodshowMoreButton.down('a').update(viewAllKeyword);
					prodshowMoreAnchor.setStyle({
						backgroundPosition: '32px 15px'
					});
				} else {
					prodshowMoreButton.down('a').update(viewLessKeyword);
					prodshowMoreAnchor.setStyle({
						backgroundPosition: '32px -74px'
					});
				}
				event.stop();
			});
		
		});
	});	
}

//Internal Page Navigation Helper
function navAppHelper(viewAllKeyword,viewLessKeyword) {
	var appLists = $$('ul.applications');
	
	if(!appLists) return false;
	
	appLists.each(function(appList, listIndex){
		var applications = $$('ul.applications li');
		
		var remainingApps = applications.slice(2);
		
		appshowMoreButton = new Element('li');
		appshowMoreButton.addClassName('more');
		appshowMoreAnchor = new Element('a', { href: "#"}).update(viewAllKeyword);
		
		
		appList.insert({ bottom: appshowMoreButton });
		appshowMoreButton.insert({ bottom: appshowMoreAnchor });
		
		remainingApps.each(function(remainingApp, index){
			remainingApp.addClassName('hidden');
			
			appshowMoreButton.observe('click', function(event){
				remainingApp.toggleClassName('hidden');
				var hiddenApps = $$('ul.applications li.hidden');
				if(hiddenApps.size() > 0){
					appshowMoreButton.down('a').update(viewAllKeyword);
					appshowMoreAnchor.setStyle({
						backgroundPosition: '32px 15px'
					});
				} else {
					appshowMoreButton.down('a').update(viewLessKeyword);
					appshowMoreAnchor.setStyle({
						backgroundPosition: '32px -74px'
					});
				}
				event.stop();
			});
		
		});
	});	
}

//Internal Page Navigation Helper
function navServicesHelper(viewAllKeyword,viewLessKeyword) {
	var servicesLists = $$('ul.services');
	
	if(!servicesLists) return false;
	
	servicesLists.each(function(servicesList, listIndex){
		var services = $$('ul.services li');
		
		var remainingServices = services.slice(2);
		
		showMoreButton = new Element('li');
		showMoreButton.addClassName('more');
		showMoreAnchor = new Element('a', { href: "#"}).update(viewAllKeyword);
		
		var listState = [];
		listState[listIndex] = 'open';
		
		servicesList.insert({ bottom: showMoreButton });
		showMoreButton.insert({ bottom: showMoreAnchor });
		
		remainingServices.each(function(remainingService, index){
			remainingService.addClassName('hidden');
			
		showMoreButton.observe('click', function(event){
			remainingService.toggleClassName('hidden');
				var hiddenServices = $$('ul.services li.hidden');
				if(hiddenServices.size() > 0){
					showMoreButton.down('a').update(viewAllKeyword);
					showMoreAnchor.setStyle({
						backgroundPosition: '32px 15px'
					});
				} else {
					showMoreButton.down('a').update(viewLessKeyword);
					showMoreAnchor.setStyle({
						backgroundPosition: '32px -74px'
					});
				}
			
			
			event.stop();
		});
		
		});
	});
	
}

//if (link.readAttribute('href') != '' && link.readAttribute('href') != '#') {
//			link.writeAttribute('target', '_blank');
//		}


//Site Highlight Rotator
//Creates navigation for Breakout Carousel
//Note: Prototype Framework
function breakoutCarousel() {
	var breakoutHighlightImages = $$('#highlightRotatorImages li');
	var breakoutHighlightTexts = $$('#highlightRotatorText li');
	
	if(!breakoutHighlightImages[0]) return false;
	if(!breakoutHighlightTexts[0]) return false;
	
	var contentArea = $('contentMain');
	var moreInfoBoxes = $$('div.moreInfo');
	var breakout = $('breakout');
	var pageHeadingHeight = breakout.down('h1').getHeight();
	var viewport = $('viewport');
	var footer = $('footer');
	var speed = 10 //time to show frame
	var viewportHeight = viewport.getHeight();
	
	var queue = Effect.Queues.get('highlightQueue');
	
	var navItems = [];
	
	breakoutHighlightImages.each(function(breakoutHighlightImage, index) {
		if(breakoutHighlightImage.empty()){
			breakoutHighlightImage.remove();
		}
	});
	
	
	
	breakoutHighlightImages.each(function(breakoutHighlightImage, index) {
		breakoutHighlightImage.setStyle ({
			backgroundImage: 'url(' + breakoutHighlightImage.down('img').src + ')',
			backgroundRepeat: 'no-repeat',
			backgroundPosition: '0 0'
		});
		
		breakoutHighlightImage.down('img').remove();
	});		
	
	breakoutHighlightTexts.each(function(breakoutHighlightText, index) {
		if(breakoutHighlightText.empty()){
			breakoutHighlightText.remove();
		} else {
			breakoutHighlightText.setStyle({
				paddingTop: pageHeadingHeight - 40 + 'px'
			});
		}
	});

	var breakoutContainer = breakoutHighlightImages[0].up('div');
	var currentHighlight = 0;
	var previousHighlight = breakoutHighlightImages.size();
	var highlightIndex = breakoutHighlightImages.size();
	
	var currentHighlightText = 0;
	var previousHighlightText = breakoutHighlightTexts.size();
	var highlightTextIndex = breakoutHighlightTexts.size();
	
	
	//Check to see if is more than one - if not don't put the controls - it's unnecessary 
	if(breakoutHighlightTexts.size() > 1) {
		//Building out new numbered nav //
			
		highlightNavigation = new Element('ul').addClassName('breakoutNav');
		
		breakout.insert({
			top: highlightNavigation
		});
		
		breakoutHighlightImages.each(function(breakoutHighlightImage, index) {	
			if(index > 0){
				breakoutHighlightImage.setOpacity(0);
			} else {
				breakoutHighlightImage.setOpacity(1);		
			}
		});	
		
		breakoutHighlightTexts.each(function(breakoutHighlightText, index) {
		
			if(index > 0){
				breakoutHighlightText.setOpacity(0);
			} else {
				breakoutHighlightText.setOpacity(1);
				breakoutHighlightText.setStyle({
					zIndex: 100
				});
			
			}
		
			navItems[index] = new Element('li').update("Panel " + (index + 1));
			
			if(index == 0){
				navItems[index].addClassName('currentPanel');
			}
			
			
				navItems[index].observe('click', function(event){
					if(queue.effects.size() == 0) {	
						var panelMove = currentHighlight - index;
						new Effect.Move(contentArea, { x: 0, y: 0, mode: 'absolute' }); 
						navItems[index].addClassName('currentPanel');
						carousel.stop();
						nextHighlightButton.addClassName('play');
						nextHighlightButton.removeClassName('pause');
						if(moreInfoBoxes){
							
							viewport.setStyle({
								height: 'auto'
							});	
							
							new Effect.Move(footer, { x: 0, y: 0, mode: 'absolute' });
							
							moreInfoBoxes.each(function(moreInfos){
								moreInfos.setStyle({
									display: 'none'
								});
								
							});	
						}
						
						navItems[index].fire('parker:updateHighlight', { indexMove: panelMove });
						
						event.stop();
					}
				});
			
			highlightNavigation.insert({
				bottom: navItems[index]
			})
		});				
			
		nextHighlightButton = new Element('li');
		nextHighlightButton.addClassName('pause');
		nextHighlightAnchor = new Element('a', { href: "#"}).update("Next");
		
		nextHighlightButton.insert({ bottom: nextHighlightAnchor });
		highlightNavigation.insert({ bottom: nextHighlightButton });
	
		nextHighlightButton.observe('click', function(event){
			
			if(nextHighlightButton.hasClassName('play')){
				carousel = new PeriodicalExecuter(function(){
					nextHighlightButton.fire('parker:updateHighlight', { indexMove: -1 });
				}, speed);
				if(moreInfoBoxes){
					moreInfoBoxes.each(function(moreInfos){
						moreInfos.setStyle({
							opacity: 0
						});
					});
					new Effect.Move(contentArea, { x: 0, y: 0, mode: 'absolute' }); 
					new Effect.Move(footer, { x: 0, y: 0, mode: 'absolute' });
				}
				
				nextHighlightButton.removeClassName('play');
				nextHighlightButton.addClassName('pause');
			} 
			else if(nextHighlightButton.hasClassName('pause')){
				carousel.stop();
				nextHighlightButton.addClassName('play');
				nextHighlightButton.removeClassName('pause');
				
			}	
			
			event.stop();
		});
	};	
	
	document.observe('parker:updateHighlight', function(event){	
		if(queue.effects.size() == 0) {	
			//console.log(queue.effects.size());
			var highlightMove = event.memo.indexMove;
			
			previousHighlight = currentHighlight;

			currentHighlight = (breakoutHighlightImages.size() + ((currentHighlight - highlightMove) % breakoutHighlightImages.size())) % breakoutHighlightImages.size();
			
			var internalPreviousHighlight = previousHighlight;
			var internalCurrentHighlight = currentHighlight;
			
			//breakoutHighlightImages[currentHighlight].setStyle({
			//	display: 'none'
			//});
			
			navItems[internalPreviousHighlight].removeClassName('currentPanel');
			navItems[internalCurrentHighlight].addClassName('currentPanel');
			
			new Effect.Parallel([
				new Effect.Tween(breakoutHighlightImages[previousHighlight], 1, 0, {sync: true}, function(value){
					this.setOpacity(value);
				}),
				new Effect.Tween(breakoutHighlightImages[currentHighlight], 0, 1, {sync: true}, function(value){
					this.setOpacity(value);
				}),
				new Effect.Tween(breakoutHighlightTexts[previousHighlight], 1, 0, {sync: true}, function(value){
					this.setOpacity(value);
					this.setStyle({
						zIndex: 0 					
					});
				}),
				new Effect.Tween(breakoutHighlightTexts[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(){		
		contentArea.fire('parker:updateHighlight', { indexMove: -1 });
	}, speed);
	
	//Functionality for hiding and showing more info texts.
	breakoutHighlightTexts.each(function(breakOutText, index){
	
		var moreLink = breakOutText.down('a.more');
		var moreInfo = breakOutText.down('div.moreInfo');
		
		if(!moreInfo) return false;
		
		breakOutText.down('a.more').observe('click', function(event){
					
			var moreInfoHeight = moreInfo.getHeight();
			var footerHeight = footer.getHeight();
			
			moreInfo.toggleClassName('visible');
			
			if(index > 0){
				nextHighlightButton.toggleClassName('pause');
				nextHighlightButton.toggleClassName('play');
			}
			new Effect.Move(footer, { x: 0, y: 0, mode: 'absolute' });
			
			if(moreInfo.hasClassName('visible')){
				moreInfo.setStyle({
					display: 'block'
				});
				
				viewport.setStyle({
					height: viewportHeight + moreInfoHeight + 100 + 'px'
				});
				
				new Effect.Move(contentArea, { x: 0, y: moreInfoHeight, mode: 'relative' }); 
				new Effect.Move(footer, { x: 0, y: moreInfoHeight, mode: 'relative' });
				
			
				closeButton = new Element('p');
				closeButton.addClassName('closeButton');
				closeButton.update('close');
				
				moreInfo.insert({ top: closeButton });
		
				closeButton.observe('click', function(event){
					moreInfo.setStyle({
						display: 'none'
					});
					
					moreInfo.toggleClassName('visible');
					
					new Effect.Move(contentArea, { x: 0, y: 0, mode: 'absolute' }); 
					new Effect.Move(footer, { x: 0, y: 0, mode: 'absolute' });
					
					viewport.setStyle({
						height: 'auto'
					});	
					
					nextHighlightButton.toggleClassName('pause');
					nextHighlightButton.toggleClassName('play');
					
					carousel = new PeriodicalExecuter(function(){
						nextHighlightButton.fire('parker:updateHighlight', { indexMove: -1 });
					}, speed);
					
				footer.setStyle({
					marginTop: 12 + 'px'
				});
					event.stop();
				});
				event.stop();
				carousel.stop();
				
			} else {
				moreInfo.setStyle({
					display: 'none'
				});
				new Effect.Move(contentArea, { x: 0, y: 0, mode: 'absolute' }); 
				
				viewport.setStyle({
					height: 'auto'
				});
				
				nextHighlightButton.toggleClassName('pause');
				nextHighlightButton.toggleClassName('play');
				
				carousel = new PeriodicalExecuter(function(){
					nextHighlightButton.fire('parker:updateHighlight', { indexMove: -1 });
				}, speed);
				
				event.stop();
			}
		});
	});
}

//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);
	dropDownHovers();
	highlightFix();
	heightClear();
	resourceBoxHelper();
	liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	externalLinks(); //Checks for a link REL=External, adds TARGET=Blank
	regionToolHelper() //Hides RegionTool if there are fewer than 2 choices.
	languageToolHelper() //Hides RegionTool if there are fewer than 2 choices.
	breakoutCarousel();
	//navAppHelper();
	//navProductHelper();
	//navServicesHelper();
	partsListHelper();
	inputFocus();
	contactHelper();
});
