/**
 * Imagens ROCCO
 *   http://www.roccoassociados.com.br
 *
**/
(function($) {

    $.fn.jimagens = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
		container:null,
        current:null,
		size:null
    };

    $.jimagens = function(e, o) {
        this.options = $.extend({}, defaults, o || {});
		$container = $(e);
		$this = this;
		$containerImagem = $(this.options.container);
		this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jimagens;

    $jc.fn = $jc.prototype = {
        jimagens: '0.2.3'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({

        setup: function() {
			if(this.options.container != null) {
				this.options.current = 0;
				this.options.size = $container.children().length;

				this.change(this.options.current);
				
				$("a",$container).unbind("click").click(function(e) {
					e.preventDefault();
					var index = $("li",$container).index($(this).parent());
					if(index >= 0) $this.change(index);
				});
				
				$(".esq",$containerImagem).unbind("click").click(function(e) {
					e.preventDefault();
					$this.prev();							  
				});
				
				$(".dir",$containerImagem).unbind("click").click(function(e) {
					e.preventDefault();
					$this.next();							  
				});
			}
        },

        change: function(i) {
			$("img:eq(0)",$containerImagem).remove();
			
			this.showLoading();
			
			var img = $("li:eq(" + i +") a",$container);
			$containerImagem.prepend($('<img>').attr('src',img.attr("href")));
			$("img:eq(0)",$containerImagem).unbind("load").load(function(e) {
				$this.hideLoading();
				$(window).scrollTop(0);
			});
			this.update(i);
        },
		update: function(i) {
			this.options.current = i;
			
			if(i > 0) $(".esq",$containerImagem).fadeIn();
			else $(".esq",$containerImagem).hide();
			
			if(i < (this.options.size-1)) $(".dir",$containerImagem).fadeIn();
			else $(".dir",$containerImagem).hide();
			var atual = ((this.options.current+1) < 10) ? "0" + (this.options.current+1) : (this.options.current+1);
			var total = (this.options.size < 10) ? "0" + this.options.size : this.options.size;
			$(".seta",$containerImagem).html("<p>" + atual  + "/"+ total + "</p>");
		},
		next: function() {
			this.options.current++;
			this.change(this.options.current);
		},
		prev: function() {
			this.options.current--;
			this.change(this.options.current);
		},
		showLoading: function() {
			$(".loading",$containerImagem).show();
		},
		hideLoading:function() {
			$(".loading",$containerImagem).hide();
		}
    });

    $jc.extend({
        defaults: function(d) {
            return $.extend(defaults, d || {});
        }
    });

})(jQuery);

