/* 
 * This javascript file contains the required code to load the latest reviews.
 * Loaded reviews get displayed using the logic in this file and the HTML gets
 * appended to a div thats passed as a parameter to the loadReviews() method.
 *
 * To use simply include this js file, and where you want to load the reviews
 * insert this code:
 *
    <div id="div_reviews">
        <script type="text/javascript">
            $(document).ready(function() {
                loadReviews("div_reviews");
            });
        </script>
    </div>
 *
 */

var reviews_home_url = "http://www.koorong.com";
var reviews_search_url = "http://www.koorong.com/search/";

// Private callback function
function setReviews(div, reviews)
{
    $("#" + div).html("");

    for (var i=0; i<reviews.length; i++)
    {
        $("#" + div).append("<div style='padding-bottom:10px;'>");
        $("#" + div).append("<span style='font-weight: bold; color: #333; font-size: 0.9em;'>" + reviews[i].title + "</span> <br />");
        $("#" + div).append("<img src='" + reviews_home_url + "/images/customerreviews/" + reviews[i].rating + "stars.gif' alt='" + reviews[i].rating + " stars' />  <br />");
        $("#" + div).append("<a href='" + reviews_search_url + "product/view.jhtml?code=" + reviews[i].product.code + "&tabs=reviews'>" + reviews[i].product.title + "</a><br />");

        var authors = "";
        for (var j=0; j<reviews[i].product.authors.length; j++)
        {
            authors += reviews[i].product.authors[j].name;
            if (j < reviews[i].product.authors.length-1) authors += ", ";
        }

        $("#" + div).append("<span style='font-size: 0.8em;'><em>" + authors + "</em></span>");
        $("#" + div).append("</div>");
    }
}

// Recent Reviews public initialisation method
// Input param: ID of a div (in text format) that you wish to load the reviews into
// Output: no synchronised output
function loadReviews(div)
{
    var url = reviews_search_url + "review/recentReviewsJson.jhtml?callback=?";
    //var url = "http://localhost:8080/search/review/recentReviewsJson.jhtml?callback=?";

    // Show a loading image
    $("#" + div).html("<div style='padding:20px; font-weight: bold; color: #333; margin-left:auto; margin-right:auto; text-align:center;'><img src='" + reviews_search_url + "images/loader.gif' alt='images/loader'/><br/>Loading Recent Reviews...</div>");

    $.ajax({
        url: url,
        cache: false,
        dataType: "jsonp",
        success: function(reviews) {
            setReviews(div, reviews);
        },
        error: function() {
            $("#" + div).html("The Recent Reviews are currently unavailable.");
        }
    });
}
