// init the gallery instance from this namespace
var Gallery = function (container, items, control_prev, control_next, options) {
	this.container = container;
	this.items = items;
	this.prev_button = control_prev;
	this.next_button = control_next;
	this.options =  options || {};
	
	// Start at the first item
	this.current_item = 0;
	
	if(this.container.length && this.items.length) {
		this.init();
	}
};

Gallery.prototype = {
	init: function () {
		this._setControlEvents();
		this._setCount(this.current_item);
		this._setAutoPlay();
	},
	
	prev: function () {
		if((this.current_item--) <= 0) {
			this.current_item = this.items.length - 1;
		}
		this._goToItem(this.current_item);
	},
	
	next: function () {
		if((this.current_item++ + 1) >= this.items.length) {
			this.current_item = 0;
		}
		this._goToItem(this.current_item);
	},
	
	// Go to item number x
	_goToItem: function (item_index) {
		this.container.animate({marginLeft: (item_index * this.items[item_index].offsetWidth) * -1 + "px"}, {queue: false, duration: 750});
		this._setCount(item_index);
	},
	
	// Set next control button
	_setControlEvents: function () {
		var scope = this; // Keep scope of instance within event block below
		
		this.prev_button.click(function () {
			scope.prev();
			clearInterval(scope._timeout);
			return false;
		});
		
		this.next_button.click(function () {
			scope.next();
			clearInterval(scope._timeout);
			return false;
		});
	},
	
	_setCount: function (item_index) {
		// Update counter if it exists
		if(this.options.count_display) {
			this.options.count_display.text((item_index + 1) + "/" + this.items.length);
		}
	},
	
	_setAutoPlay: function () {
		if(this.options.auto_play_timeout) {
			var scope = this;
			this._timeout = setInterval(function () {scope.next()}, this.options.auto_play_timeout);
		}
	}
};

/* 
	Events will be tied to elements that have the correct classes and / elements contained within them
	This will make up the two gallery types in the web site.
*/
$(function () {
	// Start home page galleries
	new Gallery($("div.news .item-container"), $("div.news .item-container .item"), $('.news .left'), $('.news .right'), {count_display: $(".news .navigation .current")});
	new Gallery($("div.featured .item-container"), $("div.featured .item-container .item"), $('.featured .left'), $('.featured .right'), {count_display: $(".featured .navigation .current")});
	//new Gallery($("div.promotion .item-container"), $("div.promotion .item-container .item"), $('.promotion .left'), $('.promotion .right'), {count_display: $(".promotion .navigation .current")});
	// End home page galleries
	
	// Start product list gallery
	new Gallery($("#wineselector #wine-wrapper"), $("#wineselector #wine-wrapper ul"), $('.control.left'), $('.control.right'));
	// End product list gallery
});
