// global variables
var nReviews = 0;
var aReviews = new Array();

var nCurrentRating = 0, nPreviousRating = 0;
var nHighestTotal = 0, nCurrentTotal = 0;
var nAverageRating = 0;

// functions
function sortReviewsBy(sCriteria) {
	switch(sCriteria) {
		case 'recent':
			aReviews.sort(function(a,b){ return b['id'] - a['id']; });
		break;
		
		case 'highest':			
		case 'lowest':
			if (sCriteria == 'lowest') {
				aReviews.sort(function(a,b){ return a['rating'] - b['rating']; });
			} else {
				aReviews.sort(function(a,b){ return b['rating'] - a['rating']; });
			}
		break;
	}
	
	$.each(aReviews, function(item, review) {
		eReview = '#productreview-' + item;

		$(eReview + ' p.productreviews-item-info span.reviews-body-rate img.productreviews-item-rating').attr('src', sImagesPath + 'rating' + review['rating'] + '.gif');
		$(eReview + ' p.productreviews-item-info span.reviews-body-rate img.productreviews-item-rating').attr('alt', 'Rated ' + review['rating'] + ' out of 5');
		$(eReview + ' p.productreviews-item-info span.reviews-body-author').html(review['author']);
		$(eReview + ' p.reviews-body-message').html(review['content']);
	});
	
	/*
	// uncomment to test the order
	$.each(aReviews, function(item, value) {
		alert(value['id'] + "-" + value['rating']);
	});
	*/
}

$(document).ready(function() {
	// iterate through reviews
	$("li.productreviews-item").each(function(index) {
		// grok the rating of this review
		nRating = $(this).children('p.productreviews-item-info').children('span.reviews-body-rate').children('img:first').attr('alt').substr(6,1);
		sAuthor = $(this).children('p.productreviews-item-info').children('span.reviews-body-author').html();
		sContent = $(this).children('p.reviews-body-message').html();
		
		// set 'id' of each review
		$(this).attr('id', function() {
			return 'productreview-' + index;
		});

		oReview = new Object();
		
		// add rating to review array
		oReview['id'] = nReviews;
		oReview['rating'] = nRating;
		oReview['author'] = sAuthor;
		oReview['content'] = sContent;
		
		aReviews[nReviews] = oReview;
		
		// increase the number of reviews
		nReviews += 1;
	});

	aSortedRatings = aReviews.sort(function(a,b) { product = a - b; return product; });

	$.each(aSortedRatings, function(index,oReview) {
		nCurrentRating = oReview['rating'];
		if (nCurrentRating == nPreviousRating) {
			nCurrentTotal++;
		} else {
			// new rating in sequence
			nCurrentTotal = 1;
		}
		
		if (nCurrentTotal > nHighestTotal) {
			nHighestTotal = nCurrentTotal;
			nAverageRating = nCurrentRating;
		}
		nPreviousRating = nCurrentRating;
	});

	if (nReviews > 0) {
		$('#productreviews-sort').css('display', 'inline');
		$('#productreviews-average').html('<img src="' + sImagesPath + '/rating' + nAverageRating + '.gif" /><br />average customer rating<br />(' + nReviews + ' reviews)');
	}
});
