/******** Start Rating Script ***************************/
// Last Update: 1/15/2008 for the SmallBiz LMS
//
// Example:
//  <span id="SampleRating1Container"></span>
//  <script>
//      var MaxRating = 4;
//      var ID = 1;
//      var RatingCount = 27;
//      var RatingAverage = 2.3;
//      var UserName = null;
//      SampleRating1 = new RatingSetup("images/"," + MaxRating + ","SampleRating1");
//      SampleRating1.InitRating("SampleRating1Container"," + ID + "," + RatingCount + "," + RatingAverage + "," + UserName + ");
//  </script>";
//
// TODO:
//      Add 1/2 star capability
//      Put image paths in RatingSetup function
//      Put processor page in RatingSetup function

var processorBasePath = "/__services/processor";
var grayStarImageName = "rating_gray_nullstar.gif";         // Used for 
var grayNullStarImageName = "rating_gray_nullstar.gif";     // Used for no ratings no star
var goldStarImageName = "rating_gold_fullstar.gif";         // Used on mouseover full star
var goldNullStarImageName = "rating_gold_nullstar.gif";     // Used on mouseover no star
var greenStarImageName = "rating_green_fullstar.gif";       // Your rating full star
var blueStarImageName = "rating_blue_fullstar.gif";         // Not Used
var IndicatorImageName = "activemacwheel.gif";              // Processing Indicator

function RatingSetup(RatingImageBasePath,MaxRating,FunctionPrefix)
{
	this.RatingImageBasePath = RatingImageBasePath;
    this.MaxRating = MaxRating;
        
    this.arrRating = new Array();
    
    // Average rating
    this.RatingAverageIdx = 0;
    this.arrRating[this.RatingAverageIdx] = 0;
        
    // Rating count
    this.RatingCountIdx = 1;
    this.arrRating[this.RatingCountIdx] = 0;
    
    // My rating value
    this.MyRatingValueIdx = 2;
    this.arrRating[this.MyRatingValueIdx] = 0;
	
	// UserName value
    this.UserNameIdx = 3;
    this.arrRating[this.UserNameIdx] = "";
    
    this.FunctionPrefix = FunctionPrefix;
}

RatingSetup.prototype.WriteProperties = function()
{
	alert("RatingImageBasePath: " + this.RatingImageBasePath + " \n MaxRating: " + this.MaxRating + " \n arrRating: " + this.arrRating);
};

RatingSetup.prototype.UpdateRating = function(id,AverageRating,RatingCount,MyRating)
{
    this.arrRating[this.RatingAverageIdx] = parseFloat(AverageRating);

    if(MyRating != null)
    {
        this.arrRating[this.MyRatingValueIdx] = parseFloat(MyRating);
    }
    
    this.arrRating[this.RatingCountIdx] = (RatingCount == null) ? (parseFloat(this.arrRating[this.RatingCountIdx])+1) : RatingCount;
    
    this.RenderRating(id);
};

RatingSetup.prototype.RenderRating = function(id)
{
    for(i=1;i<=this.MaxRating;i++)
    {
        //document.getElementById("RatingStar" + id + "_" + i).src = ((this.arrRating[i] == 1) || (this.arrRating[this.MyRatingValueIdx] >= i)) ? ((this.arrRating[this.MyRatingValueIdx] >= i) ? this.RatingImageBasePath + goldStarImageName : this.RatingImageBasePath + goldStarImageName) : this.RatingImageBasePath + grayStarImageName;
        //document.getElementById("RatingStar" + id + "_" + i).src = ((this.arrRating[this.RatingAverageIdx] >= i) || (this.arrRating[this.MyRatingValueIdx] >= i)) ? ((this.arrRating[this.MyRatingValueIdx] >= i) ? this.RatingImageBasePath + greenStarImageName : this.RatingImageBasePath + blueStarImageName) : this.RatingImageBasePath + grayStarImageName;
		document.getElementById("RatingStar" + id + "_" + i).src = (this.arrRating[this.RatingAverageIdx] >= i) ? this.RatingImageBasePath + blueStarImageName : this.RatingImageBasePath + grayStarImageName;
    }

    var ratingInfo = "";

    if ((this.arrRating[this.RatingAverageIdx] == undefined) && (this.arrRating[this.MyRatingValueIdx] == 0))
    { ratingInfo = "This item is not yet rated."; }
    else
    { 
        // "Average rating : " + 
        ratingInfo = this.round_decimals(parseFloat(this.arrRating[this.RatingAverageIdx]),2) + " star";
        if(this.arrRating[this.RatingAverageIdx] != "1" && this.arrRating[this.RatingAverageIdx] != 1)
            ratingInfo += "s";
        ratingInfo += " (" + this.arrRating[this.RatingCountIdx] + " rating";
        if(this.arrRating[this.RatingCountIdx] != "1" && this.arrRating[this.RatingCountIdx] != 1)
            ratingInfo += "s";
        ratingInfo += ")"; 
    }

	this.ShowYourRating(id);
	    
    document.getElementById("RatingCaption" + id).innerHTML = ratingInfo;
};

