$(document).ready(function(){

	// NEWS
	var root = $("div.news-blend");
	var news = $("div.news-blend div.news-latest-item");
	var legends = [];
	
	var fading = false;
	var next = null;	
	var visible = 0;
	
	$("div.news-blend").css({
		height: '200px'
	});
	
	var timer = null;
	var legend = $('<div class="legend"></div>');
	
	var doTick = function( nr ){
		fading = true;
		$(news[ visible ]).fadeOut(800, function(){
			fading = false;
			if( next != null ){
				restartInterval();
				forceTick( next );
				next = null;
			}
		});
		$(legends[ visible ]).removeClass('active-legend', 500);
		nr = (( nr < news.length ) ? nr : 0);
		$(news[ nr ]).fadeIn(500);		
		$(legends[ nr ]).addClass('active-legend', 500);
		return nr;
	}
	
	var forceTick = function( nr ){
		visible = doTick( nr );
	}
	
	var tick = function(){
		forceTick( visible+1 );
	};	
		
	var startInterval = function(){
		if( timer == null ){
			timer = setInterval( tick, tickrate );
		}
	}
	var stopInterval = function(){
		if( timer != null ){
			clearInterval( timer );
			timer = null;
		}
	}
	var restartInterval = function(){
		startInterval();
		stopInterval();
	}
	
	var tickrate = 3000;
	
	news.each( function( i, el ){
		$(el).children(".news-latest-text").css({
			height: '64px',
			overflow: 'auto'
		});
		var x = $(el).wrap('<div class="news-wrap" />');
		
		if( news.length > 1 ){
			var l = $('<div>' + (i+1) + '</div>');
			l.bind('click', function(){
				if( i != visible ){
					if( fading ) {
						next = i
					} else {
						restartInterval();
						forceTick( i );
					}
				}
			});
			if( i == 0 ) {
				l.addClass('active-legend');
			}
			legends.push( l );
			
			legend.append( l );
			x.bind('mouseenter', function( e ){
				stopInterval();
			}).bind('mouseleave', function( e ){
				startInterval();
			});
		}
		if( i != visible ) {
			$(el).hide();
		}
	});
	
	if( news.length > 1 ){
		visible = news.length;
		tick();
		startInterval();
		root.append( legend );
	}
	
});