var selectedRecBooks = [];

function renderRecList(offset) {
	if (selectedRecBooks.length == 0) {
		$('recommendations').style.display = 'none';
		if ($('arrow_left')) $('arrow_left').style.display = 'none';
		if ($('arrow_right')) $('arrow_right').style.display = 'none';
		if(navigator.appName.indexOf("Microsoft") > -1){
			$('no_recommendations_box').style.display = 'block';
		} else {
			$('no_recommendations_box').style.display = 'table-cell';
		}
		allowTagsCloud = 0;

		return;
	} else {
		//allowTagsCloud = 1;
		//$('no_recommendations_box').style.display = 'none';
		/*if(navigator.appName.indexOf("Microsoft") > -1){
			$('recommendations').style.display = 'block';
		} else {
			$('recommendations').style.display = 'table-cell';
		}
		$('recommendations').style.verticalAlign = 'top';*/
	}
	
	
	if (!offset) offset = 0;
	var width = 4;
  try {
    width = recsPerPage;
  } catch (ex) {}

	try {
		if (recPaneWidth)
			width = recPaneWidth;
		} catch (e) {}

	remain = width;
	if (selectedRecBooks.length - offset < width)
		remain = selectedRecBooks.length - offset;
	
	div = document.createElement('div');
  var onBs, addtoBs, addtoBsIcon;
	for (i = offset; i < offset+remain; i++) {
		book = selectedRecBooks[i];
		var book_id = book.Book['id'];
		bookdiv = document.createElement('div');
		bookdiv.id='C'+book.Book['id'];
		bookdiv.className='book';
		bookdiv.style.display='block';
		a = document.createElement('a');
		a.href="/books/bookprofile/"+book_id;
		
		cimg = document.createElement('img');
		cimg.id = 'B'+book_id;
		cimg.className = 'covers_img';
		cimg.style.height = '100px';
		cimg.style.width  = '64px';
		cimg.src = '/img/no_image_available_large.png';
		if (book.Cover.length > 0) {
				cimg.src = '/img/'+book.Cover;
		}
		a.appendChild(cimg);
		
		bookdiv.appendChild(a);
		
		bookdiv.appendChild(document.createElement('br'));
		arv1 = document.createElement('input');
		arv1.id = '_arv_rating_'+book_id;
		arv1.type = 'hidden';
		arv1.value = book.rating;
		arv1.name='data[Rating][Bar]';
		bookdiv.appendChild(arv1);
		arv2 = document.createElement('input');
		arv2.id = '__arv_rating_'+book_id;
		arv2.type = 'hidden';
		arv2.value = book_id;
		arv2.name='data[Rating][Bar]';
		bookdiv.appendChild(arv1);

    ratingBar = document.createElement('div');
    ratingBar.className = 'rating-bar';
    
    ratingBox = document.createElement('div');
    ratingBox.className = 'rating-box';
    ratingBar.appendChild(ratingBox);
    
    ratingStars = document.createElement('span');
    ratingStars.className = 'stars';
    ratingStars.title = AVERAGE_RATING+': '+book.rating;
    ratingStars.style.backgroundPosition = '0 -'+(book.rating*32)+'px';
    ratingStars.style.margin = '8px 0';
    ratingStars.innerHTML = '&nbsp;';
    ratingBox.appendChild(ratingStars);
    
    bookdiv.appendChild(ratingBar);
    
    // Add to BS button
    /*addtoBs = document.createElement('p');
    
    onBs = true;
    addtoBsIcon = new Element('img', {
      src: onBs ? '/img/remove_off.png' : '/img/add_off.png',
      title: onBs ? INFO_REMOVE_FROM_BOOKSHELF : INFO_ADD_TO_BOOKSHELF,
      events: {
        click: function() {
          toggle_img_ab_checkbox(this);
          setBookShelf(event);
        }
      }
    });
    
    addtoBs.appendChild(addtoBsIcon);
    
    bookdiv.appendChild(addtoBs);*/
		
		tp = document.createElement('p');
		
		ta = document.createElement('a');
		ta.className = 'book_title';
		ta.href= '/books/bookprofile/'+book_id;
		ta.innerHTML = book.Book.title_lead+' '+book.Book.title;
		tp.appendChild(ta);

		bookdiv.appendChild(tp);

		ap = document.createElement('p');
		
		var authors = book.authors;
		
		for(authcnt = 0; authcnt < authors.length; authcnt++) {
			author = authors[authcnt];
			aa = document.createElement('a');
			aa.href= '/authors/profile/'+author['id']+'/'+book_id;
      aa.className = 'grey_text';
			aa.innerHTML = author.name;
			ap.appendChild(aa);
		}
		bookdiv.appendChild(ap);
		
		div.appendChild(bookdiv);
	}

	while ($('recommendations').hasChildNodes()) {$('recommendations').removeChild($('recommendations').lastChild);}
	$('recommendations').appendChild(div);
	
	// Determine arrows
	if (offset > 0)
		$('arrow_left').style.display = canSee();
	else
		$('arrow_left').style.display = 'none';
		
	if (offset + width < selectedRecBooks.length)
		$('arrow_right').style.display = canSee();
	else
		$('arrow_right').style.display = 'none';

	updateBDEvents();
}

function scrollRecPane(val){
	var width = 4;
  try {
    width = recsPerPage;
  } catch(ex) {}
	try {
	  if (recPaneWidth) {
		  width = recPaneWidth;
    }
	} catch (e) {}
	if (val == 0) {
		start = 0;
	} else {
		start += val * width;
	}
	renderRecList(start);
}

