﻿// JScript File
		
function ValidateRatings()
{    
    //alert("check!"); 
	try
	{	
	    var Total = 0; 
	    var Count = 0; 
	    
	    var Reviews_Rating = null; 
	    
	    for(var i=0; i<EditRegions.all.length; i++)
		{
			var eR = EditRegions.all[i];
			var plName = eR.GetMetaData("PlaceHolderFriendlyName")
		    
		    if (plName == "Reviews_Appearance" || 
		        plName == "Reviews_BuildQuality" || 
		        plName == "Reviews_Finish" || 
		        plName == "Reviews_Construction" || 
		        plName == "Reviews_Materials" || 
		        plName == "Reviews_DeliveryTime") 
		    {
		        var value = eR.GetValue();

		        if(IsBlankOrDefaultContent(eR, value)) continue;
		        
		        if (ValidateRating(plName.substring("Reviews_".length), value))
		        {
		            Count += 1; 
		            Total = Total + parseFloat(value); 
                }
                else 
                    return false;		        
		    }
		    else if (plName == "Reviews_Rating") 
		    {
		        Reviews_Rating = EditRegions.all[i]; 
		    }  
		    
		}	
		
		if (Reviews_Rating != null) 
	    {
	        var Average = 0; 
	        
	        if (Count > 0) 
	            Average = (Total * 10) / Count; 
            
	        Reviews_Rating.SetValue(Average.toString());
	    }
	    else 
	    {
	        alert("Could not find the placeholder for the overall rating: 'Reviews_Rating'");
	        return false;
	    }		    
	}
	catch(e)
	{
		alert('There was an error with the rating values: ' + e.message);
		return false;
	}
	return true;
};

// Register the validator with the update system
RegisterValidator(ValidateRatings);


function ValidateRating(name, str) 
{		
	if (str.trim() == "") 
	{
		return true;
	}	
	else if (!(/^\d+(\x2e\d*){0,1}$/.test(str)))
    {
		alert("The rating value '" + str + "' is not valid: please type numbers only");			
        return false; 
	} 
    else 
    {
        var value = parseFloat(str); 
        
        if (value < 0 || value > 10) 
        {
            alert("The rating value '" + str + "' is not valid: value must be in the range 0 to 10 inclusive");			
            return false;    
        }
        
        return true;   
	}
};
