/**
 * Star Rating - jQuery plugin
 *
 * Copyright (c) 2007 Wil Stuckey
 * Modified by John Resig
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a degradeable star rating interface out of a simple form structure.
 * Returns a modified jQuery object containing the new interface.
 *   
 * @example jQuery('form.rating').rating();
 * @cat plugin
 * @type jQuery 
 * @modified Nio Xiao, 2007.09.24
 */
jQuery.fn.rateable = function(){
    
    return this.each(function(){
        var div = jQuery("<div/>").attr({
            title: this.title,
            className: this.className
        }).insertAfter( this );
        		
        jQuery(this).find("select option").each(function(){
            div.append( this.value == "-1" || this.value == "" ?
                "" :
                "<div class='star'><a href='#" + this.value + "' title='Give it a " + 
                    this.value + " Star Rating'>" + this.value + "</a></div>" );
        });

		// we will use this object var in click event
		var select = jQuery(this).find('select');
        
        // this needs to be updated to be the 'selected' value if the form reposts. we save default value in "title" attribute.
		// current selected value
		// var selectedValue = (this.title && !isNaN(this.title)) ? parseInt(this.title) : -1;
		var selectedValue = select.val() ? select.val() : -1;

        // hover events and focus events added
        var stars = div.find("div.star")
            .mouseover(drainFill).focus(drainFill)
            .mouseout(drainReset).blur(drainReset)
            .click(click);

        // cancel button events
        div.find("div.cancel")
            .mouseover(drainAdd).focus(drainAdd)
            .mouseout(resetRemove).blur(resetRemove)
            .click(click);

        reset();

        function drainFill(){ drain(); fill(this); }
        function drainReset(){ drain(); reset(); }
        function resetRemove(){ reset(); jQuery(this).removeClass('on'); }
        function drainAdd(){ drain(); jQuery(this).addClass('on'); }

        function click(){
			var value;
			
            // when clicked, the star needs to update the hidden select box
            selectedValue = stars.index(this) + 1;
			
            if ( selectedValue == 0 ) {	//didn't select any stars. cancel it.
	            drain();
				value = -1;
			} else if ( selectedValue > 0) {	//select a value
	            stars.lt(selectedValue).addClass("on");
				value = selectedValue;
			}	//end if
			
			// set form field value as 'selectedValue'.
			select.val(value);

            return false;
        }

        // fill to the current mouse position.
        function fill( elem ){
            stars.find("a").css("width", "100%");
            stars.lt( stars.index(elem) + 1 ).addClass("hover");
        }
    
        // drain all the stars.
        function drain(){
            stars.removeClass("on hover");
        }

        // Reset the stars to the default index.
        function reset(){				
			// draw red star(s) for current selected value
			stars.lt(selectedValue).addClass("on");
			select.val(selectedValue);
        }
    }).hide();
};

// fix ie6 background flicker problem.
if ( jQuery.browser.msie == true )
    document.execCommand('BackgroundImageCache', false, true);
    
jQuery.fn.rateabledisplay = function(){
    return this.each(function(){
        var div = jQuery("<div/>").attr({
            title: this.title,
            className: this.className
        }).insertAfter( this );

        var averageRating = this.title.split(/:\s*/)[1].split("."),
            url = this.action,
            averageIndex = averageRating[0],
            averagePercent = averageRating[1];

       jQuery(this).find("select option").each(function(){
            div.append( "<div class='star'><a class='display' href='#' title='Average Rating: " + 
                    averageRating + "'>" + averageRating + "</a></div>" );
        });
        
        var stars = div.find("div.star");
        reset();
        
        // fill to the current mouse position.
        function fill( elem ){
            stars.find("a").css("width", "100%");
            stars.lt( stars.index(elem) + 1 );
        }
    
        // Reset the stars to the default index.
        function reset(){
            stars.lt(averageIndex).addClass("on");

            var percent = averagePercent ? averagePercent * 10 : 0;
            if (percent > 0)
                stars.eq(averageIndex).addClass("on").children("a").css("width", percent + "%");
        }
    }).remove();
};
