
Ext.namespace("Ext.ux");

Ext.ux.StartMenu = Ext.extend(Ext.menu.Menu, {
    initComponent: function(config) {
    	Ext.ux.StartMenu.superclass.initComponent.call(this, config);
        var tools = this.toolItems;
        this.toolItems = new Ext.util.MixedCollection();
        if(tools){ this.addTool.apply(this, tools); }        
    },
    
    // private
    onRender : function(ct, position){
	Ext.ux.StartMenu.superclass.onRender.call(this, ct, position);        
	var el = this.el.addClass('ux-start-menu');
        var header = el.createChild({tag: "div",cls: "x-window-header x-unselectable x-panel-icon "+this.iconCls});
	this.header = header;
	var headerText = header.createChild({ tag: "span",cls: "x-window-header-text"});
	var tl = header.wrap({ cls: "ux-start-menu-tl" });
	var tr = header.wrap({ cls: "ux-start-menu-tr" });
	var tc = header.wrap({ cls: "ux-start-menu-tc"});
	this.menuBWrap = el.createChild({ tag: "div", cls: "x-window-body x-border-layout-ct ux-start-menu-body" });
	var ml = this.menuBWrap.wrap({ cls: "ux-start-menu-ml"});
	var mc = this.menuBWrap.wrap({ cls: "x-window-mc ux-start-menu-bwrap"});
	this.menuPanel = this.menuBWrap.createChild({ tag: "div", cls: "x-panel x-border-panel ux-start-menu-apps-panel"});
	this.toolsPanel = this.menuBWrap.createChild({ tag: "div", cls: "x-panel x-border-panel ux-start-menu-tools-panel"});
	var bwrap = ml.wrap({cls: "x-window-bwrap"});
	var bc = bwrap.createChild({ tag: "div", cls: "ux-start-menu-bc" });
	var bl = bc.wrap({ cls: "ux-start-menu-bl x-panel-nofooter" });
	var br = bc.wrap({ cls: "ux-start-menu-br" });
        this.ul.appendTo(this.menuPanel);
        var toolsUl = this.toolsPanel.createChild({ tag: "ul",cls: "x-menu-list"});
        this.mon(toolsUl, 'click', this.onClick, this);
        this.mon(toolsUl, 'mouseover', this.onMouseOver, this);
        this.mon(toolsUl, 'mouseout', this.onMouseOut, this);
        
        this.items.each(function(item){
            item.parentMenu = this;
        }, this);
        
        this.toolItems.each(
        	function(item){
	            var li = document.createElement("li");
	            li.className = "x-menu-list-item";
	            toolsUl.dom.appendChild(li);
	            item.render(li);
                item.parentMenu = this;
	        }, this);
        this.toolsUl = toolsUl;
        this.menuBWrap.setStyle('position', 'relative');  
        this.menuBWrap.setHeight(this.height - 28);
        this.menuPanel.setStyle({ padding: '2px', position: 'absolute', overflow: 'auto'});
        this.toolsPanel.setStyle({ padding: '2px 4px 2px 2px', position: 'absolute', overflow: 'auto'});
        this.setTitle(this.title);
    },
    
    findTargetItem : function(e){
        var t = e.getTarget(".x-menu-list-item", this.ul,  true);
        if(t && t.menuItemId){
        	if(this.items.get(t.menuItemId)){
            	return this.items.get(t.menuItemId);
            }else{
            	return this.toolItems.get(t.menuItemId);
            }
        }
    },

    show : function(el, pos, parentMenu){
        this.parentMenu = parentMenu;
        if(!this.el){ this.render(); };
        this.fireEvent("beforeshow", this);
        this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
        var tPanelWidth = 100;      
        var box = this.menuBWrap.getBox();
        this.menuPanel.setWidth(box.width-tPanelWidth);
        this.menuPanel.setHeight(box.height);
        this.toolsPanel.setWidth(tPanelWidth);
        this.toolsPanel.setX(box.x+box.width-tPanelWidth);
        this.toolsPanel.setHeight(box.height);
    },
    
    addTool : function(){
        var a = arguments, l = a.length, item;
        for(var i = 0; i < l; i++){
            var el = a[i];
            if(el.render){ // some kind of Item
                item = this.addToolItem(el);
            }else if(typeof el == "string"){ // string
                if(el == "separator" || el == "-"){
                    item = this.addToolSeparator();
                }else{
                    item = this.addText(el);
                }
            }else if(el.tagName || el.el){ // element
                item = this.addElement(el);
            }else if(typeof el == "object"){ // must be menu item config?
                item = this.addToolMenuItem(el);
            }
        }
        return item;
    },
    
    addToolSeparator : function(){
        return this.addToolItem(new Ext.menu.Separator({itemCls: 'ux-toolmenu-sep'}));
    },

    addToolItem : function(item){
        this.toolItems.add(item);
        if(this.ul){
            var li = document.createElement("li");
            li.className = "x-menu-list-item";
            this.ul.dom.appendChild(li);
            item.render(li, this);
            this.delayAutoWidth();
        }
        return item;
    },

    addToolMenuItem : function(config){
        if(!(config instanceof Ext.menu.Item)){
            if(typeof config.checked == "boolean"){ // must be check menu item config?
                config = new Ext.menu.CheckItem(config);
            }else{
                config = new Ext.menu.Item(config);
            }
        }
        return this.addToolItem(config);
    },
    
    setTitle : function(title, iconCls){
        this.title = title;
        this.header.child('span').update(title);
        return this;
    }
});


