// 08:52
//JS contain functions for for rating media

$(document).ready(function() {
	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	var message = $('#message').val();
	var error = $('#error').val();
	var isEdit = $('#isEdit').val();
	//Force the default cat to display on page load
	$('#category option').filter(':first').attr('selected', 'selected');
	var selectedCategory = $('#category').val();
	var itemSortType = $('#itemSortType').val();
	showMessage(message, error, isEdit);
	
	
	/*
	* Rockstarba layout specific actions
	*/
	
	//Create tabs
	if( $('#category').length ){
		$('#category option').each( function() {
			$('.rockstarbaReTemplates.contentTabs ul').append('<li><a href="#" id="c-'+$(this).val()+'"><span>'+$(this).text()+'</span></a></li>');
		});
	}
	
	//Force the default cat to display on page load
	$('.rockstarbaReTemplates.contentTabs ul li a').filter(':first').addClass('activeTabNav');
	
	//Tab click triggers the select change 
	$('.rockstarbaReTemplates.contentTabs ul li a').click( function(){
		var currentTab = $(this);		
		var catId = $(this).attr('id').substr(2);
		$('.rockstarbaReTemplates.contentTabs ul li a').removeClass('activeTabNav');
		
		$('#category option').each( function() {
			if( $(this).val() == catId ){
				$(this).attr('selected', 'selected');
				selectCategory();
				currentTab.addClass('activeTabNav');
				pagination_currentPage = 1;
			}
		});
		
		return false;
	});
	
	$('.comments', $('.unit-mu_rating_engine')).hide();
	
	// Load current item from pagination component
	window.ratingEngineFirstLoad = true;
});

function showLinkBox() {
	if ($('#linkBox').length <= 0) {
		$('<input type="text" id="linkBox"/>').insertAfter('#linkIt');
		$('#linkBox').val($('#linkIt').attr('href'));
		
		$('#linkBox').focus(function () {
			$(this).select();
		});
	}
	else {
		$('#linkBox').remove();
	}
	return false;
	
}

//get user submission form
function showUserSubmissionForm(){
	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	var vals = $('#formVals').val();
	$('#ratingContainer').hide();
	$('#userSubmissionButton').hide();
	$('#userSubmissionContainer').show();
	
	$.post(site_url+"ajax/get_user_submission_form/", {ratingEngineId: ratingEngineId, sessionName : sessionName, currentItemId: currentItemId, vals: vals}, function(data) {
		data = eval("("+data+")");
		if (data['result']!=0){
			$('#userSubmissionContainer').html(data['output']);
		}
	});
}

//hide user submission form
function hideUserSubmissionForm(){
	clearMessage();
	$('#userSubmissionContainer').hide();
	$('#ratingContainer').show();
	$('#userSubmissionButton').show();
	showItemList(0, pageLimit);
}

//show media to rate
function showMedia(currentMediaId){
	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();

	$.get(site_url+"ajax/get_media_to_rate/", {ratingEngineId: ratingEngineId, currentItemId: currentItemId, currentMediaId: currentMediaId}, function(data) {
		//, sessionName : sessionName was in the ajax param before
		data = eval("("+data+")");

		$('#mediaToRate').html(data['output']);
		
		//add hover to image div
		$(".horizontalGalleryImage").hover(
			function(){
				$(".largeImgLeft,.largeImgRight").css("visibility", "visible");
			},
			function(){
				$(".largeImgLeft,.largeImgRight").css("visibility", "hidden");
			}
		)				
		selectMedia();
	});
}


