
var sMax;	// Isthe maximum number of stars
var holder; // Is the holding pattern for clicked state
var preSet; // Is the PreSet value onces a selection has been made
var rated;

var styleOut = '/images/ratings/star_off.png';
var styleOver = '/images/ratings/star_on.png';
var styleHalf = '/images/ratings/star_half.png';

var enabledCode = '" onclick="rateIt(this)" title="" onmouseover="rating(this)" onmouseout="off(this)"';
var Domain = document.location.host;
var rs;
var _IsIE = false;

//Check the browser version
 if (navigator.appVersion.match(/\bMSIE\b/))
{
    _IsIE = true;
}


Domain += "/NonACM/ajax";


function RatingSystem (assetID, userID, RatingDiv, AggregateDiv, HeaderDiv)
{
    //userID = "300f5908-9ce9-4b41-9e84-9ee9a2a4b443"; //Used for testing
    
    this.AssetID = assetID;
    this.UserID = userID;
    this.Rating = "";
    this.DateRated = "";
    this.AverageRating = "";
    this.TotalRatings = "";
    this.NumberOfIcons = 0;
    this.AggregateTargetElementID = AggregateDiv;
    this.RatingTargetElementID = RatingDiv;
    this.RatingHeaderTargetElementID = HeaderDiv;
    
    this.CreateInterface =  function CreateInterface(numOfIcons)
                                {
                                    // Create the interface with the correct number of Rating Icons (Stars, etc...)
                                      
                                        var link = "";
                                        
                                        this.NumberOfIcons = numOfIcons;
                                        
                                        sMax = this.NumberOfIcons;
                                        
                                    for (var x = 0; x < numOfIcons; x++)
                                        {
                                            //If the user is not logged in then make the interface read-only
                                            link += '<img src="' + styleOut + '" id="_' + x + '"  {0}></img>';
                                            
                                            if (isLoggedIn() == true)
                                                {
                                                    enabledCode = enabledCode.replace("{X}", x);
                                                    link = link.replace("{0}",enabledCode);
                                                }
                                            else
                                                {
                                                    link = link.replace("{0}","");
                                                }
                                            //alert(link);
                                        }
                                       return link;
                                };
    

    this.SaveRating =  function SaveRating(rating)
                        {
                            var me = this;
                            
                            var callMethod = "GET";
                            
                             if (_IsIE)
                            {
                                callMethod = "POST";
                            }
                            
                            var requestCall = new Ajax.Request('http://' + Domain + '/A2process.aspx?mode=updateAssetRating&assetid=' + me.AssetID + '&Rating=' + rating + '&UserID=' + me.UserID,
                                                                {
                                                                  method: callMethod,
                                                                  onSuccess: function(transport){me.GetAggregates(me.AssetID , me.UserID);}
                                                                }
                                                              );
                            
                        };
                        
	this.GetAggregates = function GetAggregates(assetID, userID)
                            {
                                 var callMethod = "GET";
                                    
                                     if (_IsIE)
                                    {
                                        callMethod = "POST";
                                    }
                                    
                                //Get the aggregate data for this asset
                                
                                var me = this;
                                                                
                                var requestCall = new Ajax.Request('http://' + Domain + '/A2process.aspx?mode=getAssetRatingAggregate&assetid=' + assetID + '&UserID=' + userID,
                                                                {
                                                                    method: callMethod,
                                                                    contentType: "text/xml",
                                                                    onSuccess: function (originalRequest)
                                                                        {
                                                                                
                                                                                //Success
                                                                                var xmlDoc = originalRequest.responseXML;  //For some reason responseXML produced a Permission denied error on A2aus.
                                                                                
                                                                                if (!_IsIE)
                                                                                {
                                                                                    xmlDoc = (new DOMParser()).parseFromString(originalRequest.responseText, "text/xml");
                                                                                }
                                                                                
                                                                                var Assets;
                                                                                
                                                                                if (xmlDoc != null)
                                                                                    {
                                                                                        Assets = xmlDoc.documentElement;
                                                                                    }
                                                                                    
                                                                                if ((Assets == null) || (Assets.childNodes.length < 1))
                                                                                    {
                                                                                        //alert('There are no ratings for AssetID:  ' + assetID);
                                                                                     
                                                                                        //Set default values for aggregate data for this asset
                                                                                        me.AssetID = assetID;
                                                                                        me.Rating = '';
//                                                                                        var d = new Date(GetElement(Assets,"DateRated"));
//                                                                                        
//                                                                                        me.DateRated = d.toDateString();
                                                                                        me.AverageRating = 0;
                                                                                        me.TotalRatings = 0;
                                                                                    }
                                                                                else
                                                                                    {
                                                                                    
                                                                                        //Get the existing aggregate data for this asset
                                                                                        me.AssetID = GetElement(Assets,"AssetID");
                                                                                        me.Rating = GetElement(Assets,"Rating");
                                                                                        var d = new Date(GetElement(Assets,"DateRated"));
                                                                                        
                                                                                        me.DateRated = d.toDateString();
                                                                                        me.AverageRating = GetElement(Assets,"AverageRating");
                                                                                        me.TotalRatings = GetElement(Assets,"NumberOfRatings");
                                                                                     }
                                                                                     
                                                                                                                                                                         
                                                                                    //Build the output
                                                                                    var aggregateOutput = "";
                                                                                    var headerOutput = "";
                                                                                    
                                                                                    aggregateOutput += "<div id='divRatedTimes'> Rated " + me.TotalRatings + " times </div>";
                                                                                    
                                                                                    //Show the Login link if necessary
                                                                                    if (isLoggedIn() != true)
                                                                                        {
                                                                                           headerOutput = "<div id='divRateLogin' class='LoginRate'><a href='http://" + document.location.host + "/session.flo'>Login</a> to rate </div>";                                                                                            
                                                                                           
                                                                                        }
                                                                                    else
                                                                                        {
                                                                                            headerOutput = "Rate this:";
                                                                                        }
                                                                                    
                                                                                    me.preSet = me.AverageRating;
                                                                                    
                                                                                    //Show when the user rated this asset if applicable
                                                                                    /*if ((me.UserID != null) && (me.UserID != "00000000-0000-0000-0000-000000000000"))
                                                                                        {
                                                                                            aggregateOutput += "You rated on, " + me.DateRated;
                                                                                        }
                                                                                    */
                                                                                    
                                                                                     //Display the Login/Rate This text
                                                                                     var hdrTarget = document.getElementById(me.RatingHeaderTargetElementID);
                                                                                    hdrTarget.innerHTML = headerOutput;
                                                                                    
                                                                                    //Display the Aggregate text
                                                                                     var aggTarget = document.getElementById(me.AggregateTargetElementID);
                                                                                    aggTarget.innerHTML = aggregateOutput;
                                                                                    
                                                                                    //Display the average rating using the icons
                                                                                    var iTarget = document.getElementById(me.RatingTargetElementID);
                                                                                    
                                                                                    //Disable the stars if this user has already rated the asset.
                                                                                    iTarget.innerHTML = CreateAverageRatingIcon(me.AverageRating, me.NumberOfIcons, (me.Rating == ''));
                                                                         }
                                
                                                                   }
                                                              );
                            };
                            
      
    rs = this;
}

   
    
    // Rollover for image Stars //
    function rating(num){
        sMax = 0;	// Is the maximum number of stars
        if ((num.parentNode != null) && (num.parentNode.childNodes != null))
        {
            for(n = 0; n < num.parentNode.childNodes.length; n++)
            {
	            if(num.parentNode.childNodes[n].nodeName == "IMG")
	            {
		            sMax++;	
	            }
            }
        }
    	
        if(!rated)
            {
	            s = num.id.replace("_", ''); // Get the selected star
	            a = 0;
	            for(i = 0; i < sMax; i++)
	                {		
		                if(i <= s)
		                    {
			                    document.getElementById("_" + i).src = styleOver;
			                    
			                    holder = a + 1;
			                    a++;
		                    }
		                else
		                    {
			                    document.getElementById("_" + i).src = styleOut;
		                    }
	                }
            }
    }

    // For when you roll out of the the whole thing //
    function off(me)
        {
            if(!rated)
                {
                    
	                 //Display the average rating using the icons
                    var iTarget = document.getElementById(rs.RatingTargetElementID);
                    
                    //Disable the stars if this user has already rated the asset.
                    iTarget.innerHTML = CreateAverageRatingIcon(rs.AverageRating, rs.NumberOfIcons, (rs.Rating == ''));
                }
        }

    // When you actually rate something //
    function rateIt(me){
        if(!rated){
	        preSet = me;
	        rated=1;
	        rating(me);
	        sendRate(me);
	        
        }
    }

    // Send the rating information somewhere using Ajax or something like that.
    function sendRate(sel){
        ratingNumber = sel.id.replace("_", '');
        rs.SaveRating(eval(ratingNumber) + 1);
        
    }
    
    function isLoggedIn()
    {
        //Check the userId cookie to see if the user is logged in.
        //alert(document.cookie);
        if ((document.cookie.indexOf("userHash") >= 0) | (document.cookie.indexOf("RESULTS_SESSION_TOKEN") >= 0))
            {
                return true;
                //return false;  // Used for testing
            }
        else
            {
                //return true;  // Used for testing
                return false;
            }
    }
    
    function CreateAverageRatingIcon(average, totalNumberOfIcons, EnableRating)
    {
        //Show the average rating using the icons
        var outputAverage = "";
        
        for (x = 1; x <= totalNumberOfIcons; x++)
        {
            if (x <= average)
            {
                outputAverage += '<img id="_' + (x-1) + '" src="' + styleOver + '" {0}></img>';
            }
            else if ((x > average) & ((x - average) < 1)) //Display any half stars
            {
                outputAverage += '<img id="_' + (x-1) + '" src="' + styleHalf + '" {0}></img>';
            }
            else 
            {
                outputAverage += '<img id="_' + (x-1) + '" src="' + styleOut + '" {0}></img>';
            }
            
            //If the user hasn't already rated this asset then enable it.
            //alert(EnableRating + '\n' + isLoggedIn());
            //EnableRating = true;  //Used for Testing
            
            if ((EnableRating == true) && (isLoggedIn() == true))
                {
                    enabledCode = enabledCode.replace("{X}", x);
                    outputAverage = outputAverage.replace("{0}", enabledCode);
                }
            else
                {
                    outputAverage = outputAverage.replace("{0}", "");      
                }
              
              //alert('Average output: ' + outputAverage);
        }
        
        return outputAverage;
    }
     function GetElement(NodeCollection, ElementName)
            {
                //Search the Node for the specified Element and return the value
                var ReturnValue = "";
                var NodeName = "";
                
                try
                {
                
                    for(var x = 0;x < NodeCollection.childNodes.length;x++)
                        {
                            NodeName = NodeCollection.childNodes[x].nodeName;
                            if ((NodeName == ElementName) && (NodeCollection.childNodes[x].firstChild != null))
                                {
                                    ReturnValue = NodeCollection.childNodes[x].firstChild.nodeValue;
                                    break;
                                }
                        }
                }
                catch(e)
                {
                    ReturnValue = "";
                }
                
                return ReturnValue;
                
            }
            
          