RatingSetup.prototype.ShowYourRating = function(id)
{
    // Allow Anonymous
	//if (this.arrRating[this.UserNameIdx] != null && this.arrRating[this.UserNameIdx] != '' && this.arrRating[this.MyRatingValueIdx] != null && this.arrRating[this.MyRatingValueIdx] != 0) 
	if (this.arrRating[this.MyRatingValueIdx] != null && this.arrRating[this.MyRatingValueIdx] != 0) 
	{
	    if(document.getElementById("YourRating" + id))
	    {
	        var yourRating = "You rated this item " + this.arrRating[this.MyRatingValueIdx] + " star"
	        if(this.arrRating[this.MyRatingValueIdx] != "1" && this.arrRating[this.MyRatingValueIdx] != 1)
                yourRating += "s";
            yourRating += "."; 
            
            document.getElementById("YourRating" + id).innerHTML = yourRating;
            
            //Turn ON
            $("YourRating" + id).show();
        }
    }
};

RatingSetup.prototype.HighlightRating = function(id, r)
{
    for(i=1;i<=this.MaxRating;i++)
        document.getElementById("RatingStar" + id + "_" + i).src = (r > (i-1)) ? this.RatingImageBasePath + goldStarImageName : this.RatingImageBasePath + goldNullStarImageName;
    
    var ratingInfo = "Click to rate as " + r + " star";
    if(r != "1" && r != 1)
        ratingInfo += "s";
    document.getElementById("RatingCaption" + id).innerHTML = ratingInfo;
};

RatingSetup.prototype.RenderStars = function(id)
{
    var returnHTML = "";

    returnHTML += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" onmouseout=\"" + this.FunctionPrefix + ".RenderRating(" + id + ");\">";
    returnHTML += "<tr>";
    for(i=1;i<=this.MaxRating;i++)
	{
		// Allow Anonymous
		//if(this.arrRating[this.UserNameIdx] != null && this.arrRating[this.UserNameIdx] != '')
		//{
			// Logged In - Allow Rating
	        returnHTML += "<td onmouseover=\"" + this.FunctionPrefix + ".HighlightRating(" + id + "," + i + ");\" onclick=\"" + this.FunctionPrefix + ".SetRating(" + id + "," + i + ");\"><img id=\"RatingStar" + id + "_" + i + "\" src=\"" + this.RatingImageBasePath + grayStarImageName + "\" border=\"0\" width=\"13\" height=\"13\" /></td>";
		//}
		//else
		//	returnHTML += "<td><img id=\"RatingStar" + id + "_" + i + "\" src=\"" + this.RatingImageBasePath + grayNullStarImageName + "\" border=\"0\" width=\"13\" height=\"13\" /></td>";
	}
    returnHTML += "</tr>";
    returnHTML += "</table>";
    //returnHTML += "<a href=\"javascript:" + this.FunctionPrefix + ".WriteProperties()\">Status</a>";

    return returnHTML;
};

