/**
 * @author ilkinulas@gmail.com
 * jquery plugin that rotates div elements inside a given div element
 */

jQuery.fn.extend({
  slideRight: function(speed) {
    return this.each(function() {
	  jQuery(this).css('overflow','hidden').animate({width: 'show',duration:speed});
    });
  },
  slideLeft: function() {
    return this.each(function(speed) {
	  jQuery(this).animate({width: 'hide',duration:speed});
    });
  },
  slideToggleWidth: function(speed) {
    return this.each(function() {
      var el = jQuery(this);
      if (el.css('display') == 'none') {
        el.slideRight(speed);
      } else {
        el.slideLeft(speed);
      }
    });
  }
});

jQuery.fn.divroller = function(options) {
	var hiddenDivs = [];
	settings = jQuery.extend( {
		visible : 3,
		pause : 3000,
		speed : 'slow',
		direction:'Down'
	}, options);

	start(settings, this);
	
	function start(settings, container) {
		var divs = container.children();
		var itemcount=divs.length;
		//hide unvisible divs
		while (settings.visible < divs.length) {
			var removedDiv = $(divs[divs.length - 1]).remove();
			hiddenDivs.push(removedDiv);
			divs = container.children();
		}
		if (itemcount>1){
			setTimeout( function() {
				roll(settings, container)
			}, settings.pause);
		}
	};

	function roll(settings, container) {
		
		//Dom manipulation.
		container.prepend(hiddenDivs.pop());
		hiddenDivs.unshift($(container.children()[settings.visible]).remove());
		//Efect
		$(container.children()[0]).hide();
			switch (settings.direction){
				case 'Right':{
					$(container.children()[0]).slideRight(settings.speed);
				break;
				}
				case 'Left':{
					$(container.children()[0]).slideLeft(settings.speed);
				break;
				}
				case 'Up':{
					$(container.children()[0]).slideUp(settings.speed);
				break;
				}
				default:{
					
					$(container.children()[0]).slideDown(settings.speed);
				break;
				}
			}
		
		//Repeat
		setTimeout( function() {
			roll(settings, container)
		}, settings.pause);
	}
}

