//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');
	});
}

//First DT Seletor
//Assigns a .first class to the first DT on a page.
function dtFirst() {
	var firstDTs = $$('dl > dt:first-child');
	
	firstDTs.each(function(firstDT) {
		firstDT.addClassName('first');
	});
	
}

//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; 
}

//Home Page Contributors Carousel Control

function contributorCarousel() {
	var carouselContainer = $('contributorCarousel');
	var items = $$('#contributorCarousel ul li');
	
	if(!carouselContainer) return false;
	
	var queue = Effect.Queues.get('highlightQueue');
	
	items.each(function(item, index) {
		if(item.empty()){
			item.remove();
		}
	});
	
	var items = $$('#contributorCarousel ul li');
	
	//Randomize from the start.
	var currentItem = Math.floor(Math.random()*(items.size()));
	
	items[currentItem].setStyle({
		left: 'auto'
	});
	
	var previousItem = items.size();
	var highlightIndex = items.size();
	
	//Create controls
	var carouselNavigation = new Element('ol');
	carouselNavigation.addClassName('navHighlights');
	
	previousItemButton = new Element('li');
	previousItemButton.addClassName('previous');
	previousItemAnchor = new Element('a', { href: "#"}).update("Previous");
	previousItemButton.setOpacity(0.65);
	
	
	previousItemButton.insert({ bottom: previousItemAnchor });
	carouselNavigation.insert({ top: previousItemButton });
	
	nextItemButton = new Element('li');
	nextItemButton.addClassName('next');
	nextItemAnchor = new Element('a', { href: "#"}).update("Next");
	nextItemButton.setOpacity(0.65);

	nextItemButton.insert({ bottom: nextItemAnchor });
	carouselNavigation.insert({ bottom: nextItemButton });

	carouselContainer.insert({ bottom: carouselNavigation });
	
	document.observe('ccp:contributorCarousel', function(event){
		
		if (queue.effects.size() == 0) {
			
			var itemMove = event.memo.indexMove;
			
			previousItem = currentItem;
			currentItem = (items.size() + ((currentItem - itemMove) % items.size())) % items.size();

			items[currentItem].setStyle({
				left: -(itemMove*items[previousItem].getWidth()) + 'px'
			});
			
			new Effect.Parallel([new Effect.Move(items[previousItem], {
				sync: true,
				x: itemMove*items[previousItem].getWidth(),
				y: 0,
				mode: 'absolute'
			}), new Effect.Move(items[currentItem], {
				sync: true,
				x: 0,
				y: 0,
				mode: 'absolute'
			})], {
				queue: {
					position: 'end',
					scope: 'highlightQueue',
					limit: 1
				}
			});
			
		}
		
	});
	
	carousel = new PeriodicalExecuter(function(){
		carouselContainer.fire('ccp:contributorCarousel', { indexMove: -1 });
	}, 10);
	
	previousItemAnchor.observe('click', function(event){
		previousItemAnchor.fire('ccp:contributorCarousel', { indexMove: 1 });
		carousel.stop();
		event.stop();
	});
	
	nextItemAnchor.observe('click', function(event){
		nextItemAnchor.fire('ccp:contributorCarousel', { indexMove: -1 });
		carousel.stop();
		event.stop();
	});
	
	nextItemAnchor.observe('mouseenter', function(event){
		nextItemAnchor.up('li').setOpacity(1);
	});
	
	previousItemAnchor.observe('mouseenter', function(event){
		previousItemAnchor.up('li').setOpacity(1);
	});
	
	nextItemAnchor.observe('mouseleave', function(event){
		nextItemAnchor.up('li').setOpacity(.65);
	});
	
	previousItemAnchor.observe('mouseleave', function(event){
		previousItemAnchor.up('li').setOpacity(.65);
	});
}


