/*
 * Copyright (c)  2006-2007 Maskat Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 maskat.lang.Class.declare("maskat.key.KeyEventManager", {
	
	_static: {
		getInstance: function() {
			var self = arguments.callee;
			if (!self.instance) {
				self.instance = new this();
			}
			return self.instance;
		}
	},
	
	handle: function(event) {
		var manager = maskat.key.KeyEventManager.getInstance();
		var element = event.currentTarget || event.srcElement;
		var widget = manager.getWidget(manager.getRootElement(element));
		if (!widget || !widget.canFocus()) {
			if (event.keyCode == 9) {
				return false;
			}
			return true;
		}
		var result = true;
		
		if (!widget.handleKeyEvent(event)) {
			result = false;
			
		} else if (event.keyCode == 9) {
			var next = manager.nextWidget(widget, event.shiftKey);
			if (next) {
				try {
					next.setFocus();
				} catch (e) {}
				result = false;
			}
		}
		if (!result) {
			/* FIreFox */
			if (event.preventDefault) {
				event.preventDefault();
			/* IE */
			} else {
				event.returnValue = false;
			}
			/* FireFox */
			if (event.stopPropagation) {
				event.stopPropagation();
			/* IE */
			} else {
				event.cancelBubble  = true;
			}
		}
		return result;
	},
	
	getRootElement: function(element) {
		while (element && !element._layoutId) {
			element = element.parentNode;
		}
		return element;
	},
	
	getWidget: function(element) {
		if (element) {
			var layout = maskat.app.getLayout(element._layoutId);
			return layout.getWidget(element._widgetName);
		}
		return null;
	},
	
	nextWidget: function(widget, shift) {
		var activeLayout = widget.getLayout();
		var tabIndexes = activeLayout.getTabIndexes();
		var pos = -1;
		for (var i = 0; i < tabIndexes.length; i++) {
			var name = widget.getTabIndexGroupName() || widget.name;
			if (tabIndexes[i] == name) {
				pos = i;
				break;
			}
		}
		for (var j = 0; j < tabIndexes.length - 1; j++) {
			if (!shift) {
				pos++;
				if (pos >= tabIndexes.length) pos = 0;
			} else {
				pos--;
				if (pos < 0) pos = tabIndexes.length - 1;
			}
			var next = activeLayout.getWidget(tabIndexes[pos]);
			if (next.canFocus()) {
				return next;
			}
		}
		return widget;
	}
});
