// 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);
	
	$('.comments', $('.unit-mu_rating_engine')).hide();
	
	// Load current item from pagination component
	window.ratingEngineFirstLoad = true;
});


//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']);
		
		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']);
		
		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();

		initializeSingleItemNav();

		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( $('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();
					}
					
					rockstarComments('1', commentCount, false);
				});
			}
			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( $('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');
				
				rockstarComments('2', commentCount, false);
			}
		}
		
		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
				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');
						rockstarComments('1', commentCount, true);	
						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();
		}
	});
}

//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);
}

//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']);
			$('#currentItemId').val(data['additional']['currentItemId']);		
			
			if( data['additional']['totalItems'] > 16){
				pagination(pageLimit, data['additional']['totalItems']);
			}
			
			// Don't reset the currently playing song when browsing. Only set the item
			// directly after page load.
			if(window.ratingEngineFirstLoad || ratingEngineBrowserMode == 'film') {
				// If we are using the single item nav buttons we need to find the first
				// item of the loaded list and select it
				
				if( singleItemNavClick ){
					if( singleItemNavDirection == 'previous' ){
						if( singleItemPreviousId == '__' ){
							//No stored ID so load the last item of list
							selectItem( $('#itemList li.vfItem:last').attr('id').substr(3) );
						}
						else{
							//Stored ID so use it
							selectItem( singleItemPreviousId );
						}
					}
					else if( singleItemNavDirection == 'next' ){
						if( singleItemNextId == '__' ){
							//No stored ID so load first item of list
							selectItem( $('#itemList li.vfItem:first').attr('id').substr(3) );
						}
						else{
							//Stored ID so use it
							selectItem( singleItemNextId );
						}
					}
				}
				else{
					selectItem(data['additional']['currentItemId']);
				}
				window.ratingEngineFirstLoad = false;
				singleItemNavClick = false;		
			}
			
			totalItems = data['additional']['totalItems'];
		}
		else{
			$('#itemList').html('');
			$('#mediaSet').html('');
			$('#itemDetail').html(data['errorMessage']);
			$('#mediaToRate').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']);
		}
		else{
			$('#itemList').html('');
			$('#mediaSet').html('');
			$('#itemDetail').html(data['errorMessage']);
			$('#mediaToRate').html('');
		}
		
		return false;
	});	
}

//user select item to rate
function selectItem(currentItemId) {
	$('#currentItemId').val(currentItemId);
	showMedia(0);
	showItemDetail();
	
	//Store next and previous ID from current item
	singleItemPreviousId = '__';
	singleItemNextId = '__';
	
	if( typeof $('#itemList #li-'+currentItemId).prev().attr('id') != 'undefined' ){
		singleItemPreviousId = $('#itemList #li-'+currentItemId).prev().attr('id').substr(3);
	}
	if( typeof $('#itemList #li-'+currentItemId).next().attr('id') != 'undefined' ){
		singleItemNextId = $('#itemList #li-'+currentItemId).next().attr('id').substr(3);
	}
	
	//Store if this item is first or last
	singleItemFirst = false;
	singleItemLast = false;
	
	if( typeof $('#itemList #li-'+currentItemId).attr('id') != 'undefined' ){
		if( $('#itemList #li-'+currentItemId).hasClass('first-item') ){
			singleItemFirst = true;
		}
		if( $('#itemList #li-'+currentItemId).hasClass('last-item') ){
			singleItemLast = true;
		}
	}
	
	//Update stored page number to be that of current one
	singleItemNavPage = pagination_currentPage;
	
}

//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, commentNo, pagingClick){
	//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') ){
			//hide pager
			$('.pager', $('#mediaToRateContent')).hide();
			$('.comment', $('#mediaToRateContent')).hide();
			$(this).removeClass('open');
			$(this).text($(this).text().substr(0, $(this).text().length-2)+' >>');
		}
		else{
			//show comment box
			$('.pager', $('#mediaToRateContent')).show();
			$(this).addClass('open');
			$(this).text($(this).text().substr(0, $(this).text().length-2)+' <<');
			$('.comment', $('#mediaToRateContent')).show();
		}
		return false;
	});

	if( commentNo !=0 ){
		if( commentNo == 1){
			$('.commentCount').html(commentNo+' Kommentti >>');
		}
		else{
			$('.commentCount').html(commentNo+' Kommenttia >>');
		}
	}
	else{
		$('.commentCount').hide();
	}
	
	if( pagingClick ){ 
		$('.pager', $('#mediaToRateContent')).show();
		$('.commentCount').addClass('open');
		$('.commentCount').text($('.commentCount').text().substr(0, $('.commentCount').text().length-2)+' <<');
		$('.comment', $('#mediaToRateContent')).show();
	}
	
	$('.rockstarbaReTemplates div.comments', $('.unit-mu_rating_engine')).show();
	$('h2.comments').hide();
	
}