function recommendationsLoadingIndicator() {
if ($('arrow_left')) $('arrow_left').style.display = 'none';
	if ($('arrow_right')) $('arrow_right').style.display = 'none';
	if ($('recommendations')) loadingIndicator('recommendations');
}

function filterByCat(){
	var categoryList = new Array();
	var filteredBookList = new Array();

	// Determine which fiction categories are selected
	try {
    for(var c = 0; c < fictionCategories.length; c++) {
      if ($('_L_C'+fictionCategories[c]).style.fontWeight == 'bold')
        categoryList[categoryList.length] = fictionCategories[c];
    }
  } catch (e) {}

	// Determine which nonfiction categories are selected
  try {
    for(var c = 0; c < nonfictionCategories.length; c++) {
      if ($('_L_C'+nonfictionCategories[c]).style.fontWeight == 'bold')
        categoryList[categoryList.length] = nonfictionCategories[c];
    }
  } catch (e) {}

	// Only allow searching all of (non-)fiction if no specifics are selected
	if (categoryList.length == 0) {
    try {
      if ($("ffiction").style.display == 'block')
        categoryList = categoryList.concat(fictionCategories);
      
      if ($("fnonfiction").style.display == 'block')
        categoryList = categoryList.concat(nonfictionCategories);
    } catch (e) {
      if(imgChecked($('fiction'))) {
        categoryList = categoryList.concat(fictionCategories);
      }
      if(imgChecked($('nonfiction'))) {
        categoryList = categoryList.concat(nonfictionCategories);
      }
    }
	}
  
	if (categoryList.length > 0) {
		for(var rec = 0; rec < recommendedBooks.length; rec++) {
			(function() {
				var book = recommendedBooks[rec];
				var bookCats = book['categories'];
				for(var bc = 0; bc < book['categories'].length; bc++) {
					var bookCat = book['categories'][bc];
					for(var cl = 0; cl < categoryList.length; cl++) {
						if (bookCat == categoryList[cl]) {
							filteredBookList[filteredBookList.length] = book;
							return;
						}
					}
				}
			})();
		}
	} else {
		//filteredBookList = recommendedBooks;
		filteredBookList = globalRecommendedBooks;
  }
	
	// Remember the books for the current category
	selectedCatBooks = filteredBookList;
  
	selectedRecBooks = selectedCatBooks;
  renderRecList();
}
function toggleTag(el){

	if (el.className == 'tag_selected') {
		el.className = 'tag';
		filterTag = '';
	}
	else {
		// Select the tag
		el.className = 'tag_selected';
		if (filterTag != '')
			$(filterTag).className = 'tag';
		
		filterTag = el.id
	}
	
	filterByCat();
 	filterByTag();
	loadTagSet();

}

function filterByTag(){
	var matchCount = 0;

		if (filterTag != '') {
		
			var subset = new Array();
			
			for(i = 0; i < selectedCatBooks.length; i++) {
				var book = selectedCatBooks[i];
				for (var j = 0; j < book.tags.length; j++) {
					if (book.tags[j] == $(filterTag).innerHTML) {
						subset[subset.length] = book;
						break;
					}
				}
			}
			selectedRecBooks = subset;
		}
	 	scrollRecPane(0);
}	



function scrollRec(val){
	
	var books = $('all_recs').getChildren();
	var width = parseInt($('_rec_shown').value);
	
	/** -1 means left a page, 1 means forward a page, 0 means start at beginning **/
	var start = parseInt($('_rec_start').value);

	if (val == 0) {
		start = 0;
	} else {
		start += val * width;
	}
	if (start < 0) start = 0;
	var showCount = 0;
	var showBook = false;
	var displayed = 0;
	
	if(start >= books.length) return 0;
	
		
	for(var i = 0; i < books.length; i++){
		showBook = false;
		
		if ($('rec_tag').value != '') {
			var tag_id = $('rec_tag').value;
			var tag_name = $(tag_id).innerHTML;
			var book_id = books[i].id.substr(1);
			var book_tags = eval($("btag_"+book_id).value);
			for (var j = 0; j < book_tags.length; j++) {
				if (book_tags[j] == tag_name) {
					showCount++;
					showBook = true;
					break;
				}
			}
		} else {
			showCount++;
			showBook = true;
		}
		
		if (showBook && showCount > start && showCount <= start+width) {
			books[i].setStyle('display', canSee());
			displayed++;
		} else {
			books[i].setStyle('display', 'none');
		}
	}
	
	if (showCount < start+width) {
		$('arrow_right').setStyle('display', 'none');
	} else {
		$('arrow_right').setStyle('display', canSee());
	}

	if (start == 0) {
		$('arrow_left').setStyle('display', 'none');
	} else {
		$('arrow_left').setStyle('display', canSee());
	}

	$('_rec_start').value = start;
}

function loadSimilar(book_id){
	recommendationsLoadingIndicator();
	if (!book_id) {
		try {
			if (currentlyReadingID)
				book_id = currentlyReadingID;
		} catch (e) {}
	}
	
	new Request({
    url: LIVING_SITE_URL+"/recommendations/recommendations2?book_id="+ book_id + '&similar=1&ts=' + new Date().getTime(),
		method: 'get',
		evalScripts: true,
		onComplete: function(){
			response = eval('('+this.response["text"]+')');
			selectedRecBooks = response.books;
			scrollRecPane(0);
	    }
	  }).send();
	  try {
	  $('similar_arrow').style.display="inline";
	  $('headSuggestBooks').className='recpane';
	  $('headSimilarBooks').className='recpane_selected';
	  } catch (e) {}
	}