Ext.ux.TaskBar = function(app){ this.app = app; this.init(); }

Ext.extend(Ext.ux.TaskBar, Ext.util.Observable, {
    init : function(){
		this.startMenu = new Ext.ux.StartMenu(Ext.apply({
			iconCls: 'user',
			height: 300,
			shadow: true,
			title: 'Anonymous',
			width: 300
		}, this.app.startConfig));
		
		this.startBtn = new Ext.Button({
            text: 'Start',
            id: 'ux-startbutton',
            iconCls:'start',
            menu: this.startMenu,
            menuAlign: 'bl-tl',
            renderTo: 'ux-taskbar-start',
            clickEvent: 'mousedown',
            template: new Ext.Template(
				'<table cellspacing="0" class="x-btn {3}"><tbody><tr>',
				'<td class="ux-startbutton-left"><i>&#160;</i></td>',
                '<td class="ux-startbutton-center"><em class="{5} unselectable="on">',
                    '<button class="x-btn-text {2}" type="{1}" style="height:30px;">{0}</button>',
                '</em></td>',
                '<td class="ux-startbutton-right"><i>&#160;</i></td>',
				"</tr></tbody></table>")
        });

        var width = this.startBtn.getEl().getWidth()+10;
        
        var sbBox = new Ext.BoxComponent({
			el: 'ux-taskbar-start',
	        id: 'TaskBarStart',
	        minWidth: width,
			region:'west',
			split: true,
			width: width
		});
		
		this.tbPanel = new Ext.ux.TaskButtonsPanel({
			el: 'ux-taskbuttons-panel',
			id: 'TaskBarButtons',
			region:'center'
		});
				
        var container = new Ext.ux.TaskBarContainer({
			el: 'ux-taskbar',
			layout: 'border',
			items: [sbBox,this.tbPanel]
		});
		
		return this;
    },
        addTaskButton : function(win){ return this.tbPanel.addButton(win, 'ux-taskbuttons-panel'); },
	removeTaskButton : function(btn){ this.tbPanel.removeButton(btn); },
	setActiveButton : function(btn){ this.tbPanel.setActiveButton(btn); }
});

Ext.ux.TaskBarContainer = Ext.extend(Ext.Container, {
    initComponent : function() {
        Ext.ux.TaskBarContainer.superclass.initComponent.call(this);
        this.el = Ext.get(this.el) || Ext.getBody();
        this.el.setHeight = Ext.emptyFn;
        this.el.setWidth = Ext.emptyFn;
        this.el.setSize = Ext.emptyFn;
        this.el.setStyle({ overflow:'hidden', margin:'0', border:'0 none' });
        this.el.dom.scroll = 'no';
        this.allowDomMove = false;
        this.autoWidth = true;
        this.autoHeight = true;
        Ext.EventManager.onWindowResize(this.fireResize, this);
        this.renderTo = this.el;
    },
    fireResize : function(w, h){ this.fireEvent('resize', this, w, h, w, h); }
});