//show item detail. Note: not include image
function showItemDetail(){
	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	//reset form values
	$('#formVals').val("");

	//Passing a parameter with a random number stops IE from caching the response
	var randomnumber=Math.floor(Math.random()*1001);

	$.get(site_url+"ajax/get_item_detail/?count="+randomnumber, {ratingEngineId: ratingEngineId, currentItemId: currentItemId}, function(data) {
		//, sessionName : sessionName was in the ajax param before
		data = eval("("+data+")");
		
		$('#itemDetail').html(data['output']);
		
		if( $('.rockstarbaReTemplates').length > 0 ){
			var newUrl = $('#linkToUrl').text();
			var newName = $('#linkToName').text();
			$('.addThisContainer').append('<div class="addthis_toolbox addthis_default_style" addthis:url="'+newUrl+'" addthis:title="'+newName+'"><a class="addthis_button_facebook"></a><a class="addthis_button_twitter"></a><a class="addthis_button_myspace"></a><a class="addthis_button_email"></a><span class="addthis_separator">|</span><a href="http://www.addthis.com/bookmark.php" class="addthis_button_compact"></a></div>');
			reinitializeAddThis();
		}
				
		refreshRatingStars( $('#lastStar').text() );
		
		//star hover			
		$(".starRate li").hover(
	      function () {
	        $(this).prevAll().andSelf().addClass("active");
	      }, 
	      function () {
	        $(this).siblings().andSelf().removeClass("active");
	      }
	    );	

		if (typeof data['additional']['comments'] != 'undefined') {
			//we need this later (it's for regenerating the comment cache when someone votes for a comment)
			var additionalUpDownClickHandler = function() {
					$.get(drupalUrl+"re_regenerate_comment_cache/"+data['additional']['nid']+"/"+ratingEngineId+"/"+currentItemId+"/?count="+randomnumber);
			};
			
			if (data['additional']['comments'].length == 0 || data['additional']['comments'] == 0) {
				//No comments, need to get them from Drupal
				var comments = false;
				$.get(drupalUrl+"re_regenerate_comment_cache/"+data['additional']['nid']+"/"+ratingEngineId+"/"+currentItemId+"/?count="+randomnumber, function(commentJson) {
				 	comments = eval("("+commentJson+")");

				 	data['additional']['comments'] = comments;

				 	//Need to recreate an empty comment div for use
				 	if( $('.rockstarbaReTemplates').length > 0 ){
						if( $('div.comments').length == 0 ){
							$('#mediaToRate').append('<div class="comments"></div>');
						}
					}

					$('div.comments', $('.unit-mu_rating_engine')).replaceWith(manipulateCommentForm(comments[0]));

					manipulatePaginationLinks(additionalUpDownClickHandler)
					setClickHandlers(); //in nelonen.js
					$('.updown-widget').find('.updown-vote a').click(additionalUpDownClickHandler);
					setAutoGrow(); //in nelonen.js
					$('div.comments').addClass('standard3Column column1');
					// Since this is done after document.ready, we need to make sure
					// editor links are shown:
					var isEditor = $.cookie('isEditor');
					if(isEditor == 1) {
						$('.showToEditor').show();
					}
					
					if( $('.rockstarbaReTemplates').length > 0){
						rockstarComments('1');
					}
				});
			}
			else {
				//if cid!=0 => go the the page contain that cid
				//else show first page
				var comments = data['additional']['comments'];			
				
				//Need to recreate an empty comment div for use
			 	if( $('.rockstarbaReTemplates').length > 0 ){
					if( $('div.comments').length == 0 ){
						$('#mediaToRate').append('<div class="comments"></div>');
					}
				}
					
				if (cid!=0){
					$.each(comments, function(i, val){
						var commentElem = $(val);
						if (commentElem.find("#comment-"+cid).length){
							 $('div.comments', $('.unit-mu_rating_engine')).replaceWith(manipulateCommentForm(val));
						}					
					});
				}
				else{
					//Show first page of comments
					$('div.comments', $('.unit-mu_rating_engine')).replaceWith(manipulateCommentForm(comments[0]));
				}
				
				
				
				manipulatePaginationLinks(additionalUpDownClickHandler);
				setClickHandlers();
				$('.updown-widget', $('.unit-mu_rating_engine')).find('.updown-vote a').click(additionalUpDownClickHandler);
				setAutoGrow();
				$('div.comments', $('.unit-mu_rating_engine')).addClass('standard3Column column1');
				
				if( $('.rockstarbaReTemplates').length > 0){
					rockstarComments('2');
				}
			}
		}
		
		function manipulateCommentForm(commentHtml) {
		
			var commentElem = $(commentHtml);

			//Logged-in users don't need all the details
			if (user) {
				commentElem.find("#edit-mail-wrapper, #edit-homepage-wrapper, fieldset.captcha").remove();
				commentElem.find("#edit-name-wrapper input").replaceWith(user.display_name);
				commentElem.find("#edit-name-wrapper span.form-required").remove();
			}
			
			commentElem.find("#comment-form *").focus(function() {
				//get actual comment form
				
				//store focused element id so that we can restore focus when the form has been re-rendered
				var focusedId = $(this).attr("id");
				
				//Rockstar comment link
				if( $('.rockstarbaReTemplates').length > 0 ){
					var commentCountLink = $('.commentCount');
				}
				
				$.get(drupalUrl+"render_comment_form/"+data['additional']['nid']+"/"+currentNid+"/", function(output) {
					var currentContent = $("#"+focusedId).val();
					$("#comment-form").parent().parent().replaceWith(output);
					
					if( commentCountLink ){
						$('.box h2', $('.unit-mu_rating_engine .comments')).append(commentCountLink);
					}
					
					setAutoGrow();
					
					//For improved user experience
					$("#"+focusedId).val(currentContent);
					$("#"+focusedId).focus();					
				});							
			});

			//Disable the dummy submit button
			commentElem.find("#submit-dummy").attr("onclick", "").click(function() { return false; });

			return commentElem;
		}
		
		function manipulatePaginationLinks(additionalUpDownClickHandler) {

			
			//Manipulate the pagination links a bit and set click handlers for them
			$(".pager a").each(function() {
				var idx = -1;
				//Find the page number
				if ((idx = $(this).attr("href").indexOf("page=")) > -1) {
					idx += "page=".length;
					var page = '';
					for (var i = idx; i < $(this).attr("href").length; i++) {
						var c = $(this).attr("href").charAt(i);
						if (c < "0" || c > "9") {
							break;
						}
						page += c;
					}
					if (!page) {
						page = 0;
					}	
				}
				else {
					var page = 0;
				}
				
				$(this).click(function() {
					if (typeof comments[page] != "undefined") {
						$("div.comments", $('.unit-mu_rating_engine')).replaceWith(manipulateCommentForm(comments[page]));
						manipulatePaginationLinks(additionalUpDownClickHandler);
						setClickHandlers();
						$('.updown-widget').find('.updown-vote a').click(additionalUpDownClickHandler);
						setAutoGrow(); //in nelonen.js
						$('div.comments', $('.unit-mu_rating_engine')).addClass('standard3Column column1');	
						return false;
					}	
				});
				
				$(this).attr("href", "#");
			});			
		}

		moveInfo();
		
		if( $.cookie('isAdmin') == 1 || $.cookie('isEditor') == 1 ){
			$('.showToEditor').show();
		}
		else{
			$('.showToEditor').hide();
		}
		
		// Shows edit and delete links on user's own items.
		$('.showToUser'+user.id).show();
		
	});	
}


