/**
 * 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 
 *
 */
 
jQuery.fn.rating = function(){
    return this.each(function(){
        var div = jQuery("<div/>").attr({
            title: this.title,
            className: this.className
        }).insertAfter( this );
        
        var fid = this.id;
        var cookieExists = ($.cookie(fid) != null) ? true : false;

        jQuery(this).find("select option").each(function(){        	
        	if(cookieExists) {
	            div.append( this.value != "0" ?
	                "<div class='star'><span></span></div>" : "" );
			} else {
				var votesMsg = (this.value > 1) ? 'balais' : 'balu';
				div.append( this.value != "0" ?
                 	"<div class='star'><a href='#" + this.value + "' title='Įvertinti " + 
                    	this.value + " " + votesMsg + "'>" + this.value + "</a></div>" : "" );
			}
        });
        
        var averageRating = this.title.split(/:\s*/)[1].split(".");
        url = this.action;
        averageIndex = averageRating[0];
        averagePercent = averageRating[1];

        if(cookieExists == false) {
	    	// hover events and focus events added
		    var stars = div.find("div.star")
		        .mouseover(drainFill).focus(drainFill)
		        .mouseout(drainReset).blur(drainReset)
		        .click(click);
		} else {
			var stars = div.find("div.star").addClass('unlink');
			div.addClass('unlink');
		}

        reset();

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

        function click(){
            averageIndex = stars.index(this) + 1;
            averagePercent = 0;
    		
            jQuery.post(url, {
            	id: fid,
                rating: jQuery(this).find('a')[0].href.slice(-1)
            }, function(msg) {
            	$('b#ratingCount, b#ratingCount' + fid).html(jQuery.trim(msg));
            	$('b#ratingCount' + fid).html(jQuery.trim(msg));
            	
            	$('b#voteCount').html(parseInt($('b#voteCount').html()) + 1);
            	$('b#voteCount' + fid).html(parseInt($('b#voteCount' + fid).html()) + 1);
            });
            
            stars.unbind('mouseover').unbind('mouseout').unbind('click').unbind('focus').unbind('blur');
            stars.children("a").remove();
            stars.addClass('unlink').html('<span></span>');
            div.addClass('unlink');
            
            $.cookie(fid, '1', { expires: 30 });
			
            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(){
        	var className = cookieExists ? 'hover' : 'on';
            stars.lt(averageIndex).addClass(className);

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

// fix ie6 background flicker problem.
if ( jQuery.browser.msie == true )
    document.execCommand('BackgroundImageCache', false, true);