//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;
}



//Facebook Status Feed Handler
//JSON Ajax Reader
function jsonFBFeed(){
	var facebookContainer = $('facebook');
	//console.log(facebookContainer);
	if(!facebookContainer) return false;
	
	var json = facebookContainer.down('div').innerHTML.evalJSON(true);
	facebookContainer.down('div').remove();	

	json.each(function(status, index){
			var statusTemplate = new Template('<dt><a href="http://www.facebook.com/HDental" target="_blank">&quot;'+ status.message + '&quot;</a></dt>');
							
			facebookContainer.down('dl').insert({
				bottom: statusTemplate.evaluate(status)
			});	
	});
	
	//Grab first DT from Facebook feed.
	var firstDTs = $$('dt:first-child');
	
	firstDTs.each(function(firstDT) {
		firstDT.addClassName('first');
	});

	
	/*
	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)
				});	
			});
			
		  },  
		  onFailure: function(){
			console.log('failed');
			//If the feed fails, this is what they should see.
			var failureMessage = '<li><p>Error retreiving feed.</p></li>'
			facebookContainer.insert({
				bottom: failureMessage
			});
		}
	  
	});*/
}



//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');
	});
	
}

//Handle the Various Colors of the navMain
function navMainBGHandler() {
	var secondItems = $$('ul#navMain > li:nth-child(2)');
	var thirdItems = $$('ul#navMain > li:nth-child(3)');
	
	secondItems.each(function(liSecond) {
		liSecond.addClassName('second');
		});
		
	thirdItems.each(function(liThird) {
		liThird.addClassName('third');
	});
	
	var navItems = $$('ul#navMain > li a');
	
	navItems.each(function(navItem, index){
		
		navItem.observe('mouseenter', function(event) {	
			new Effect.Tween(navItems[index], 0, -48, {duration: .2}, function(value){
					this.setStyle({
						backgroundPosition: '0px ' + value + 'px'
					});
			});
				
		});
		navItem.observe('mouseleave', function(event) {
			new Effect.Tween(navItems[index], -48, 0, {duration: .2}, function(value){
					this.setStyle({
						backgroundPosition: '0px ' + value + 'px'
					});
			});
		});
	});
	
	
}

//Home Breakout Carousel
function breakoutCarousel(){
	var carouselContainer = $('breakout');
	var items = $$('#highlights > li');
	
	if(!carouselContainer) return false;
	
	var queue = Effect.Queues.get('highlightQueue');
	
	items.each(function(item, index) {
		if(item.empty()){
			item.remove();
		}
	});
	
	items.each(function(item, index){
		item.setStyle({
			backgroundImage: 'url(' + item.down('img').src + ')',
			backgroundRepeat: 'no-repeat'
		});
		
		item.down('img').remove();
	});
	
	var items = $$('#highlights > li');
	
	var navItems = [];
	
	var currentItem = 0
	var previousItem = items.size();
	var highlightIndex = items.size();
	
	//Create controls
	var carouselNavigation = new Element('ol');
	carouselNavigation.addClassName('navHighlights');
	carouselContainer.insert({ bottom: carouselNavigation });
	
	var borderLeft = new Element('span').writeAttribute('class','borderLeft');
	var borderRight = new Element('span').writeAttribute('class','borderRight');
	
	carouselContainer.insert({top: borderLeft});
	carouselContainer.insert({top: borderRight});
	
	items.each(function(item, index){
		navItems[index] = new Element('li').update('<strong>' + (index + 1) + '</strong>');
		
		if(index == 0){
			navItems[index].addClassName('currentPanel');
		}
		
		navItems[index].observe('click', function(event){			
			if(queue.effects.size() == 0) {	
				var panelMove = currentItem - index;
				navItems[index].addClassName('currentPanel');
				navItems[index].fire('hudec:carousel', { indexMove: panelMove });
				carousel.stop();
			}
		});
		
		carouselNavigation.insert({bottom: navItems[index]});
			
	});
	
	
	
	document.observe('hudec:carousel', 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'
			});
			
			navItems[previousItem].removeClassName('currentPanel');
			navItems[currentItem].addClassName('currentPanel');
			
			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('hudec:carousel', { indexMove: -1 });
	}, 10);	
	
	//Lightbox Fix
	var lightboxLinks = $$('a.lightview');
	
	lightboxLinks.each(function(lightboxLink){
		lightboxLink.observe('click', function(event){
			carousel.stop();
		});
	});
}


//Handles the bouncing ball mechanism for the special offer listed on the homepage.
function specialOffer() {
	var specialOffer = $('specialOffer');

	if(!specialOffer) return false;
		
	var bounce = new Effect.Morph(specialOffer, {
			style: 'height: 136px',
			duration: 1.75,
			transition: Effect.Transitions.spring,
			delay: 2
	});
}

function testimonialReveal(){
	var testimonial = $('testimonial');
	
	if(!testimonial) return false;
	//Wrapped, for blind effect:
	var quoteWrapper = testimonial.down('div');
	var testimonialButton = testimonial.down('h3');
	var testimonialImage = testimonial.down('img');
	var testimonialBlockquote = testimonial.down('blockquote');
	var testimonialCite = testimonial.down('cite');
		
	//var randomNumber = Math.floor(Math.random()*(testimonialImages.length))  //Randomization math based on the amount of h1s
	
	quoteWrapper.setStyle({
		display: 'none'
	});
	
	testimonialButton.on('click', function(event){
	
		if(!quoteWrapper.hasClassName('open')){
			if(testimonialImage){
				testimonialImage.setStyle({
					height: '240px'
				});
			}	
			
			new Effect.BlindDown(quoteWrapper, { 
				duration: .5,
				afterFinish: function(){
					quoteWrapper.addClassName('open');
				}
			});
		} else {
			new Effect.BlindUp(quoteWrapper, { 
				duration: .5,
				afterFinish: function(){
					quoteWrapper.removeClassName('open');
				}
			});
		}	
	});
}


//Handles SWF Object for homepage flash insertion
function flashMap() {	
	if(!$('flashMap')) return false;

	var flashvars = {};
	var params = {};
	params.wmode = "transparent";
	var attributes = {};
	attributes.id = "flashMap";

	swfobject.embedSWF('/flash/HudecDentalSite.swf', 'flashMap', "396", "480", "10.0.0", false, flashvars, params, attributes);
}


//Footer Padding Corrector
//Adjust the footer padding for the browser size
function positionElements() {
	var docFooter = $('footer');
	
	var viewportDimensions = document.viewport.getDimensions();
	
	docFooter.setStyle({
		padding: '0 ' + (viewportDimensions.width - 960)/2 + 'px',
		width: viewportDimensions.width - (viewportDimensions.width - 960) + '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; 
}

//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');
	});
}

//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
	navMainBGHandler();
	breakoutCarousel();
	positionElements();
	Event.observe(document.onresize ? document : window, "resize", function() {
		positionElements();
	});
	flashMap();
	specialOffer();
	testimonialReveal();
	externalLinks();
	jsonFBFeed();
});
