$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */
	
	var totWidth=0;
	var positions = new Array();
	var current = 0;
	
	$('#slides .slide').each(function(i){
		/* Traverse through all the slides and store their accumulative widths in totWidth */
		positions[i]= totWidth;
		totWidth += $(this).outerWidth();
	});
	$('#slides').width(totWidth);

	$('#slides_next').click(function(e,keepScroll){
		current=current+5;
		if(current>=positions.length) current = 0;
		$('#slides').stop().animate({marginLeft:-positions[current]+'px'},450);
		e.preventDefault();
		if(!keepScroll) clearInterval(itvl);
	});
	
	$('#slides_previous').click(function(e,keepScroll){
		current=current-5;
		if(current<0) current = 0;
		$('#slides').stop().animate({marginLeft:-positions[current]+'px'},450);
		e.preventDefault();
		if(!keepScroll) clearInterval(itvl);
	});
	
	$('#menu ul li a').click(function(e,keepScroll){

			/* On a thumbnail click */

			$('li.menuItem').removeClass('act').addClass('inact');
			$(this).parent().addClass('act');
			
			var pos = $(this).parent().prevAll('.menuItem').length;
			
			$('#slides').stop().animate({marginLeft:-positions[pos]+'px'},450);
			/* Start the sliding animation */
			
			e.preventDefault();
			/* Prevent the default action of the link */
			
			
			// Stopping the auto-advance if an icon has been clicked:
			if(!keepScroll) clearInterval(itvl);
	});
	
	$('#menu ul li.menuItem:first').addClass('act').siblings().addClass('inact');
	/* On page load, mark the first thumbnail as active */
	
	function autoAdvance() {
		$('#slides_next').trigger('click',[true]);
	}

	
	var changeEvery = 10;
	var itvl = setInterval(function(){autoAdvance()},changeEvery*1000);

	
	//function tick() {
	var ts = new Date().getTime();
	
	$.whileAsync({
		delay: 5000,
		bulk: 0,
		test: function() { return true },
		loop: function() {
			$.get('ajax/home_discounts?ts='+ts, function(data) {
				if(data!="") {
					//there's something new!
					$('div#home_discounts').prepend(data);
					$('div#home_discounts div.discount:first').animate({ height: "show", opacity: "show", queue: true },500);
					$('div#home_discounts div.discount:last').fadeOut('fast', function() {$(this).remove();});
					ts = new Date().getTime();
				}
				//$('.result').html(data);
			});
		}
	});
		
	//}
	
	//var interval = setInterval(function(){tick()}, changeEvery*500);
	
});
