/**
 * @author Laurynas Karvelis
 * @author "made.By" - www.by.lt
 * @date 2008-02-26
 */

var ratingItemId = '';
var ul;

// star rating system
jQuery.fn.rating = function() {
    return this.each(function() {
    	ul = $('ul', this);
    	var id = $(this).attr('id');
    	var url = $(this).attr('action');
    	var parent = ul.parent().get(0);
    	
    	// create stars
    	var stars = '';
    	var voted = jQuery.cookie(id);
    	
    	if(voted || ul.hasClass('static')) {
    		$('li', ul).addClass('voted');
    		$('div.vote', parent).hide();
		    $('div.vote-already', parent).show();
		} else {
			for(var i = 0; i < 5; i++) {
    			if(!voted) {
    				stars += '<li><a href="#" class="node' + (i + 1) + '" title="' + (i + 1) + ' iš 5"></a></li>';
				}
    		}
    		
    		ul.append(stars);
    		$('a', ul).click(click);
		}
    	
    	function click() {
    		var value = parseInt(this.className.substring(4));
    		ratingItemId = id;

    		$.post(
				url, { 'id' : id, 'value' : value },
				function(data) {
		    		data = parseFloat(jQuery.trim(data));
		    		$('li.current', ul).css('width', (data * 20) + '%');
		    		$('a', ul).hide();
		    		$('li', ul).addClass('voted');
		    		
		    		$('div.vote', parent).hide();
		    		$('div.vote-thank', parent).show();
		    		
		    		var next = $('h4.' + ratingItemId + ' span:first').text(data).next();
		    		var count = (next.text() == 'nėra') ? 1 : (parseInt(next.text()) + 1);
		    		
		    		next.text(count);
		    		jQuery.cookie(ratingItemId, 1, { expires: 365});
				}
			);
			
    		return false;
    	}
    })
};
