var Azexis = Azexis || {};

Azexis.SlideViewer = function(container, links, options) {
	container = $(container);
	options = $merge({
		scrollWidth: 200,
		matchHeight: true,
		linkBase: ''
	}, options);
	
	var animating = false;
	
	var xhr = new XHR({
		onSuccess: function(response) {
			// Append response text to div.
			container.innerHTML += response;
			// Reset progress cursor.
			$(document.body).setStyle("cursor", "default");
			
			// Scroll both items.
			var scrollables = container.getElementsByTagName("div");
			var left = scrollables[0];
			var right = scrollables[1];
			
			var completes = 0;
			function onComplete() {
				completes++;
				if (completes === 2) {
					left.remove();
					right.setStyle("left", 0);
					animating = false;
				}
			}
			
			var fx = new Fx.Style(left, "left", {
				onComplete: onComplete
			});
			fx.start(-options.scrollWidth);
			var fx2 = new Fx.Style(right, "left", {
				onComplete: onComplete
			});
			fx2.start(-options.scrollWidth);
			
			// Adjust the height to match the incomming date lists.
			if (options.matchHeight) {
				var heightFx = new Fx.Style(container, "height");
				heightFx.start(right.clientHeight);
			}
		},
		
		onFailure: function() {
			// Request failed, but allow them to click something again.
			animating = false;
			$(document.body).setStyle("cursor", "default");
		}
	});
	
	var curLink = 0;
	
	function next() {
		if (animating) {
			return false;
		}
		
		animating = true;
		$(document.body).setStyle("cursor", "progress");
		
		curLink += 1;
		xhr.send(options.linkBase + links[curLink%links.length]);
		return true;
	}
	
	// Set container height explicitly to the current height to prevent
	// automatic resizing when the ajax response is inserted.
	container.setStyle("height", container.getStyle("height"));
	
	return {
		next: next
	};
}

