// JavaScript Document
$(document).ready(function(){
	
	
	var comment_array = new Array();
	var comment_up_array = new Array();
	var comment_li;

	if($('#allcomments').length!=0){
            // If the comments block exists, proceed with preparation of the array.
            comment_li = $("#allcomments").children("li");
            // Prepare the array with all comments + thumbs up
            comment_li.each(function(index){
                    comment_array[index] = new Array();
                    comment_array[index][0]=($(this)); // Original comments in the original order.
                    comment_array[index][1] = $(this).find("span[id*=up]").text();
                    comment_array.reverse(); // default listing is most recent on the bottom. This will reverse it.

            });
        }

       
	
	$("#most_helpful").click(function(event) {

                event.preventDefault();
		//tmp = comment_array[0].children('span[id*=up]:first');
		// first hide all comments
                //$("#allcomments").children("li").fadeOut(300)
                $("#allcomments").children("li").remove();
                
                tmp_array = new Array();
                for(var i = 0; i < comment_array.length; i++)
                {
                    tmp_array.push(comment_array[i].slice());
                }
                // Sort the new array based on the second value, which is the thumbs up
                tmp_array.sort(sortfunction);

                for(var i=0; i<tmp_array.length; i++){
                    tmp_array[i][0].appendTo("#allcomments");
                }

                //$("#allcomments").children("li").fadeIn(300)
                //alert(comment_array[0]);

	});

        $("#most_recent").click(function(event){

            event.preventDefault();
            // Detach all the current list items
            $("#allcomments").children("li").remove();
            for(var i=0; i<comment_array.length; i++){
                comment_array[i][0].appendTo("#allcomments");
            }
        });
	
});

function sortfunction(a, b){
    if (a[1]<b[1]) return 1;
    if (a[1]>b[1]) return -1;
    return 0;
}

