
//Search Assistance
//Modifies Search Results based on Pseudo-dropdown
function searchAssist(){
	var modifiers = $$('.modifiers');
	
	modifiers.each(function(modifier){
		var optionSelection = modifier.previous('input');
		var options = modifier.select('li');
		
		options.each(function(option, index){
			if(index > 0){
				option.observe('click', function(event){
					options[0].update(option.innerHTML.truncate(20, '...'));
					optionSelection.value = option.innerHTML;
				});
			}
		});
	});
}

//Google Analytics Tracking
function eventTracking() {
	document.observe('materion:trackEvent', function(event){
		//console.log('test');
		trackingCategory = event.memo.trackingCategory;
		trackingAction = event.memo.trackingAction;
		trackingLabel = event.memo.trackingLabel;
		_gaq.push('_trackEvent(' + trackingCategory + ', ' + trackingAction + ', ' + trackingLabel + ')');
		//console.log('pageTracker._trackEvent('+trackingCategory+', '+trackingAction+', '+trackingLabel+');');
	});
}

//External Links set to Target Blank
//Note: Prototype Driven
function externalLinks() {
	$$('a[rel="external"], a[target="_blank"]').each(function (link) {
		if (link.readAttribute('href') != '' && link.readAttribute('href') != '#') {

			link.writeAttribute('target', '_blank');

			link.observe('click', function (event) {
				//console.log('test');
				var parentID = '';
				var linkAncestors = link.ancestors();

				linkAncestors.each(function (linkAncestor) {
					if (parentID == '' && linkAncestor.readAttribute('id')) {
						parentID = linkAncestor.readAttribute('id');
					}
				});

				var externalAction = parentID.capitalize() + ' Link';
				var externalLabel = link.readAttribute('title') + ' @ ' + link.readAttribute('href');

				link.fire('materion:trackEvent', {
					trackingCategory: 'External Link',
					trackingAction: externalAction,
					trackingLabel: externalLabel
				});
			});
		}
	});
}


//Function: List Groups
//Takes Lists of class group, and collapses their children
function listGroups(){
	var lists = $$('ul.groups, ol.groups');

	lists.each(function (list) {
	    var listItems = list.select('li');
	    listItems.each(function (listItem) {
	        var subList = listItem.down('ul');
	        if (subList && !listItem.hasClassName('active')) {
	            listItem.addClassName('hasChildren');

	            listItem.observe('click', function (event) {
	                window.log('Event Node Name: ', event.target.nodeName.toLowerCase());
	                if (event.target.nodeName.toLowerCase() == 'li') {
	                    listItem.toggleClassName('open');
	                }
	            });
	        }
	    });
	});
}

//Columned List Sort Utility
//Properly reorganizes a list to allow for columns
function listSorter(listArray, columns) {
	var numColumns = columns;
	var lists = listArray;
		
	function arrayHeight(arrays, index) {
		var totalHeight = 0;
		arrays.each(function(array){
			if(array[index]){
				totalHeight++;
			}
		});
		
		return totalHeight;
	}

	lists.each(function(list){
		var listItems = list.childElements();
		window.log(listItems)
		var totalItems = listItems.size();

		var sortedItems = [];

		var numRows = totalItems / numColumns;
		numRows = numRows.ceil();
		window.log('Number of Rows: ', numRows);
		
		var listGroups = [];
		
		listItems.eachSlice(numColumns, function(listGroup, index){
			listGroups[index] = listGroup;
		});
		
		window.log('List Groups: ', listGroups);
		
		var indexesPushed = [];
		
		numRows.times(function(n){
			var psuedoIndex = 0;
			var sortedRow = [];

			numColumns.times(function(m){
				var increment = arrayHeight(listGroups, m);
				window.log('Increment: ', increment);
				window.log('Attempting to grab item @ ', psuedoIndex + n);
				if(indexesPushed.include(psuedoIndex + n)){
					window.log('Rejected item @ ', psuedoIndex + n);
					psuedoIndex = psuedoIndex + increment;
					return false;
				}
				
				var item = listItems[psuedoIndex + n];
				
				indexesPushed.push(psuedoIndex + n);

				if(item){
					sortedRow.push(item);
				}
				
				psuedoIndex = psuedoIndex + increment;
			});
			window.log('Row: ', sortedRow);

			sortedItems[n] = sortedRow;
		});
		                
		sortedItems = sortedItems.flatten();
		                
		sortedItems.each(function(sortedItem){
			list.insert({
				bottom: sortedItem
			});
		});

		return sortedItems;

	});

}


