//Dropdown Menus
function dropdownMenus() {
	var dropdowns = $$('ul.dropdown');

	dropdowns.each(function (dropdown) {
		var container = new Element('div');
		container.addClassName('dropdown');

		dropdown.insert({
			before: container
		});

		container.insert({
			top: dropdown
		});
	});
}

//Iframe Replacement
function iframeReplacement() {
	var iframeLinks = $$('a.iframe');

	iframeLinks.each(function (iframeLink) {
		var iframe = new Element('iframe');
		iframe.writeAttribute('src', iframeLink.readAttribute('href'));
		iframe.writeAttribute('frameborder', 'no');
		iframe.writeAttribute('scrolling', 'auto');

		iframeLink.replace(iframe);
	});
}

// Simple Carousel class w/ CSS Transitions
// Christian Wesselhoeft <christian@cwesselhoeft.com>
// Arguments:
// containing element, rotation delay in seconds (optional)
var Carousel = Class.create({
	initialize: function(container, rotation) {
		if (!container) {
			return;
		}

		var that = this,
			rotateIndex = 0;

		this.slides = container.select('.carousel li');

        // Check if browser supports CSS Transitions
        this.hasTransitions = 'transition' in container.style ||
	            'webkitTransition' in container.style ||
	            'MozTransition' in container.style ||
	            'OTransition' in container.style;   

        // Set up rotation
        if (rotation) {
        	var rotate = function() {
	        		var index = ++rotateIndex % that.slides.length;
	        		container.down('menu ol').childElements()[index].fire('carousel:change');
	        	},

	        	interval = setInterval(rotate, rotation * 1000);

	        container.on('mouseover', function() {
	        	clearInterval(interval);
	        });

	        container.on('mouseout', function() {
	        	interval = setInterval(rotate, rotation * 1000);
	        });
        }	


        // Event handler for changing slides
        var change = function(event, el) {
        	// Index of clicked button
        	// Set rotateIndex so rotation resumes correctly
        	var index = rotateIndex = el.previousSiblings().length;

        	for (var i = that.slides.length; i--;) {
        		if (i === index) {
        			that.fade('in', i);
        		} else {
        			that.fade('out', i);
        		}
        	}
        };

        container.on('click', 'menu li', change);
        container.on('carousel:change', 'menu li', change);
	},

	fade: function(dir, index) {
		var el = this.slides[index];

		if (this.hasTransitions) {
				
			if (dir === 'in') {
				el.addClassName('visible');
			} else {
				el.removeClassName('visible');
			}

		} else {

			// Firefox doesn't apply 'opacity: 1' inline
			dir = dir === 'in' ? 0.999 : -1;

			var opacity;
				
			var interval = setInterval(function() {

				opacity = (opacity || el.getStyle('opacity')) + (dir / 10);
				el.setStyle({ opacity: opacity });

				if (opacity >= 1 || opacity <= 0) {
					clearInterval(interval);
				}
			}, 10);
		}
	}
});


//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');
	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');
	});
}

//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;
}

// 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));
	}
};


//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function () {

	new Carousel($('breakout'), 10);
	dropdownMenus();
	iframeReplacement();
	//dynamicShadow('/images/global/shadow.png', 'page-container', 16, 0);
	//liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
});
