if (window.jQuery) {
	(function($){
		$.fn.rate = function(opts){
			opts = $.extend({
				
			}, opts);
			var ratingCss = {
				cursor: 'pointer'
			};
			var ratingHTML = '<b></b><b></b><b></b><b></b><b></b><b></b><b></b><b></b><b></b><b></b>';
			return this.each(function(){
				var rating = $(this), saveCss = rating.attr('style'), result = rating.next(".result");

				rating.css(ratingCss).html(ratingHTML);
				var bg_pos = {
					rated_0: '0 0',
					rated_0_5: '0 -22px',
					rated_1 : '0 -44px',
					rated_1_5: '0 -66px',
					rated_2: '0 -88px',
					rated_2_5: '0 -110px',
					rated_3: '0 -132px',
					rated_3_5: '0 -154px',
					rated_4: '0 -176px',
					rated_4_5: '0 -198px',
					rated_5: '0 -220px'	
				}[rating.attr('class')], items = $("b", rating), video_id = (rating.attr('id').split(':'))[1];
				
				var success = function(vote) {
					if (typeof(parseInt(vote,10)) == 'number') {
						items.unbind('mouseover.rate').unbind('mouseout.rate').unbind('click.rate');
						rating.html(vote).attr('style', saveCss || '').attr('class', 'rated rated_'+ $.roundHalf(vote).toString().replace('.','_'));
						result.text(vote+'/5');
					}
				};
				
				var hide = function(e){
					rating.removeAttr('style');
					$(this).removeAttr('current');
				};				
				var start = function(e){
					var curElem = $(this).attr('current','true'), index = 10-$("b[current] ~ b").length;
					new_css = bg_pos.split(' ');
					new_css[0] = '-100px';
					new_css[1] = index * (-22)+'px';
					rating.css('background-position', new_css.join(' '));
				};
				
				items.bind('mouseover.rate', start);
				items.bind('mouseout.rate', hide);
				items.bind('click.rate', function(){
					var curElem = $(this).attr('current','true'), vote = (10-$("b[current] ~ b").length)*5;
					$.ajax({
					 type: "GET",
					 url: "/ajax/rating/add/id/"+video_id+"/rate/"+vote,
					 dataType: "text",
					 success: success
					});
				});
			});
		};
		$.roundHalf = function(fl){
			fl = parseFloat(fl);
			dec = (fl - parseInt(fl, 10));
			dec = Math.round(dec * 10);
			if (dec == 5) {
				return (parseInt(fl, 10)+0.5); 
			}
			if ( (dec < 3) || (dec > 7) ) {
				return Math.round(fl);
			} 
			else {
				return (parseInt(fl, 10)+0.5);
			} 
		};		
	})(jQuery);
}