// refresh the rating stars
function refreshRatingStars(rating) {
	var rate = Math.round(rating);
	//clear stars	
	for(i=0; i<$('.starRate li').length; i++){
		$('.starRate li').eq(i).removeClass('selected');
	}	
	//set stars
	for(i=0; i<rate; i++){
		$('.starRate li').eq(i).addClass('selected');
	}
	
	//set stars
	for(i=0; i<rate; i++){
		$('.starRated li').eq(i).addClass('selected');
	}
}

//move item description and extra info below media item
function moveInfo(){
	$('#ratingItemDecriptionNew').html($('#ratingItemDescription').html());
	$('#extraInfoNew').html($('#extraInfo').html());
}

//user rate item
function rateItem(score){
	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	
	$.post(site_url+"ajax/vote_item/", {ratingEngineId: ratingEngineId,currentItemId: currentItemId, score: score, sessionName : sessionName}, function(data) {
		data = eval("("+data+")");
		if (data['result']==1){
			showItemDetail();
		}
	});
}


//display media set block
function showMediaSet(){

	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	
	$.get(site_url+"ajax/get_media_set_by_item/", {ratingEngineId: ratingEngineId, currentItemId: currentItemId}, function(data) {
		//, sessionName : sessionName was in the ajax param before
		data = eval("("+data+")");
		$('#mediaSet').html(data['output']);
		
		var direction = '';
		
		//Rating engine media set
		$('#reMediaSetUp').click( function() {
			direction = 'up';
		});
		
		$('#reMediaSetDown').click( function() {
			direction = 'down';
		});
		
		if( $('#horizontalCarousel .horizontal-list li').length > 5 ){
			// Make the arrows visible
			$('#reMediaSetLeft').css('display', 'block');
			$('#reMediaSetRight').css('display', 'block');
		
			var controls = $('#hidden-controls').val();
			controls = controls.split(',');

			$('#horizontalCarousel').jCarouselLite({
				btnNext: controls[1],
		        btnPrev: controls[0],
		        start: 0,
				circular: false,
		        visible: 5,
		        vertical: false,
		        beforeStart: function(a) {
			        if( direction == 'left' ){
			        	$('#horizontalCarousel li.active').removeClass('active').prev().addClass('active');
			        }
			        else{
			        	$('#horizontalCarousel li.active').removeClass('active').next().addClass('active');
			        }
			        $('#horizontalCarousel li.active img').trigger('click');
			    }
			});
		
		}
		
				
		selectMedia();
	});
}

