//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');
	});
}


//Highlight Carousel
//Prototype driven JS to cycle through highlighted list items
//And creates a carousel navigation to manually select each items
//Prototype and Scriptaculous Driven
function highlightCarousel() {
	var highlights = $$('ul#productHighlights li');  //declare variables for the items we'll fade in and out.
	var carouselContainer = $('breakout');
	var speed = 1;

	if(!highlights[0]) return false; //lets be sure they exist, before we break anything
	
	
	var queue = Effect.Queues.get('highlightQueue'); // a queu's necessary for the overall animation.
	
	highlights.each(function(highlight, index) {
		if(highlight.empty()){
			highlight.remove();
		}
	});
	
	var highlights = $$('ul#productHighlights li');  //we've removed empties, now lets redefine the variable
	
	
	
	highlights.each(function(highlight){ //swap out the image inside the list items for their specific background
		highlight.setStyle ({
			backgroundImage: 'url(' + highlight.down('img').src + ')',
			opacity: '0'
		});
			
		highlight.down('img').remove();
	});
	
	highlights.each(function(highlight, index){
		highlights[0].setStyle({
			opacity: '1'
		})
	});	
	
	highlights.each(function(highlight, index){
	
	});		
	
	var breakoutContainer = highlights[0].up('div');
	var currentHighlight = 0;
	var previousHighlight = highlights.size();
	
	//create the navigation which takes the number of items and lists them as such.
	
	highlightNavigation = new Element('ul');
	highlightNavigation.addClassName('navModule');
	
	previousListingButton = new Element('li');
	previousListingButton.addClassName('previous');
	previousListingAnchor = new Element('a', { href: "#"}).update("Previous");
	previousListingButton.insert({ bottom: previousListingAnchor });
	highlightNavigation.insert({ top: previousListingButton });
	
	nextListingButton = new Element('li');
	nextListingButton.addClassName('next');
	nextListingAnchor = new Element('a', { href: "#"}).update("Next");
	nextListingButton.insert({ bottom: nextListingAnchor });
	highlightNavigation.insert({ bottom: nextListingButton });
	
	statusButton = new Element('li');
	statusButton.addClassName('pause');
	statusAnchor = new Element('a', { href: "#"}).update("Pause");
	
	statusButton.insert({bottom: statusAnchor});
	highlightNavigation.insert({bottom: statusButton});
	
	

	carouselContainer.insert({ top: highlightNavigation });
	
	var carouselControls = $$('ul.navModule li');	
	
	document.observe('customfresheners:carouselUpdate', function(event){
		if(queue.effects.size() == 0) {
			var highlightMove = event.memo.indexMove;
			
			previousHighlight = currentHighlight;
			currentHighlight = (highlights.size() + ((currentHighlight - highlightMove) % highlights.size())) % highlights.size();

			if(previousHighlight == currentHighlight){
				return false;
			}
			
			 new Effect.Parallel([
	         	new Effect.Fade(highlights[previousHighlight],{duration: 1 }),
	        	new Effect.Appear(highlights[currentHighlight],{duration: 1 })
	       		 ], {
	       		 	queue: {
						position: 'end',
						scope: 'highlightQueue',
						limit: 1
					}
	       		}
	         );		
		}
	});
	
	carousel = new PeriodicalExecuter(function(){
		highlights[0].fire('customfresheners:carouselUpdate', { indexMove: -1 });
	}, speed);
	
	previousListingAnchor.observe('click', function(event){
		previousListingAnchor.fire('customfresheners:carouselUpdate', { indexMove: 1 });
		carousel.stop();
	});
	
	nextListingAnchor.observe('click', function(event){
		nextListingAnchor.fire('customfresheners:carouselUpdate', { indexMove: -1 });
		carousel.stop();
	});	
	
	
	statusButton.observe('click', function(event){
		/*carousel.stop();
		statusButton.addClassName('play');
		statusButton.removeClassName('pause');
		event.stop();
	*/	
		if(statusButton.hasClassName('play')){
				carousel = new PeriodicalExecuter(function(){
					statusButton.fire('customfresheners:carouselUpdate', { indexMove: -1 });
				}, speed);
				
				statusButton.removeClassName('play');
				statusButton.addClassName('pause');
			} 
			else if(statusButton.hasClassName('pause')){
				carousel.stop();
				statusButton.addClassName('play');
				statusButton.removeClassName('pause');
				
			}	
			
			event.stop();

		
		
	
	});
}



//Navigation Hovers
//Note: Prototype Driven
function navHover() {
	var navigationListItems = $$('#navigation ul li');
	
	navigationListItems.each(function(navigationListItem){
		navigationListItem.observe('mouseenter', function(event){
			navigationListItem.addClassName('hover');
		});
		navigationListItem.observe('mouseleave', function(event){
			navigationListItem.removeClassName('hover');
		});
	});
}


//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,days) { 
	if (days) { 
		var date = new Date(); 
		date.setTime(date.getTime()+(days*24*60*60*1000)); 
		var expires = ";expires="+date.toGMTString(); 
	} else { 
		expires = ""; 
	} 
	document.cookie = name+"="+value+expires+";"; 
}

// 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; 
}

function preloadCssImages() {
  var allImgs = [];

  $A(document.styleSheets).each(function(sheet) {
    var cssPile = '',
     csshref    = sheet.href || window.location.href,
     baseURLarr = csshref.split('/');

    baseURLarr.pop();//remove file path from baseURL array
    var baseURL = baseURLarr.join('/'); //create base url for the images in this sheet (css file's dir)
    if (baseURL) baseURL += '/'; //tack on a / if needed

    if (sheet.cssRules) {
      $A(sheet.cssRules).each(function(rule) {
        cssPile += rule.cssText;
      });
    } else cssPile += sheet.cssText;

    //parse cssPile for image urls and load them into the DOM
    cssPile.gsub(/[^\(]+\.(?:gif|jpg|jpeg|png)/, function(match) { //reg ex to get a string of between a "(" and a ".filename"
       var url = match[0];
       allImgs.push(new Image());
       allImgs.last().src = (url[0] == '/' || url.match('http://')) ? 
         url : baseURL + url;  //set src either absolute or rel to css dir
    });
  });

  return allImgs;
};

//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function() {
	//preloadCssImages();
	//dynamicShadow('/images/global/shadow.png', 'page-container', 16, 0);
	liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	navHover(); //Adds and removes 'hover' class to respective LIs	
	Cufon.replace('h1');
	Cufon.replace('h2');
	Cufon.replace('#main table.productList tr th p');
	Cufon.replace('#main h3');
	Cufon.replace('#header h3');
	Cufon.replace('#footer p.madeinUSA');
	Cufon.replace('#main p.more a');
	Cufon.replace('#footer h3', {
		textShadow: '#000 1px 1px'
	});
	Cufon.replace('#footer h2', {
		textShadow: '#000 1px 1px'
	});
	Cufon.now();
	highlightCarousel();//activates animation and controls on homepage carousel.
});
