Ext.ns('Ext.ux');

Ext.ux.TabUrlOpenerPlugin = function(){
	
	var tabs, menu, ctxItem;
	
	this.init = function(tabPanel){
        tabs = tabPanel;
        tabs.on('contextmenu', onContextMenu);
        
        if(tabPanel){
            this.tabPanel = tabPanel;

            //attach event to add on activate event when dynamic tabs are added
            this.tabPanel.on('add', attachOnActivateEventOnAdd);
            
            activateTabByHash();

            if(tabPanel.items){
                var items = tabPanel.items.items;
                for(var i=0; i<items.length; i++){
                    var item = items[i];
                    attachOnActivateEvent(item);
                }
            }
                
        }
    }

    function onContextMenu(ts, item, e){
        if(!menu){ // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: tabs.id + '-close',
                text: 'Close Tab',
                handler : function(){
                    tabs.remove(ctxItem);
                }
            },{
                id: tabs.id + '-close-others',
                text: 'Close Other Tabs',
                handler : function(){
                    tabs.items.each(function(item){
                        if(item.closable && item != ctxItem){
                            tabs.remove(item);
                        }
                    });
                }
            }]);
        }
        ctxItem = item;
        var items = menu.items;
        items.get(tabs.id + '-close').setDisabled(!item.closable);
        var disableOthers = true;
        tabs.items.each(function(){
            if(this != item && this.closable){
                disableOthers = false;
                return false;
            }
        });
        items.get(tabs.id + '-close-others').setDisabled(disableOthers);
        menu.showAt(e.getPoint());
    }
    
    function attachOnActivateEventOnAdd(tabPanel, newTab, index){
        attachOnActivateEvent(newTab);
    }
    
    function attachOnActivateEvent(item){

        function addHashToUrl(){
            var hash = '#' + this.id;
            window.location.hash = hash;
        }
        item.on('activate', addHashToUrl.createDelegate(item));
    }
    
    function activateTabByHash(){
        var hash = getUrlHash();
        if(hash){
            tabs.setActiveTab(hash);
        }
        
    }
    
    function getUrlHash(){
        var hash = window.location.hash;
        if(hash) hash = hash.replace('#', '');
        return hash;
    }   
	
};


