/**
 * Star Rating - jQuery plugin
 *
 * Copyright (c) 2006 Wil Stuckey
 *
 * 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 
 *
 */
(function($){ //create local scope
    /**
     * Takes the form element, builds the rating interface and attaches the proper events.
     * @param {Object} $obj
     */
    var buildRating = function(modo, $obj){
		if(modo==1 || modo==11)
			nstar=".star";
		else
			nstar=".star2";

        var $obj = buildInterface(modo, $obj),
            averageIndex = $obj.averageRating[0],
            averagePercent = $obj.averageRating[1],
            $stars = $($obj.children(nstar)),
            $cancel = $($obj.end().children('.cancel'));
        $obj.end();
        
		
		if(modo==1 || modo==11) {
		   if(modo==1)
				$('div.rating').before('<p id="votame"><strong>¡Vótame!</strong></p>');
			else if(modo==11)
				$('div.rating').before('<p id="votame_index"><strong>Vota la foto para ver la siguiente</strong></p>');
			// hover events.
			// and focus events added
			$stars
				.mouseover(function(){
					event.drain();
					event.fill(this);
				})
				.mouseout(function(){
					event.drain();
					event.reset();
				})
				.focus(function(){
					event.drain();
					event.fill(this)
				})
				.blur(function(){
					event.drain();
					event.reset();
				});
			
			// cancel button events
			$cancel
				.mouseover(function(){
					event.drain();
					$(this).addClass('on')
				})
				.mouseout(function(){
					event.reset();
					$(this).removeClass('on')
				})
				.focus(function(){
					event.drain();
					$(this).addClass('on')
				})
				.blur(function(){
					event.reset();
					$(this).removeClass('on')
				});
			
			// click events.
			$cancel.click(function(){
				event.drain();
				averageIndex = 0;
				averagePercent = 0;
				$.post($obj.url, {
					"rating": $(this).children('a')[0].href.split('#')[1] 
				});
				return false;
			});
			$stars.click(function(){
				averageIndex = $stars.index(this) + 1;
				averagePercent = 0;
				urlbase=document.location.href;
				urlficha_tmp=urlbase.split("www.conocm.com");
				urlficha=urlficha_tmp[1];
				idtmp=urlficha.split("/");
				idusuario=idtmp[2]; // a quien votamos
				rating=$(this).children('a')[0].href.split('#')[1];
				$.post($obj.url, {
					funcion: "votar",
					idusuario: idusuario,
					rating: rating,
					ajax: 1
				},	function(html){
						// Se quita lo de vótame y se da las gracias por votar
						$('#votame').fadeOut("fast").html('<strong>¡Gracias por votar!</strong>').fadeIn("slow");
						$('#votame').after('<p><strong>Puntuación media: ' + html + '</strong></p>');
						$('div.rating').removeAttr("title");
					});
	
				// Se buscan todas las estrellas que no tengan como clase "star hover", que son las que deben quedar apagadas
				// y se les cambia la clase para evitar que se hagan amarillas por el a:hover de los css
				$('div.rating').find('div[@class!="star hover"]').removeClass('star').addClass('star2');
				// También se eliminan todos los títulos ("puntuar 5 de 10" etc) de las estrellas (todo lo que contenga "star")
				$('div.rating').find('div[@class*="star"]').each(function() {
					$(this).children('a').removeAttr("title");
				});
				// Ahora se quita cualquier evento de todas las estrellas. El efecto de hover de las estrellas no se puede quitar
				// sin afectar totalmente al plugin porque las estrellas son enlaces...
				$stars.unbind();
				
				return false;
			});
		}//Del if(modo==1)

        var event = {
            fill: function(el){ // fill to the current mouse position.
                var index = $stars.index(el) + 1;
                $stars
                    .children('a').css('width', '100%').end()
                    .lt(index).addClass('hover').end();
            },
            drain: function() { // drain all the stars.
                $stars
					.filter('.on').removeClass('on').end()
					.filter('.hover').removeClass('hover').end();
            },
            reset: function(){ // Reset the stars to the default index.
                $stars.lt(averageIndex).addClass('on').end();
                var percent = (averagePercent) ? averagePercent * 10 : 0;
                if (percent > 0) {
                    $stars.eq(averageIndex).addClass('on').children('a').css('width', percent + "%").end().end()
                }  
            }
        }        
        event.reset();
        return $obj;
    }
    
    /**
     * Accepts jQuery object containing a form element.
     * Returns the proper div structure for the star interface.
     * 
     * @return jQuery
     * @param {Object} $form
     * 
     */
    var buildInterface = function(modo, $form){
        var $container = $(document.createElement('div')).attr({
            "title": $form.title(),
            "class": $form.attr('class')
        });
        $.extend($container, {
            averageRating: $.trim($container.title().split(':')[1]).split('.'),
            url: $form.attr('action')
        });
        var $optionGroup = $form.children('select').children('option');
		
		if(modo==1 || modo==11) clase="star";
		else clase="star2";
			
        for (var i = 0, option; option = $optionGroup[i]; i++){
            var size = $optionGroup.size() - 1;
            if (option.value == "0") {
                $div = $('<div class="cancel"><a href="#0" title="Cancel Rating">Cancel Rating</a></div>');
            } else {
				title="";
				if(modo==1 || modo==11)
					title=' title="Puntuar ' + option.value + ' de 10"';
                $div = $('<div class="'+ clase +'"><a href="#' + option.value + '"' + title + '>' + option.value + '</a></div>');
            }
            $container.append($div[0]);                    
        }
        $form.end().end().after($container).remove();
        return $container;
    }
    
    /**
     * Set up the plugin
     */
    $.fn.rating = function(modo){
        var stack = [];
        this.each(function(){
            var ret = buildRating(modo, $(this));
            stack = $.merge(ret, stack);
        });
        return $(stack);
    }
	// fix ie6 background flicker problem.
	if ($.browser.msie == true) {
		document.execCommand('BackgroundImageCache', false, true);
	}
})(jQuery)