Ext.ux.TaskButtonsPanel = Ext.extend(Ext.BoxComponent, {
	activeButton: null,
	enableScroll: true,
	scrollIncrement: 0,
	scrollRepeatInterval: 400,
	scrollDuration: .35,
	animScroll: true,
	resizeButtons: true,
	buttonWidth: 168,
	minButtonWidth: 118,
	buttonMargin: 2,
	buttonWidthSet: false,
	initComponent : function() {
        Ext.ux.TaskButtonsPanel.superclass.initComponent.call(this);
        this.on('resize', this.delegateUpdates);
        this.items = [];
        
        this.stripWrap = Ext.get(this.el).createChild({
        	cls: 'ux-taskbuttons-strip-wrap',
        	cn: {
            	tag:'ul', cls:'ux-taskbuttons-strip'
            }
		});
        this.stripSpacer = Ext.get(this.el).createChild({
        	cls:'ux-taskbuttons-strip-spacer'
        });
        this.strip = new Ext.Element(this.stripWrap.dom.firstChild);
        
        this.edge = this.strip.createChild({
        	tag:'li',
        	cls:'ux-taskbuttons-edge'
        });
        this.strip.createChild({
        	cls:'x-clear'
        });
	},
	
	addButton : function(win){
		var li = this.strip.createChild({tag:'li'}, this.edge); // insert before the edge
        var btn = new Ext.ux.TaskBar.TaskButton(win, li);
		
		this.items.push(btn);
		
		if(!this.buttonWidthSet){
			this.lastButtonWidth = btn.container.getWidth();
		}
		
		this.setActiveButton(btn);
		return btn;
	},
	
	removeButton : function(btn){
		var li = document.getElementById(btn.container.id);
		btn.destroy();
		li.parentNode.removeChild(li);
		
		var s = [];
		for(var i = 0, len = this.items.length; i < len; i++) {
			if(this.items[i] != btn){
				s.push(this.items[i]);
			}
		}
		this.items = s;
		
		this.delegateUpdates();
	},
	
	setActiveButton : function(btn){
		this.activeButton = btn;
		this.delegateUpdates();
	},
	
	delegateUpdates : function(){
		/*if(this.suspendUpdates){
            return;
        }*/
        if(this.resizeButtons && this.rendered){
            this.autoSize();
        }
        if(this.enableScroll && this.rendered){
            this.autoScroll();
        }
    },
    
    autoSize : function(){
        var count = this.items.length;
        var ow = this.el.dom.offsetWidth;
        var aw = this.el.dom.clientWidth;

        if(!this.resizeButtons || count < 1 || !aw){ // !aw for display:none
            return;
        }
        
        var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.buttonMargin, this.buttonWidth), this.minButtonWidth); // -4 for float errors in IE
        var btns = this.stripWrap.dom.getElementsByTagName('button');
        
        this.lastButtonWidth = Ext.get(btns[0].id).findParent('li').offsetWidth;
        
        for(var i = 0, len = btns.length; i < len; i++) {            
            var btn = btns[i];
            
            var tw = Ext.get(btns[i].id).findParent('li').offsetWidth;
            var iw = btn.offsetWidth;
            
            btn.style.width = (each - (tw-iw)) + 'px';
        }
    },
    
    autoScroll : function(){
    	var count = this.items.length;
        var ow = this.el.dom.offsetWidth;
        var tw = this.el.dom.clientWidth;
        
        var wrap = this.stripWrap;
        var cw = wrap.dom.offsetWidth;
        var pos = this.getScrollPos();
        var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos;
        
        if(!this.enableScroll || count < 1 || cw < 20){ // 20 to prevent display:none issues
            return;
        }
        
        wrap.setWidth(tw); // moved to here because of problem in Safari
        
        if(l <= tw){
            wrap.dom.scrollLeft = 0;
            //wrap.setWidth(tw); moved from here because of problem in Safari
            if(this.scrolling){
                this.scrolling = false;
                this.el.removeClass('x-taskbuttons-scrolling');
                this.scrollLeft.hide();
                this.scrollRight.hide();
            }
        }else{
            if(!this.scrolling){
                this.el.addClass('x-taskbuttons-scrolling');
            }
            tw -= wrap.getMargins('lr');
            wrap.setWidth(tw > 20 ? tw : 20);
            if(!this.scrolling){
                if(!this.scrollLeft){
                    this.createScrollers();
                }else{
                    this.scrollLeft.show();
                    this.scrollRight.show();
                }
            }
            this.scrolling = true;
            if(pos > (l-tw)){ // ensure it stays within bounds
                wrap.dom.scrollLeft = l-tw;
            }else{ // otherwise, make sure the active button is still visible
				this.scrollToButton(this.activeButton, true); // true to animate
            }
            this.updateScrollButtons();
        }
    },

    createScrollers : function(){
        var h = this.el.dom.offsetHeight; //var h = this.stripWrap.dom.offsetHeight;
		
        // left
        var sl = this.el.insertFirst({
            cls:'ux-taskbuttons-scroller-left'
        });
        sl.setHeight(h);
        sl.addClassOnOver('ux-taskbuttons-scroller-left-over');
        this.leftRepeater = new Ext.util.ClickRepeater(sl, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollLeft,
            scope: this
        });
        this.scrollLeft = sl;

        // right
        var sr = this.el.insertFirst({
            cls:'ux-taskbuttons-scroller-right'
        });
        sr.setHeight(h);
        sr.addClassOnOver('ux-taskbuttons-scroller-right-over');
        this.rightRepeater = new Ext.util.ClickRepeater(sr, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollRight,
            scope: this
        });
        this.scrollRight = sr;
    },
    
    getScrollWidth : function(){
        return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos();
    },

    getScrollPos : function(){
        return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0;
    },

    getScrollArea : function(){
        return parseInt(this.stripWrap.dom.clientWidth, 10) || 0;
    },

    getScrollAnim : function(){
        return {
        	duration: this.scrollDuration,
        	callback: this.updateScrollButtons,
        	scope: this
        };
    },

    getScrollIncrement : function(){
    	return (this.scrollIncrement || this.lastButtonWidth+2);
    },
    
    /* getBtnEl : function(item){
        return document.getElementById(item.id);
    }, */
    
    scrollToButton : function(item, animate){
    	item = item.el.dom.parentNode; // li
        if(!item){ return; }
        var el = item; //this.getBtnEl(item);
        var pos = this.getScrollPos(), area = this.getScrollArea();
        var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos;
        var right = left + el.offsetWidth;
        if(left < pos){
            this.scrollTo(left, animate);
        }else if(right > (pos + area)){
            this.scrollTo(right - area, animate);
        }
    },
    
    scrollTo : function(pos, animate){
        this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false);
        if(!animate){
            this.updateScrollButtons();
        }
    },
    
    onScrollRight : function(){
        var sw = this.getScrollWidth()-this.getScrollArea();
        var pos = this.getScrollPos();
        var s = Math.min(sw, pos + this.getScrollIncrement());
        if(s != pos){
        	this.scrollTo(s, this.animScroll);
        }        
    },

    onScrollLeft : function(){
        var pos = this.getScrollPos();
        var s = Math.max(0, pos - this.getScrollIncrement());
        if(s != pos){
            this.scrollTo(s, this.animScroll);
        }
    },
    
    updateScrollButtons : function(){
        var pos = this.getScrollPos();
        this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('ux-taskbuttons-scroller-left-disabled');
        this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('ux-taskbuttons-scroller-right-disabled');
    }
});