//set current media class
function selectMedia() {
	if( $('#mediaToRateContent img').length ){
		//image
		var mediaId = $('#mediaToRateContent img').attr('id');
	}
	else if( $('#mediaToRateContent embed').length ){
		//video
		var mediaId = $('#mediaToRateContent embed').attr('id').substring(8);
	}
	
	$('#thumb-'+ mediaId).parent().parent().siblings().removeClass('active');		
	$('#thumb-'+ mediaId).parent().parent().addClass('active');
	
	moveInfo();
}

//user select one of the media inside media set
function selectMediaSet(mediaId){
	showMedia(mediaId);
}

//handle click from item list
function findItem(itemId, totalItems) {
	
	//get total number of items
	var total = parseInt(totalItems);

	//get clicked list position
	var pos = $('#li-'+ itemId).attr('class');
	
	//get current offset
	var offset = $('#offset').val();
	offset = parseInt(offset);
			
	//calculate new offset change based on clicked item
	var pos = parseInt(pos);
	switch(pos)	{
		case 1:
		  offset = offset - 2;
		  //if start of list		  
		  if(offset <= 0) {
		  	offset = 0;
		  }		  	  
		  break;
		case 2:
		  offset = offset - 1;
		  //if start of list
		  if(offset < 1) {
		  	offset = 0;
		  }			  	  
		  break;
		case 3:
		  //no change
		  break;
		case 4:
		  offset = offset + 1;
		  //if end of list
		  if(offset >= (total-4)){
		   	offset = offset - 1; 
		  }
		  break;
		case 5:
		  offset = offset + 2;		  		  
		  //if end of list		  
		  if(offset >= (total-3)){
		   	offset = offset - 2; 
		  }
		  break;				
	}	
	$('#offset').val(offset);
	$('#currentItemId').val(itemId);
	
	if( pageLimit == 5 ){
		showItemList(offset, pageLimit);
	}
	else{
		selectItem(itemId);
	}

	return false;
}

//item list next arrow
function nextItem() {
	var nextItem = $('ul#topCarousel li.active').next().attr('id');
	$('#'+nextItem+ ' img').trigger('click');	
}

//item list previous arrow
function previousItem() {
	var previousItem = $('ul#topCarousel li.active').prev().attr('id');
	$('#'+previousItem+ ' img').trigger('click');	
}

