(function() {

mouseInsideCarousel = false;

function $(id) {
	return document.getElementById(id);	
}

function updateCarouselOpacities()
{
	var items = carousel.getElementForItems();
	for(var i = 0; i < items.length; i++)
	{
		var el = new YAHOO.util.Element(items[i]);
		if (!el.hasClass('yui-carousel-item-selected'))
			el.setStyle('opacity', 0.4);
	}
}

// Called whenever a different thumbnail in the carousel is selected
// Replaces the image and caption in the carousel viewer, using the appropriate animations
function updateCarouselDetails(selectedIndex) {

	var el = new YAHOO.util.Element(carousel.getElementForItem(selectedIndex));
	el.setStyle('opacity', 1);
	updateCarouselOpacities();

	var viewerImg = $('mainImg');
	var captionContainer = $('captionContainer');
	var detailsContainer = $('detailsContainer');
	
	//update main image
	var newImg = viewerImg.cloneNode(true);
	newImg.setAttribute('src', mediawallData[selectedIndex].large);
	// we're already providding caption text adjacent to the image, so alt text is not absolutely necesary. 
	// instead we provide an empty alt. Alternatively, the alt text coult contain a short description of the item it represents
	newImg.setAttribute('alt', "");
	newImg.setAttribute('id', 'replacementImg');
	viewerImg.parentNode.appendChild(newImg);
	newImg.style.left = "480px";
	
	YAHOO.util.Event.onContentReady('replacementImg', function() {
		
		var elId = 'mediaWallViewport';
		YAHOO.util.Event.purgeElement(elId);
		var el = new YAHOO.util.Element($(elId));
		
		if (mediawallData[selectedIndex].movie != undefined)
		{
			YAHOO.util.Event.addListener(elId, "click", function() {
				Shadowbox.open({
					content:    mediawallData[selectedIndex].movie,
					player:     "flv",
					title:      mediawallData[selectedIndex].caption,
					width:      512,
					height:     384+20
				});
			});
			el.addClass('clickable');
		}
		else if (mediawallData[selectedIndex].link != undefined)
		{
			YAHOO.util.Event.addListener(elId, "click", function() {
				window.location.href = mediawallData[selectedIndex].link.url;
			});
			el.addClass('clickable');
		}
		else
		{
			el.removeClass('clickable');
		}
		
		var imgSlideAnim = new YAHOO.util.Anim(newImg, {}, 0.3, YAHOO.util.Easing.easeOut);
		imgSlideAnim.attributes.left = {to : 0};
		imgSlideAnim.onComplete.subscribe(function(ev)
		{
			$('mediaWallViewport').removeChild($('mainImg'));
			$('replacementImg').id = "mainImg";
		});
		imgSlideAnim.animate();
	});
	
	//animate the caption text
	captionAnim.attributes.bottom = {by : 10-captionContainer.clientHeight};
	captionAnim.animate(); //down...
	captionAnim.onComplete.subscribe(function(ev) {	
		YAHOO.util.Selector.query('#captionContainer p', undefined, true).innerHTML = mediawallData[selectedIndex].subtitle;
		
		var nodeBuyNowInfo = YAHOO.util.Selector.query('#buyNowInfo', undefined, true);
		if (mediawallData[selectedIndex].sale == undefined)
		{
			nodeBuyNowInfo.style.display = 'none';
		}
		else
		{
			nodeBuyNowInfo.style.display = 'block';
			YAHOO.util.Selector.query('div', nodeBuyNowInfo, true).innerHTML = mediawallData[selectedIndex].sale.msg;
			var nodeLink = YAHOO.util.Selector.query('a', nodeBuyNowInfo, true);
			nodeLink.href = mediawallData[selectedIndex].sale.url;
		}
		
		captionAnim.attributes.bottom = {to : 0};
		captionAnim.animate(); // ...and up again
		captionAnim.onComplete.unsubscribe();
	});

	// Again, normally this content would be loaded from a remote source in a more intelligent way, using the proper markup (heasdings, lists, etc.) 
	var detailsString = "<h2>" + mediawallData[selectedIndex].caption +"</h2>";	
	detailsString += "<div>";
	detailsString += mediawallData[selectedIndex].content;
	if (mediawallData[selectedIndex].link != undefined)
	{
		detailsString += "<p><a href='"
			+ mediawallData[selectedIndex].link.url + "'>"
			+ mediawallData[selectedIndex].link.text
			+ "</a></p>";
	}
	detailsString += "</div>";
	detailsContainer.innerHTML = detailsString;
}

function Countdown(current, future, id_days, id_hours, id_minutes, id_seconds)
{
	this._current = new Date(current);
	this._future = new Date(future);
	this._nodeDays = $(id_days);
	this._nodeHours = $(id_hours);
	this._nodeMinutes = $(id_minutes);
	this._nodeSeconds = $(id_seconds);

	var thisobj=this;
	this._interval = setInterval(function(){thisobj.updateTime()}, 1000);
}
Countdown.prototype.updateTime = function()
{
	this._current.setSeconds(this._current.getSeconds()+1);
	
	var timediff = (this._future-this._current)/1000 //difference btw target date and current date, in seconds
	
	if (timediff<0){ //if time is up
		clearInterval(this._interval);
		return
	}
	
	var oneMinute=60; //minute unit in seconds
	var oneHour=60*60; //hour unit in seconds
	var oneDay=60*60*24; //day unit in seconds
	var dayfield=Math.floor(timediff/oneDay);
	var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour);
	var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute);
	var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute));

	this._nodeDays.innerHTML = dayfield;
	this._nodeHours.innerHTML = hourfield;
	this._nodeMinutes.innerHTML = minutefield;
	this._nodeSeconds.innerHTML = secondfield;
}

