(function($) {

    /* ------------------------------------------------------------------
    Animate Popin --------------------------------------------------- */
    $.fn.animatePopin = function(which, url, divFrame) {
        if (divFrame == null) divFrame = "#main";
        var targetOffset = $(divFrame).offset().top;
        $('html, body').animate({ scrollTop: targetOffset }, 600);

        return this.each(function() {
            finalSize = { width: $(this).width() + "px" }
        })
		.css({ width: '1px' })
		.animate(finalSize, 1200);
    };


    /* ------------------------------------------------------------------
    Modify Input Tabindex ------------------------------------------- */
    $.fn.changeTabIndex = function() {
        return this.each(function() {
            var $input = $(this).find(":input");
            if ($input.size() > 0) {
                $input
				.each(function() { this.tabIndex = this.tabIndex + 80; });
            }
        });
    };


    /* ------------------------------------------------------------------
    Bind Events ------------------------------------------------------ */
    $.fn.bindEvents = function(which, url) {
        $().bind('keypress.bindEvents', function(e) {
            e = e || window.event;
            var kC = e.keyCode;
            var Esc = e.DOM_VK_ESCAPE /* moz */ || 27;
            if (kC == Esc) { closePopin(); }
        });

        if (which == 'share') {
            // Bind Click on link
            $("a", this).bind("click.bindEvents", function() {

                var size, share_item = $(this).attr("class").replace('b_', '');
                switch (share_item) {
                    case 'facebook': size = "width=620,height=436"; break;
                    case 'delicious': size = "width=725,height=400"; break;
                    case 'digg': size = "width=800,height=600"; break;
                    case 'stumbleupon': size = "width=550,height=400"; break;
                    default: size = "width=500,height=500";
                }

                // Log the share in Google Analytics
                if (undefined !== window.pageTracker) {
                    pageTracker._trackPageview('/share/' + share_item);
                }

                var my_popup = window.open($(this).attr("href"), "share_" + share_item, "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no," + size);
                if (my_popup) { my_popup.focus(); }
                return !my_popup;
            });
        } else {
            // Bind Click on button
            $(":button", this)
			.bind("click.bindEvents", function() {
			    $(this)
					.attr('disabled', 'disabled')
					.css({ cursor: "default", opacity: .6 })
					.submitPopin(which, url);
			    return false;
			});
        };

        return this;
    };


    /* ------------------------------------------------------------------
    Save .Net Hidden Field inside Popin - Allow Callback ------------ */
    $.fn.getContent = function(which, resp) {
        var $form = $("#frm-" + which, resp);
        // Update TabIndex
        $form.changeTabIndex();

        //Fix IE Hover and Focus
        if ($.browser.msie && $.browser.version < 8) {
            // Fix button:hover
            $form.find(".btn").addHover("overBtn");

            //Fix Abbr
            $form.fixAbbr();

            //Add Focus
            $form.inpFocus();
        }

        return this.html($form);
    };


    /* ------------------------------------------------------------------
    Fix ASP.Net form submit - Allow to press enter ------------------ */
    $.fn.SubmitListener = function() {
        $().bind('keypress.SubmitListener', function(e) {
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
            var target = e.target.tagName.toLowerCase();
            if (key === 13 && target === 'input') {
                e.preventDefault();
                $(e.target)
					.parents('fieldset:first')
					.find(":image, :button")
					.trigger('click');
            }
        });
        return this;
    };



    /* ------------------------------------------------------------------
    Save .Net Hidden Field inside Popin - Allow Callback ------------ */
    $.fn.fixCallback = function(resp) {
        //Keep the .Net hidden Field
        var $hidden = $(resp).find("#__VIEWSTATE, #__EVENTTARGET, #__EVENTARGUMENT, #__EVENTVALIDATION").each(function() { this.id = "POPIN" + this.id; this.name = "POPIN" + this.name; });

        return this.append($hidden);
    };

    $.fn.serializeFixCallback = function() {
        return this
			.find(":input")
			.filter("#POPIN__VIEWSTATE, #POPIN__EVENTTARGET, #POPIN__EVENTARGUMENT, #POPIN__EVENTVALIDATION")
			.each(function() { this.name = this.name.replace(/POPIN/, ""); })
			.end()
			.serialize();
    };


    /* ------------------------------------------------------------------
    Ajax Call - Submit Popin ---------------------------------------- */
    $.fn.submitPopin = function(which, url) {
        var $btn = $(this);
        $.ajax({
            type: "POST",
            url: url,
            //Serialize only fields inside Popin
            data: $btn.parents("#popin:first").serializeFixCallback(),
            complete: function() {
                $btn.attr('disabled', '').css({ cursor: "pointer", opacity: 1 });
            },
            success: function(resp) {
                // Log the action in Google Analytics
                if (undefined !== window.pageTracker) {
                    pageTracker._trackPageview(url);
                }

                //if(resp.substr(0,7).toLowerCase() === "success"){
                if (resp.indexOf("success") >= 0) {
                    loc = window.location.toString();
                    loc = loc.replace("/" + resp.split('~')[2] + "/", "/" + resp.split('~')[1] + "/");
                    window.location = loc;
                    //location.href = location.href;
                } else {
                    $("#popin")
						.find(".popin_content")
						.getContent(which, resp)
						.bindEvents(which, url)
						.fixCallback(resp);
                }
            }
        });

        return this;
    };


    /* ------------------------------------------------------------------
    Clears the form data -------------------------------------------- */
    $.fn.clearForm = function() {
        return this.each(function() {
            $(".error", this).removeClass("error");
            $('input,select,textarea', this).clearFields();
        });
    };

    // Clears the selected form elements.
    $.fn.clearFields = $.fn.clearInputs = function() {
        return this.each(function() {
            var t = this.type, tag = this.tagName.toLowerCase();
            if (t == 'text' || t == 'password' || tag == 'textarea')
                this.value = '';
            else if (t == 'checkbox' || t == 'radio')
                this.checked = false;
            else if (tag == 'select')
                this.selectedIndex = 0;
        });
    };


    /* ------------------------------------------------------------------
    Registration ---------------------------------------------------- */
    $.fn.chooseYourBird = function(imagesPath) {
        return this.each(function() {
            if (imagesPath == 0 || imagesPath == null) {
                imagesPath = "/~/birds/images.aspx";
            }
            //Init
            $("select :selected", this).each(function() {

                //Load the Selected Bird
                $.get(imagesPath, { b: $(this).val() }, function(resp) {


                    $("#chooseyourbirds")
						.addClass("isLoaded")
						.html(resp)
                    .bind("click.bindChooseYourBirdEvents", function(e) {
                        e.preventDefault();
                        var $this = $(this);
                        var $click = $(e.target);
                        if ($click.is("a") || $click.is(".thumb_img")) {
                            var $link = $click.is(".thumb_img") ? $click.parent() : $click;
                            switch ($link.attr("class")) {
                                case 'i_prev':
                                case 'i_next':
                                case 'b_prev':
                                case 'b_next':
                                    $this.load($link.attr("href"),
                                     function() {
                                         var avatarImage = $("#avatarImage");
                                         if (avatarImage != null) {
                                             $("#profile-bird").css('background', 'url(\'' + avatarImage.val() + '\') no-repeat 50% 7px');
                                         }
                                         var avatarThumbToSet = $("#avatarThumb");
                                         if (avatarThumbToSet != null) {
                                             var currentBirdThumb = $("[id*='inpBirdThumbUrlSelected']");
                                             currentBirdThumb.val(avatarThumbToSet.val());
                                         }
                                     }
                                    );


                                    break;
                                case 'b_thumb':
                                case 'b_thumb selected':
                                    //Get New Color from the Hash
                                    var newColor = $link.get(0).hash.substring(1);
                                    //Get the Old Color and remove selected class
                                    var oldColor;
                                    $(".selected", $this).each(function() {
                                        oldColor = $(this).get(0).hash.substring(1);
                                    }).removeClass("selected");

                                    //Replace the Bird
                                    $(".thebird", $this)
										.each(function() {
										    this.src = this.src.replace(oldColor, newColor);
										});
                                    // Sanctuary div
                                    $("#profile-bird").each(function() {
                                        var avatarImage = $("#avatarImage");
                                        var avatarThumbToSet = jQuery("[id*='avatarThumb']");
                                        if (avatarImage != null) {
                                            avatarImage.val(avatarImage.val().replace(oldColor, newColor));


                                            $(this).css('background', 'url(\'' + avatarImage.val() + '\') no-repeat 50% 7px');
                                            $(this).blur();
                                        }
                                        if (avatarThumbToSet != null) {
                                            avatarThumbToSet.val(avatarThumbToSet.val().replace(oldColor, newColor));
                                            var currentBirdThumb = jQuery("[id*='inpBirdThumbUrlSelected']");
                                            currentBirdThumb.val(avatarThumbToSet.val());
                                        }
                                    });


                                    //Update Hidden field
                                    $("#avatar").each(function() {
                                        $(this).val($(this).val().replace(oldColor, newColor));
                                    });

                                    //Add Arrow to the new color
                                    $link.addClass("selected");


                                 


                                    break;
                                default: ;
                            }
                            return false;
                        }
                    });
                });
            });
        })
    }


    /*  ------------------------------------------------------------------
    Hover function --------------------------------------------------- */
    $.fn.addHover = function(classOver) {
        var classHover = classOver || "over";
        return this.hover(
            function() { $(this).addClass(classHover); },
            function() { $("." + classHover).removeClass(classHover); }
        );
    };


    /*  ------------------------------------------------------------------
    Vertically align Function ---------------------------------------- */
    $.fn.vAlign = function() {
        return this.each(function(i) {
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = (ph - ah) / 2;

            $(this).css('margin-top', mh);
        });
    };


    /*  ------------------------------------------------------------------
    Fix Input Focus -------------------------------------------------- */
    $.fn.inpFocus = function(settings) {

        // defaults settings
        settings = $.extend({
            classFocus: "inpFocus"
        }, settings);

        return this.each(function() {
            $(this).find("input:text, input:password, textarea, select").each(function() {
                $(this)
				.bind("focus.inpFocus", function() {
				    $(this).addClass(settings.classFocus);
				})
				.bind("blur.inpFocus", function() {
				    $(this).removeClass(settings.classFocus);
				})
				.blur(); // now change all inputs
            });
        });
    };


    /*  ------------------------------------------------------------------
    Rollover --------------------------------------------------------- */
    function imgExist(img) { return $.ajax({ url: img, async: false }).status; }

    $.fn.rollover = function(settings) { // param checkIfExist used to check if the image exist, default value "false"
        var container = this;

        // defaults settings
        settings = jQuery.extend({
            classOver: ".ro",
            over: "_o",
            checkIfExist: false
        }, settings);

        return container.each(function() {
            var Elm = this;
            var overElm = $(settings.classOver, Elm);

            overElm.each(function() {
                var srcOut = $(this).attr('src');
                var ftype = srcOut.substring(srcOut.lastIndexOf('.'), srcOut.length);
                var fname = srcOut.substring(0, srcOut.lastIndexOf('.'));
                var srcOver = fname + settings.over + ftype;
                var exist = true;
                if (settings.checkIfExist === true) { exist = (imgExist(srcOver) != 404); }
                if (exist) {
                    $(this).hover(
                        function() { $(this).attr('src', srcOver); },
                        function() { $(this).attr('src', srcOut); }
                    );
                }
            });
        });
    };


    /*  ------------------------------------------------------------------
    Plugin/Cookie ---------------------------------------------------- */
    $.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';

            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };


    /*  ------------------------------------------------------------------
    switchSize ------------------------------------------------------- */
    $.fn.switchSize = function(settings) {

        // defaults settings
        settings = $.extend({
            container: 'body',
            arrSizeClass: ['small', 'medium', 'large'],
            defaultClass: 'medium',
            saveCookie: true
        }, settings);

        var $container = $(settings.container);
        return this
			.each(function() {
			    if ($.cookie('switchSize')) { $container.addClass($.cookie('switchSize')); $(this).data("current", $.cookie('switchSize')) }
			})
			.bind("click", function() {
			    var pos;
			    if ($(this).data("current")) {
			        pos = jQuery.inArray($(this).data("current"), settings.arrSizeClass);
			    } else {
			        pos = jQuery.inArray(settings.defaultClass, settings.arrSizeClass);
			    }
			    if (pos >= 0) { //Found Class
			        if (pos == settings.arrSizeClass.length - 1) { //Check if last
			            $(this).data("current", settings.arrSizeClass[0]);
			        } else {
			            $(this).data("current", settings.arrSizeClass[pos + 1]);
			        }
			    } else {
			        //To prevent error
			        $(this).data("current", settings.arrSizeClass[0]);
			    }

			    $container.removeClass(settings.arrSizeClass[pos]).addClass($(this).data("current"));

			    if (settings.saveCookie === true) {
			        $.cookie('switchSize', $(this).data("current"), { expires: 365, path: '/' });
			    }
			});
    };


    /*  ------------------------------------------------------------------
    External Link ---------------------------------------------------- */
    $.extend($.expr[':'], {
        external: function(a, i, m) {
            if (!a.href) { return false; }
            return $(a).is('[rel*="external"]');
        }
    });

    $.fn.externalLinks = function() {
        return this.each(function() {
            $("a", this)
                .filter(function() {
                    if ($(this).is(":external")) {
                        return true;
                    } else {
                        return $(this).is("[href^='http://']:not([href*='" + location.hostname + "'])");
                    }

                })
				.bind("click", function() {
				    if (undefined !== window.pageTracker) {
				        pageTracker._trackPageview('/external/' + this.href);
				    }
				    return !window.open(this.href);
				});
        });
    };

    /* ------------------------------------------------------------------
    Fix IE6 Abbr ---------------------------------------------------- */
    $.fn.fixAbbr = function() {
        return this.each(function() {
            var container = $(this);
            $(".inp_field", this).each(function() {
                var $label = $("[for=" + $(this).attr("id").replace(/parent_/, '') + "]", container);
                if ($label.size() > 0) {
                    $label.html($label.html().replace(/<ABBR([^>]*)>([^<]*)<\/ABBR>/g, "<SPAN class=\"abbrIE\" $1>$2</SPAN>"));
                }
            })
        });
    };

})(jQuery);


