function ImageSwitcher(id, imagesURL) {
	var objId = id;
	var images = [];
	var index = -1;

	// This function requires jquery objects for obj and image
	var swap = function (obj, image, filename) {
		var overlay = image.clone();

		overlay.attr({
			src: filename
		});
		var pos = image.position();
		overlay.css({
			opacity: 0,
			position: 'absolute',
			left: pos.left + 'px',
			top: pos.top + 'px'
		});

		obj.append(overlay);

		(overlay.animate(
			{ opacity: 1.0 },
			1000,
			function () {
				image.attr({
					src: filename
				});
				overlay.remove();
			}
		));
	};

	var swapImage = function () {
		var filename = images[index];
		var obj = $('#' + objId);
		var image = $('img', obj);

		var pre = new Image();
		pre.onload = function () {
			swap(obj, image, filename);
		};
		pre.src = filename;
	};

	this.next = function () {
		if (images.length > 0) {
			index = (index + 1) % images.length;
			swapImage();
		}
	};

	this.prev = function () {
		if (images.length > 0) {
			index = index - 1;
			if (index < 0) {
				index = images.length - 1;
			}
			swapImage();
		}
	};

	var findCurr = function () {
		var obj = $('#' + objId);
		var img = $('img', obj);
		if (img.length > 0) {
			var c = img.attr('src').split('/').pop();
			var i;
			for (i = 0; i < images.length; i = i + 1) {
				var n = images[i].split('/').pop();
				if (c === n) {
					index = i;
				}
			}
		}
	};

	($.ajax({
		url: imagesURL,
		dataType: "json",
		success: function (data) {
			images = data.images;
			findCurr();
		}
	}));
}

function Slideshow(id, autostart, imagesURL) {
	var timer = null;
	var switcher = new ImageSwitcher(id, imagesURL);
	var duration = 8000;

	var startTimer = function () {
		timer = setInterval(function () {
			switcher.next();
		}, duration);

	};

	var stopTimer = function () {
		clearInterval(timer);
		timer = null;
	};

	if (autostart) {
		startTimer();
	}

	this.start = function () {
		if (timer === null) {
			switcher.next();
			startTimer();
		}
	};

	this.stop = function () {
		if (timer !== null) {
			stopTimer();
		}
	};

	this.toggle = function () {
		if (timer === null) {
			this.start();
		} else {
			this.stop();
		}
	};

	this.next = function () {
		switcher.next();
		if (timer !== null) {
			stopTimer();
			startTimer();
		}
	};

	this.prev = function () {
		switcher.prev();
		if (timer !== null) {
			stopTimer();
			startTimer();
		}
	};
}


var slideshow;
$(document).ready(function () {
	var imagesURL = "/content/us/splash/slides.json";
	if ($('#slide').attr('lang') === 'zh-Hans-CN') {
		imagesURL = "/content/cn/splash/slides.json";
	}
	slideshow = new Slideshow('slide', 1, imagesURL);
});

