var StarRating = Class.create ();

StarRating.prototype = {

    // ratingContainer should be a ul element with the star rating CSS class, generally 'starRating'
    // mediaID should be an integer media item ID
    // currentRating may be a decimal value from 0 through 10, defaults to 0 if anything else is passed
    // loggedIn should be a boolean, true when logged in, false otherwise, this determines if the click handlers are set

    initialize: function ( ratingContainer, mediaID, currentRating, loggedIn ) {
        // Width of 'star' image in pixels
        this.starWidth = 16;

        this.mediaItemID = mediaID;

        this.container = $( ratingContainer );

        if ( this.container.select ( 'li.currentRating' ).length != 1 )
            throw new Exception ( 'Invalid argument, container must contain exactly one li element with class "currentRating"' );
        
        // new:
        currentRating = currentRating;
        
        // old: 
        // currentRating = parseInt ( currentRating, 10 );


        if ( isNaN ( currentRating ) )
            currentRating = 0;

        //currentRating = Math.round ( currentRating / 2 );

        this.updateRating ( currentRating );

        this.setHandlers ( loggedIn );
    },

    setHandlers: function ( loggedIn ) {
        this.container.select ( 'li a' ).each (
            function ( rateLink ) {
                if ( loggedIn )
                    Event.observe (
                        rateLink,
                        'click',
                        function () {
                            this.rateFile ( parseInt ( rateLink.innerHTML ) * 2 );
                        }.bind ( this )
                    );
            }.bind ( this )
        );
    },

    rateFile: function ( newRating ) {
        jsonRequest (
            'media.rateFile',
            {
                id: this.mediaItemID,
                rating: newRating
            },
            function ( newRating ) {
                this.updateRating.bind ( this, newRating );
                $('ratingFeedback').innerHTML = 'Thanks for your rating!';
            }.bind ( this ),
            function () { throw new Exception ( 'Rating failed' ); }
        );

        return false;
    },

    updateRating: function ( rating ) {
        this.container.select ( 'li.currentRating' ) [ 0 ].style.width = (( rating * this.starWidth ) / 2 ) + 'px';
    }
};