//Height Balance
//Normalizes the height of the elements passed in,
//based on the number of columns desired
function heightBalance(balanceElements, columns){
	balanceElements.eachSlice(columns, function(balanceElementSlice){
		var sliceHeight = balanceElementSlice.max(function(sliceElement){
			return sliceElement.getHeight();
		});
		
		balanceElementSlice.each(function(balanceElement){
			balanceElement.setStyle({
				height: sliceHeight + 'px'
			});
		});
	});
}

//Category Assist
//Employs the Height Balancer and List Sorter
//To create an organized Category List
function categoryAssist(){
	window.log('Running Category Assist');
	var categoryLists = $$('.categories');
	
	if(categoryLists.size() == 0){
		return false;
	}
	
	var columns = 2;
	var contentType = $('main').down('section.detail');
	if(contentType.getWidth() > 700){
		columns = 3;
	}
	
	window.log('Columns: ', columns);
	window.log('contentType: ', contentType);
	
	listSorter(categoryLists, columns);
	
	categoryLists.each(function(categoryList){
		var categoryItems = categoryList.select('> li');
		heightBalance(categoryItems, columns);
	});
}

//Class: Carousel
//Assists in the rotation of Carousel Items
//IN DEVELOPMENT - NEED DEBUG ON BALANCE
var carousel = Class.create({

	initialize: function(container, direction){
		//console.log('Initialize Carousel');
		
		//Set DOM Containers
		//console.log('Set DOM Containers');
		this.carouselContainer = container;
		this.carouselItems = this.carouselContainer.select('> li');
		this.carouselContainer.setStyle({
			position: 'relative'
		});
		
		//Set Size Constraints
		//console.log('Set Size Constraints');
		this.size = this.carouselItems.size();
		this.currentItem = 0;
		this.previousItem = this.size;
		
		//Set Dimensions & Positioning
		//console.log('Set Dimensions & Positioning');
		this.dimensions = $H(this.carouselContainer.getDimensions());
		
		if(direction == 'vertical'){
			this.measure = 'height';
		}
		else {
			this.measure = 'width';
		}
		
		//console.log('Carousel Items', this.carouselItems);
		this.itemDimensions = $H(this.carouselItems[0].getDimensions());
		this.lastPosition = 0;
		
		var carouselPointer = this;
		
	/*	this.carouselItems.each(function(carouselItem, index){
			console.log('Measurement', carouselPointer.dimensions.get(carouselPointer.measure));
			carouselItem.setStyle({
				position: 'absolute',
				top: carouselPointer.lastPosition + 'px'
			});
			carouselPointer.lastPosition = carouselPointer.lastPosition + carouselPointer.itemDimensions.get(carouselPointer.measure);
		});*/
	},
	get: function(itemIndex) {
		return this.carouselItems[itemIndex]
	},
	getChildren: function(){
		return this.carouselItems;
	},
	getIndex: function(){
		return { currentIndex: this.currentItem, previousIndex: this.previousItem};
	},
	move: function(itemMove){
		this.previousItem = this.currentItem;
		this.currentItem = (this.size + ((this.currentItem + itemMove) % this.size)) % this.size; //incrementally step up the index
		
		return { current: this.get(this.currentItem), previous: this.carouselItems[this.previousItem], currentIndex: this.currentItem, previousIndex: this.previousItem };
	},
	getCurrentItem: function(){
		return { current: this.carouselItems[currentItem], currentIndex: currentItem };
	}
});


