/**
 * @author gwilliams
 * @classDescription Applies a star style rating to 5 radio buttons
 * @version 0.9
 * @namespace jQueryRating-0.9
 */
jQuery.fn.rating = function(url, settings){
	return this.each(function(){
		
		settings = jQuery.extend({
			radio: "rating",
			hidden: "rating",
			mouseover: "over",
			normal: "star"
		}, settings);

		var t = this;		
		var radios = jQuery(this).find("input[@name=" + settings.radio + "]");

		/**
		 * If there are no radio buttons, quit
		 */		
		if(!radios.length){
			if(window.console){
				window.console.warn("Did not apply rating to form, could not find radio buttons with name: " + settings.radio);
			}
			return false;
		} 		
		
		/**
		 * Add a new hidden input to handle the rating
		 */
		jQuery(this).append("<input type='hidden' name='" + settings.hidden + "' value='0' />");		
		var rating = jQuery(this).find("input[@type=hidden][@name=" + settings.hidden + "]:first");		
		var fields = jQuery(this).find("input").not("[@type=radio][@type=submit]");

		/**
		 * Hide the submit button
		 */
		jQuery(this).find("input[@type=submit]").hide();
		jQuery("span#ctl00_content_logInMessage").hide();
		
		/**
		 * Apply actions and styles to all of the radio buttons
		 * @param {Object} i
		 */
		radios.each(function(i){
			jQuery(this).hide();
			jQuery(this).next().addClass(settings.normal);
			jQuery(this).next().attr("index", i+1);
			jQuery(this).next().hover(
				function(){
					var label = jQuery(t).find(this);
					label.addClass(settings.mouseover);
					var index = label.attr("index") - 1;
					for(i = index; i >= 0; i--){
					    var index2 = i+1;
						jQuery(t).find("label[@index=" + index2 +"]").addClass(settings.mouseover);
					}
			},
				function(){
					var label = jQuery(this);
					label.removeClass(settings.mouseover);
					var index = label.attr("index") - 1;
					for(i = index; i >= 0; i--){
					    var index2 = i+1;
						jQuery(t).find("label[@index=" + index2 +"]").removeClass(settings.mouseover);
					}
				}
			);
			
			/**
			 * Disable the rating form, send the data and highlight the stars based on the response
			*/			
			jQuery(this).next().bind("click", function(){				
				jQuery(rating).val(jQuery(this).prev().val());				
				jQuery(radios).each(function(i){
					jQuery(this).next().unbind();
				});		
			
				var data = fields.serialize();		
				jQuery.get(url, data, function(xml){
				    var rating = jQuery("rating", xml).text();

				    if (rating == "999") {
				        jQuery("form.ratingform").fadeOut("slow", function() {
				            jQuery("span#ctl00_content_logInMessage").fadeIn("fast");
				        });				        
				    } else {
					    jQuery("span#averageRating").html(rating);
				    }
				});
			});						
		});		
		return this;		
	});	
};