﻿function StarRating(oItem) {

    this.obj = oItem;
    this.offSprite = this.obj.getAttribute('offSprite');
    this.onSprite = this.obj.getAttribute('onSprite');
    this.showLabel = null != this.obj.getAttribute('showLabel');
    if(this.showLabel)
        this.showLabel = (this.obj.getAttribute('showLabel') == "true");
 
    this.images = [];
    this.label = document.createElement("SPAN");
    
    this.UpdateRating = function(index)
    {
        if(null == index)
            index = this.control.selectedIndex;
            
        for(var i = 0; i < this.images.length; i++)
        {
            if(i <= index)
                this.images[i].src = this.onSprite;
            else
                this.images[i].src = this.offSprite;
        }
        this.label.innerHTML = this.control.options[index].text;
    }

    this.SelectRating = function(index)
    {
        this.control.selectedIndex = index;
        this.UpdateRating();
    }
    
    for(var i=0; i<this.obj.childNodes.length; i++)
    {
        if(this.obj.childNodes[i].nodeName == "SELECT")
            this.control = this.obj.childNodes[i];
    }
    this.control.onchange = funcPointer(this,this.UpdateRating);
    
    for(var i = 0; i < this.control.options.length; i++)
    {
        oImg = document.createElement("IMG");
        oImg.src = this.offSprite;
        if(!this.obj.disabled && !this.control.disabled)
        {
            oImg.onmouseover = funcPointer(this,this.UpdateRating,i);
            oImg.onmouseout = funcPointer(this,this.UpdateRating);
            oImg.onmousedown = funcPointer(this,this.SelectRating,i);
        }
        this.obj.appendChild(oImg);
        this.images[this.images.length] = oImg;
    } 
    
    this.label.className = "label";
    this.control.style.display = "none";
    if(this.showLabel)
        this.obj.appendChild(this.label); 
    this.UpdateRating();
}

// funcPointer is a helper function which takes an object and function as arguments
// and returns a function which will execute the given method as if it were executed
// from the context of the given object.

// JavaScript is... interesting. :-P
function funcPointer(context,method){
    var args = Array.prototype.slice.apply(arguments);
    return function(ev){method.apply(context,args.slice(2))};
}

function initStarRatings()
{
    var allElems = (document.all) ? document.all : document.getElementsByTagName("*");
    for(i = 0; i < allElems.length; i++)
    {
        if(allElems[i].className == "StarRating")
            new StarRating(allElems[i]);        
    }
}