//dynamicShadow - Creates a dynamic shadow for images
//Defaults to shadow.gif, 10 width, no offset
//Note: Prototype Framework
function dynamicShadow(shadowURL, containerID, shadowWidth, shadowOffset) {
	var shadowURL = (shadowURL == null) ? "../images/global/shadowTest.gif" : shadowURL;
	var containerID = (containerID == null) ? "page-container" : containerID;
	var shadowWidth = (shadowWidth == null) ? 10 : shadowWidth;
	var shadowOffset = (shadowOffset == null) ? 0 : shadowOffset;

	
	var images = $$(
		'#' + containerID + ' img.shadow,'
		+ '#' + containerID + ' img.shadowLeft,'
		+ '#' + containerID + ' img.shadowRight,'
		+ '#' + containerID + ' img.shadowCenter');
	var imageClone;
	var imageHeight;
	var imageWidth;
	var shadowContainer;
	var shadowDiv = [];
	
	images.each(function(imageObject){
		imageClone = Object.extend(imageObject);
		imageHeight = imageObject.getHeight();
		imageWidth = imageObject.getWidth();
		imageClass = imageObject.className;
		
		// Create the Shadow Container
		shadowContainer = new Element('div');
		shadowContainer.addClassName('shadowContainer');
		shadowContainer.addClassName(imageClass);
		shadowContainer.setStyle({
			position: 'relative',
			padding: shadowWidth + 'px',
			width: imageWidth + 'px',
			height: imageHeight + 'px',
			background: 'transparent'
		});

		// Create Top Left Div
		shadowDiv[0] = new Element('div');
		shadowDiv[0].setStyle({
			position: 'absolute',
			top: 0,
			left: 0,
			width: shadowWidth + 'px',
			height: shadowWidth + 'px',
			background: 'transparent url("' + shadowURL + '") top left no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[0] });
		
		// Create Top Right Div
		shadowDiv[1] = new Element('div');
		shadowDiv[1].setStyle({
			position: 'absolute',
			top: 0,
			right: 0,
			width: shadowWidth + 'px',
			height: shadowWidth + 'px',
			background: 'transparent url("' + shadowURL + '") top right no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[1] });
		
		// Create Bottom Right Div
		shadowDiv[2] = new Element('div');
		shadowDiv[2].setStyle({
			position: 'absolute',
			bottom: 0,
			right: 0,
			width: shadowWidth + 'px',
			height: shadowWidth + 'px',
			background: 'transparent url("' + shadowURL + '") bottom right no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[2] });
		
		// Create Bottom Left Div
		shadowDiv[3] = new Element('div');
		shadowDiv[3].setStyle({
			position: 'absolute',
			bottom: 0,
			left: 0,
			width: shadowWidth + 'px',
			height: shadowWidth + 'px',
			background: 'transparent url("' + shadowURL + '") bottom left no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[3] });
		
		// Create Center Top Div
		shadowDiv[4] = new Element('div');
		shadowDiv[4].setStyle({
			position: 'absolute',
			top: 0,
			left: shadowWidth + 'px',
			width: imageWidth + 'px',
			height: shadowWidth + 'px',
			background: 'transparent url("' + shadowURL + '") top center no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[4] });
		
		// Create Center Right Div
		shadowDiv[5] = new Element('div');
		shadowDiv[5].setStyle({
			position: 'absolute',
			top: shadowWidth + 'px',
			right: 0,
			width: shadowWidth + 'px',
			height: imageHeight + 'px',
			background: 'transparent url("' + shadowURL + '") center right no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[5] });
		
		// Create Center Bottom Div
		shadowDiv[6] = new Element('div');
		shadowDiv[6].setStyle({
			position: 'absolute',
			bottom: 0,
			right: shadowWidth + 'px',
			width: imageWidth + 'px',
			height: shadowWidth + 'px',
			background: 'transparent url("' + shadowURL + '") bottom center no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[6] });
		
		// Create Center Right Div
		shadowDiv[7] = new Element('div');
		shadowDiv[7].setStyle({
			position: 'absolute',
			top: shadowWidth + 'px',
			left: 0,
			width: shadowWidth + 'px',
			height: imageHeight + 'px',
			background: 'transparent url("' + shadowURL + '") center left no-repeat'
		});
		shadowContainer.insert({ bottom: shadowDiv[7] });
		
		imageObject.replace(shadowContainer);
		
		shadowContainer.insert({ bottom: imageClone });
		
	});
	
	return false;
}

//First and Last LI Selector
//Note: Prototype Driven
function liFirstLast() {
	var firstLIs =	$$('ul > li:first-child, ol > li:first-child');
	var lastLIs = $$('ul > li:last-child, ol > li:last-child');
	
	firstLIs.each(function(liFirst) {
		liFirst.addClassName('first');
		});
		
	lastLIs.each(function(liLast) {
		liLast.addClassName('last');
	});
}

//Navigation Hover Adjustements
function navHoverAdjust() {
	var navigationItems = $$('#navMain > li, ol.navCarousel > li');
	
	navigationItems.each(function(navigationItem){
		navigationItem.observe('mouseenter', function(event){
			this.addClassName('hover');
		});
		navigationItem.observe('mouseleave', function(event){
			this.removeClassName('hover');
		});
	});
}

//Flash Replacements
function flashReplacement() {
	//var breakoutArea
	
	var flashvars = {};
	var params = {};
	params.wmode = 'transparent';
	params.menu = "true";
	params.quality = "high";
	
	var attributes = {};
		
	swfobject.embedSWF("/flash/clients.swf", "clientList", "952", "75", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
	
	swfobject.embedSWF("/flash/main.swf", "homeAdvert", "952", "368", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
}

//Carousel Controls
//Rotates through OL.carousel and gives control and updates OL.carousel
function carousel() {

	var items = $$('ol.carousel li'); //Array of carousel list items
	var controls = $$('ol.navCarousel li'); //Array of carousel controls

	if(!items[0]) return false; //Let's check to be sure this exists

	var queue = Effect.Queues.get('carouselQueue'); //create the queue for the animation sequence.
	
	items.each(function(item, index) {
		if(item.empty()){
			item.remove();
		}
		if(index != 0){
			item.setStyle({
			  left: 954 + 'px'
			});
		}
		
		controls[index].observe('click', function(event){
			controls[index].fire('novar:carouselUpdate', { indexMove: -(index - currentItem) });
			carouselPE.stop();
			event.stop();
		});
		
	});
	
	var items = $$('ol.carousel li'); //we've removed empties, now redefine variable correctly.
	
	var currentItem = 0; //We need to make sure our current items starts with the 1st, ala the 0
	
	var previousItem = items.size(); //Previous item is the last one, grabbing the total amount tells us what # that is.
	
	var navLists = $$('ol.navCarousel');
	
	navLists.each(function(navList) {
		var navListWidth = navList.getWidth();
		
		//Gets the navCarousel lis and makes them grow to the width of the carousel bar so that if there are less items they each expand in width
		controls.each(function(control) {
			control.setStyle({
			  width: (navListWidth/previousItem)-3 + 'px'
			});
		});
		
	});
	
	controls[currentItem].addClassName('current'); //Add a current class to the active items specific control
	
	document.observe('novar:carouselUpdate', function(event){ 
		if(queue.effects.size() == 0) {
			
			controls[currentItem].removeClassName('current'); //Remove the class from the previous items control.
			var itemMove = event.memo.indexMove;
			
			previousItem = currentItem;
			currentItem = (items.size() + ((currentItem - itemMove) % items.size())) % items.size(); //incrementally step up the index
			
			if(previousItem == currentItem){ //Stops the user from choosing the already current item twice.
				controls[currentItem].addClassName('current');
				return false;
			}
			
			var effectDirection = 1;
			
			if (previousItem < currentItem) {
				effectDirection = -1;
			}
			
			new Effect.Parallel([
				new Effect.Tween(items[previousItem], 0, effectDirection*954, {sync: true}, function(value){
					this.setStyle({
						left: value + 'px'
					});
				}),
				new Effect.Tween(items[currentItem], -(effectDirection)*954, 0, {sync: true}, function(value){
					this.setStyle({
						left: value + 'px'
					});
				})], {
				queue: {
					position: 'end',
					scope: 'carouselQueue',
					limit: 1
				}
			});	

			controls[currentItem].addClassName('current');

		};
		
	});
	
	carouselPE = new PeriodicalExecuter(function(){
		controls[currentItem].fire('novar:carouselUpdate', { indexMove: -1 });
	}, 9);
	
}

//News Carousel Controls
//Rotates through OL.carouselNews and gives control and updates OL.carouselNews
function carouselNews() {

	var items = $$('ol.carouselNews li'); //Array of carousel list items
	var controls = $$('ol.navCarouselNews li'); //Array of carousel controls

	if(!items[0]) return false; //Let's check to be sure this exists
	
	//console.log(items);
	//console.log(controls);

	var queue = Effect.Queues.get('carouselNewsQueue'); //create the queue for the animation sequence.

	items.each(function(item, index) {
		//console.log(index);
		if(item.empty()){
			item.remove();
		}
		if(index != 0){
			item.setOpacity(0);
		}	
		
	});
		
	controls[0].observe('click', function(event){
		//console.log('clicked left');
		controls[0].fire('novar:carouselNewsUpdate', { indexMove: (1) });
		carouselNewsPE.stop();
		event.stop();
	});
	
	controls[1].observe('click', function(event){
		//console.log('clicked right');
		controls[1].fire('novar:carouselNewsUpdate', { indexMove: -(1) });
		carouselNewsPE.stop();
		event.stop();
	});
	
	var items = $$('ol.carouselNews li'); //we've removed empties, now redefine variable correctly.
	
	var currentItem = 0; //We need to make sure our current items starts with the 1st, ala the 0
	
	var previousItem = items.size(); //Previous item is the last one, grabbing the total amount tells us what # that is.
	
	
	document.observe('novar:carouselNewsUpdate', function(event){ 
		//console.log('queue size is ' + queue.effects.size());
		
		if(queue.effects.size() == 0) {
			
			var itemMove = event.memo.indexMove;
			
			previousItem = currentItem;
			currentItem = (items.size() + ((currentItem - itemMove) % items.size())) % items.size(); //incrementally step up the index
			
			//console.log('current item is ' + currentItem);
			//console.log('previous item is ' + previousItem);
			
			if(previousItem == currentItem){ //Stops the user from choosing the already current item twice
				return false;
			}
			
			new Effect.Parallel([
				new Effect.Tween(items[previousItem], 100, 0, {sync: true}, function(value){
					this.setOpacity(value * .01);
					this.setStyle({
						zIndex: 0 					
					});
				}),
				new Effect.Tween(items[currentItem], 0, 100, {sync: true}, function(value){
					this.setOpacity(value * .01);
					this.setStyle({
						zIndex: 100 					
					});
				})], {
				queue: {
					position: 'end',
					scope: 'carouselNewsQueue',
					limit: 1
				}
			});	

		};
		
	});
	
	carouselNewsPE = new PeriodicalExecuter(function(){
		/*console.log('carouselNewsPE');*/
		controls[1].fire('novar:carouselNewsUpdate', { indexMove: -(1) });
	}, 4);
	
}


//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'
            });
        });
    });
}


//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');
	});
}

//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; 
}

//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
    navHoverAdjust();
    flashReplacement();
    carousel();
	carouselNews();
    externalLinks();
	heightBalance($$('div.section'), 3);
});