Ext.ux.TaskBar.TaskButton = function(win, el){
	this.win = win;
    Ext.ux.TaskBar.TaskButton.superclass.constructor.call(this, {
        iconCls: win.iconCls,
        text: Ext.util.Format.ellipsis(win.title, 12),
        renderTo: el,
        handler : function(){
            if(win.minimized || win.hidden){
                win.show();
            }else if(win == win.manager.getActive()){
                win.minimize();
            }else{
                win.toFront();
            }
        },
        clickEvent:'mousedown',
        template: new Ext.Template(
			'<table cellspacing="0" class="x-btn {3}"><tbody><tr>',
			'<td class="ux-taskbutton-left"><i>&#160;</i></td>',
            '<td class="ux-taskbutton-center"><em class="{5} unselectable="on">',
                '<button class="x-btn-text {2}" type="{1}" style="height:28px;">{0}</button>',
            '</em></td>',
            '<td class="ux-taskbutton-right"><i>&#160;</i></td>',
			"</tr></tbody></table>")            
    });
};

Ext.extend(Ext.ux.TaskBar.TaskButton, Ext.Button, {
    onRender : function(){
        Ext.ux.TaskBar.TaskButton.superclass.onRender.apply(this, arguments);
        this.cmenu = new Ext.menu.Menu({
            items: [{
                text: 'Restore',
                handler: function(){
                    if(!this.win.isVisible()){
                        this.win.show();
                    }else{
                        this.win.restore();
                    }
                },
                scope: this
            },{
                text: 'Minimize',
                handler: this.win.minimize,
                scope: this.win
            },{
                text: 'Maximize',
                handler: this.win.maximize,
                scope: this.win
            }, '-', {
                text: 'Close',
                handler: this.closeWin.createDelegate(this, this.win, true),
                scope: this.win
            }]
        });

        this.cmenu.on('beforeshow', function(){
            var items = this.cmenu.items.items;
            var w = this.win;
            items[0].setDisabled(w.maximized !== true && w.hidden !== true);
            items[1].setDisabled(w.minimized === true);
            items[2].setDisabled(w.maximized === true || w.hidden === true);
        }, this);

        this.el.on('contextmenu', function(e){
            e.stopEvent();
            if(!this.cmenu.el){
                this.cmenu.render();
            }
            var xy = e.getXY();
            xy[1] -= this.cmenu.el.getHeight();
            this.cmenu.showAt(xy);
        }, this);
    },
    
    closeWin : function(cMenu, e, win){
		if(!win.isVisible()){
			win.show();
		}else{
			win.restore();
		}
		win.close();
	}
});

