/*
* Tadas Juozapaitis ( kasp3rito@gmail.com )
*
Small modifications made by c.Spot:
- some variable naming
- allowing individual news items to be of varying height
- fading now works
*/
(function($){
$.fn.vTicker = function(options) { // Make this an extension of jQuery
	var defaults = {
		speed: 700,
		pause: 4000,
		showItems: 3,
		animation: '',
		mousePause: true,
		isPaused: false
	};

	var options = $.extend(defaults, options);

	moveUp = function(grandPar){ // Note this is declared globally so that setInterval has no problem accessing it
    if(options.isPaused) return; // If paused, then don't move

    var par = grandPar.children('ul'); // Get the container for the individual articles
		var kids = par.children('li');
		var first = $(kids[0]);
		var firstCpy = first.clone(true);
		var firstH = first.height();
		var newH = 0;
		var shown = options.showItems;

		// Make new height exactly that of the next 3 children
		for(var i = 1; i <= shown; i++) newH += $(kids[i]).height(); // Skip past first child since he'll be going away soon

    if(options.animation == "fade"){
      first.fadeOut(options.speed);
      $(kids[shown]).hide().fadeIn(options.speed);
    }

    par.animate(
      {top: '-=' + firstH + 'px'}, // Moving it up by height of first child
      options.speed,
      function() {
        first.remove(); // Remove once out of sight
        par.css('top', '0px'); // Readjust the position
				grandPar.height(newH+8); // Adjust height. Note: May cause a shift in the position of content below it
    });

    firstCpy.appendTo(par); // Copy first and add to the end to solidify repeat stage
	};

	return this.each(function() { // Returns a jQuery object. This is only returned once though setInterval runs indefinitely
		var grandPar = $(this);
    var kids = grandPar.children("ul").children("li");
    var shown = options.showItems;
    var newH = 0;

    for(var i = 0; i < shown; i++) newH += $(kids[i]).height();

		grandPar
			.height(newH+8)
			.css({overflow: 'hidden', position: 'relative'})
			.children('ul').css({position: 'absolute', margin: 0, padding: 0})
			.children('li').css({margin: 0, padding: 0}); // Stripping margin, padding helps to give consistent heights

    if(options.mousePause){
			grandPar.mouseenter(function(){ options.isPaused = true; })
      .mouseleave(function(){ options.isPaused = false; });
		}

    setInterval(function(){ moveUp(grandPar); }, options.pause);
	});
};
})(jQuery);

