;(function($) {

$.widget("ui.stringInput", {
    get: function() {
        return this.$input.val()
    },

	set: function(value) {
		if (value) {
			this.$input.val(value)
		} else {
			// undefined or other == undefined argument for val() will not set, but GET value
			this.$input[0].value = ''
		}

		this.renderValue()

		this.element.triggerHandler('select', [value])
	},

	renderValue: function() {
		this.$input.hide()
		var val = this.$input.val()
		// if value is empty, show it like long space (underlined)
		this.element.html(val.length ? val : '&nbsp;&nbsp;&nbsp;')
		this.element.show()
	},

	showInput: function(focus) {
		this.element.hide();
		this.$input.show();
		if (focus) {
			this.focus()
		}
	},

	focus: function() {
		this.$input.focus()
		this.$input.select()
	},

	/**
	 * Create input element, setup events on input and this.element
	 * set value from getData('value')
	 */
	_init: function() {
		
		this.init(arguments);
	},
	
	init: function() {
		$.widget.prototype._init.apply(this,arguments)
		var o = this.element[0]

		this.element.after('<input class="inb1 hide" type="text" value="" name="'+o.id+'_input" id="'+o.id+'_input" maxlength="10" /">')

		this.$input = $(document.getElementById(o.id+'_input'))

		var self = this

		this.$input.focus(function() {self.inputFocused = true;self.selectInput()})
			.change(function() {self.blurInput()})
			.blur(function() {self.inputFocused = false;self.blurInput()})
		    .keydown(function(e) {
                switch(e.keyCode) {
                    case 9:  // tab
                    case 13: // return
                        self.blurInput()
                }
			})

		// helper not to trigger twice
		var is_focus = false

		this.element.click(function() {
			if(is_focus) {
				is_focus = false;
				return;
			}
			self.showInput(true)

			is_focus = false;
		})
		.focus(function() {
			is_focus = true;
			self.showInput(true)

		})

		this.set(this._getData('value'))

	},

	selectInput: function() {
		var o = this.element[0]
		if(o.setSelectionRange)
			o.setSelectionRange(0, o.value.length);
		else if(typeof(Selection) != 'undefined' && Selection.isSupported){
			var t = o.createTextRange();
			t.move('character', 0);
			t.moveEnd('character', o.value.length);
			t.select();
		}
	},

	blurInput: function() {
		this.set(this.$input.val())
	},

	hasInputFocus: function() {
		return this.inputFocused
	}

})

$.extend($.ui.stringInput, {
	
	getter: "hasInputFocus get"
});

})(jQuery);