//Hide navigation arrows on item list
function hideNav(totalItems, offset) {
	if(offset == 0){
		if( $('#topCarousel li').eq(0).hasClass('active') ){
			$('#itemListLeft').addClass('disabled');
		}
	}
	
	offset = parseInt(offset);
	if( offset + 5 == totalItems && $('#topCarousel li').eq(4).hasClass('active') ){
		$('#itemListRight').addClass('disabled');
	}
}

//display media item list
function showItemList(offset, limit){
	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	var selectedCategory = $('#category').val();
	var itemSortType = $('#itemSortType').val();
	$.get(site_url+"ajax/get_item_list/", {ratingEngineId: ratingEngineId, currentItemId: currentItemId, offset: offset, limit: limit, selectedCategory: selectedCategory, itemSortType: itemSortType}, function(data) {
		//, sessionName : sessionName was in the ajax param before	
		data = eval("("+data+")");
		if (data['result']==1){
			$('#itemList').html(data['output']).show();
			$('#mediaSet').show();
			$('#currentItemId').val(data['additional']['currentItemId']);					
			
			// Don't reset the currently playing song when browsing. Only set the item
			// directly after page load.
			if(window.ratingEngineFirstLoad || ratingEngineBrowserMode == 'film') {
				window.ratingEngineFirstLoad = false;
				selectItem(data['additional']['currentItemId']);			
			}

			hideNav(data['additional']['totalItems'], $('#offset').val());
			
			if( pageLimit != 5 && data['additional']['totalItems'] > 16){
				pagination(pageLimit, data['additional']['totalItems']);
			}	
		}
		else{
			$('#itemList').html('').hide();
			$('#mediaSet').html('').hide();
			$('#itemDetail').html(data['errorMessage']);
			$('#mediaToRate').html('');
			$('#ratingItemDecriptionNew').html('');
			$('#extraInfoNew').html('');
		}
		
		return false;
	});	
}

//display media item list
function showItemListOnly(offset, limit){
	//get current info from hidden field
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	var selectedCategory = $('#category').val();
	var itemSortType = $('#itemSortType').val();
	$.get(site_url+"ajax/get_item_list/", {ratingEngineId: ratingEngineId, currentItemId: currentItemId, offset: offset, limit: limit, selectedCategory: selectedCategory, itemSortType: itemSortType}, function(data) {
		//, sessionName : sessionName was in the ajax param before
		data = eval("("+data+")");
		if (data['result']==1){	
			$('#itemList').html(data['output']);
			$('#currentItemId').val(data['additional']['currentItemId']);					
			$('#itemList').createInstances();				
		}
		else{
			$('#itemList').html('');
			$('#mediaSet').html('');
			$('#itemDetail').html(data['errorMessage']);
			$('#mediaToRate').html('');
		}
		
		return false;
	});	
}

//user select item to rate
function selectItem(itemId) {
	$('#currentItemId').val(itemId);
	showMedia(0);
	showMediaSet();
	showItemDetail();
	$('#li-'+ itemId).siblings().removeClass('active');
	$('#li-'+ itemId).addClass('active');	
}

//show message
function showMessage(message, error, isEdit){
	$('#messageError').hide();
	$('#messageOK').hide();
	$('#messageError').empty();
	$('#messageOK').empty();
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();

	if (message!=""){
		if (error == 1){
			$('#messageError').show();
			$('#messageOK').hide();
			$('#messageError').html(message);
			$("#mediaSet").empty();	
			$('#itemList').empty();
			if (isEdit==1){
				showEditItemForm(ratingEngineId, currentItemId);
				showItemListOnly(0, 5);
			}
			else{
				showUserSubmissionForm();
				showItemListOnly(0, 5);
			}
			
			return false;
		}
		else if(error == 2) {
			// fatal error that we don't need to recover from
			$('#messageError').show();
			$('#messageOK').hide();
			$('#messageError').html(message);
		}
		else{
			$('#messageOK').show();
			$('#messageOK').html(message);
			$('#messageError').hide();
		}
	}
	$('#message').val('');
	$('#error').val(0);

	offset = 0;
	
	showItemList(offset, pageLimit); //get 5 items
}

