/**!
	* jQuery Plugin - fiveGallery
	* By Rafael Peruggia <rsouza@fivecom.com.br>
	* Version: 0.2 2010-09-24
	* Copyright 2010, Fivecom
**/
(function($){
	$.fn.extend({
		FiveGallery:function(settings){
			var config = {
				left:'.left',
				right:'.right',
				body:'.body',
				miolo:'.miolo',
				item:'li',
				animateTime:300,
				auto:false,
				changeTime:1000
			};
			if(settings){ $.extend(config,settings); }
			return this.each(function(){
				var itens = $(this).find(config.item);
				var body = $(this).find(config.body);
				var miolo = $(this).find(config.miolo);
				var itemWidth = itens.width()+parseInt(itens.css('marginLeft'))+parseInt(itens.css('marginRight'));
				miolo.css('width',(itemWidth*itens.size())+'px');
				var totalItens = miolo.width()/itemWidth;
				var visibleItens = body.width()/itemWidth;
				var hiddenItens = totalItens-visibleItens;
				
				function clickRight(){
					if(hiddenItens > Math.abs(parseInt(miolo.css('marginLeft')))/itemWidth){
						miolo.animate({
							marginLeft:'-='+itemWidth
						},config.animateTime);
					}else{
						miolo.animate({
							marginLeft:0
						},config.animateTime);
					}
					return false;
				}
				
				function clickLeft(){
					if(parseInt(miolo.css('marginLeft'))<0){
						miolo.animate({
							marginLeft:'+='+itemWidth
						},config.animateTime);
					}else{
						miolo.animate({
							marginLeft:'-'+(itemWidth*hiddenItens)
						},config.animateTime);
					}
					return false;
				}
				if(config.auto){
					var timer = window.setInterval(clickRight,config.changeTime);
					miolo.mouseover(function(){
						window.clearInterval(timer);
					}).mouseout(function(){
						timer = window.setInterval(clickRight,config.changeTime);
					});
				}
				$(this).find(config.left).click(clickLeft);
				$(this).find(config.right).click(clickRight);
			});
		}
	});
})(jQuery);
