// JavaScript Document
(function() {
	/*
	 * GeoKBD 0.1 - Georgian keyboard and text convertation library
	 *
	 * Copyright (c) 2007 Ioseb Dzmanashvili (http://www.code.ge)
	 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
	 */
	String.prototype.pasteTo = function(field) {
		field.focus();
		if (document.selection) {
			var selection = document.selection;
			var range = selection.createRange();
			range.colapse;
			if (range) {
				range.text = this;
			}
		} else if (field.selectionStart || field.selectionEnd) {
			var scrollTop = field.scrollTop;
			var start = field.selectionStart;
			var end = field.selectionEnd;
			var value = field.value.substring(0, start) + this + field.value.substring(end, field.value.length);
			field.value = value;
			field.scrollTop = scrollTop;
			field.selectionStart = start + this.length;
			field.selectionEnd = start + this.length;
		} else {
			field.value += this;
		}
	},
	String.prototype.translateToKA = function() {
		/**
		 * Original idea by Irakli Nadareishvili
		 * http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
		 */
		var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
		for (var i = 0; i <this.length; i++) {
			chr = this.substr(i, 1);
			if ((index = symbols.indexOf(chr))>= 0) {
				text.push(String.fromCharCode(index + 4304));
			} else {
				text.push(chr);
			}
		}
		return text.join('');
	},
	GeoKBD = {
		event: {
			get: function(e) {
				return e || window.event;
			},
			getKeyCode: function(e) {
				e = this.get(e);
				return e.keyCode || e.which;
			},
			targetIs: function(e, tagName) {
				e = this.get(e);
				var t = e.target || e.srcElement;
				return t.tagName.toLowerCase() == tagName ? t : null;
			}
		},
		map: function(form, contentFieldName, switcher) {
			var self = this;
			form = (typeof form == 'string') ? document.forms[form] : form;
			switcher = switcher || 'geo';
			form.onkeypress = function(e) {
				e = self.event.get(e);
				if (e.altKey || e.ctrlKey) return;
				var target, fieldName = contentFieldName, _switcher = switcher, keyCode = self.event.getKeyCode(e);
				if (keyCode == 96) {
					this[_switcher].checked = !this[_switcher].checked;
					return false;
				}
				if (!this[_switcher].checked) return;
				if ((target = (self.event.targetIs(e, 'textarea') || self.event.targetIs(e, 'input')))) {
					if (fieldName && (target.name != fieldName)) return;
					text = String.fromCharCode(keyCode);
					kaText = text.translateToKA();
					if (kaText != text) {
						kaText.pasteTo(target);
						return false;
					}
				}
			}
			form = null;
		}
	};
	window.GeoKBD = GeoKBD;
})();