Ext.Desktop = function(app){
	var desktopEl = Ext.get('x-desktop');
	var taskbarEl = Ext.get('ux-taskbar');
	var shortcuts = Ext.get('x-shortcuts');
	var windows   = new Ext.WindowGroup();
    	var activeWindow,taskbar;

	function minimizeWin(win){ win.minimized = true; win.hide();}
	function markActive(win){
        	if(activeWindow && activeWindow != win){
            		markInactive(activeWindow);
        	}
        	taskbar.setActiveButton(win.taskButton);
        	activeWindow = win;
        	Ext.fly(win.taskButton.el).addClass('active-win');
        	win.minimized = false;
    	}

    	function markInactive(win){
	        if(win == activeWindow){
            	activeWindow = null;
            	Ext.fly(win.taskButton.el).removeClass('active-win');
        	}
    	}

    	function removeWin(win){
	    	taskbar.removeTaskButton(win.taskButton);
	        layout();
    	}

	function layout(){
	        desktopEl.setHeight(Ext.lib.Dom.getViewHeight()-taskbarEl.getHeight());
    	}

	Ext.EventManager.onWindowResize(layout);
    	this.layout = layout;

	this.createWindow = function(config, cls){
    		var win = new (cls||Ext.Window)(
            		Ext.applyIf(config||{}, {
		                manager: windows,
                		minimizable: true,
                		maximizable: true,
				showtaskbar: true
            		})
        	);
        	win.render(desktopEl);
        	win.cmenu = new Ext.menu.Menu({items: []});
		if (config.showtaskbar != false ) {
	        	win.taskButton = this.taskbar.addTaskButton(win);
	        	win.animateTarget = win.taskButton.el;
        		win.on({
		        	'activate': {fn: markActive},
        			'beforeshow': {fn: markActive},
        			'deactivate': {fn: markInactive},
        			'minimize': {fn: minimizeWin},
        			'close': { fn: removeWin }
	        	});
        	}
        	layout();
        	return win;
    	};

	this.loadTaskBar = function () {
		this.taskbar = new Ext.ux.TaskBar(app);
		taskbar = this.taskbar;
	}

	this.getManager = function(){ return windows;};
	this.getWindow = function(id){ return windows.get(id); }
	this.getWinWidth = function(){ var width = Ext.lib.Dom.getViewWidth(); return width < 200 ? 200 : width; }
	this.getWinHeight = function(){ var height = (Ext.lib.Dom.getViewHeight()-taskbarEl.getHeight()); return height < 100 ? 100 : height; }
	this.getWinX = function(width){ return (Ext.lib.Dom.getViewWidth() - width) / 2 }
	this.getWinY = function(height){ return (Ext.lib.Dom.getViewHeight()-taskbarEl.getHeight() - height) / 2;}

    	layout();

    	if(shortcuts){
	        shortcuts.on('click', function(e, t){
            	if(t = e.getTarget('dt', shortcuts)){
	                e.stopEvent();
                	var module = app.getModule(t.id.replace('-shortcut', ''));
                	if(module){
                    	module.createWindow();
                	}
            	}
        	});
    	}
};

Ext.app.App = function(cfg){
    Ext.apply(this, cfg);
    this.addEvents({'ready' : true, 'beforeunload' : true });
    Ext.onReady(this.initApp,this);
};

