var Riess = function(){
	var intervalHolder;
	var switchTo = function (spriteRepository, offset) {
		var active = $("#active");
		var deactive = $("#next-active");
		deactive.attr({src: active.attr("src")});
		var activeInRepo = $("#ss-buffer img.active");
		
		var nextInRepo;
		if (offset > 0) {
			var nextInRepo =  activeInRepo.next().length ? activeInRepo.next() : $("#ss-buffer img:first");
		}
		else if (offset < 0) {
			var nextInRepo =  activeInRepo.prev().length ? activeInRepo.prev() : $("#ss-buffer img:last");
		}
		
		nextInRepo.addClass('active');
		activeInRepo.removeClass('active last-active');
		
		deactive.attr({src: nextInRepo.attr("src")});
		active.animate({opacity: 0.0}, 1500, function() {
            active.removeClass('active last-active');
    	});
		deactive.animate({opacity: 1.0}, 1500, function() {
				deactive.addClass('active');
				active.attr({id: "swap-active"});
				deactive.attr({id: "active"});
				active.attr({id: "next-active"}).css({opacity: 0.0});
		});
	};
	var play = function(spriteRepository) {
		intervalHolder = setInterval("Riess.switchTo('"+spriteRepository+"', 1)", 5000);
	};
	var playKM = function(spriteRepository) {
		intervalHolder = setInterval("Riess.switchTo('"+spriteRepository+"', 1)", 2500);
	};
	var stop = function () {
		clearInterval(intervalHolder);
	};
	var showOverlay = function(overlayId){
		var overlay = $(overlayId);
		$("div.overlay").hide(100);
		overlay.fadeIn(300);
		$(overlayId + " input.focus").focus().select();
		$("a#close-overlay").fadeIn(300);
	};
	
	var closeOverlay = function(){
		$("div.overlay").fadeOut(300);
		$("#close-overlay").fadeOut(300);
	};
	
	var submit = function(formChild) {
		var form = $(formChild).parents("form");
		var notificationDiv = $(form).children("div.notification");
		var serializedForm = form.serialize();
		$.ajax({
			   type: "POST",
			   url: form.attr("action"),
			   data: serializedForm,
			   success: function(msg){
			   		notificationDiv.html(msg);
			   }
		});
		return false;
	};

	return{
		switchTo : switchTo,
		showOverlay : showOverlay,
		closeOverlay : closeOverlay,
		play : play,
		stop : stop,
		submit : submit,
		playKM : playKM
	}
}();