YAHOO.namespace("mikkelricky.AccessKeys");

(function() {
	function highlightAccessKeys(node, accessKey, cfg) {
		var done = false;
		var e;

		if (node.nodeType == 3) {
			// TEXT_NODE
			var text = node.nodeValue;

			var index = text.toLowerCase().indexOf(accessKey);

			if (index >= 0) {
				var prefix = text.substring(0, index);
				accessKey = text.substring(index, index+1);
				var postfix = text.substring(index+1);
				var parent = node.parentNode;
				var replaceNode = node;

				YAHOO.log("prefix: "+prefix);
				YAHOO.log("accessKey: "+accessKey);
				YAHOO.log("postfix: "+postfix);

				var wrap = cfg.getProperty("wrap");

				if (prefix) {
					parent.insertBefore(document.createTextNode(prefix), replaceNode);
				}

				if (wrap && wrap[0]) {
					parent.insertBefore(document.createTextNode(wrap[0]), replaceNode);
				}

				e = document.createElement(cfg.getProperty("elementName"));
				var attributes = cfg.getProperty("elementAttributes");
				for (var p in attributes) {
					// MSIE really sucks!
					if ((p == "class")) {
						YAHOO.util.Dom.addClass(e, attributes[p]);
					} else {
						e.setAttribute(p, attributes[p]);
					}
				}
				e.appendChild(document.createTextNode(accessKey));
				parent.insertBefore(e, replaceNode);

				if (wrap && wrap[1]) {
					parent.insertBefore(document.createTextNode(wrap[1]), replaceNode);
				}

				if (postfix) {
					parent.insertBefore(document.createTextNode(postfix), replaceNode);
				}

				parent.removeChild(replaceNode);

				YAHOO.log(parent.innerHTML);

				done = true;
			}
		} else {
			for (e = node.firstChild; e; e = e.nextSibling) {
				if (highlightAccessKeys(e, accessKey, cfg)) {
					done = true;
					break;
				}
			}
		}

		return done;
	}

	YAHOO.mikkelricky.AccessKeys.highlight = function(config) {
		try {
			var cfg = new YAHOO.util.Config(this);

			cfg.addProperty("elementName", {
					value: "span"
						});
			cfg.addProperty("elementAttributes", {
					value: { "class": "accesskey" }
				});
			cfg.addProperty("tag", {
					value: null
						});
			cfg.addProperty("wrap", {
					value: []
						});
			cfg.addProperty("root", {
					value: document
						});

			if (config) {
				cfg.applyConfig(config);
			}

			//  YAHOO.log(cfg.getProperty("elementName"));
			//  YAHOO.log(cfg.getProperty("elementAttributes"));
			//  YAHOO.log(cfg.getProperty("tag"));
			//  YAHOO.log(cfg.getProperty("root"));

			var elements = YAHOO.util.Dom.getElementsBy(function(e) {
					return e.getAttribute("accesskey");
				}, cfg.getProperty("tag"), cfg.getProperty("root"));

			for (var i = 0; i < elements.length; i++) {
				var element = elements[i];
				var accessKey = element.getAttribute("accesskey").toLowerCase();

				highlightAccessKeys(element, accessKey, cfg);
			}
		} catch (ex) {}
	}
}());

