/*-------------------------------------------------------------------------------
	MyjQuery myRating
	Version 1.0
	Autor : Roberto Herrero
	Web : http://www.miblog.indomita.org/
	27/06/2009
-------------------------------------------------------------------------------*/

$.fn.myRating= function(options){
	//features
	var defaults = {
        max_value  : 5,    // max number of stars
        cur_value  : 0,    // number of selected stars	
		vote	  : true,  // permite votar o solo lectura
		url		  : '',	   // url para enviar votación ajax	
		id		  : 0,	   // identificador que acompaña al ajax
		ajax_return: '',   // to return ajax (selector expression)
		title		: 'Give __i__ / __max__',  // default title ( __i__ = points, __max__ = max_points ) array y tal
		star_class  : 'my_star',  //class to star (_ok to start ok, _no to no star) para tener varios tipos de estrellas
		extra_class : ''   // add others class
    };
	var options = $.extend(defaults, options);
	var $this = $(this);
	var url_ok= options.url.length>0;
	var ajax_ok= options.ajax_return.length>0;
	var star_ok = options.star_class+'_ok';
	var star_no = options.star_class+'_no';
	var is_array= $.isArray(options.title);

	var contenido='';

	$this.addClass('my_rating');
		
	for(var i= 1; i <= options.max_value ; i++){
		var mi_title = (is_array) ? options.title[i-1] : options.title.replace('__i__', i).replace('__max__', options.max_value);
		contenido = contenido+'<a href="#" alt="'+i+'" class="my_stars '+options.star_class+' '+((i<=options.cur_value) ? star_ok : star_no) +' '+ options.extra_class +'" title="'+mi_title+'"><span>'+i+'</span></a>';		
	}
	contenido = contenido+'<div class="my_clear"></div>';
    $this.html(contenido);
	
	if(options.vote){
		$this.children("a.my_stars")
			.bind('click', function(e){
			//controlamos el click
					e.stopPropagation(); 
				//actualizamos el nuevo valor
					options.cur_value=$(this).attr('alt');
				//refrescamos las estrellitas
					refresh($this, options);
				//puntuamos
					if(url_ok)
						puntua($this, options);

					return false;
				});

		//envía la petición ajax
		puntua = function($this, options){
			$.post(options.url, { rating: options.cur_value, id: options.id}, function(data){ if(ajax_ok) $(options.ajax_return).html(data); return false; });
		}

		//refresca los datos
		refresh = function($this, options){
			$this.children("a.my_stars").removeClass(star_ok+' '+star_no).each(function(){	
					var clase=($(this).attr('alt')<=options.cur_value) ? star_ok : star_no; 
					$(this).addClass(clase) 
				});
		}
	}else
		$this.children("a.my_stars").bind('click', function(e){ return false;});

}


