var tab = {

	key: 9,

	string: "\t",

	nl2br: true,

	tosp: true,

	watching: {},

	results: {},

	$: function(id){
		return document.getElementById(id);
	},

	watch: function(obj){
		if(obj && this.$(obj)){
			this.watching["_" + obj] = this.$(obj);
			this.addEvent(this.$(obj), "keydown", function(evt){
				var sct = tab.$(obj).scrollTop;
				var l = tab.$(obj).value.length;
				var evt = (evt)? evt : ((window.event)? event : null);
				
				if(evt){
					var elem = (evt.target)? evt.target : ((evt.srcElement)? evt.srcElement : null);

					if(elem){
						var char_code = (evt.charCode)? evt.charCode : ((evt.which)? evt.which : evt.keyCode);

						if(char_code == tab.key){
							if(tab.$(obj).attachEvent){
								var range = document.selection.createRange();

								range.text = tab.string;
								range.moveStart("character", - 1);
								//range.select();
							} else if(typeof tab.$(obj).selectionStart != "undefined"){
								var start = tab.$(obj).value.substr(0, tab.$(obj).selectionStart);
								var end = tab.$(obj).value.substr(tab.$(obj).selectionStart, l);
								var selection = tab.$(obj).value.replace(start, "").replace(end, "")
								tab.$(obj).value = start + tab.string + selection + end;
								tab.$(obj).setSelectionRange(start.length + 1, start.length + 1);
								tab.$(obj).scrollTop = sct;
							} else {
								tab.$(obj).value += tab.string;
							}
							
							if(evt.preventDefault){
								evt.preventDefault();
								evt.stopPropagation();
							} else {
								evt.returnValue = false;
								evt.cancelBubble = true;
							}

							return false;
						}
					}
				}
			});
		}
	},

	click: function(obj, fn){
		if(obj && this.$(obj)){
			this.addEvent(this.$(obj), "click", function(){
				tab.results["_" + this.id.split("_")[1]] = tab.parse(tab.watching["_" + this.id.split("_")[1]].value);

				if(fn && fn.constructor == Function){
					fn();
				}
			});
		}
	},

	get: function(obj){
		if(obj && this.$(obj)){
			return this.results["_" + obj];
		}
	},

	parse: function(str){
		var str = (str)? str : "";

		if(str.length){
			if(this.tosp){
				str = str.replace(/\t/g, "&nbsp;&nbsp;&nbsp;");
			}

			if(this.nl2br){
				str = str.replace(/\r?\n/g, "<br />");
			}	
		}

		return str;
	},

	addEvent: function(obj, type, fn){
		if(obj.attachEvent){
			obj["e" + type + fn] = fn;
			obj[type + fn] = function(){
				obj["e" + type + fn](window.event);
			}

			obj.attachEvent("on" + type, obj[type + fn]);
		} else {
			obj.addEventListener(type, fn, false);
		}
	}
};