Ext.extend(Ext.app.App, Ext.util.Observable, {
    isReady: false,
    startMenu: null,
    modules: null,
    getStartConfig : function(){
    },
    init : Ext.emptyFn,
    initApp : function(){
    	this.startConfig = this.startConfig || this.getStartConfig();
	this.startConfig.toolItems = new Array();
        this.desktop = new Ext.Desktop(this);
	if (this.startConfig.requirelogin == true) {
		this.startConfig.toolItems[this.startConfig.toolItems.length] = {text:'Logout',iconCls:'logout',scope:this,handler:this.getLogout};
		if (this.getCookie(this.startConfig.authsession) == '') {
			this.getLogin();
		} else {
			this.loadApp();
		} 
	} else {
		this.loadApp();
	}
    },
    loadApp : function() {
		//*** Loader app

		//*** Start rendering
		this.desktop.loadTaskBar();
		this.launcher = this.desktop.taskbar.startMenu;
		this.modules = this.getModules();
        	if(this.modules){ this.initModules(this.modules); }
        	this.init();
        	Ext.EventManager.on(window, 'beforeunload', this.onUnload, this);
		this.fireEvent('ready', this);
        	this.isReady = true;
    },
    getModules : Ext.emptyFn,
    getCookie : function(cookie_name) {
	var cookie = new Ext.state.CookieProvider();
	return cookie.get(cookie_name,''); 
    },
    setCookie : function(cookie_name,cookie_value) {
	var cookie = new Ext.state.CookieProvider();
    },
    clearCookie : function(cookie_name) {
	var cookie = new Ext.state.CookieProvider();
        cookie.clear(cookie_name);
    },

    initModules : function(ms){
	for(var i = 0, len = ms.length; i < len; i++){
            var m = ms[i];
            this.launcher.add(m.launcher);
            m.app = this;
        }
    },

    getModule : function(name){
    	var ms = this.modules;
    	for(var i = 0, len = ms.length; i < len; i++){
    		if(ms[i].id == name || ms[i].appType == name){
    			return ms[i];
		}
        }
        return '';
    },
    getDesktop : function(){ return this.desktop; },
    showLogin : function() {

    },
    getLogin : function(){
	var app = this;
 	var win = app.desktop.getWindow('login-win');
        if(!win){
	    var login  = new Ext.FormPanel({ 
        	labelWidth:80,
        	url: app.startConfig.rpcserver, 
        	frame:true, 
        	title:'Please Login', 
        	defaultType:'textfield',
		monitorValid:true,
        	items:[
			{ fieldLabel:'Username', name:'lguser', allowBlank:false },
			{ fieldLabel:'Password', name:'lgpwds',id:'lgpwds', inputType:'password', allowBlank:false },
			{ name:'method', inputType:'hidden', value:'login' }
		],
        	buttons:[{ 
	                text:'Login',
                	formBind: true,
			scope: this,
                	handler: function() {
			var user = Ext.getCmp('lgpwds');
  			user.setValue(Ext.util.MD5(user.getValue()));
                    	login.getForm().submit({ 
                        	method:'POST',
                        	waitTitle:'Connecting', 
                        	waitMsg:'Sending data...',
                        	success: function(){ 
                        		app.initApp();
					win.close();
                        	},
                        	failure:function(form, action){ 
                            		if(action.failureType == 'server'){ 
                                		obj = Ext.util.JSON.decode(action.response.responseText); 
                                		Ext.Msg.alert('Login Failed!', obj.errors.reason); 
                            		}else{ 
                                		Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText); 
                            		} 
                            		login.getForm().reset(); 
                        	} 
                    	}); 	
			},
             	}],
	    });	      
            win = this.desktop.createWindow({
		layout:'fit',
        	width:300,
        	height:150,
                shim:false,
		showtaskbar: false,
        	closable: false,
		minimizable: false,
               	maximizable: false,
        	resizable: false,
                items: [login]
            });
	}
        win.show();
    },
    getLogout : function() {
        this.clearCookie(this.startConfig.authsession);
	window.location.reload(); 
    },
    onReady : function(fn, scope){
        if(!this.isReady){ this.on('ready', fn, scope); } else { fn.call(scope, this); }
    },

    onUnload : function(e){
        if(this.fireEvent('beforeunload', this) === false){
            e.stopEvent();
        }
    }
});

Ext.app.Module = function(config){ Ext.apply(this, config); Ext.app.Module.superclass.constructor.call(this); this.init(); }
Ext.extend(Ext.app.Module, Ext.util.Observable, { init : Ext.emptyFn });


