/*
Written by Daniel Macias
Please Include Prototype 1.6 or above and Scriptaculous!

CSS is currently in /css/widgets/
*/
//------ Featured Block
document.observe("dom:loaded", init);

//Controls
var delay = 10000;
var isCycling = true;
var activeIndex = 4;

//Lists
var itemList;
var imageList;

//Animation
var timer;
var listTimer;
var bgStart = -154;
var currBgX = bgStart;
var t = 0;


function init(){
	createLists();	
	startCycling();
};

function createLists(){
	contentList = $$('.showcase_products .showcase_content .showcase').invoke('removeClassName','hidden').invoke('hide');	
	
	itemList = $$('.showcase_products .item_list a');
	
	itemList.each(function(listItem){
		listItem.observe('click', function(event){
			event.stop();
			activateItem(itemList.indexOf(listItem));
			stopCycling();
		})
		listItem.observe('mouseover', function(event){
		 	this.setStyle({background: 'url(http://daniel.realtown.com/images/main/showcase_list_selected.png) 0 0 no-repeat'});
			//listTimer = setInterval(function(){tweenBg(listItem, -154, 0, 4)}, 33);
		})
		listItem.observe('mouseout', function(event){			
			if (itemList[activeIndex] != this) this.setStyle({background: 'url(http://daniel.realtown.com/images/main/showcase_list_selected.png) -154px 0 no-repeat'});
		})
	})
};

function tweenBg(e, b, ty, sp){
	t += sp;
	if (Math.floor(Math.abs(ty - currBgX)) > 3){
		currBgX = 2*t + b;
		e.setStyle({backgroundPosition: currBgX + 'px 0'});			
	}else{
		e.setStyle({backgroundPosition: ty + 'px 0'});
		clearInterval(listTimer);
	}
}
function resetBg(e){
	t = 0;
	currBgX = bgStart;		
	e.setStyle({backgroundPosition: '0 ' + bgStart + 'px'});
	clearInterval(listTimer);
}

function startCycling(){
	isCycling = true;
	timer = setTimeout(startCycling, delay);
	(activeIndex == itemList.length - 1) ? activateItem(0) : activateItem(activeIndex + 1);
};

function stopCycling(){
	isCycling = false;
	clearTimeout(timer);
};

function toggleCycling(){
	(isCycling) ? stopCycling() : startCycling();
};

function activateItem(pointer){
	deactivateItem(activeIndex);
	activeIndex = pointer;
	listTimer = setInterval(function(){tweenBg(itemList[activeIndex], -154, 0, 4)}, 33);	
	contentList[activeIndex].show();
};

function deactivateItem(pointer){
	resetBg(itemList[activeIndex]);
	content = contentList[activeIndex].hide();
};