/*
 meta: {
	 title: "editableSelect.js",
	 copy: "copyright 2009 nori (norimania@gmail.com)",
	 license: "MIT",
	 author: "5509 - http://moto-mono.net",
	 date: "2009-06-17"
 }
 */

(function($j){

	$j.fn.editableSelect = function(options){
	
		var c = $j.extend({
			value: '(value)'
		},options || {});
	
		$j(this).each(function(){
		
			// variables
			var that = $j(this),
				option = $j('option',that),
				inputField = document.createElement('input'),
				input = $j(inputField),
				
				overwrite = function(){
				// replace input & select and add new option
					var value = input.val();
					if(value!=''){
						that.append('<option value="'+value+'">'+value+'</option>');
					}
					input.val('').remove();
					that.show().focus();		
					$j('option:last-child',that).attr('selected','selected');
				
				};
				
			// set input default attrs
			input.attr({
    			type: 'text',
    			id: 'editable_'+that.attr('id'),
    			name: 'editable_'+that.attr('name'),
    			className: 'contemporary_input',
    			value: ''
    		});
			
			// append editableSelect trigger to target select
			that.append('<option value="#edit">'+c.value+'</option>');
			
			// if that value has changed...			
			that.change(function(){
			
				// pull the trigger
				if(that.val()=='#edit'){
				
					that.before(inputField);
					that.hide();
					input.focus();
					
					// blur or keydown('return') call the overwrite func
					input.blur(overwrite).keydown(function(e){
					
						if(e.keyCode=='13'){
						
							overwrite();
						
						}
					
					});
				
				}
			
			});
			
		});
				
	}

})(jQuery);

