(function( $ ){

	function HomeNews(_element, _options) {
		this.options = {
			"itemClass" : 'homeNewsItem',
			"buttonClass" : 'homeNewsButton',
			"activeClass" : 'active',
			"idPrefix" : '#homeNewsItem',
			"switchTime" : 6000
		};

		if (_options) {
			$.extend(this.options, _options);
		}

		this.element = _element;

		this._create();
	}

	HomeNews.prototype = {
		_create: function() {
			this.e_items = this.element.find('.' + this.options.itemClass);
			this.e_buttons = this.element.find('.' + this.options.buttonClass);

			var self = this;
			this.loopFunction = function() { self._cycleLoop(); };

			$(this.element).hover(
				function() {
					if (self.timeOut) {
						window.clearTimeout(self.timeOut);
						self.timeOut = false;
					}
				},
				function() {
					if (!self.timeOut) {
						self.timeOut = window.setTimeout(self.loopFunction, self.options.switchTime);
					}
				}
			);
			this.timeOut = window.setTimeout(self.loopFunction, self.options.switchTime);
		},

		"prev" : function() {
			this._move(-1);
		},

		"next" : function() {
			this._move(1);
		},

		_cycleLoop : function() {
			this.next();

			this.timeOut = setTimeout(this.loopFunction, this.options.switchTime);
		},

		"_move" : function(d) {
			var active = this.e_items.filter('.' + this.options.activeClass);
			var i = this.e_items.index(active);
			i += d;
			if (i < 0) i = this.e_items.length - 1;
			if (i >= this.e_items.length) i = 0;

			this.e_items.hide().removeClass(this.options.activeClass);
			this.e_items.eq(i).show().addClass(this.options.activeClass);

			this._setButtons(i);
		},

		"_setButtons" : function(i) {
			this.e_buttons.attr('src', this.options.bia);
			this.e_buttons.eq(i).attr('src', this.options.ba);
		},

		"setItem" : function(itemId) {
			this.e_items.hide().removeClass(this.options.activeClass);
			var s = $(this.options.idPrefix + itemId);
			var i = this.e_items.index(s);
			s.show().addClass(this.options.activeClass);

			this._setButtons(i);
		}


	};

	$.fn.homeNews = function(_options) {
		if (typeof(_options) === 'string') {
			var args = Array.prototype.slice.call(arguments, 1);
			this.each(
				function() {
					if (this._homeNews && this._homeNews[_options]) {
						this._homeNews[_options].apply(this._homeNews, args);
					}
				}
			);
			return;
		}
		this.each(
			function() {
				this._homeNews = new HomeNews($(this), _options);
			}
		);
	};

})( jQuery );