//Twitter Feed Handler
//JSON Ajax Reader
function jsonFeed(){
	var twitterContainer = $('twitterFeed');
	var speed = 30;
	var currentTweet = 0;
	if(!twitterContainer) return false;
	//Below is what needs to be created on the back in as a proxy/cache for the actual feed so we 
	//don't hit the limits twitter has imposed on json feeds. (150 requests a minute)
	var url = '/twitter/fetchProxyTwitter.aspx?req=http://api.twitter.com/1/statuses/user_timeline.json?user=creativeplay';
	//var url = '/wp-content/themes/CPP2.0/scripts/user_timeline.js';
	
	//new Ajax.PeriodicalUpdater(twitterContainer, url, {frequency: 2, decay: 2})
	
	//The initial loading of the latest twitter post
	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) {
			var json = transport.responseText.evalJSON();
			
			json.each(function(tweet, index){
				if(index > 4){
					tweet.remove();
				} 
					
				//currentTweet = tweet.text;
				
				var username = tweet.user.screen_name
				var created = tweet.created_at.truncate(20, '.');

				var tweetID = tweet.id
				var tweetURL = "http://www.twitter.com/" + username + "/status/" + tweetID + ""
				
				var tweetAnchor = new Element('a', { href: tweetURL}).update("Latest Tweet");
				
				var profileURL = "http://www.twitter.com/" + username + "/"
				
				//Regex magic that goes through each tweet looking for properly made URLs and turns them into links.
				function urlify(text) {
					var urlRegex = /(https?:\/\/[^\s]+)/g;
					return text.replace(urlRegex, function(url) {
						return '<a href="' + url + '" title="Visit ' + url + '" target="_blank">' + url + '</a>';
					});
				}
				
				var tweetURLified = urlify(tweet.text); //Tell the urlifier to process the tweet's text
				
				var tweetTemplate = new Template('<li>&quot;'+ tweetURLified + '&quot;</li>');
								
				twitterContainer.insert({
					bottom: tweetTemplate.evaluate(tweet)
				});	

			});
			
	  },
	  onFailure: function(){
		//If the feed fails, this is what they should see.
		var failureMessage = '<p>It appears our twitter stream is temporarily unavailable.</p><p><a href="https://twitter.com/signup?follow=creativeplay&commit=Join+Today" target="_blank">Please click here to visit our feed at Twitter</a>, or try again later.</p>'
		twitterContainer.insert({
			bottom: failureMessage
		});
	  }
	  
	  
	});
}



//Facebook Status Feed Handler
//JSON Ajax Reader
function jsonFBFeed(){
	var facebookContainer = $('facebookFeed');
	if(!facebookContainer) return false;
	//Below is what needs to be created on the back in as a proxy/cache for the actual feed so we 
	//don't hit the limits twitter has imposed on json feeds. (150 requests a minute)
	//var url = 'http://api.twitter.com/1/statuses/user_timeline.json?user=creativeplay';
	//var url = '/proxy.php';
	var url = '/fetchProxy.aspx';

	//The initial loading of the latest facebook post
	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) {
			var json = transport.responseText.evalJSON(true);
			
			json.each(function(status, index){
				if(index > 3){
					status.remove();
				} 
				var statusTemplate = new Template('<li><a href="http://www.facebook.com/creativeplay" target="_blank">&quot;'+ status.message + '&quot;</a></li>');
								
				facebookContainer.insert({
					bottom: statusTemplate.evaluate(status)
				});	
			});
			
	  },
	  onComplete: function(){	
		var footerItems = $$('#footer > ul > li');	
		heightBalance(footerItems, 3);
	  },  
	  onFailure: function(){
		//If the feed fails, this is what they should see.
		var failureMessage = '<li><p>Error retreiving feed.</p></li>'
		facebookContainer.insert({
			bottom: failureMessage
		});
	  }
	  
	  
	});
}


//Backpage Height Fix.
function heightFix(){
	var article = $('article');
	var related = $('related');
	var aside = $('aside');
	var pageBody = document.body;
	
	var articleHeight = article.getHeight();
	var relatedHeight = related.getHeight();
	
	if(aside){
		var asideHeight = aside.getHeight();
		if(asideHeight >= articleHeight){
			article.setStyle({height: '' + asideHeight + 'px'});
		}
	} else {
		if(relatedHeight >= articleHeight){
			article.setStyle({height: '' + relatedHeight + 'px'});
		}
	}	
		
}




//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'
			});
		});
	});
}

//Related Category Assist
function categoryAssist() {
	var pageBody = document.body
	
	if(!pageBody.hasClassName('home')) return false;
	
	var categoryLists = $$('#related > ul');
	
	categoryLists.each(function(categoryList){
		var balanceElements = categoryList.childElements();	
		heightBalance(balanceElements, 4);
	});
	
	categoryLists = $$('#related > ul');
	
	categoryLists.each(function(categoryList){
		var balanceElements = categoryList.childElements();	
		heightBalance(balanceElements, 4);
	});
}

function footerAssist() {
	var footerItems = $$('#footer > ul > li');
	
	heightBalance(footerItems, 3);
}

//Breakout Image Helper
//Grabs the image admin adds into WP and makes it the BG of the breakout div.
function breakout() {
	var breakout = $('breakout');
	
	if(!breakout) return false;
	
	var backgroundImage = breakout.down('img').readAttribute('src');
	
	breakout.setStyle({
		background: 'url(' + backgroundImage + ') no-repeat'
	});
		
	breakout.down('img').remove();	
}




//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
	dtFirst();
	contributorCarousel();
	jsonFeed();
	jsonFBFeed();
	inputClear();
	heightFix();
	breakout();
	categoryAssist();
	externalLinks();
	//footerAssist();
});
