﻿/* LiteTest gradable
* Version 0.9
* Author Jonas Hagstedt
* URI: http://www.litetest.com/Resources.aspx/Gradable
* Released with the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
	$.fn.gradable = function(callback, options) {
		var settings = jQuery.extend({
			defaultClass: "lt_gradable_default",
			hoverClass: "lt_gradable_hover",
			inactiveClass: "lt_gradable_inactive",
			showCheckbox: false,
			range: 5
		}, options);

		return this.each(function() {
			var changeGrade = true;

			$(this).addClass(settings.defaultClass);
			var ths = $(this);
			var gradeLight = $("<div></div>").addClass(settings.hoverClass);
			//gradeLight.appendTo($(this));
			gradeLight.prependTo($(this));
			gradeLight.css("width", "0px");

			if (settings.showCheckbox == false)
				$(this).find("input").hide();

			// Select value
			function selectRating(val) {
				var x = Math.ceil(ths.width()) / settings.range;

				showInactive(true);

				// Fill the grade to div
				gradeLight.css("width", Math.round((val * x)) + "px");

				// Select the radio button
				$(this).find("input[value=" + val + "]").attr("checked", true);
			}

			function showInactive(isTrue) {
				if (isTrue) {
					gradeLight.addClass(settings.inactiveClass);
					gradeLight.removeClass(settings.hoverClass);
				} else {
					gradeLight.removeClass(settings.inactiveClass);
					gradeLight.addClass(settings.hoverClass);
				}
			}

			// Click action
			$(this).click(function(e) {
				if (changeGrade == true) {
					changeGrade = false;
					var x = Math.ceil($(this).width()) / settings.range;
					var selectedValue = Math.ceil((e.pageX - $(this).offset().left) / x);
					selectRating(selectedValue);

					// Callback
					callback(selectedValue, $(this));
				}
				else {
					showInactive(false);
					changeGrade = true;
				}
			});

			if ($(this).find("input:checked").length > 0) {
				selectRating($(this).find("input:checked").val());
			}

			$(this).mousemove(function(e) {
				if (changeGrade) {
					showInactive(false);
					var width = e.pageX - $(this).offset().left + "px";
					gradeLight.css("width", width);
				}
			});

			$(this).mouseleave(function(e) {
				if (changeGrade) {
					if (ths.find("input:checked").length > 0) {
						selectRating(ths.find("input:checked").val());
					} else {
						gradeLight.css("width", "0px");
					}
				} else {
				}
			});

		});
	};
})(jQuery);