(function ($) {
	$.widget('ui.SlideBox', {
		_init: function() {
			this.element.addClass("ui-slidebox");
			this.refresh();
			this.initButton();
			this.start();
		},

		initButton: function() {
			var self = this;
			this.buttons = this.element.offsetParent().find(this.options.buttons);
			this.buttons.click(function() {
				var idx = self.buttons.index(this) + 1;
				self.start(idx);
				return false;
			});
		},

		refresh: function(e) {
			this.items = $(this.options.items, this.element);
		},

		start: function(idx) {
			var self = this;
			if (typeof idx != 'undefined' && (idx > 0 && idx <= this.items.length)) {
				idx = idx - 1;
			} else {
				idx = 0;
			}
			//this.items.removeClass('hide').removeClass('active').addClass('hide');
			//this.current_item = $(this.items[idx]).addClass('active');
			this.items.removeClass('hide').removeClass('active').css('display', 'none');
			this.current_item = $(this.items[idx]).css('display', 'block');
			if (this.timer) {
				clearInterval(this.timer);
			}
			this.timer = setInterval(function() {
				self.startSwitch();
			}, this.options.delay);
		},
		
		startSwitch: function() {
			var next = this.current_item.next().length ? this.current_item.next() : $(this.items[0]);
			//next.addClass('active');
			//this.current_item.removeClass('active');
			next.css('display', 'block');
			this.current_item.css('display', 'none');
			this.current_item = next;
		},

		destroy: function() {
			if (this.timer) {
				clearInterval(this.timer);
			}
			this.timer = null;
			this.buttons.unbind("click");
			this.buttons = null;
			this.element.removeClass("ui-slidebox");
			this.items.removeClass('hide').removeClass('active');
			this.items = null;
			this.current_item = null;
		}
	});

	$.extend($.ui.SlideBox, {
		version: "0.0.1",
		defaults: {
			items: '> *',
			buttons: 'div.module-switch a',
			delay: 5000
		}
	});
})(jQuery);
