if (!Ext.EMC) {
	Ext.namespace('Ext.EMC');
}

/**
 * @class Ext.EMC.SideNav A side nav menu
 * @extends Ext.util.Observable
 * @constructor
 * @param {string} elementId
 * The menu ul element id
 **/
Ext.define('Ext.EMC.SideNav', {
    extend: 'Ext.util.Observable',
    currentContent : null,
    enableNavigation : true,
    enableHistory : true,
    constructor: function(elId, config) {
        Ext.EMC.SideNav.superclass.constructor.call(this, config);
        
        var container = Ext.get(elId);
		if (!container) {
			return false;
		}
        
        this.els = {
            'container' : container,
            'as' : container.query('a')
        };

        var columns = Ext.select('.column-content');
        if(columns.elements.length > 1){
        	columns.addCls('hidden');
        }
        
        if (!this.enableNavigation) { container.addCls('side-nav-disabled') }
        
        this.initEvents();
        if (this.enableHistory) {
            this.initHistory();
        } else {
            this.selectItem(this.els.as[0]);
        }
        
    },
    initEvents : function () {
        var _this = this;
        for (var i = 0, l = _this.els.as.length; i < l; i++) {
            Ext.get(_this.els.as[i]).on('click', function(e){
                if (!_this.enableNavigation) { e.preventDefault(); return false; }
                // don't do anything if already selected.
                var parent = Ext.get(this).up('li');
                if (parent && parent.hasCls('selected') && !this.hasCls('can-click-while-active')){
                    e.preventDefault();
                    return false;
                } else {
                    var currentUrl = window.location.href.replace(/#.*$/,'');
                    
                	if(this.getAttribute('href').replace(/#.*$/,'') === currentUrl){
	                	var url = this.getAttribute('href').replace(/^.*#/, '');
                        
                        if (_this.lastHash != url.substring(1,url.length)) { jQuery.history.load(url); }
                        else { window.location.reload( false );}

	                    return false;
                	}
                }
            }, this.dom );
        };
    },

    selectItem : function(item, token) {
        if (typeof item === 'string') {
            item = this.els.container.query('a[href$='+item+']')[0];
        }
        item = Ext.get(item);
        var hash = item.dom.hash.substr(1);
        
        
        
        // remove all selected elements
        this.els.container.select('li.selected').each(function(){
            this.removeCls('selected');
        });

        // find all li parents and add selected class
        var parent = Ext.get(item).up('li');
        while(parent) {
            parent.addCls('selected');
            parent = Ext.get(parent).up('li');
        }

        // switch content
        //if (this.currentContent) { this.currentContent.addCls('hidden'); }
        hash = decodeURI(hash);
        this.currentContent = Ext.get(hash.substring(1, hash.length));
        
        Ext.select('.column-content').addCls('hidden');
        if(!this.currentContent){
        	this.currentContent = Ext.get(Ext.select('.column-content').elements[0]);
        }
        this.currentContent.removeCls('hidden');
        
        if (item.hasCls('overview')) { Ext.EMC.Leadspace.getInstance().animate('expand'); }
        else if (Ext.EMC.Leadspace) { Ext.EMC.Leadspace.getInstance().animate('collapse'); }
        
        this.selected = hash;
    },

/**
 * Creates the necessary DOM elements required for Ext.History to manage state
 * Sets up a listener on Ext.History's change event to fire this.handleHistoryChange
 */
    initHistory : function() {
    	var _this = this;
    	jQuery.history.init(function(hash){
    		_this.handleHistoryChange(hash, _this);
        });
	},
	
    handleHistoryChange: function(hash, sideNav){
        
        if ( !sideNav.fireEvent('historyChange', hash) ) {
            if ( sideNav.selected ) { return; }
            else { hash = '' }
        };
        
        // determine the selected item
        var sel = null;
        
        // 1. check hash
        if (hash && hash != '#') {
        	hash = hash.substring(1, hash.length);
            sel = sideNav.els.container.select('a[href$=#!'+hash+']');
        }
        
        // 2. if no hash (or hash is not a valid option) check if there is an 
        //    option marked as selected in HTML markup. (Auxiliary Detail case)
        if (!sel || sel.elements.length === 0) {
            sel = sideNav.els.container.select('li.selected a');

        }
        
        // 3. so, if no hash or markup selection => use the first item in menu
        sel = (sel && sel.elements.length !== 0) ? sel.elements[0] : sideNav.els.container.first().first();
        
        this.selectItem(sel, hash);
        
        sideNav.lastHash = hash;
    }
});
