/*
 oh my god, the fleshlight monolith is full of stars!
 @jalley
*/
(function ($) {
	$.fn.starify = function (options) {
		var o = $.extend({star_html: []}, $.fn.starify.defaults, options);

		// you gotta at least get a gold star
		if (o.span < 1) {
			return false;
		}

		// create the interface
		for (var i = 1; i <= o.span; i++) {
			o.star_html.push('<div>', i, '</div>');
		}
		o.star_html.push('<br class="starify-clear" />');
		o.star_html = o.star_html.join('');

		return this.each(function () {
			var $$ = $(this);

			// set the rating -- argument overrides, defaults to the input field, otherwise nada
			var embedded_rating = $$.find('input[type="hidden"]');
			var rating = (o.rating) ? o.rating : ((embedded_rating.length) ? embedded_rating.val() : 0);

			// flip to read only if there's no input
			if (!embedded_rating.length) {
				o.read_only = true;
			}

			// draw the interface and turn on stars
			$$.addClass('starify').prepend(o.star_html).find(['div:lt(', Math.floor(rating), ')'].join('')).addClass('rating-on');

			// any half stars?  turn them on appropriately
			if (Math.ceil(rating) != rating) {
				$$.find(['div:eq(', Math.ceil(rating) - 1, ')'].join('')).addClass('rating-half');
			}

			// mouseover action for rating if not read only
			if (o.read_only === false) {
				$$.find('div').mouseover(function () {
					$$.find('div').addClass('rating-custom-off');
					$(this).addClass('rating-custom-on').prevAll('div').addClass('rating-custom-on');
				}).mouseleave(function () {
					$$.find('div').removeClass('rating-custom-on rating-custom-off');
				}).click(function () {
					$$.find('input[type="hidden"]').val($$.find('div').index(this) + 1).parent().find('div').unbind('mouseover').unbind('mouseleave').unbind('click');
				});
			}
		});
	};

	$.fn.starify.defaults = {
		read_only: false,
		rating: false, // specifying this will draw out this rating if no input is found
		span: 5        // from 1 to n
	};
})(jQuery);