/**
 * Lightweight carousel slider plugin
 * 
 * @param {Object} options
 */

(function(jQuery){
	
	
	var carousel = function(element, options)
	{
		this.target = element;
		
		this.item_width = jQuery(this.target).find('li:first').width();
		this.item_count = jQuery(this.target).find('li').size();
		
		this.width = jQuery(this.target).find('.carousel_clip').width();
		this.position = 0;
		this.new_position = 0;
	  this.items_by_position = this.width / this.item_width;
		this.position_count = Math.ceil( this.item_count / this.items_by_position  );
		
		this.total_width = this.item_count * this.width;
		
		jQuery(this.target).find('ul').css( 'width', this.total_width ); // wrapper
		
		//this.setPellet();
		
		this.options = jQuery.extend({}, jQuery.fn.carousel.defaults, options);
		
		this.position = this.options.position;
		
    this.delegates = [];
    for(var f in this)
    {
      if (typeof(this[f]) == 'function')
        this.delegates[f] = this.createDelegate(this, this[f]);
    }

		jQuery(this.target).find('a[rel=carousel_next]').unbind('click', this.delegates.next).bind('click', this.delegates.next );
		jQuery(this.target).find('a[rel=carousel_prev]').unbind('click', this.delegates.prev).bind('click', this.delegates.prev );
		
		this.animate();
	};
	
    //setPage
	carousel.prototype.setPage = function(p)
    {
        this.position = p;
        this.animate();
        return false;
    }

	// next
	carousel.prototype.next = function(event)
	{
		this.position += 1;
		if(this.position == this.position_count)
			this.position = 0;
		
		this.animate();
		return false;
	}
	
	
	// previous
	carousel.prototype.prev = function(event)
	{
		this.position -= 1;
		
		if(this.position == -1) this.position = this.position_count - 1;
		
		this.animate();
		return false;
	}

	// animate
	carousel.prototype.animate = function()	
	{
		//this.updatePellet();
		
		this.new_position = this.width * this.position;
		jQuery(this.target).find('ul').animate({
			left: '-'+this.new_position+'px'
		});
	}
	
	
  carousel.prototype.createDelegate = function(target, handler)
  { 
    var delegate = function() 
    {
      return handler.apply(target, Array.prototype.slice.call(arguments));
    };
    
    return delegate;
  };
 
  carousel.jqinit = function(options)
	{
		this.each(function()
		{
			if(jQuery(this).data('carousel')) return;
			
			var instance = new carousel(this, options);
			
			jQuery(this).data('carousel', instance);
			return this;
			
		});
		
		return this;
	};
	
	
	carousel.defaults =
	{
		bgcolor: "#FF00FF",
		position: 0
	};
	
	jQuery.fn.carousel = carousel.jqinit;
	jQuery.fn.carousel.defaults = carousel.defaults;
	
})(jQuery);