//Activate the carousel on the home page.
function carouselCall() {
	var carouselContainers = $$('ol.carousel');
	var navOpacity = .7;
	//console.log(carouselContainers);
	carouselContainers.each(function (carouselContainer) {
		var carouselNav = carouselContainer.next('.navCarousel');
		var carouselNavItems = carouselNav.select('li');

		var currentItem = 0;

		var newCarousel = new carousel(carouselContainer, 'horizontal');
		//console.log(newCarousel);
		var carouselItems = newCarousel.getChildren();
		//window.log(carouselItems);

		carouselItems.each(function (carouselItem, index) {
			var contentImage = carouselItem.down('img');

			carouselItem.setStyle({
				background: 'url("' + contentImage.src + '") 0 0 no-repeat'
			});

			contentImage.remove();

			if (index > 0) {
				carouselItem.setOpacity(0);
			}

			carouselItem.showAnimation = new S2.FX.Morph(carouselItem, {
				style: 'opacity:' + 1,
				transition: 'easeFromTo',
				duration: .5,
				after: function () {

				},
				before: function () {

				}
			});

			carouselItem.hideAnimation = new S2.FX.Morph(carouselItem, {
				style: 'opacity:' + 0,
				transition: 'easeFromTo',
				duration: .5,
				after: function () {

				},
				before: function () {

				}
			});

		}); //End Carousel Items Loop

		var carouselRotator = new PeriodicalExecuter(function (pe) {
			window.log('Periodical Executer Fired ', pe);
			var carouselIndex = newCarousel.getIndex();

			var itemMove = 1;
			var carouselUpdate = newCarousel.move(itemMove);

			carouselItems[carouselUpdate.currentIndex].setStyle({
				zIndex: 10000
			});

			carouselItems[carouselUpdate.previousIndex].setStyle({
				zIndex: 100
			});

			carouselNavItems[carouselUpdate.currentIndex].addClassName('current');
			carouselNavItems[carouselUpdate.previousIndex].removeClassName('current');
			carouselNavItems[carouselUpdate.previousIndex].setOpacity(navOpacity);

			carouselItems[carouselUpdate.currentIndex].showAnimation.play();
			window.setTimeout(function () {
				carouselItems[carouselUpdate.previousIndex].setOpacity(0);
			}, 1000);
		}, 8)

		carouselNavItems.each(function (carouselNavItem, index) {
			if (index > 0) {

			}
			else {
				carouselNavItem.addClassName('current');
			}

			carouselNavItem.enterAnimation = new S2.FX.Morph(carouselNavItem, {
				style: 'opacity:' + 1,
				transition: 'easeFromTo',
				duration: .25
			});

			carouselNavItem.leaveAnimation = new S2.FX.Morph(carouselNavItem, {
				style: 'opacity:' + navOpacity,
				transition: 'easeFromTo',
				duration: .25
			});

			//console.log(carouselNavItem.leaveAnimation);

			carouselNavItem.observe('mouseenter', function (event) {
				if (carouselNavItem.hasClassName('current')) {

				}
				else {
					//carouselNavItem.leaveAnimation.finish();
					//carouselNavItem.enterAnimation.play();
				}
			});

			carouselNavItem.observe('mouseleave', function (event) {
				if (carouselNavItem.hasClassName('current')) {

				}
				else {
					//carouselNavItem.enterAnimation.finish();
					//carouselNavItem.leaveAnimation.play();
				}
			});

			carouselNavItem.down('a').observe('click', function (event) {
				window.log('Nav Item Clicked ', index);
				carouselRotator.stop();
				var carouselIndex = newCarousel.getIndex();

				if (index == carouselIndex.currentIndex) {
					return;
				}

				var itemMove = index - carouselIndex.currentIndex;
				var carouselUpdate = newCarousel.move(itemMove);

				carouselItems[carouselUpdate.currentIndex].setStyle({
					zIndex: 10000
				});

				carouselItems[carouselUpdate.previousIndex].setStyle({
					zIndex: 100
				});

				carouselNavItems[carouselUpdate.currentIndex].addClassName('current');
				carouselNavItems[carouselUpdate.previousIndex].removeClassName('current');
				carouselNavItems[carouselUpdate.previousIndex].setOpacity(navOpacity);

				carouselItems[carouselUpdate.currentIndex].showAnimation.play();
				window.setTimeout(function () {
					carouselItems[carouselUpdate.previousIndex].setOpacity(0);
				}, 1000);

				event.stop();
			});

			carouselNavItem.observe('click', function (event) {
				window.log('Nav Item Clicked ', index);
				carouselRotator.stop();
				var carouselIndex = newCarousel.getIndex();

				if (index == carouselIndex.currentIndex) {
					return;
				}

				var itemMove = index - carouselIndex.currentIndex;
				var carouselUpdate = newCarousel.move(itemMove);

				carouselItems[carouselUpdate.currentIndex].setStyle({
					zIndex: 10000
				});

				carouselItems[carouselUpdate.previousIndex].setStyle({
					zIndex: 100
				});

				carouselNavItems[carouselUpdate.currentIndex].addClassName('current');
				carouselNavItems[carouselUpdate.previousIndex].removeClassName('current');
				//carouselNavItems[carouselUpdate.previousIndex].setOpacity(navOpacity);

				carouselItems[carouselUpdate.currentIndex].showAnimation.play();
				window.setTimeout(function () {
					carouselItems[carouselUpdate.previousIndex].setOpacity(0);
				}, 1000);

				event.stop();

				//carouselItems[carouselUpdate.previousIndex].hideAnimation.play();
			});
		}); //End Carousel Nav Items Loop

	});   // End Carousel Loop
}

