/**
 * @class Ext.ux.folderorganizer.Button
 *
 * @extend Ext.button.Button
 *
 * Icon only button
 *
 * <p>Usage:</p>
 * <pre><code>
    {
        xtype: 'ip2Button',
        handler: function() {
            alert('You clicked the button!')
        }
    }
 * </code></pre>
 *
 */

Ext.define('Ext.ux.folderorganizer.Button', {
	extend: 'Ext.button.Button',
	alias: ['widget.ip2button', 'widget.ip2Button'],
	minWidth: 75,
	initComponent: function() {
		var button = this;

		if (button.keyMap) {
			if (button.keyMap.primary) {
				// add "ip2-default" class
				button.renderTpl =
				'<em id="{id}-btnWrap" class="{splitCls}">' +
				'<tpl if="href">' +
				'<a id="{id}-btnEl" href="{href}" target="{target}"<tpl if="tabIndex"> tabIndex="{tabIndex}"</tpl> role="link">' +
				'<span id="{id}-btnInnerEl" class="{baseCls}-inner">' +
				'{text}' +
				'</span>' +
				'<span id="{id}-btnIconEl" class="{baseCls}-icon"></span>' +
				'</a>' +
				'</tpl>' +
				'<tpl if="!href">' +
				'<button id="{id}-btnEl" type="{type}" hidefocus="true"' +
				'<tpl if="tabIndex"> tabIndex="{tabIndex}"</tpl> role="button" autocomplete="off">' +
				'<span id="{id}-btnInnerEl" class="{baseCls}-inner ip2-default" style="{innerSpanStyle}">' +
				'{text}' +
				'</span>' +
				'<span id="{id}-btnIconEl" class="{baseCls}-icon {iconCls}">&#160;</span>' +
				'</button>' +
				'</tpl>' +
				'</em>';
			}
			if (button.keyMap.bindTo && button.keyMap.key) {
				var bindTo = button.keyMap.bindTo,
				listeners = bindTo.listeners || {};
				bindTo.listeners = Ext.apply(listeners, {
					afterrender: function() {
						button.setKeyMap(bindTo);
					}
				});

				// save key mapping for this key in the bindto commponent.
				if (!bindTo.ip2Buttons) bindTo.ip2Buttons = [];
				bindTo.ip2Buttons.push(button);
			}
		}

		button.callParent();
	},
	setKeyMap: function(bindTo) {
		var buttons = [];

		for (var i = 0; i < bindTo.ip2Buttons.length; i++) {
			var button = bindTo.ip2Buttons[i],
			keyMap = button.keyMap;
			buttons.push({
				key: keyMap.key,
				alt: (typeof keyMap.alt === "undefined") ? false : keyMap.alt,
				ctrl: (typeof keyMap.ctrl === "undefined") ? false : keyMap.ctrl,
				shift: (typeof keyMap.shift === "undefined") ? false : keyMap.shift,
				fn: function() {
					this.handler.call(this);
				},
				scope: button,
				defaultEventAction: 'preventDefault'
			});
		}

		var i_keymap = Ext.create("Ext.util.KeyMap", {
			target: button,
			binding: buttons
		});
	}
});
