Ext.ns('Nexts.desktop');

/**
 * @class Nexts.desktop.Shortcuts
 */

Nexts.desktop.Shortcuts = function(config){
	var desktopEl = Ext.get(config.renderTo)
		, taskbarEl = config.taskbarEl
		, btnPadding = 10
		, col = null
		, row = null
		, items = [];
	
	initColRow();
	
	function initColRow(){
		col = {index: 1, x: btnPadding};
		row = {index: 1, y: btnPadding};
	}
	
	function isOverflow(y){
		if(y > (Ext.lib.Dom.getViewHeight() - taskbarEl.getHeight())){
			return true;
		}
		return false;
	}
	
	this.addShortcut = function(config) {
		if (!config.id) {
			config.id = Ext.id();
		}
		
		var btn = new Nexts.ShortcutButton(Ext.apply(config, {
			id: 'shortcut.button.' + config.id,
			text: String.ellipsiz(config.text, 20),
			cls: 'ne-desktop-shortcut-btn',
			renderTo: desktopEl
		}));
		
		//btn.container.initDD('DesktopShortcuts');
		
		items.push(btn);
		this.setXY(btn);
		
		return btn;
	};
	
	this.removeShortcut = function(b) {
		b.destroy();
		items.remove(b);
		this.handleUpdate();
	}
	
	this.handleUpdate = function(){
		initColRow();
		for (var i = 0, len = items.length; i < len; i++) {
			this.setXY(items[i]);
		}
	}
	
	this.setXY = function(item) {
		var bw = item.el.getWidth();
		var bh = item.el.getHeight();
		
		var bottom = row.y + bh,
			overflow = isOverflow(row.y + bh);
		
		if (overflow && bottom > (bh + btnPadding)){
			col = {
				index: col.index++,
				x: col.x + bw + btnPadding
			};
			row = {
				index: 1,
				y: btnPadding
			};
		}
		
		item.el.setXY([ col.x, row.y ]);
		
		row.index++;
		row.y = row.y + bh + btnPadding;
	};
	
	Ext.EventManager.onWindowResize(this.handleUpdate, this, {delay:500});
};