//Web Forms for Maketers Required Label Selector (Labels are used how we usually use dfn's)
//Note: Prototype Driven
function requiredLabels() {
	var spans = $$('span.scfRequired, span.scfValidatorRequired');
	//var downSpans =  $$('span.scfValidator');
	window.log(spans);
		
	spans.each(function(span){
		var requiredLabels = span.adjacent('label');
		window.log(requiredLabels);
		
		requiredLabels.each(function(requiredLabel) {
			requiredLabel.addClassName('required');
		});
	});
	
/*	downSpans.each(function(downSpan){
		if(downSpan.up('div').previous('label')) {
			var validatedRequiredLabel = downSpan.up('div').previous('label');
			window.log(validatedRequiredLabel);
			
			validatedRequiredLabel.addClassName('required');	
			window.log('true');
		} else {
			window.log('false');
			return false;
		}

	});*/
}

//Error Helper
//Moves view to top of page upon finding form errors
function errorHelper() {
	var pageErrors = $$('div.scfValidationSummary ul');

	pageErrors.each(function (pageError) {
		inputExecuter = new PeriodicalExecuter(function () {
			pageError.scrollTo();
			inputExecuter.stop();
		}, .1);
	});
}


//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');
	});
}

//External Link Helper
//Updates Links with External Relation to
//use target="_blank"
function externalLinks(){
	var links = $$('a[rel=external]');
	
	links.each(function(externalLink){
		externalLink.writeAttribute('target', '_blank');
	});
}

//Video Players
//Change video objects via JWPlayer
function videoPlayers() {

	var videoObjects = $$('video');
	var hasIE = $$('.hasIE');

	videoObjects.each(function (videoObject) {
		var videoID = videoObject.identify();
		var mp4Source = videoObject.down('source').getAttribute('src');

		if (hasIE.size() > 0) {

			var videoID = videoObject.up('div').identify();
			jwplayer(videoID).setup({
				controlbar: "bottom",
				height: 230,
				icons: false,
				file: mp4Source,
				players: [
					{ type: "flash", src: "/themes/global/scripts/mediaplayer-5.4/player.swf" }
				]
			});
		}
		else {
			var videoID = videoObject.identify();
			jwplayer(videoID).setup({
				controlbar: "bottom",
				icons: false,
				players: [
				{ type: "flash", src: "/themes/global/scripts/mediaplayer-5.4/player.swf" }
			]
			});
		}

	});

}

//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;
}


//Setup Zebra Striping Classing on all Tables.
function zebraStripe() {
    var evens = $$('table tr:nth-child(even)');

    if (evens) {
        evens.each(function (tr) {
            tr.addClassName('even');
        });
    }
}

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};

// catch all document.write() calls
(function(doc){
	var write = doc.write;
	doc.write = function(q){
		log('document.write(): ',arguments);
		if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments); 
	};
})(document);

//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
	carouselCall();
	searchAssist();
	listGroups();
	categoryAssist();
	zebraStripe();
	eventTracking();
	externalLinks();
	requiredLabels();
	videoPlayers();
	errorHelper();
});
