(function($) {
	$.fn.newsticker = function(options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.newsticker.defaults, options);
		
		// iterate and reformat each matched element
		return this.each(function() {
			container = $(this);
			
			// build element specific options
			var o = opts;
			
			// get elements and buttons for the navigation
			var elements = container.find(o.news);
			var autoPlay = o.autoPlay;
			var delayTime = o.delayTime;
			var pauseOnHover = o.pauseOnHover;
			var transition = o.transition;
			var childCount = elements.length;
			var current = 0;
			
			// update element styles
			elements.each(function(i){
				this.id = 'news_ticker_' + i;
			});
			
			elements.hide();
			$('#news_ticker_0').show();
			$(o.currentNews).text((current + 1) + '/' + childCount);
			
			// buttons functions
			$(o.nextBtn).click(function(){
				next('next');
			});	
			
			$(o.prevBtn).click(function(){
				next('prev');
			});
			
			if(autoPlay == true){
                interval = setInterval (function(){next('next');}, delayTime);
				if(pauseOnHover == true){
					$(o.news).hover(
						function(){
		                    //$(o.news).css('cursor', 'pointer');
							clearInterval(interval);
						},
						function(){
		                    interval = setInterval (function(){next('next');}, delayTime);
						}
					);
				}
			}

			function next(type){
                currentVisibleElement = "#news_ticker_" + (current);
                
				if(type == "next"){
					nextVisibleElement = "#news_ticker_" + (current + 1);

					current = current + 1
					if(current == childCount){
						nextVisibleElement = '#news_ticker_0';
						current = 0;
					}

				}

				else if(type == "prev"){
					
					nextVisibleElement = "#news_ticker_" + (current - 1);

					current = current - 1;
					if(current < 0){
						nextVisibleElement = '#news_ticker_' + (childCount-1);
						current = childCount - 1;
					}
				}

				if(transition == true){
                    $(currentVisibleElement).slideUp();
					$(nextVisibleElement).slideDown('slow');
				}
				else{
                    $(currentVisibleElement).hide();
					$(nextVisibleElement).show();
				}
				
				if(autoPlay == true){
					clearInterval(interval);
                    interval = setInterval (function(){next('next');}, delayTime);
				}
				container.find(o.currentNews).text((current + 1) + '/' + childCount);

			}
	  });
	};
	
	$.fn.newsticker.defaults = {
		news: '.news',
		nextBtn: '.next',
		prevBtn: '.prev',
		currentNews: '.current',
		autoPlay: true,
		delayTime: 2000,
		pauseOnHover: true,
		transition: false
	};
})(jQuery);
