/** Simple JavaScript scroller for Special Deals section
* @author Matt Campbell
* @date 2009-07-28
* @version 1.0
* @revision $Id: $
*/
(function() {
	var j, imageWidth = 563,
		allImages = document.getElementsByTagName("IMG"),
		images = [],parent,timeoutID = -1,scrollID = -1, xSpeed = 0,
		more = document.getElementById("specials_more"),
		
		/* Ensure all images are beside eachother */
		resetPositions = function() {
			for (j = 0;j < images.length;j+=1) {
				images[j].style.left = (j*imageWidth)+"px";
			}
		},
		
		/* Initiate scrolling */
		scrollNext = function() {
			if (timeoutID !== -1) { // currently scrolling
				return;
			}
			clearTimeout(scrollID);
			xSpeed = 20;
			timeoutID = setTimeout(scroll,25);
		},
		
		/* Scroll the images */
		scroll = function() {
			var tmp, j;
			
			/* Clear previous timer */
			clearTimeout(timeoutID);
			
			/* Scroll each image a bit */
			for (j = 0;j < images.length;j+=1) {
				images[j].style.left = (parseInt(images[j].style.left,10)+xSpeed)+"px";
			}
			if (parseInt(images[1].style.left,10) <= 0) { // done scrolling
				images[1].style.left = "0px"; // avoid scrolling too far
				
				/* Swap the array so the current slide becomes first element */
				tmp = [images[1],images[2],images[0]];
				images = [tmp[0],tmp[1],tmp[2]];
				
				resetPositions();
				timeoutID = -1;
				scrollID = setTimeout(scrollNext,5000);
				return;
			}
			xSpeed = Math.max(-20,xSpeed-2); // cap the scroll speed
			
			/* .. do it all again .. */
			timeoutID = setTimeout(scroll,25);
		};
	
	/* Step 1: Find the correct images */
	for (j = 0;j < allImages.length;j+=1) {
		parent = allImages[j].parentNode.parentNode;
		if (parent !== null && parent.tagName.toUpperCase() === "LI") {
			images.push(allImages[j]);
		}
	}
	if (images.length < 2) { // not enough images to scroll!
		return;
	}
	
	/* Step 2: Ensure images are beside eachother */
	resetPositions();
	
	/* Step 3: Set up "More" link */
	if (more !== null) {
		more.onclick = function() {
			scrollNext();
			this.blur();
			return false;
		};
	}
	
	/* Step 4: Scroll! */
	scrollID = setTimeout(scrollNext,5000);
	
}());