//initialize YUI components
YAHOO.util.Event.onDOMReady( function(ev) {
	if ($('cd_current') != undefined)
	{
		// start counter
		new Countdown($('cd_current').innerHTML, $('cd_future').innerHTML, 'cd_days', 'cd_hours', 'cd_minutes', 'cd_seconds');
	}

	var bannerRotator = new YAHOO.widget.Carousel("bannerRotator", { 
		 animation: { speed: .5, effect : YAHOO.util.Easing.easeBoth }
		//,usearia : true
		,carouselEl: "OL"
		,isCircular: true
		,numVisible: 1
		,autoPlayInterval: 10000
	});
	bannerRotator.render();
	bannerRotator.startAutoPlay();

	if (mediawallData != undefined)
	{
		var imgPreloads = [];
		for (var i = 0 ; i < mediawallData.length; i++) {
			imgPreloads[i] = new Image(100,25); 
			imgPreloads[i].src= mediawallData[i].large; 
		}
		
		var numVisible = 3;
		var numDuplicated = 0;
		
		// Copy tiles from the first page to the last page, the last page has some blank tiles
		if (mediawallData.length > numVisible)
		{
			numDuplicated = (numVisible - mediawallData.length % numVisible) % numVisible;
			var tiles = YAHOO.util.Selector.query('#mediaWallCarousel ol li');
			var parent = YAHOO.util.Selector.query('#mediaWallCarousel ol')[0];
			
			for (i=0; i<numDuplicated; i++)
			{
				mediawallData.push(mediawallData[i]);
				var newTile = tiles[i].cloneNode(true);
				parent.appendChild(newTile);
			}
		}
		
		carousel = new YAHOO.widget.Carousel("mediaWallCarousel", { 
			animation: { speed: .5, effect : YAHOO.util.Easing.easeBoth },
			usearia : true,
			carouselEl: "OL",
			isCircular: true,
			numVisible: numVisible
		});
		
		var nodeLink = YAHOO.util.Selector.query('#buyNowInfo a', undefined, true);
		YAHOO.util.Event.addListener(nodeLink, "click", function(e) {
			YAHOO.util.Event.stopEvent(e);
		});
		
		carousel.on("itemSelected", updateCarouselDetails);
		
		if (numDuplicated > 0)
		{
			carousel.on('beforeSelectedItemChange', function(e) {
				var prev = e.prevValue;
				var next = e.newValue;
				var lastItemIndex = carousel.get('numItems')-1;
				
				if (prev == lastItemIndex && next == 0)
				{
					carousel.set('selectedItem', numDuplicated);
					return false;
				}
				else if (prev == 0 && next == lastItemIndex)
				{
					carousel.set('selectedItem', lastItemIndex - numDuplicated);
					return false;
				}
			});
		}
		
		var autoPlayInterval = setInterval(function () {
			carousel.selectNextItem();
		}, 10000);
		
		YAHOO.util.Event.addListener("prevBtnContainer", "click", function() {
			clearInterval(autoPlayInterval);
			carousel.selectPreviousItem();
		});
		YAHOO.util.Event.addListener("nextBtnContainer", "click", function() {
			clearInterval(autoPlayInterval);
			carousel.selectNextItem();
		});
		YAHOO.util.Event.addListener("mediaWallCarousel", "click", function() {
			clearInterval(autoPlayInterval);
		});
		carousel.on("keydown", function() { clearInterval(autoPlayInterval); });
		
		captionAnim = new YAHOO.util.Anim('captionContainer', {}, 0.2, YAHOO.util.Easing.easOut);
		
		carousel.render();
		
		var el = new YAHOO.util.Element('mediaWallCarousel');
		var items = el.getElementsByTagName('li');
		
		YAHOO.util.Event.addListener(items, "mouseenter", function(e) {
			var el = new YAHOO.util.Element(this);
			el.setStyle('opacity', 1);
			mouseInsideCarousel = true;
		});
		
		YAHOO.util.Event.addListener(items, "mouseleave", function(e) {
			updateCarouselOpacities();
			mouseInsideCarousel = false;
		});
	}
});

})()
