function Gallery(div) {
	
	//Settings
	this.delay = 5000; //5 seconds of the delay
	
	//Protected	
	var _index = 0; //Current image
	var _int; //Auto play iterval
	
	//Cache
	var _me = this;
	var _div = div
	var _holder = div.find(".items");
	var _items = div.find(".item");
	var _num = _items.length;//Total number of the images
	var _w = _items.eq(0).css("width").replace("px", "") * 1;//The width of one item
	
	//Once images begin swap
	this.onSwap = function(index){
		//Override me
	}
	
	//Show next image	
	this.next = function(){
		
		//Get next image index
		++_index;
		if(_index >= _num){
			_index = 0;
		}
		
		//Scroll to the item
		this.show(_index);
	}
	
	//Show the item
	this.show = function(index){
		
		//Validate index
		if(index < 0 || index >= _num){
			return false;
		}
		_index = index;
		
		this.onSwap(index);
		
		//Calculate the position
		_holder.stop().animate({"left": -index * _w});
	}
	
	//Start autoplay
	this.startAutoplay = function(){
		clearInterval(_int);
		
		var me = this;
		_int = setInterval(function(){me.next()}, me.delay);
	}
	
	//Start autoplay
	this.stopAutoplay = function(){
		clearInterval(_int);
	}
}

var gallery;

jQuery(document).ready(function(){
	
	//Create a gallery
	gallery = new Gallery(jQuery("div.gallery"));
	gallery.onSwap = selectThumb;
	gallery.startAutoplay();
	
	//Big image events
	jQuery(".items").mouseover(bigOver).mouseout(bigOut);
	
	//Thumbs events
	jQuery(".thumb").mouseover(thumbOver).mouseout(thumbOut);
	selectThumb(0);
});

//Once mouse is over the thumbnail
function thumbOver(){
	
	//Highlight the thumb
	selectThumb(this.id);
	
	//Show the image	
	gallery.show(this.id);
	
	//Cancel autoplay
	gallery.stopAutoplay();
}

//Once mouse is out the thumbnail
function thumbOut(){
	
	//Start autoplay
	gallery.startAutoplay();
}

//Once mouse is over the big image
function bigOver(){	
	gallery.stopAutoplay();
}

//Once mouse is out the big image
function bigOut(){	
	gallery.startAutoplay();
}

//Mark the current thumb
function selectThumb(index){
	jQuery(".thumb.current").removeClass("current");
	jQuery(".thumb:eq("+index+")").addClass("current");
}
