jQuery.fn.slider = function (options) {
	var s = slider.init($(this), options);
	return s;
};

var slider =
{
	options: {
		instance: 0,
		timeout: 6500,
		animationTimeout: 150,
		containerClass: '.js-container',
		controlClass: '.js-control',
		onInit: null,
		onSlideNext: null,
		onSlideComplete: null,
		onSlideTo: null,
		activeIndex: 1,
		timer: null,
		count: null,
		active: null,
		container: null,
		self: null
	},
	init: function (el, options) {
		$.extend(this.options, options);
		var o = this.options;
		o.self = el;
		var id = 'slider_' + o.instance;
		o.self.html('<div id="' + id + '">' + o.self.html() + '</div>');
		o.instance += 1;
		o.self.css({ 'position': 'relative' });
		$(o.controlClass + ':first').addClass('active');
		var containers = o.self.find(o.containerClass);
		o.active = o.self.find(o.containerClass + ':first');
		o.count = containers.length;
		containers.css({ 'float': 'left', 'position': 'relative' });
		o.container = o.self.find('#' + id);
		o.container.css('width', o.active.width() * o.count + 'px');

		if (o.onInit != null) {
			o.onInit(o.active, o);
		}

		var self = this;
		$(o.controlClass).bind('click', function () {
			self.slideTo($(this).index());
			clearTimeout(o.timer);
			o.timer = null;
		}).bind('mouseenter', function () {
			clearTimeout(o.timer);
			o.timer = null;
		}).bind('mouseleave', function () {
			o.timer = setTimeout(function () {
				self.slideNext();
			}, 3000);
		});

		if (o.count > 1)
			this.setTimer();
	},
	setControl: function () {
		var o = this.options;
		$(o.controlClass).removeClass('active');
		var c = $(o.controlClass + ':eq(' + o.activeIndex + ')');
		if (c.length > 0) {
			c.addClass('active');
		}
	},
	slideTo: function (index) {
		var o = this.options;
		if (o.onSlideTo != null) {
			o.onSlideTo(o.active, o);
		}
		o.activeIndex = index;
		this.slideNext();
	},
	slideNext: function () {
		var o = this.options;
		var margin = (o.active.width() * o.activeIndex);
		o.container.stop().animate({ marginLeft: '-' + margin }, o.animationTimeout, function () {
			if (o.onSlideComplete != null) {
				o.onSlideComplete(o.active, o);
			}
		});
		o.active = o.self.find(o.containerClass + ':eq(' + o.activeIndex + ')');
		if (o.onSlideNext != null) {
			o.onSlideNext(o.active, o);
		}
		this.setControl();
		o.activeIndex = ((o.activeIndex + 1) < o.count) ? o.activeIndex += 1 : 0;
		this.setTimer();
	},
	setTimer: function () {
		var self = this;
		this.options.timer = setTimeout(function () {
			self.slideNext();
		}, this.options.timeout);
	}
};
