/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/
	
	// IE6 Background Image Fix
	if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { };
	// Thanks to http://www.visualjquery.com/rating/rating_redux.html
	
	// plugin initialization
	$.fn.probstars = function(options){
		if(this.length==0) return this; // quick fail
		
		// Handle API methods
		if(typeof arguments[0]=='string'){
			// Perform API methods on individual elements
			if(this.length>1){
				var args = arguments;
				return this.each(function(){
					$.fn.probstars.apply($(this), args);
				});
			};
			// Invoke API method handler
			$.fn.probstars[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			// Quick exit...
			return this;
		};
		
		// Initialize options for this call
		var options = $.extend(
			{}/* new object */,
			$.fn.probstars.options/* default options */,
			options || {} /* just-in-time options */
		);
		
		// Allow multiple controls with the same name by making each call unique
		$.fn.probstars.calls++;
		
		// loop through each matched element
		this
		.not('.star-rating-applied')
		.addClass('star-rating-applied')
		.each(function(){
			
			// Load control parameters / find context / etc
			var input = $(this);
			var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
			var context = $(this.form || document.body);
			
			// FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
			var raters = context.data('rating');
			if(!raters || raters.call!=$.fn.probstars.calls) raters = { count:0, call:$.fn.probstars.calls };

			// Initialize options for this raters
			var control = $.extend(
				{}/* new object */,
				options || {} /* current call options */,
				($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
				{ count:0, stars: [], inputs: [] }
			);
			
			// increment number of rating controls
			control.serial = raters.count++;

			// calc siteval
			if(control.sitenum==0){
				control.siteval = 0;
			} else {
				control.siteval = Math.floor(4*control.sitesum/control.sitenum+1/2);
			}
			
			// create rating element
			var rater = $('<div class="probstars-rating-control"/>');
			input.append(rater);
			
			// Mark element for initialization (once all stars are ready)
			rater.addClass('rating-to-be-drawn');
			
			// Create 'cancel' button
			rater.append(
				control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>')
				.mouseover(function(){
					if (!control.cancel.is('.rating-cancel-hidden')) {
						$(this).probstars('drain');
						$(this).addClass('rating-cancel-hover');
						//$(this).probstars('focus');
					}
				})
				.mouseout(function(){
					if (!control.cancel.is('.rating-cancel-hidden')) {
						$(this).probstars('draw');
						$(this).removeClass('rating-cancel-hover');
						//$(this).probstars('blur');
					}
				})
				.click(function(){
					$(this).probstars('select');
				})
				.data('rating', control)
				.data('probstars-value','')
			);

			for(var i=0; i<5; ++i) {
				// insert rating star
				var star = $('<div class="star-rating probstars-star rater-'+ control.serial +'"/>').width(16);
				rater.append(star);
				star.data('rating', control);
				star.data('probstars-value',i+1);

				// inherit attributes from input element
				if(this.id) star.attr('id', this.id);
				if(this.className) star.addClass(this.className);
			
				// readonly?
				if(control.readonly){
					// Mark star as readonly so user can customize display
					star.addClass('star-rating-readonly')
						// Attach mouse events
						.click(function(){
							$(this).probstars('select');
						})
					;
				}
				else{
					// Enable hover css effects
					star.addClass('star-rating-live')
						// Attach mouse events
						.mouseover(function(){
							$(this).probstars('fill');
							$(this).probstars('focus');
						})
						.mouseout(function(){
							$(this).probstars('draw');
							$(this).probstars('blur');
						})
						.click(function(){
							$(this).probstars('select');
						})
					;
				};
				
				for(var j=0; j<4; ++j) {
					var part = $('<div class="star-rating probstars-part rater-'+ control.serial +'"><a title="'+ (control.readonly?control.title:control.labels?control.labels[i]:i+1) +'">'+ (i+1) +'</a></div>');
					star.append(part);
					part.width(4).find('a').css({ 'margin-left':'-'+ (4*j) +'px' });
					part.data('probstars-value',4*i+j+1);
				}
			}
				
			
			// store control information in form (or body when form not available)
			control.stars[control.stars.length] = star[0];
			control.inputs[control.inputs.length] = input[0];
			control.rater = raters[eid] = rater;
			control.context = context;
			
			input.data('rating', control);
			rater.data('rating', control);
			context.data('probstars', raters);
		}); // each element
		
		// Initialize ratings (first draw)
		$('.rating-to-be-drawn').probstars('draw').removeClass('rating-to-be-drawn');
		
		return this; // don't break the chain...
	};
	
	/*--------------------------------------------------------*/
	
	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.probstars, {
		// Used to append a unique serial number to internal control ID
		// each time the plugin is invoked so same name controls can co-exist
		calls: 0,
		
		focus: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.focus) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
			// focus handler, as requested by focusdigital.co.uk
			if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.probstars.focus
		
		blur: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.blur) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
			// blur handler, as requested by focusdigital.co.uk
			if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.probstars.blur
		
		fill: function(){ // fill to the current mouse position.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readonly) return;
			// Reset all stars and highlight them up to this element
			this.probstars('drain');
			this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover');
		},// $.fn.probstars.fill
		
		drain: function() { // drain all the stars.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readonly) return;
			// Reset all stars
			control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-hover');
			control.rater.children().filter('.rater-'+ control.serial).children().removeClass('star-rating-on').removeClass('star-rating-v2').removeClass('star-rating-on-v2');
			control.cancel.removeClass('rating-cancel-hover');
		},// $.fn.probstars.drain
		
		draw: function(){ // set value and stars to reflect current selection
			var control = this.data('rating'); if(!control) return this;
			// Clear all stars
			this.probstars('drain');
			// Set control value
			control.rater.children('.probstars-star').each(function(){
				$(this).children().each(function(){
					if ($(this).data('probstars-value') <= control.siteval) {
						if ($(this).data('probstars-value') <= 4*control.voteval) {
							$(this).addClass('star-rating-on-v2');
						} else {
							$(this).addClass('star-rating-on');
						}
					} else {
						if ($(this).data('probstars-value') <= 4*control.voteval) {
							$(this).addClass('star-rating-v2');
						}
					}
				});
			});
			// Show/hide 'cancel' button
			control.cancel[control.readonly || control.required?'hide':'show']();
			control.cancel[control.voteval?'removeClass':'addClass']('rating-cancel-hidden');
			// Add/remove read-only classes to remove hand pointer
			this.siblings()[control.readonly?'addClass':'removeClass']('star-rating-readonly');
		},// $.fn.probstars.draw
		
		select: function(value){ // select a value
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readonly){
				alert(control.title);
				return;
			}
			// programmatically (based on user input)
			if(control.voteval == 0){
				control.sitenum++;
			} else {
				control.sitesum -= control.voteval;
			}
			if(typeof value!='undefined'){
				// select by index (0 based)
				if(typeof value=='number'){
					control.voteval = value;
				}
			}
			else{
				control.voteval = this.data('probstars-value');
			}
			if(control.voteval == 0){
				control.sitenum--;
			} else {
				control.sitesum += control.voteval;
			}
			// recalc siteval
			if(control.sitenum==0){
				control.siteval = 0;
			} else {
				control.siteval = Math.floor(4*control.sitesum/control.sitenum+1/2);
			}
			// Update display
			this.probstars('draw');
			// click callback
			if(control.callback) control.callback.apply(control.rater.parent()[0], [control.voteval,control.sitesum,control.sitenum]);// callback event
		},// $.fn.probstars.select
		
		readonly: function(toggle, disable){ // make the control read-only (still submits value)
			var control = this.data('rating'); if(!control) return this;
			// setread-only status
			control.readonly = toggle || toggle==undefined ? true : false;
			// enable/disable control value submission
			if(disable) $(control.inputs).attr("disabled", "disabled");
			else     			$(control.inputs).removeAttr("disabled");
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.probstars('draw');
		},// $.fn.probstars.readonly
		
		disable: function(){ // make read-only and never submit value
			this.probstars('readonly', true, true);
		},// $.fn.probstars.disable
		
		enable: function(){ // make read/write and submit value
			this.probstars('readonly', false, false);
		}// $.fn.probstars.select
		
	});
	
	/*--------------------------------------------------------*/
	
	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.probstars.options.cancel = 'Clear';
	*/
	$.fn.probstars.options = { //$.extend($.fn.probstars, { options: {
			cancel: 'Cancel Rating',   // advisory title for the 'cancel' link
			cancelValue: '',           // value to submit when user click the 'cancel' link
			split: 0,                  // split the star into how many parts?
			value: 0,
			value2: 0,
			
			// Width of star image in case the plugin can't work it out. This can happen if
			// the jQuery.dimensions plugin is not available OR the image is hidden at installation
			starWidth: 16//,
			
			//NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
			//half:     false,         // just a shortcut to control.split = 2
			//required: false,         // disables the 'cancel' button so user can only select one of the specified values
			//readonly: false,         // disable rating plugin interaction/ values cannot be changed
			//focus:    function(){},  // executed when stars are focused
			//blur:     function(){},  // executed when stars are focused
			//callback: function(){},  // executed when a star is clicked
	}; //} });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default implementation ###
		The plugin will attach itself to file inputs
		with the class 'multi' when the page loads
	*/
	$(function(){
		$('div.probstars').probstars();
	});
	
	
	
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/

