var scrollCounter = 0;
var itemCount = 0;
var $carpic;
var $rbanimate;
var $speclist;
var $usedcarspecials;
var $linkitems;
var $nrbody;

$(document).ready(function(){	
	$carpic = $("#carpic");
	$rbanimate = $("#rbanimate");
	$speclist = $("#speclist");
	$usedcarspecials = $("#usedcarspecials");
	$linkitems = $("#offerlink, #carpic");
	$nrbody = $("#newsreel DIV.nrbody");
	
	$(".ribbon").css("opacity", 0.8);
	setupNewsreel();
	animateNewsItem();
	cycleNewsreelItem();
	
	setupUsedCarSpecialsData();
	animateCarItem();
	cycleCarData();
});
	
function setupNewsreel() {
	$("#newsreel .nrtitle span").height($("#newsreel .nrbody").height()-8);
	itemCount = $("#newsreellist LI").length;
	$("#newsreellist LI:eq(0)").clone().appendTo($("#newsreellist"));	
}
	
function animateNewsItem() {
	$nrbody.animate({ scrollLeft: "+=500px" }, { duration: 4000, complete: function() {
		scrollCounter++;
		if (scrollCounter == itemCount) {
			$nrbody.scrollLeft(0);
			scrollCounter = 0;
		}				
	}});
}

function cycleNewsreelItem() {
	setInterval('animateNewsItem();', 6000);
}
	
function animateCarItem() {
	var targetElem = $usedcarspecials.find("LI:eq(0)");
	var clone = targetElem.clone().css("opacity", 0).addClass("hide");
	
	clone.data("image", targetElem.data("image"));
	clone.data("imageribbon", targetElem.data("imageribbon"));
	clone.data("speclist", targetElem.data("speclist"));
	clone.data("id", targetElem.data("id"));
	$usedcarspecials.append(clone);
	
	$usedcarspecials.find("LI").stop().animate({ opacity: 0 }, { duration: 500, complete: function() {
		$(targetElem).fadeOut(400).remove();
		$usedcarspecials.find("LI:lt(2)").removeClass("hide").stop().animate({ opacity: 1 }, { duration: 500 });
	}});			
			
	var speclistHTML = "<li>" + clone.data("speclist").replace(/;/g, "</li>\n\t<li>") + "</li>";
	
	$linkitems.attr("href", clone.data("id"));
	//console.log(clone.data("id"));
	
	$carpic.fadeOut(500, function() { 
		$(this).css("backgroundImage", "url(" + clone.data("image") + ")");
		$(this).fadeIn(500);
	});
	$rbanimate.fadeOut(500, function() { 
		$(this).css("backgroundImage", "url(" + clone.data("imageribbon") + ")");
		$(this).fadeIn(500);
	});
	$speclist.fadeOut(500, function() { 
		$(this).html(speclistHTML);
		$(this).fadeIn(500);
	});
}

function cycleCarData() {
	setInterval('animateCarItem();', 6000);
}	