jQuery(function($) {
	$(".link-prev").click(function(e) {
		clearInterval(timer);
		loadPrevPicture();
		timer = setInterval("loadNextPicture()", 8000);
		return false;
	});

	$(".link-next").click(function(e)
	{
		clearInterval(timer);
		loadNextPicture();
		timer = setInterval("loadNextPicture()", 8000);
		return false;
	});
});

var timer;

// Initializes the images.
function logoChanger() {
	// Set the opacity of all images to 0
	$(".customer-logos li").css({ opacity: 0.0 });

	// Get the first image and display it (set the full opacity)
	$(".customer-logos li:first").css({ opacity: 1.0 });

	$(".customer-logos ul").fadeIn(500); // Tweek for IE

	timer = setInterval("loadNextPicture()", 8000);
}

var itemPath = ".customer-logos li";

// Gets the current image inside the item path.
function getCurrentPic() {
	var item = $(itemPath + ".show")
		? $(itemPath + ".show")
		: $(itemPath + ":first");

	if (item.length == 0)
		item = $(itemPath + ":first");

	return item;
}

// Gets the previous image, when it reaches the start, rotates it back to the last image.
function getPrevPic(current) {
	var currentPrev = current.prev();
	var prev = (currentPrev.length)
		? ((currentPrev.hasClass("show")) ? $(itemPath + ":last") : currentPrev)
		: $(itemPath + ":last");

	return prev;
}

// Gets the next image, when it reaches the end, rotates it back to the first image.
function getNextPic(current) {
	var currentNext = current.next();
	var next = (currentNext.length)
		? ((currentNext.hasClass("show")) ? $(itemPath + ":first") : currentNext)
		: $(itemPath + ":first");

	return next;
}

// Sets the fade in effect for the target image and hides the source image.
function fadeInPicture(sourcePicture, targetPicture) {
	if (targetPicture.hasClass("show"))
		return;

	// Set the fade in effect for the target image, the show class has higher z-index.
	targetPicture.css({ opacity: 0.0 })
		.addClass("show")
		.animate({ opacity: 1.0 }, 500);

	// Hide the source image.
	sourcePicture.animate({ opacity: 0.0 }, 500)
		.removeClass("show");
}

// Loads the previous image.
function loadPrevPicture() {
	// Get the current image.
	var current = getCurrentPic();

	// Get the previous image, when it reaches the start, rotate it back to the last image.
	var prev = getPrevPic(current);

	fadeInPicture(current, prev);
};

// Loads the next image.
function loadNextPicture() {
	// Get the current image.
	var current = getCurrentPic();

	// Get the next image, when it reaches the end, rotate it back to the first image.
	var next = getNextPic(current);

	fadeInPicture(current, next);
};

