// very rough newsticker plugin to mimic the behaviour of the one on http://news.bbc.co.uk/sport/
// needs clean up & optimisation etc!
// Author: mark@medium.io

;(function($) {

	var defaults = {
		speed : 4000,
		swap  : 2000,
		wait  : 2000
	};

	$.fn.newsticker = function( options )
	{
		return this.each(function(){

			var opts 	= $.extend({}, defaults, options), // set options
				$this	= $(this);
			
			opts.items   = $this.find('li');
			opts.width   = opts.items.eq(0).width();
			opts.total 	 = opts.items.length;
			opts.current = opts.total -1;

			opts.items.each(function(){
				
				var $this = $(this);
				
				$this.data('start_offset', $this.find('.ticker_header').width());
				$this.data('content_width', $this.find('.ticker_content').width());
				$this.append('<span class="ticker_slider">_</span>');
				$(this).hide();
			});
			
			next( opts );

		});
	};
	
	function next( opts )
	{
		var nextcount  	= ( opts.current == opts.total-1 ) ? 0 : opts.current+1
			next_item	= opts.items.eq(nextcount);
			
		if ( $.browser.msie )
		{
		    opts.items.eq(opts.current).hide();
		    
		    setTimeout(function(){
		        
                next_item.find('.ticker_slider').show().css('left', next_item.data('start_offset'));

    		    next_item.show();

    		    next_item.find('.ticker_slider').animate({'left': next_item.data('content_width')+next_item.data('start_offset') }, opts.speed, function(){

    				$(this).fadeOut('fast');

    				opts.current = nextcount;

    				setTimeout(function(){

    					next( opts );

    				}, opts.wait );

    			});		        
		        
		    }, 1000);

		}
		else
		{
		 	opts.items.eq(opts.current).fadeOut(function(){
    			next_item.find('.ticker_slider').show().css('left', next_item.data('start_offset'));
    		});

    		next_item.fadeIn(opts.swap, function(){

    			next_item.find('.ticker_slider').animate({'left': next_item.data('content_width')+next_item.data('start_offset') }, opts.speed, function(){

    				$(this).fadeOut('fast');

    				opts.current = nextcount;

    				setTimeout(function(){

    					next( opts );

    				}, opts.wait );

    			});

    		});   
		}
	}

})(jQuery);