//clear message
function clearMessage(){
	$('#message').val('');
	$('#error').val(0);
	$('#messageError').empty();
	$('#messageOK').empty();
	
	$('#messageError').hide();
	$('#messageOK').hide();
}

//user select category
function selectCategory(){
	$('#currentItemId').val(0);
	clearMessage();
	showItemList(0, pageLimit);
}

/*
 * select item type: 1 = all, 2 = latest, 3 = best of week, 4 = best of month
 * 5 = highest rated, 6 = lowest rated, 7 = most rated, 8 = most commented
 *
 *
 */
function selectItemSortType(type){
	$('#itemSortType').val(type);
	
	for (var i=1;i<=8;i++){
		if (type==i){
			$('#itemType-'+i).addClass("itemSortSelected");
		}
		else{
			$('#itemType-'+i).removeClass("itemSortSelected");
		}
	}
	$('#currentItemId').val(0);
	$('#messageError').empty();
	$('#messageOK').empty();
	
	$('#messageError').hide();
	$('#messageOK').hide();
	showItemList(0, pageLimit);
}

//delete an item
function deleteItem(ratingEngineId,itemId){
	var answer = confirm("Oletko varma?");
	if (answer){
		$.post(site_url+"ajax/delete_item/", {ratingEngineId: ratingEngineId, itemId: itemId, sessionName : sessionName}, function(data) {
			data = eval("("+data+")");

			if (data['result']==1){
				//calling the drupal node deletion callback from here with AJAX
				$.get(tobeDeletedNodeURL);
				$('#currentItemId').val(0);
				showMessage(data['output'], 0, 0);
			}
		});
	}
}

//edit an item
function showEditItemForm(ratingEngineId,itemId){
	$('#ratingContainer').hide();
	$('#userSubmissionButton').hide();
	$('#userSubmissionContainer').show();
	var vals = $('#formVals').val();
	$.post(site_url+"ajax/show_edit_item_form/", {ratingEngineId: ratingEngineId, sessionName : sessionName, itemId: itemId, vals: vals}, function(data) {
		data = eval("("+data+")");
		if (data['result']!=0){
			$('#userSubmissionContainer').html(data['output']);
			
			$('#uploadedFilesContainer img').hover(
				function(){
					$(this).css('border', 'solid red 2px');
				},
				function(){
					$(this).css('border', 'none');
				}
			)
		}
	});
	
}

//remove a files from an item when editing item
function editItemRemoveFile(fid){
	var currentItemId = $('#currentItemId').val();
	var ratingEngineId = $('#ratingEngineId').val();
	var answer = confirm("Haluatko varmasti poistaa tämän tiedoston?");
	if (answer){
		$.post(site_url+"ajax/remove_file_from_item/", {ratingEngineId: ratingEngineId, sessionName : sessionName, currentItemId: currentItemId, fid: fid}, function(data) {
			data = eval("("+data+")");
			if (data['result']!=0){
				$('#uploadedFilesContainer').html(data['output']);
				$('#uploadedFilesContainerMsg').removeClass('message error hidden');
				$('#uploadedFilesContainerMsg').addClass('message ok');
				$('#uploadedFilesContainerMsg').html("Tiedosto on poistettu.");
			}
			else{
				if (data['errorMessage']=='one file left'){
					$('#uploadedFilesContainerMsg').removeClass('message ok hidden');
					$('#uploadedFilesContainerMsg').addClass('message error');
					$('#uploadedFilesContainerMsg').html("Vain yksi kuva jäljellä. Sinun täytyy lisätä kuva ennen kuin voit poistaa tämän kuvan.");
				}
			}
		});
	}
}

/**
 * @param limit Integer The current limit for this section
 * @param length Integer The total amount of items available, returned in the JSON data.
 *
 */

