/*
 * jQuery plugin: fieldSelection - v0.1.1 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */

(function() {

    $.fn.getSelection = function() {

		var e = (this.jquery) ? this[0] : this;

		return (

			/* mozilla / dom 3.0 */
			('selectionStart' in e && function() {
				var l = e.selectionEnd - e.selectionStart;
				return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
			}) ||

			/* exploder */
			(document.selection && function() {

				e.focus();

				var r = document.selection.createRange();
				if (r === null) {
					return { start: 0, end: e.value.length, length: 0 }
				}

				var re = e.createTextRange();
				var rc = re.duplicate();
				re.moveToBookmark(r.getBookmark());
				rc.setEndPoint('EndToStart', re);

				return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
			}) ||

			/* browser not supported */
			function() { return null; }

		)();

	},

	$.fn.replaceSelection = function(insert) {

		return this.each(function() {
		
    		var e = this;
    		var elem = $(this);
    		
    		var text = typeof(insert) == 'string' ? insert : '';
            elem.focus();

    		return (
    
    			/* mozilla / dom 3.0 */
    			('selectionStart' in e && function() {
    			    start = e.selectionStart;
    				e.value = e.value.substr(0, start) + text + e.value.substr(e.selectionEnd, e.value.length);
    				elem.focus();
    				e.setSelectionRange(start+ text.length, start + text.length);
    				return this;
    			}) ||
    
    			/* exploder */
    			(document.selection && function() {
    				e.focus();
    				document.selection.createRange().text = text;
    				return this;
    			}) ||
    
    			/* browser not supported */
    			function() {
    				e.value += text;
    				return jQuery(e);
    			}
    
    		)();
    	});

	}

})();
