(function($) {
window.addEvent("domready", function() {
	
	function setClassToItem(item, index) {
		item.removeClass(item.retrieve("fs_class"));
		var cls = "fs_item_" + index;
		item.addClass(cls).store("fs_class", cls);
	}
	
	$$(".fadeslide").each(function(context) {
		var container = context.getElement("*[class*=fadeslide_]");
		if(!container.getChildren()[1]) return;
		
		var params = /(^|\s)fadeslide_([0-9]+)_([0-9]+)(_([0-9]+))?(\s|$)/.exec(container.get("class"));
		if(!params) return;
		
		var	sleep = params[3].toInt(),
			step = params[5] ? params[5].toInt() : 1,
			next,
			prev,
			group,
			items = container.getChildren();
			
		
		items.set("tween", {
			duration: params[2].toInt(),
			transition: "linear",
			link: "cancel"
		}).setStyle("z-index", 99).fade("hide");
		
		group = $$(items.slice(0, step));

		group.setStyle("z-index", 100).fade("show").each(setClassToItem);
		container.store("fs_next", step);
		container.store("fs_current", group);
		
		next = function() {
			$clear(container.retrieve("fs_auto"));
			var end, off = container.retrieve("fs_next");
			if(off + step <= items.length) {
				end = off + step;
				group = $$(items.slice(off, end));
			} else {
				end = off + step - items.length;
				group = $$(items.slice(off).concat(items.slice(0, end)));
			}
			container.retrieve("fs_current").setStyle("z-index", 99).fade("out");
			group.setStyle("z-index", 100).fade("in").each(setClassToItem);
			container.store("fs_current", group).store("fs_next", end).store("fs_auto", next.delay(sleep));
		};
		prev = function() {
			$clear(container.retrieve("fs_auto"));
			var end, off = container.retrieve("fs_next") - 2 * step;
			if(off < 0) off = off + items.length;
			
			if(off + step <= items.length) {
				end = off + step;
				group = $$(items.slice(off, end));
			} else {
				end = off + step - items.length;
				group = $$(items.slice(off).concat(items.slice(0, end)));
			}
			container.retrieve("fs_current").setStyle("z-index", 99).fade("out");
			group.setStyle("z-index", 100).fade("in").each(setClassToItem);
			container.store("fs_current", group).store("fs_next", end).store("fs_auto", prev.delay(sleep));
		};

		container.store("fs_auto", next.delay(sleep));
		context.getElement(".fadeslide_next").addEvent("click", next);
		context.getElement(".fadeslide_prev").addEvent("click", prev);
	});
});
})(document.id);