function pagination(limit, length){
	//number of pages
	var noPages = Math.ceil(length/limit);
	var currentPage = pagination_currentPage;

	//active class for first page
	if(currentPage == 1){
		var activeClass = ' class="active"';
	}
	else{
		var activeClass = '';
	}

	var navOutput = '<li><a'+activeClass+' href="0">1</a></li>';

	if(noPages > 7){
		if(currentPage <= 4){
			for( i=2; i < 7; i++){
				offset = (i-1) * limit;
				//active class for current page
				if((currentPage-1) * limit == offset){
					activeClass = ' class="active"';
				}
				else{
					activeClass = '';
				}
				navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
			}
			navOutput += '<li class="rightDot">...</li>';
		}
		else if(currentPage >= (noPages - 4)){
			var pageFrom = noPages - 5;
			var pageTo = noPages;

			navOutput += '<li class="leftDot">...</li>';
			for( i=pageFrom; i < pageTo; i++){
				offset = (i-1) * limit;
				//active class for current page
				if((currentPage-1) * limit == offset){
					activeClass = ' class="active"';
				}
				else{
					activeClass = '';
				}
				navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
			}
		}
		else{
			var pageFrom = currentPage - 2;
			var pageTo = pageFrom + 5;

			navOutput += '<li class="leftDot">...</li>';
			for( i=pageFrom; i < pageTo; i++){
				offset = (i-1) * limit;
				//active class for current page
				if((currentPage-1) * limit == offset){
					activeClass = ' class="active"';
				}
				else{
					activeClass = '';
				}
				navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
			}
			navOutput += '<li class="rightDot">...</li>';
		}
	}
	else{
		for(i=2; i < noPages; i++){
			if( i==1 ){
				offset = 0;
			}
			else{
				offset = (i-1) * limit;
			}
			if(currentPage == i){
				activeClass = ' class="active"';
			}
			else{
				activeClass = '';
			}
			navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
		}
	}

	//active class for last page
	if(currentPage == noPages){
		activeClass = ' class="active"';
	}
	else{
		activeClass = '';
	}
	navOutput += '<li><a'+activeClass+' href="'+(noPages-1)*limit+'">'+noPages+'</a></li>';

	$('#itemList .vfPaging').html('');
	$('#itemList .vfPaging').html(navOutput);
	$('#itemList .vfPaging').show();
	
	//register pagination clicks
	$('#itemList .pagination li a').click( function() {
		//get the offset
		var offset = $(this).attr('href');
		if( offset.indexOf('/') ) {
			offset = offset.substr(offset.lastIndexOf('/')+1);
		}
		showItemList(offset, pageLimit);
		pagination_currentPage = (offset/limit)+1;
		
		return false;
	});
	
}	

function rockstarComments(loop){
	//Rockstarba Comments
	
	if( loop == 1 || (loop == 2  && $('#mediaToRateContent div.comments').length == 0)){
		$('#mediaToRateContent').append($('div.comments', $('.unit-mu_rating_engine')));
		$('<a href="#" class="commentCount">Kommentoi</a>').insertAfter('.box h2', $('.unit-mu_rating_engine .comments .box'));
	}
	
	//Comment link event
	$('.commentCount').click( function(){
		if( $(this).hasClass('open') ){
			$('.comment', $('#mediaToRateContent')).hide();
			$(this).removeClass('open');
			$(this).text($(this).text().substr(0, $(this).text().length-2)+' >>');
		}
		else{
			//show comment box
			$(this).addClass('open');
			$(this).text($(this).text().substr(0, $(this).text().length-2)+' <<');
			$('.comment', $('#mediaToRateContent')).show();
		}
		return false;
	});
	
	var commentCount  = $('.comment', $('.unit-mu_rating_engine .comments')).length;

	if( commentCount !=0 ){
		if( commentCount == 1){
			$('.commentCount').html(commentCount+' Kommentti >>');
		}
		else{
			$('.commentCount').html(commentCount+' Kommenttia >>');
		}
	}
	else{
		$('.commentCount').hide();
	}
	
	$('.rockstarbaReTemplates div.comments', $('.unit-mu_rating_engine')).show();
	$('h2.comments').hide();
	
}

function reinitializeAddThis(){
      if (window.addthis){
         window.addthis.ost = 0;
         window.addthis.ready();
         
        
      }
   }
