$(function() {

	var pics =[
		["images/rotator/1.jpg","http://www.peakfitnessnow.com/transformation.html"],
		["images/rotator/7.jpg","http://www.peakfitnessnow.com/transformation.html"],
		["images/rotator/3.jpg","http://www.peakfitnessnow.com/transformation.html"],
		["images/rotator/5.jpg","http://www.peakfitnessnow.com/transformation.html"],
		["images/rotator/4.jpg","http://www.peakfitnessnow.com/transformation.html"],
		["images/rotator/6.jpg","http://www.peakfitnessnow.com/transformation.html"],
		["images/rotator/2.jpg","http://www.peakfitnessnow.com/transformation.html"]
	];
	
	var count = pics.length;
	var cur = 1;
	
	// preload the images
	var $imgs = new Array();
	for(var i=0;i<count-1;i++) {
		$imgs.push($('<img>').attr('src', pics[i][0]));
	}
	
	// add the main ul
	$("#pics_holder").append("<ul>");
	// it must be as wide as all the children for it to span horizontally
	$("#pics_holder ul").css("width",(count)*990);
	
	// add each image as an li
	for(var i=0;i<count-1;i++) {
		var $li = $("<li>").append($imgs[i]);
		$("#pics_holder ul").append($li);
	}
	
	// put the last one in front to start
	var $last_li = $("<li><img src='"+pics[pics.length-1][0]+"'/><\/li>");
	$("#pics_holder ul").prepend($last_li);
	
	// right handle
	var $right = $("<div class='right_handle'>");
	$("#pics_holder").append($right);
	$(".right_handle").click(function() {
		
		// reset the left position when adding a new element
		var left = parseInt($("#pics_holder ul").css("left"));
		$("#pics_holder ul").css("left",left-990+"px");
		
		// add the last element to the front of the list
		$("#pics_holder ul").prepend($("#pics_holder li:last"));
		
		// move the ul to the right
		if(!$("#pics_holder ul").is(":animated")) {
			$("#pics_holder ul").animate({
				left : '+=990'
			},function() {
				(cur == 1) ? cur = count : cur--;
				$("#pics_holder .pic_link").attr("href",pics[cur-1][1]);
			});
		}	
	});
	
	var $left = $("<div class='left_handle'>");
	$("#pics_holder").append($left);
	$(".left_handle").click(function() {
		var left = parseInt($("#pics_holder ul").css("left"));
		
		// reset the left position when adding a new element
		$("#pics_holder ul").css("left",left+990+"px");
		
		// add the first element to the end
		$("#pics_holder ul").append($("#pics_holder li:first"));
		
		// animate the ul to the left
		if(!$("#pics_holder ul").is(":animated")) {
			$("#pics_holder ul").animate({
				left : '-=990'
			},function() {
				(cur == count) ? cur = 1 : cur++;
				$("#pics_holder .pic_link").attr("href",pics[cur-1][1]);
			});
		}	
	});
	
	var $link = $("<a class='pic_link' href='"+pics[0][1]+"'>&nbsp;<\/a>");
	$("#pics_holder").append($link);
	
});