function reinitializeAddThis(){
   if (window.addthis){
      window.addthis.ost = 0;
      window.addthis.ready();
   }
}
 
//Item navigation
function itemSelection(currentItemId, obj) {

	//Force load of item as these are single item nav buttons and not pagination clicks
	window.ratingEngineFirstLoad = true;
	singleItemNavClick = true;

	//Check the current item is on the item list, otherwise reload the item list
	if( singleItemNavPage != pagination_currentPage ){
		if( singleItemFirst && singleItemNavDirection == 'previous' ){
			//Going backwards so need to reduce the stored page number
			singleItemNavPage--;
			offset = (singleItemNavPage - 1) * pageLimit;
		}
		else if( singleItemLast && singleItemNavDirection == 'next' ){
			//Going forwards so need to increse the stored page number
			singleItemNavPage++;
			offset = (singleItemNavPage - 1) * pageLimit;
		}
		else{
			//Normal action, we are staying on the stored page number
			offset = (singleItemNavPage - 1) * pageLimit;
		}
		
		//Update the item list pagination with stored so it shows correctly		
		pagination_currentPage = singleItemNavPage;
		
		//Load new item list		
		showItemList(offset, pageLimit);
	}
	else{
		//Force load of item as these are single item nav buttons and not pagination clicks
		window.ratingEngineFirstLoad = true;
		singleItemNavClick = true;
		
		if( singleItemFirst && singleItemNavDirection == 'previous' ){
			//We are going back 1 page from the page we are on se we can do this with triggering pagination click
			$('.vfPaging .active').parent().prev().find('a').trigger('click');
			singleItemNavPage--;
		}
		else if( singleItemLast && singleItemNavDirection == 'next' ){
			//We are going forward 1 page from the page we are on se we can do this with triggering pagination click
			$('.vfPaging .active').parent().next().find('a').trigger('click');
			singleItemNavPage++;
		}
		else{
			//Normal operation, check which way we are going and then load the stored ID item
			if( singleItemNavDirection == 'previous' ){
				selectItem( singleItemPreviousId );
			}
			else if( singleItemNavDirection == 'next' ){
				selectItem( singleItemNextId );
			}
		}
	}
	
	return false;
}  
 
function initializeSingleItemNav() {
	
	var str = window.location.href;
	var patt1=/iid=/gi;
	
	if( str.match(patt1) == null ){
		if( $('.vfPaging li').length ) {
			var offset = $('.vfPaging .active').attr('href');
			if( offset.indexOf('/') ) {
				offset = offset.substr(offset.lastIndexOf('/')+1);
			}
		}
		else{
			var offset = 0;
		}
	
		//Show correct buttons
		if( offset == 0 && $('#itemList ul.payload li.vfItem:first').attr('id').substr(3) == $('#currentItemId').val() ){
			$('.itemSinglePrevious').hide();	
		}
		else{
			$('.itemSinglePrevious').show();
		}
		
		if( totalItems - offset < pageLimit && $('#itemList ul.payload li.vfItem:last').attr('id').substr(3) == $('#currentItemId').val() ){
			$('.itemSingleNext').hide();	
		}
		else{
			$('.itemSingleNext').show();
		}
		
		//Bind event to buttons
		$('.itemSinglePrevious').bind('click', function() { 
			singleItemNavDirection = 'previous'; 
			itemSelection( $('#currentItemId').val(), $(this) ); 
			return false; 
		});
			
		$('.itemSingleNext').bind('click', function() { 
			singleItemNavDirection = 'next';
			itemSelection( $('#currentItemId').val(), $(this) ); 
			return false; 
		});
	}
	
}
