jQuery.each( [ "eq", "lt", "gt", "contains" ], function(i,n){
	jQuery.fn[ n ] = function(num,fn) {
		return this.filter( ":" + n + "(" + num + ")", fn );
	};
});


(function($) {
  var buildRating = function(obj) {
    var rating = averageRating(obj),
        obj    = buildInterface(obj),
        stars  = $("div.star", obj),
        cancel = $("div.cancel", obj)

        var fill = function() {
          drain();
          $("a", stars).css("width", "100%");
		  stars.lt(stars.index(this) + 1).addClass("hover");
        },
        drain = function() {
          stars.removeClass("on").removeClass("hover");
        },
        reset = function() {
          drain();
          stars.lt(rating[0]).addClass("on");
          if(percent = rating[1] ? rating[1] * 10 : null) {
            stars.eq(rating[0]).addClass("on").children("a").css("width", percent + "%");
          }
        },
        cancelOn = function() {
          drain();
          $(this).addClass("on");
        },
        cancelOff = function() {
          reset();
          $(this).removeClass("on")
        }

    stars
      .hover(fill, reset).focus(fill).blur(reset)
      .click(function() {
        rating = [stars.index(this) + 1,0];
		id = obj.attr('id');
        $.post(obj.url, { myrate: stars.index(this) + 1, id: id },
			function(data){
				if(data == 'done')
				{
					var span = $(obj.find("span"));
					var new_value = parseInt(span.text()) + 1;
					span.text(new_value);
				}
				else alert(data);
			});
        reset(); stars.unbind().addClass("done");
        $(this).css("cursor", "default");
        return false;
      });

    reset();
    return obj;

  }

	

  var buildInterface = function(form) {
    var container = $("<div></div>").attr({"id": $(form).attr('id'), "class": form.className});
    $.extend(container, {url: form.action})
    var optGroup  = $("option", $(form));
    var size      = optGroup.length;
    optGroup.each(function() {
      container.append($('<div class="star"><a href="#' + this.value + '" title="' + this.value + '/'+ size +'">' + this.value + '</a></div>'));
    });
	
    $(form).after(container).remove();
	//container.append('&nbsp;<span>'+totalRates(form)+'</span> đánh giá');
    return container;
  }

  var averageRating = function(el) { return el.title.split("|")[0].split("."); }
  var totalRates = function(el) { return el.title.split("|")[1]; }

  $.fn.rating = function() { return $($.map(this, function(i) { return buildRating(i)[0] })); }

	if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { }

})(jQuery)