RatingSetup.prototype.RenderCaption = function(id)
{
    var returnHTML = "";

    returnHTML += "<span id=\"RatingCaption" + id + "\" class=\"RatingCaption\" nowrap></span>";
    //returnHTML += "<a href=\"javascript:" + this.FunctionPrefix + ".WriteProperties()\">Status</a>";

    return returnHTML;
};

RatingSetup.prototype.RenderProgress = function(id)
{
    var returnHTML = "";

    returnHTML += "<span id=\"RatingProgress" + id + "\" class=\"RatingProgress\" nowrap></span>";
    //returnHTML += "<a href=\"javascript:" + this.FunctionPrefix + ".WriteProperties()\">Status</a>";

    return returnHTML;
};

RatingSetup.prototype.InitRating = function(ContainerName,id,RatingCount,AverageRating,UserName)
{
    this.arrRating[this.RatingCountIdx] = (RatingCount == null) ? 0 : parseFloat(RatingCount);
    this.arrRating[this.RatingAverageIdx] = (AverageRating == null) ? 0 : parseFloat(AverageRating);
    
    // Allow Anonymous
    //if(UserName != null && UserName != "")
	//{
		this.arrRating[this.UserNameIdx] = UserName;
		
		//var url = processorBasePath + "?task=GetYourRating&ContentIdOrCode=" + id + "&ProfileIdOrCode=" + UserName;
		var url = processorBasePath + "?task=GetYourRating&id=" + id;  // Uses current user

		// Append current time to prevent caching
		var now = new Date();
		url = url + "&tm=" + String(now.getTime());
		
		var myAjax = new Ajax.Request(url, 
		{
			method: 'get', 
			evalScripts: true,
			asynchronous: false
		});
		//alert(myAjax.transport.responseText);
		var MyRating = myAjax.transport.responseText;
		//alert("MyRating " + MyRating);
		if(MyRating != "")
	        this.arrRating[this.MyRatingValueIdx] = parseFloat(MyRating);
	//}
    //else
	//{
	//	this.arrRating[this.UserNameIdx] = "";
    //    this.arrRating[this.MyRatingValueIdx] = null;
	//}
    
    document.getElementById("StarContainer" + id).innerHTML = this.RenderStars(id)
	//document.getElementById(ContainerName).innerHTML = this.RenderStars(id) + this.RenderCaption(id) + this.RenderProgress(id);
    
    this.RenderRating(id);
    
    this.ShowYourRating(id);
};

RatingSetup.prototype.SetRating = function(id,r) 
{
	// Allow Anonymous
	//if(this.arrRating[this.UserNameIdx] != null && this.arrRating[this.UserNameIdx] != '')
	//{
	    var destinationDiv = document.getElementById("RatingProgress" + id);
		
		//var url = processorBasePath + "?task=PostRating&ContentIdOrCode=" + id + "&ProfileIdOrCode=" + this.arrRating[this.UserNameIdx] + "&Rating=" + r;
		var url = processorBasePath + "?task=AddRating&id=" + id + "&AddRating=" + r; // Uses current user
	    
	    // Append current time to prevent caching
		var now = new Date();
		url = url + "&tm=" + String(now.getTime());
		
		destinationDiv.innerHTML = "<img src=\"" + this.RatingImageBasePath +  IndicatorImageName + "\" alt=\"Updating...\" title=\"Updating...\" border=\"0\" />";
		
		var myAjax = new Ajax.Updater(destinationDiv,url, 
			{
				method: "get", 
				evalScripts: true 
			});
	//}
};


/**************************************************************
round_decimals(original_number, decimals)

Parameters: 
original_number - the number to be rounded
decimals - the number of decimal places desired
***************************************************************/
RatingSetup.prototype.round_decimals = function(original_number, decimals) 
{
    var result1 = original_number * Math.pow(10, decimals);
    var result2 = Math.round(result1);
    var result3 = result2 / Math.pow(10, decimals);
    //return this.pad_with_zeros(result3, decimals);
    return result3;
};

RatingSetup.prototype.pad_with_zeros = function(rounded_value, decimal_places) 
{
    // Convert the number to a string
    var value_string = rounded_value.toString();
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".");

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0;
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : "";
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1;
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length;
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0";
        }
    return value_string;
};
