/* SLIDER NEWS */
(function($) {
	/* CONFIGURAZIONI DI DEFUALT */
	$.sliderNews = {
		defaults: {
			sliderTime: 10000,
			sliderTimeOut: 10,
			sliderDuration: 'slow',
			readAll: '#primo-piano-bottom > a.read-all'
		}
	};
	
	$.fn.extend({
		sliderNews: function(options) {
			
			var elements = this,
				totArt = elements.length,
				overflow = elements.parent(),
				w = elements.eq(0).outerWidth(true),
				timeout = null,
				timer = null,
				sc = 1,
				conf = $.extend($.sliderNews.defaults, options),
				readAll = $(conf.readAll);
				
			function init() {
				if(totArt > 1) scrollNews();
			}
			
			function scrollNews() {
				clearTimeout(timeout);
				
				timer = setInterval(function(){
					if(sc == totArt) {
						overflow.animate({'left': 0}, conf.sliderDuration);
						sc = 1;
					} else {
						overflow.animate({'left': '-=' + w}, conf.sliderDuration);
						sc++;
					}
					
					var element = elements.eq(sc - 1);
					
					updateIndex(element);
				}, conf.sliderTime);
			}
			
			function updateIndex(element) {
				var idSplit = element.attr('id').split('primo-piano-'),
					index = parseInt(idSplit[1], 10),
					active = $('a.select-art-h').removeClass('select-active').eq(index - 1);
				
				$('.primo-piano-container').removeClass('active');
				element.addClass('active');
				active.addClass('select-active');
				readAll.attr('href', active.attr('href'));
			}
			
			init();
			
			$('a.select-art-h').click(function(e){
				e.preventDefault();
				
				var $this = $(this),
					index = $this.index();
				
				if (!$this.hasClass('select-active')) {
					clearInterval(timer);
					clearTimeout(timeout);
					
					$('#primo-piano-overflow').animate({
						'left': '-' + (w * index) + 'px'
					}, conf.sliderDuration, function(){
						timeout = setTimeout(function(){
							scrollNews();
						}, conf.sliderTimeOut);
					});
					sc = index + 1;
					
					$('.select-art-h').removeClass('select-active');
					$this.addClass('select-active');
					$('.primo-piano-container').removeClass('active');
					$('.primo-piano-container').eq(index).addClass('active');
					readAll.attr('href', $this.attr('href'));
				}
			});
			
			return this;
		}
	});
})(jQuery);
