$(document).ready(function(){
   $('ul#news').hide();

   var newsIDs = [];
   var newsTitles = [];
   var c=0;
	//save id attributes of each news and title of each news, limiting to 7
   	$('ul#news li').each(function(i, e) {
   		if(c<7){
	   		newsIDs[i] = $(e).attr('id');
	   		newsTitles[i] = $("div.news_title", e).html();
	   		$('div.latest_short_news').append('<div class="short_new blue"><div class="three_pt"><a href="http://www.lu.lv/#"><img src="fileadmin/templates/lu_portal/img/three_pt_bl.jpg"></a></div><div class="short_new_txt"><a href="http://www.lu.lv/#" id="cell'+i+'">'+newsTitles[i]+'</a></div></div>')
   		}
   		++c;
	});

	var newsCount = newsIDs.length;
	//index of news title array that will always be in leftmost position in slider
	var chosedNewNum = 0;

   	//places headings to actual news blocks and html of active news to central position
	function titlesToSlider(){
		$("div.brown").removeClass("brown").addClass("blue");//rem selected class, add non selected
		var grndPrnt = $("#cell"+chosedNewNum).parent().parent();
		grndPrnt.removeClass("blue").addClass("brown");

		var newsContent = $("#news #"+newsIDs[chosedNewNum]+" div.main_new").html();
		$("#newsContent").html(newsContent);
   };

   var tID = null;
   function rotateNews(){
   		titlesToSlider();
   		chosedNewNum = (++chosedNewNum) % newsCount;
 		tID = setTimeout(rotateNews,8000);
   };

   function stopRotating(){
		--chosedNewNum;
	   	if(chosedNewNum < 0) chosedNewNum = newsCount - 1;
	   	clearTimeout(tID);
		tID = null;
   }
   //clicking 'next'
	$("#next").click(function(event){
	   event.preventDefault();
	   if(tID!=null) stopRotating();

	   chosedNewNum = (++chosedNewNum) % newsCount;
	   titlesToSlider();
	});
	//clicking 'prev'
	$("#prev").click(function(event){
	   event.preventDefault();
	   if(tID!=null) stopRotating();
	   --chosedNewNum;
	   if(chosedNewNum < 0) chosedNewNum = newsCount - 1;
	   titlesToSlider();
	});
	//choose news
	$("div.short_new_txt a").click(function(event){
		event.preventDefault();
		if(tID!=null) stopRotating();
		idAttr = $(this).attr('id');
	   var elemNum = parseInt(idAttr.substring(4));
	   chosedNewNum = elemNum;
	   titlesToSlider();
	});

	rotateNews();
});