/*
 ### jQuery Star Rating Plugin v3.12 - 2009-04-16 ###
 * Home: http://www.fyneworks.com/jquery/star-rating/
 * Code: http://code.google.com/p/jquery-star-rating-plugin/
 *
	* Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 ###
*/

/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/
	
	// plugin initialization
	$.fn.rating = 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.rating.apply($(this), args);
    });
			};
			// Invoke API method handler
			$.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			// Quick exit...
			return this;
		};
		
		// Initialize options for this call
		var options = $.extend(
			{}/* new object */,
			$.fn.rating.options/* default options */,
			options || {} /* just-in-time options */
		);
		
		// Allow multiple controls with the same name by making each call unique
		$.fn.rating.calls++;
		
		// loop through each matched element
		this
		 .not('.star-rating-applied')
			.addClass('star-rating-applied')
		.each(function(){
			
			// Load control parameters / find context / etc
			var control, 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.rating.calls) raters = { count:0, call:$.fn.rating.calls };
			var rater = raters[eid];
			
			// if rater is available, verify that the control still exists
			if(rater) control = rater.data('rating');
			
			if(rater && control)//{// save a byte!
				// add star to control if rater is available and the same control still exists
				control.count++;
				
			//}// save a byte!
			else{
				// create new control if first star or control element was removed/replaced
				
				// Initialize options for this raters
				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++;
				
				// create rating element
				rater = $('<span class="star-rating-control"/>');
				input.before(rater);
				
				// Mark element for initialization (once all stars are ready)
				rater.addClass('rating-to-be-drawn');
				
				// Accept readOnly setting from 'disabled' property
				if(input.attr('disabled')) control.readOnly = true;
				
				// Create 'cancel' button
				rater.append(
					control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>')
					.mouseover(function(){
						$(this).rating('drain');
						$(this).addClass('star-rating-hover');
						//$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).removeClass('star-rating-hover');
						//$(this).rating('blur');
					})
					.click(function(){
					 $(this).rating('select');
					})
					.data('rating', control)
				);
				
			}; // first element of group
			
			// insert rating star
			var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>');
			rater.append(star);
			
			// inherit attributes from input element
			if(this.id) star.attr('id', this.id);
			if(this.className) star.addClass(this.className);
			
			// Half-stars?
			if(control.half) control.split = 2;
			
			// Prepare division control
			if(typeof control.split=='number' && control.split>0){
				var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
				var spi = (control.count % control.split), spw = Math.floor(stw/control.split);
				star
				// restrict star's width and hide overflow (already in CSS)
				.width(spw)
				// move the star left by using a negative margin
				// this is work-around to IE's stupid box model (position:relative doesn't work)
				.find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
			};
			
			// readOnly?
			if(control.readOnly)//{ //save a byte!
				// Mark star as readOnly so user can customize display
				star.addClass('star-rating-readonly');
			//}  //save a byte!
			else//{ //save a byte!
			 // Enable hover css effects
				star.addClass('star-rating-live')
				 // Attach mouse events
					.mouseover(function(){
						$(this).rating('fill');
						$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).rating('blur');
					})
					.click(function(){
						$(this).rating('select');
					})
				;
			//}; //save a byte!
			
			// set current selection
			if(this.checked)	control.current = star;
			
			// hide input element
			input.hide();
			
			// backward compatibility, form element to plugin
			input.change(function(){
    $(this).rating('select');
   });
			
			// attach reference to star to input element and vice-versa
			star.data('rating.input', input.data('rating.star', star));
			
			// 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);
			star.data('rating', control);
			context.data('rating', raters);
  }); // each element
		
		// Initialize ratings (first draw)
		$('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');
		
		return this; // don't break the chain...
	};
	
	/*--------------------------------------------------------*/
	
	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.rating, {
		// 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.rating.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.rating.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.rating('drain');
			this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover');
		},// $.fn.rating.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-on').removeClass('star-rating-hover');
		},// $.fn.rating.drain
		
		draw: function(){ // set value and stars to reflect current selection
			var control = this.data('rating'); if(!control) return this;
			// Clear all stars
			this.rating('drain');
			// Set control value
			if(control.current){
				control.current.data('rating.input').attr('checked','checked');
				control.current.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-on');
			}
			else
			 $(control.inputs).removeAttr('checked');
			// Show/hide 'cancel' button
			control.cancel[control.readOnly || control.required?'hide':'show']();
			// Add/remove read-only classes to remove hand pointer
			this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly');
		},// $.fn.rating.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) return;
			// clear selection
			control.current = null;
			// programmatically (based on user input)
			if(typeof value!='undefined'){
			 // select by index (0 based)
				if(typeof value=='number')
 			 return $(control.stars[value]).rating('select');
				// select by literal value (must be passed as a string
				if(typeof value=='string')
					//return 
					$.each(control.stars, function(){
						if($(this).data('rating.input').val()==value) $(this).rating('select');
					});
			}
			else
				control.current = this[0].tagName=='INPUT' ? 
				 this.data('rating.star') : 
					(this.is('.rater-'+ control.serial) ? this : null);
			
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
			// find data for event
			var input = $( control.current ? control.current.data('rating.input') : null );
			// click callback, as requested here: http://plugins.jquery.com/node/1655
			if(control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
		},// $.fn.rating.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.rating('draw');
		},// $.fn.rating.readOnly
		
		disable: function(){ // make read-only and never submit value
			this.rating('readOnly', true, true);
		},// $.fn.rating.disable
		
		enable: function(){ // make read/write and submit value
			this.rating('readOnly', false, false);
		}// $.fn.rating.select
		
 });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.rating.options.cancel = 'Clear';
	*/
	$.fn.rating.options = { //$.extend($.fn.rating, { 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?
			
			// 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(){
	 $('input[type=radio].star').rating();
	});
	*/
	
	
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/

