/**
 * @author arjen
 */

/*
$(function(){
	var a = $('form.genreMonthSelect select').autoSelect();
	if (a.length) {
		$('form.genreMonthSelect').addClass('genreMonthSelect-auto');
	}
});
*/

/**
 * autoSelect, jQuery plugin, debug version
 * 
 * Auto-submit forms when select options has changed
 * Smoothens out (almost) behaviour differences between  browsers.
 * Inpsired on: http://themaninblue.com/writing/perspective/2004/10/19/
 * 
 * usage: $selection.autoSelect({options})
 * 
 * @author AK | Peppered
 * @version 1.0-beta-debug
 * 
 */
;(function($) {
	$.fn.autoSelect = function(options){
		options = $.extend({
			debug: true
		}, options);
		
		return this.each(function() {
			var $this = $(this);
						
			$this.validKeyChange = true;		// for browser that trigger change event when option changed by keyboard (IE)
			$this.initValue = $(this).val();
			
			$this.change(function(){
				if (options.debug) $.log('event: change');
				if ($this.validKeyChange && (this.value != $this.initValue)) {		
					if (options.debug) $.log("The select has been changed from " + $this.initValue + " to " + this.value);
					$this.initValue = this.value;
					if (options.debug)
						return false;
					else
						this.form.submit();
				}
			});
			
			$this.keydown(function(e){
				// 9=tab, 13=enter, esc=27
				if ((e.keyCode == 13 || e.keyCode == 9) && this.value != $this.initValue) {			
					$this.validKeyChange = true;
					$this.change();
				}
				else {
					if (e.keyCode == 27 || ((e.keyCode == 13 || e.keyCode == 9) && this.value == $this.initValue)) {
						this.value = $this.initValue; // a.o. for Safari when opening select with mouse, using keys & tabbing off
					}
					else {
						$this.validKeyChange = false;
					}
				}			
			});		
		});
	}
})(jQuery);

