﻿
function set_cookie(name, value, expires, path, domain, secure) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
var uidkey='demo';
/*
 * This will retrieve the cookie by name, if the cookie does not exist, it will return false, so you can do things like 
 * if ( Get_Cookie( 'your_cookie' ) ) do something.
 */
var loginurl={};
function get_cookie(name) {
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length )))
	{
		return 'Demo1';
	}
	if (start == -1) return 'Demo2';
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}

/*
 * Here all you need to do is put in: Delete_Cookie('cookie name', '/', '') and the cookie will be deleted. Remember to match 
 * the cookie name, path, and domain to what you have it in Set_Cookie exactly, or you may get some very hard to diagnose errors.
 */

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
	if(Get_Cookie(name)) document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


/*
 * SAMPLE CODE
 *
 * <script type="text/javascript">
 * // remember, these are the possible parameters for Set_Cookie:
 * // name, value, expires, path, domain, secure
 * Set_Cookie( 'test', 'it works', '', '../default.htm', '', '' );
 * if ( Get_Cookie( 'test' ) ) alert( Get_Cookie('test'));
 * // and these are the parameters for Delete_Cookie:
 * // name, path, domain
 * // make sure you use the same parameters in Set and Delete Cookie.
 * Delete_Cookie('test', '../default.htm', '');
 * ( Get_Cookie( 'test' ) ) ? alert( Get_Cookie('test')) : 
 * alert( 'it is gone');
 * </script>
 */
/**
 * @class Ext.ux.StartMenu
 * @extends Ext.menu.Menu
 * A start menu object.
 * @constructor
 * Creates a new StartMenu
 * @param {Object} config Configuration options
 *
 * SAMPLE USAGE:
 *
 * this.startMenu = new Ext.ux.StartMenu({
 *		iconCls: 'user',
 *		height: 300,
 *		shadow: true,
 *		title: get_cookie('memberName'),
 *		toolPanelWidth: 110,
 *		width: 300
 *	});
 *
 * this.startMenu.add({
 *		text: 'Grid Window',
 *		iconCls:'icon-grid',
 *		handler : this.createWindow,
 *		scope: this
 *	});
 *
 * this.startMenu.addTool({
 *		text:'Logout',
 *		iconCls:'logout',
 *		handler:function(){ window.location = "logout.php"; },
 *		scope:this
 *	});
 */

Ext.namespace("Ext.ux");

Ext.ux.StartMenu = function(config){
	Ext.ux.StartMenu.superclass.constructor.call(this, config);
    
    var tools = this.toolItems;
    this.toolItems = new Ext.util.MixedCollection();
    if(tools){
        this.addTool.apply(this, tools);
    }
};

Ext.extend(Ext.ux.StartMenu, Ext.menu.Menu, {
	height : 300,
	toolPanelWidth : 90,
	width : 300,
	
    // private  нажали на кнопку пуск.
    render : function(){
        if(this.el){
            return;
        }
        var el = this.el = new Ext.Layer({
            cls: "x-menu ux-start-menu",
            shadow:this.shadow,
            constrain: false,
            parentEl: this.parentEl || document.body,
            zindex:15000
        });
        
        var header = el.createChild({
        	tag: "div", 
        	cls: "x-window-header x-unselectable x-panel-icon "+this.iconCls 
        });
        header.setStyle('padding', '0 0 0 0');
        
		this.header = header;
		/* Don't create header text span tag.
		 * Can be uncommented.*/
		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: "ux-start-menu-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: "ux-start-menu-mc ux-start-menu-bwrap"
		});
		
		this.menuPanel = this.menuBWrap.createChild({
			tag: "div",
			cls: "x-panel x-border-panel ux-start-menu-apps-panel opaque"
		});
		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"
		});
		
		bc.setStyle({
			height: '0px',
			padding: '0 0 6px 0'
		});
		
        this.keyNav = new Ext.menu.MenuNav(this);

        if(this.plain){
            el.addClass("x-menu-plain");
        }
        if(this.cls){
            el.addClass(this.cls);
        }
        // generic focus element
        this.focusEl = el.createChild({
            tag: "a",
            cls: "x-menu-focus",
            href: "#",
            onclick: "return false;",
            tabIndex:"-1"
        });
        
        var ul = this.menuPanel.createChild({
        	tag: "ul",
        	cls: "x-menu-list"});
        var toolsUl = this.toolsPanel.createChild({
        	tag: "ul",
        	cls: "x-menu-list"
        });
        
        var ulListeners = {
        	"click": {
        		fn: this.onClick,
        		scope: this
        	},
        	"mouseover": {
        		fn: this.onMouseOver,
        		scope: this
        	},
        	"mouseout": {
        		fn: this.onMouseOut,
        		scope: this
        	}
        };
        
        ul.on(ulListeners);
        
        this.items.each(
        	function(item){
	            var li = document.createElement("li");
	            li.className = "x-menu-list-item";
	            ul.dom.appendChild(li);
	            item.render(li, this);
	        }, this);

        this.ul = ul;
        this.autoWidth();

        toolsUl.on(ulListeners);
        
        this.toolItems.each(
        	function(item){
	            var li = document.createElement("li");
	            li.className = "x-menu-list-item";
	            toolsUl.dom.appendChild(li);
	            item.render(li, this);
	        }, this);
	        
        this.toolsUl = toolsUl;
        this.autoWidth();
             
        this.menuBWrap.setStyle('position', 'relative');  
        this.menuBWrap.setHeight(this.height);
        
        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);
    },
    
    // private  событие при наведении мышки на меню.
    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); //возвр. эл. дополнительного толс меню
            }
        }
    },

    /**
     * Displays this menu relative to another element
     * @param {Mixed} element The element to align to
     * @param {String} position (optional) The {@link Ext.Element#alignTo} anchor position to use in aligning to
     * the element (defaults to this.defaultAlign)
     * @param {Ext.ux.StartMenu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
     */
   //клик по кнопке старт меню 
    show : function(el, pos, parentMenu){
        this.parentMenu = parentMenu;
        if(!this.el){
            this.render(); //~124
        }
        //отображение меню
        this.fireEvent("beforeshow", this);
        this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
        
        var tPanelWidth = this.toolPanelWidth;      
        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;
    },
    
    /**
     * Adds a separator bar to the Tools
     * @return {Ext.menu.Item} The menu item that was added
     */ //Начало загрузки рабочего стола.
    addToolSeparator : function(){
        return this.addToolItem(new Ext.menu.Separator({itemCls: 'ux-toolmenu-sep'}));
    },

    addToolItem : function(item){
        this.toolItems.add(item);
        if(this.toolsUl){
            var li = document.createElement("li");
            li.className = "x-menu-list-item";
            this.toolsUl.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);
                //config = new Ext.menu.Adapter(this.getToolButton(config), {canActivate:true});
            }
        }
        return this.addToolItem(config);
    },
    
    setTitle : function(title, iconCls){
        this.title = title;
		if (this.header!=null)
        if(this.header.child('span')){
        	this.header.child('span').update(title);
        }
        return this;
    },
    
    getToolButton : function(config){
    	var btn = new Ext.Button({
			handler: config.handler,
			//iconCls: config.iconCls,
			minWidth: this.toolPanelWidth-10,
			scope: config.scope,
			text: config.text
		});
		
    	return btn;
    }
});


Ext.namespace("Ext.ux");

/**
 * @class Ext.ux.TaskBar
 * @extends Ext.util.Observable
 */
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: 170,
			shadow: true,
			title: 'Demo',
			width: 280
		}//, this.app.startConfig
		));
		
		this.startButton = new Ext.Button({
            text: 'СТАРТ',
            id: 'ux-startbutton',
            iconCls: 'start',
            menu: this.startMenu,
            menuAlign: 'bl-tl',
            renderTo: 'ux-taskbar-start'
        });
        
        var startWidth = Ext.get('ux-startbutton').getWidth() + 10;
        
        var sbBox = new Ext.BoxComponent({
			el: 'ux-taskbar-start',
	        id: 'TaskBarStart',
	        minWidth: startWidth,
			region:'west',
			split: false,
			width: startWidth
		});
		
		this.quickStartPanel = new Ext.ux.QuickStartPanel({
			el: 'ux-quickstart-panel',
	        id: 'TaskBarQuickStart',
	        minWidth: 60,
			region:'west',
			split: true,
			width: 94
		});
		
		this.taskButtonPanel = new Ext.ux.TaskButtonsPanel({
			el: 'ux-taskbuttons-panel',
			id: 'TaskBarButtons',
			region:'center'
		});
		
		var panelWrap = new Ext.Container({
			el: 'ux-taskbar-panel-wrap',
			items: [this.quickStartPanel,this.taskButtonPanel],
			layout: 'border',
			region: 'center'
		});
				
        var container = new Ext.ux.TaskBarContainer({
			el: 'ux-taskbar',
			layout: 'border',
			items: [sbBox,panelWrap]
		});
		this.el = container.el;
		
		return this;
    },
    
	setActiveButton : function(btn){
		this.taskButtonPanel.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'
        });
	},
	// вызывается из render
	add : 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;
	},
	//удаляет окно.
	remove : 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');
    }
});



/**
 * @class Ext.ux.TaskBar.TaskButton
 * @extends Ext.Button
 */
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),
        tooltip: win.taskbuttonTooltip || win.title,
        renderTo: el,
        handler : function(){
            if(win.minimized || win.hidden){
                win.show();
            }else if(win == win.manager.getActive()){
                win.minimize();
            }else{
                win.toFront();
            }
        },
        clickEvent:'mousedown'
    });
};

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: [{
            	id: 'restore',
                text: 'Restore',
                handler: function(){
                    if(!this.win.isVisible()){
                        this.win.show();
                    }else{
                        this.win.restore();
                    }
                },
                scope: this
            },{
                id: 'minimize',
                text: 'Minimize',
                handler: this.win.minimize,
                scope: this.win
            },{
                id: 'maximize',
                text: 'Maximize',
                handler: this.win.maximize,
                scope: this.win
            }, '-', {
                id: 'close',
                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);
			items[2].setDisabled(w.maximizable === false);
			items[3].setDisabled(w.closable === false);
        }, 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();
	},
	
	/**
	 * override so autoWidth() is not called
     * @param {String} text The text for the button
     */
    setText : function(text){
		if(text){
			this.text = text;
			if(this.el){
				this.el.child("td.x-btn-center " + this.buttonSelector).update(Ext.util.Format.ellipsis(text, 12));
			}
		}
    },
    
    /**
     * @param {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
     */
    setTooltip : function(text){
    	if(text){
    		this.tooltip = text;
        	var btnEl = this.el.child(this.buttonSelector);
        	Ext.QuickTips.unregister(btnEl.id);
        	
            if(typeof this.tooltip == 'object'){                
                Ext.QuickTips.register(Ext.apply({
                      target: btnEl.id
                }, this.tooltip));
            } else {
            	btnEl.dom[this.tooltipType] = this.tooltip;
            }
        }
    }
});



/**
 * @class Ext.ux.QuickStartPanel
 * @extends Ext.BoxComponent
 */
Ext.ux.QuickStartPanel = Ext.extend(Ext.BoxComponent, {
	enableMenu: true,
	
	initComponent : function(){
        Ext.ux.QuickStartPanel.superclass.initComponent.call(this);
        
        this.on('resize', this.delegateUpdates);
        
        this.menu = new Ext.menu.Menu();
        
        this.items = [];
        
        this.stripWrap = Ext.get(this.el).createChild({
        	cls: 'ux-quickstart-strip-wrap',
        	cn: {tag:'ul', cls:'ux-quickstart-strip'}
		});
		
        this.stripSpacer = Ext.get(this.el).createChild({
        	cls:'ux-quickstart-strip-spacer'
        });
        
        this.strip = new Ext.Element(this.stripWrap.dom.firstChild);
        
        this.edge = this.strip.createChild({
        	tag:'li',
        	cls:'ux-quickstart-edge'
        });
        
        this.strip.createChild({
        	cls:'x-clear'
        });
	},
	
	add : function(config){
		var li = this.strip.createChild({tag:'li'}, this.edge); // insert before the edge
        
		var btn = new Ext.Button(Ext.apply(config, {
			cls:'x-btn-icon',
			menuText: config.text,
			renderTo: li,
			text: '' // do not display text
		}));
        
		this.items.push(btn);
		
		this.delegateUpdates();
		
		return btn;
	},
	
	remove : 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();
	},
	
	menuAdd : function(config){
		this.menu.add(config);
	},
	//возникло при расширении быстрого запуска
	delegateUpdates : function(){
        if(this.enableMenu && this.rendered){
        	this.showButtons();
        	this.clearMenu();
            this.autoMenu();
        }
    },
    
    showButtons : function(){
    	var count = this.items.length;
    	
    	for(var i = 0; i < count; i++){
			this.items[i].show(); 	
		}
    },
    
    clearMenu : function(){
    	this.menu.removeAll();
    },
	
	autoMenu : 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 l = this.edge.getOffsetsTo(this.stripWrap)[0];
        
        if(!this.enableMenu || count < 1 || cw < 20){ // 20 to prevent display:none issues
            return;
        }
        
        wrap.setWidth(tw);
        
        if(l <= tw){
            if(this.showingMenu){
                this.showingMenu = false;
                this.menuButton.hide();
            }
        }else{
        	tw -= wrap.getMargins('lr');
            
            wrap.setWidth(tw > 20 ? tw : 20);
            
            if(!this.showingMenu){
                if(!this.menuButton){
                    this.createMenuButton();
                }else{
                    this.menuButton.show();
                }
            }
            
            mo = this.getMenuButtonPos();
            
            for(var i = count-1; i >= 0; i--){
            	var bo = this.items[i].el.dom.offsetLeft + this.items[i].el.dom.offsetWidth;
            	
            	if(bo > mo){
            		this.items[i].hide();

            		var ic = this.items[i].initialConfig,
            			config = {
	            			iconCls: ic.iconCls,
	            			handler: ic.handler,
	            			scope: ic.scope,
	            			text: ic.menuText
	            		};
            		
            		this.menuAdd(config);
            	}else{
            		this.items[i].show();
            	}
            }
            
            this.showingMenu = true;
        }
    },
    
    createMenuButton : function(){
    	
       	var h = this.el.dom.offsetHeight;

        var mb = this.el.insertFirst({
            cls:'ux-quickstart-menubutton-wrap'
        });
        
        mb.setHeight(h);
        
        var btn = new Ext.Button({
        	cls:'x-btn-icon',
        	id: 'ux-quickstart-menubutton',
        	menu: this.menu,
        	renderTo: mb
        });
        
        mb.setWidth(Ext.get('ux-quickstart-menubutton').getWidth());
        
        this.menuButton = mb;
    },
    
    getMenuButtonPos : function(){
    	return this.menuButton.dom.offsetLeft;
    }
});


// Use our blank image
Ext.BLANK_IMAGE_URL = 'resources/images/default/s.gif';



Ext.Desktop = function(app){
	
	this.taskbar = new Ext.ux.TaskBar(app);
	var taskbar = this.taskbar;
	
	this.el = Ext.get('x-desktop');
	var desktopEl = this.el;
	
    var taskbarEl = Ext.get('ux-taskbar');
    
    this.shortcuts = new Ext.ux.Shortcuts({
    	renderTo: 'x-desktop',
    	taskbarEl: taskbarEl
    });
	
	this.config = null;
	this.initialConfig = null;

    var windows = new Ext.WindowGroup();
    var activeWindow;
		
    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');
        }
    }
    //вызывается после n markInactive потом вызывается remove 566 remove : function(btn){
    function removeWin(win){
    	taskbar.taskButtonPanel.remove(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
            })
        );
        win.render(desktopEl); //переходит на 555 на add
        win.taskButton = taskbar.taskButtonPanel.add(win);

        win.cmenu = new Ext.menu.Menu({
            items: [

            ]
        });

        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.getManager = function(){
        return windows;
    };

    this.getWindow = function(id){
        return windows.get(id);
    };
    
    this.getViewHeight = function(){
    	return (Ext.lib.Dom.getViewHeight()-taskbarEl.getHeight());
    };
    
    this.getViewWidth = function(){
    	return Ext.lib.Dom.getViewWidth();
    };
    //вызывается после открытия например помощи	
    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;
	};
	
	this.setBackgroundColor = function(hex){
		if(hex){
			Ext.get(document.body).setStyle('background-color', '#'+hex);
			this.config.styles.backgroundcolor = hex;
		}
	};
	
	this.setFontColor = function(hex){
		if(hex){
			Ext.util.CSS.updateRule('.ux-shortcut-btn-text', 'color', '#'+hex);
			this.config.styles.fontcolor = hex;
		}
	};
	
	this.setTheme = function(o){
		if(o && o.id && o.name && o.pathtofile){
			Ext.util.CSS.swapStyleSheet('theme', o.pathtofile);
			this.config.styles.theme = o;
		}
	};
	
	this.setTransparency = function(b){
		if(String(b) != ""){
			if(b){
				taskbarEl.addClass("transparent");
			}else{
				taskbarEl.removeClass("transparent");
			}
			this.config.styles.transparency = b
		}
	};
	
	this.setWallpaper = function(o){
		if(o && o.id && o.name && o.pathtofile){
			
			var notifyWin = this.showNotification({
				html: 'Загрузка, пожалуйста подождите'
				, title: 'Информация'
			});
			
			var wp = new Image();
			wp.src = o.pathtofile;
			
			var task = new Ext.util.DelayedTask(verify, this);
			task.delay(200);
			
			this.config.styles.wallpaper = o;
		}
		
		function verify(){
			if(wp.complete){
				task.cancel();
				
				notifyWin.setIconClass('x-icon-done');
				notifyWin.setTitle('Информация');
				notifyWin.setMessage('Страница загруженна');
				this.hideNotification(notifyWin);
				
				document.body.background = wp.src;
			}else{
				task.delay(200);
			}
		}
	};
	
	this.setWallpaperPosition = function(pos){
		if(pos){
			if(pos === "center"){
				var b = Ext.get(document.body);
				b.removeClass('wallpaper-tile');
				b.addClass('wallpaper-center');
			}else if(pos === "tile"){
				var b = Ext.get(document.body);
				b.removeClass('wallpaper-center');
				b.addClass('wallpaper-tile');
			}			
			this.config.styles.wallpaperposition = pos;
		}
	};
	
	this.showNotification = function(config){
		var win = new Ext.ux.Notification(Ext.apply({
			animateTarget: taskbarEl
			, autoDestroy: true
			, hideDelay: 5000
			, html: ''
			, iconCls: 'x-icon-waiting'
			, title: ''
		}, config));
		win.show();

		return win;
	};
	
	this.hideNotification = function(win, delay){
		if(win){
			(function(){ win.animHide(); }).defer(delay || 3000);
		}
	};
	
	this.addAutoRun = function(id){
		var m = app.getModule(id),
			c = this.config.launchers.autorun;
			
		if(m && !m.autorun){
			m.autorun = true;
			c.push(id);
		}
	};
	
	this.removeAutoRun = function(id){
		var m = app.getModule(id),
			c = this.config.launchers.autorun;
			
		if(m && m.autorun){
			var i = 0;
				
			while(i < c.length){
				if(c[i] == id){
					c.splice(i, 1);
				}else{
					i++;
				}
			}
			
			m.autorun = null;
		}
	};
	
	// Private
	this.addContextMenuItem = function(id){
		var m = app.getModule(id);
		if(m && !m.contextMenuItem){
			/* if(m.moduleType === 'menu'){ // handle menu modules
				var items = m.items;
				for(var i = 0, len = items.length; i < len; i++){
					m.launcher.menu.items.push(app.getModule(items[i]).launcher);
				}
			} */
			this.cmenu.add(m.launcher);
		}
	};

	this.addShortcut = function(id, updateConfig){
		var m = app.getModule(id);
		
		if(m && !m.shortcut){
			var c = m.launcher;
			
			m.shortcut = this.shortcuts.addShortcut({
				handler: c.handler,
				iconCls: c.shortcutIconCls,
				scope: c.scope,
				text: c.text
			});
			
			if(updateConfig){
				this.config.launchers.shortcut.push(id);
			}
		}
		
	};

	this.removeShortcut = function(id, updateConfig){
		var m = app.getModule(id);
		
		if(m && m.shortcut){
			this.shortcuts.removeShortcut(m.shortcut);
			m.shortcut = null;
			
			if(updateConfig){
				var sc = this.config.launchers.shortcut,
					i = 0;
				while(i < sc.length){
					if(sc[i] == id){
						sc.splice(i, 1);
					}else{
						i++;
					}
				}
			}
		}
	};

	this.addQuickStartButton = function(id, updateConfig){
    	var m = app.getModule(id);
    	
		if(m && !m.quickStartButton){
			var c = m.launcher;
			
			m.quickStartButton = this.taskbar.quickStartPanel.add({
				handler: c.handler,
				iconCls: c.iconCls,
				scope: c.scope,
				text: c.text,
				tooltip: c.tooltip || c.text
			});
			
			if(updateConfig){
				this.config.launchers.quickstart.push(id);
			}
		}
    };
    
    this.removeQuickStartButton = function(id, updateConfig){
    	var m = app.getModule(id);
    	
		if(m && m.quickStartButton){
			this.taskbar.quickStartPanel.remove(m.quickStartButton);
			m.quickStartButton = null;
			
			if(updateConfig){
				var qs = this.config.launchers.quickstart,
					i = 0;
				while(i < qs.length){
					if(qs[i] == id){
						qs.splice(i, 1);
					}else{
						i++;
					}
				}
			}
		}
    };

    layout();
    
    this.cmenu = new Ext.menu.Menu();
    
    desktopEl.on('contextmenu', function(e){
    	if(e.target.id === desktopEl.id){
	    	e.stopEvent();
			if(!this.cmenu.el){
				this.cmenu.render();
			}
			var xy = e.getXY();
			xy[1] -= this.cmenu.el.getHeight();
			this.cmenu.showAt(xy);
		}
	}, this);
	
	/*
	var bogusMarkup = '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>';
	this.portal = new Ext.ux.Portal({
		id: 'portal',
		items: [{
			//columnWidth:.9,
			style:'padding:10px 0 10px 10px',
			items:[{
				title: 'Panel 2',
				html: bogusMarkup
				},{
				title: 'Another Panel 2',
				html: bogusMarkup
			}],
			width: 400
		}],
		minWidth: 64,
		renderTo: 'x-desktop',
		width: 204
	}); */
};



Ext.ux.NotificationMgr = {
    positions: []
};

Ext.ux.Notification = Ext.extend(Ext.Window, {
	initComponent : function(){
		Ext.apply(this, {
			iconCls: this.iconCls || 'x-icon-information'
			, width: 200
			, autoHeight: true
			, closable: true
			, plain: false
			, draggable: false
			, bodyStyle: 'text-align:left;padding:10px;'
			, resizable: false
		});
		if(this.autoDestroy){
			this.task = new Ext.util.DelayedTask(this.close, this);
		}else{
			this.closable = true;
		}
		Ext.ux.Notification.superclass.initComponent.call(this);
    }

	, setMessage : function(msg){
		this.body.update(msg);
	}
	
	, setTitle : function(title, iconCls){
        Ext.ux.Notification.superclass.setTitle.call(this, title, iconCls||this.iconCls);
    }

	, onRender : function(ct, position) {
		Ext.ux.Notification.superclass.onRender.call(this, ct, position);
	}

	, onDestroy : function(){
		Ext.ux.NotificationMgr.positions.remove(this.pos);
		Ext.ux.Notification.superclass.onDestroy.call(this);
	}

	, afterShow : function(){
		Ext.ux.Notification.superclass.afterShow.call(this);
		this.on('move', function(){
			Ext.ux.NotificationMgr.positions.remove(this.pos);
			if(this.autoDestroy){
				this.task.cancel();
			}
		}, this);
		if(this.autoDestroy){
			this.task.delay(this.hideDelay || 5000);
		}
	}

	, animShow : function(){
		this.pos = 0;
		while(Ext.ux.NotificationMgr.positions.indexOf(this.pos)>-1){
			this.pos++;
		}
		Ext.ux.NotificationMgr.positions.push(this.pos);
		this.setSize(200,100);
		this.el.alignTo(this.animateTarget || document, "br-tr", [ -1, -1-((this.getSize().height+10)*this.pos) ]);
		this.el.slideIn('b', {
			duration: .7
			, callback: this.afterShow
			, scope: this
		});
	}

	, animHide : function(){
		Ext.ux.NotificationMgr.positions.remove(this.pos);
		this.el.ghost("b", {
			duration: 1
			, remove: true
		});
	}
});


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,
    modules : null,
    /*
	 * The the URL of the script that allows a module to connect to its 
	 * server script without knowing the path.
	 * 
	 * Example ajax call:
	 * 
	 * Ext.Ajax.request({
	 *     url: this.app.connection,
	 *     // Could also pass moduleId and fileName in querystring like this,
	 *     // instead of in the params config option.
	 *      
	 *     // url: this.app.connection+'?moduleId='+this.id+'&fileName=Preferences.php',
	 *      params: {
	 *			moduleId: this.id,
	 *			fileName: 'Preferences.php',
	 *
	 *			...
	 *		},
	 *		success: function(){
	 *			...
	 *		},
	 *		failure: function(){
	 *			...
	 *		},
	 *		scope: this
	 *	});
	 */
	connection : 'Connect',
    
    initApp : function(){
    	// prevent backspace (history -1) shortcut
		var map = new Ext.KeyMap(document, [
		{
			key: Ext.EventObject.BACKSPACE,
			stopEvent: true,
			fn: function(key, e){
				var t = e.target.tagName;
				if(t != "INPUT" && t != "TEXTAREA"){
					e.stopEvent();
				}
			}
		}]);
		
    	this.startConfig = this.startConfig || this.getStartConfig();
        this.desktop = new Ext.Desktop(this);
		
		this.modules = this.getModules();
        if(this.modules){
            this.initModules(this.modules);
            this.initDesktopConfig();
        }

        this.init();

        Ext.EventManager.on(window, 'beforeunload', this.onUnload, this);
		this.fireEvent('ready', this);
        this.isReady = true;
    },

	getModules : Ext.emptyFn,
    getStartConfig : Ext.emptyFn,
    getLogoutButtonConfig : Ext.emptyFn,
	getDesktopConfig : Ext.emptyFn,
    init : Ext.emptyFn,

    initModules : function(ms){
		for(var i = 0, len = ms.length; i < len; i++){
            ms[i].app = this;
        }
    },
    //инициализация рабочего стола
    initDesktopConfig : function(o){
    	if(!o){
			this.getDesktopConfig();
		}else{
			var l = o.launchers;
			
			l.contextmenu = l.contextmenu || [];
			l.startmenu  = l.startmenu || [];
			l.startmenutool = l.startmenutool || [];
			l.quickstart = l.quickstart || [];
			l.shortcut = l.shortcut || [];
			o.styles = o.styles || [];
			l.autorun = l.autorun || [];
			
			this.desktop.config = o;
			this.desktop.initialConfig = o;
			
			this.initContextMenu(l.contextmenu);
			this.initStartMenu(l.startmenu, false);
	        this.initStartMenu(l.startmenutool, true);
	        this.initLogoutButton();
	        this.initQuickStart(l.quickstart);
	        this.initShortcuts(l.shortcut);
	        this.initStyles(o.styles);
	        this.initAutoRun(l.autorun);
			QoDesk.desktop.taskbar.startMenu.setTitle(loginurl.username);
		}
    },
    
    initAutoRun : function(mIds){
    	if(mIds){
    		for(var i = 0, len = mIds.length; i < len; i++){
	            var m = this.getModule(mIds[i]);
	            if(m){
	            	m.autorun = true;
	            	m.createWindow();
	            }
			}
		}
    },

    initContextMenu : function(mIds){
    	if(mIds){
    		for(var i = 0, len = mIds.length; i < len; i++){
    			this.desktop.addContextMenuItem(mIds[i]);
	        }
    	}
    },
    
    initLogoutButton : function(){
    	var config = this.getLogoutButtonConfig();
    	this.desktop.taskbar.startMenu.addTool(config);
    },

    initShortcuts : function(mIds){
		if(mIds){
			for(var i = 0, len = mIds.length; i < len; i++){
	            this.desktop.addShortcut(mIds[i], false);
	        }
		}
    },
    
    initStartMenu : function(mIds, tool){		
		var startMenu = this.desktop.taskbar.startMenu;
		
		if(mIds){	        
	        for(var i = 0, iLen = mIds.length; i < iLen; i++){
				var m = this.getModule(mIds[i]);
	            if(m){
	            	var app = this;
	            	addItems(startMenu, m);
				}
	        }
		}
		
		function addItems(menu, m){ // recursive function, allows sub menus
			if(m.moduleType == 'menu' && m.items){
				var items = m.items;
				for(var j = 0, jLen = items.length; j < jLen; j++){
					var item = app.getModule(items[j]);
					if(item){
						addItems(m.menu, item);
					}
				}
			}
			if(m.launcher){
				if(tool === true){
					menu.addTool(m.launcher);
				}else{
					menu.add(m.launcher);
				}
			}		
		}
    },

	initQuickStart : function(mIds){
		if(mIds){
			for(var i = 0, len = mIds.length; i < len; i++){
	            this.desktop.addQuickStartButton(mIds[i], false);
	        }
		}
    },
    
    initStyles : function(s){
    	this.desktop.setBackgroundColor(s.backgroundcolor);
    	this.desktop.setFontColor(s.fontcolor);
    	this.desktop.setTheme({
    		id: s.themeid,
    		name: s.themename,
    		pathtofile: s.themefile
    	});
    	this.desktop.setTransparency(s.transparency);
    	this.desktop.setWallpaper({
    		id: s.wallpaperid,
    		name: s.wallpapername,
    		pathtofile: s.wallpaperfile
    	});
    	this.desktop.setWallpaperPosition(s.wallpaperposition);
    },
    
    getModule : function(v){
    	var ms = this.modules;
    	for(var i = 0, len = ms.length; i < len; i++){
    		if(ms[i].moduleId == v || ms[i].moduleType == v){
    			return ms[i];
			}
        }
        return '';
    },

    onReady : function(fn, scope){
        if(!this.isReady){
            this.on('ready', fn, scope);
        }else{
            fn.call(scope, this);
        }
    },

    getDesktop : function(){
        return this.desktop;
    },
//вызывается при перезагрузке окна.
    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
});

var status={ok: 0};
QoDesk = new Ext.app.App({
	
	init :function(){
		Ext.QuickTips.init();
	},
	
	// config for the logout button
	getLogoutButtonConfig : function(){
		var te='';
		if (loginurl.user=='logout'){
           te='Выход';	
		   
		}else {
           te='Вход';
		}
		CarCurrent.Update();
		return {
			text: te,
			id: 'id-logout',
			iconCls: 'logout',
			handler: function(){ 
 					window.location.href=loginurl.url;
 			},
			scope: this
		};
	},

	// modules to initialize (make available to your desktop)
	getModules : function(){
		return [
			// The next line is being replaced by os.php
			new QoDesk.QoPreferences(),
			new QoDesk.GridWindow(),
			new QoDesk.TabWindow(),
			new QoDesk.AccordionWindow(),
			new QoDesk.LayoutWindow(),
			new QoDesk.IframeWindow(),
			new QoDesk.ViewAnket(),
			new QoDesk.AnketaWindow(),
			new QoDesk.AnketaWindowNew(),
		//	new QoDesk.BogusMenu(),
		//	new QoDesk.BogusSubMenu(),  
			new QoDesk.BogusModule()
		];
	},
	
	// config for the start menu
    getStartConfig : function(){
    	return {
        	iconCls: 'user',
            title: 'Demo1', 
			toolPanelWidth: 115
        };
    },
    
    // config for the desktop
    getDesktopConfig : function(){
    	// can also call server for saved config
		Ext.Ajax.request({
			success: function(o){
				var decoded = Ext.decode(o.responseText);
				loginurl = decoded.urllogin;

				if(decoded.success){
					this.initDesktopConfig(decoded.config);
				}else{
					// error
				}
			},
			failure: function(){
				// error
			},
			scope: this,
			params:{ uid: uidkey},
			url: 'DesktopConfig'
		}); 
   }
});
/*
 * qWikiOffice Desktop 0.7.1
 * Copyright(c) 2007-2008, Integrated Technologies, Inc.
 * licensing@qwikioffice.com
 * 
 */

Ext.namespace("Ext.ux");

/**
 * @class Ext.ux.Shortcuts
 */

Ext.ux.Shortcuts = function(config){
	var desktopEl = Ext.get(config.renderTo)
		, taskbarEl = config.taskbarEl
		, btnHeight = 74
		, btnWidth = 64
		, btnPadding = 15
		, col = null
		, row = null
		, items = [];
	
	initColRow();
	
	//Инициализация колонок переходит на (this.setXY = function(item))
	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){
		var div = desktopEl.createChild({tag:'div', cls: 'ux-shortcut-item'}),
			btn = new Ext.ux.ShortcutButton(Ext.apply(config, {
				text: Ext.util.Format.ellipsis(config.text, 16)
			}), div);
		
		//btn.container.initDD('DesktopShortcuts');
		
		items.push(btn);
		this.setXY(btn.container);
		
		return btn;
	};
	
	this.removeShortcut = function(b){
		var d = document.getElementById(b.container.id);
		
		b.destroy();
		d.parentNode.removeChild(d);
		
		var s = [];
		for(var i = 0, len = items.length; i < len; i++){
			if(items[i] != b){
				s.push(items[i]);
			}
		}
		items = s;
		
		this.handleUpdate();
	}
	//Обновление рабочего стола. (перемещение иконок при необходимости.)
	this.handleUpdate = function(){
		initColRow();
		for(var i = 0, len = items.length; i < len; i++){
			this.setXY(items[i].container);
		}
	}
	//уст видимо новые размеры раб ст. вызывается постоянно function isOverflow(y)
	this.setXY = function(item){
		var bottom = row.y + btnHeight,
			overflow = isOverflow(row.y + btnHeight);
		
		if(overflow && bottom > (btnHeight + btnPadding)){
			col = {
				index: col.index++
				, x: col.x + btnWidth + btnPadding
			};
			row = {
				index: 1
				, y: btnPadding
			};
		}
		
		item.setXY([
			col.x
			, row.y
		]);
		
		row.index++;
		row.y = row.y + btnHeight + btnPadding;
	};
	
	Ext.EventManager.onWindowResize(this.handleUpdate, this, {delay:500});
};



/**
 * @class Ext.ux.ShortcutButton
 * @extends Ext.Button
 */
Ext.ux.ShortcutButton = function(config, el){
	
    Ext.ux.ShortcutButton.superclass.constructor.call(this, Ext.apply(config, {
        renderTo: el,
        //clickEvent: 'dblclick',
		template: new Ext.Template(
			'<div class="ux-shortcut-btn"><div>',
				'<img src="'+Ext.BLANK_IMAGE_URL+'" />',
				'<div class="ux-shortcut-btn-text">{0}</div>',
			'</div></div>')
    }));
    
};

Ext.extend(Ext.ux.ShortcutButton, Ext.Button, {

	buttonSelector : 'div:first',
	
     onRender : function(){
        Ext.ux.ShortcutButton.superclass.onRender.apply(this, arguments);

        this.cmenu = new Ext.menu.Menu({
            items: [{
                id: 'open',
                text: 'Open',
                //handler: this.win.minimize,
                scope: this.win
            }, '-', {
                id: 'remove',
                iconCls: 'remove',
                text: 'Remove Shortcut',
                //handler: this.closeWin.createDelegate(this, this.win, true),
                scope: this.win
            }]
        });

        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);
    }, 
    
    initButtonEl : function(btn, btnEl){
    	Ext.ux.ShortcutButton.superclass.initButtonEl.apply(this, arguments);
    	
    	btn.removeClass("x-btn");
    	
    	if(this.iconCls){
            if(!this.cls){
                btn.removeClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
            }
        }
    },
    
    autoWidth : function(){
    	// do nothing
    },
	
	/**
     * Sets this shortcut button's text
     * @param {String} text The button text
     */
    setText : function(text){
        this.text = text;
        if(this.el){
        	this.el.child("div.ux-shortcut-btn-text").update(text);
        }
    }
});




QoDesk.QoPreferences = Ext.extend(Ext.app.Module, {
	
	moduleType : 'system',
	moduleId : 'qo-preferences',
	
	actions : null,
	cards : [
		'pref-win-card-1', // navigation
		'pref-win-card-2', // quickstart
		'pref-win-card-3', // color and appearance
		'pref-win-card-4', // wallpaper
		'pref-win-card-5', // autorun
		'pref-win-card-6'  // shortcuts
	],
	contentPanel : null,
	cardHistory : [
		'pref-win-card-1' // default
	],
	layout: null,
	win : null,
	
    init : function(){
        this.launcher = {
        	iconCls: 'pref-icon',
            handler : this.createWindow,
            scope: this,
            shortcutIconCls: 'pref-shortcut-icon',
            text: 'Настройки',
            tooltip: '<b>Настройки</b><br />Модификация рабочего стола'
        }
    },

    createWindow : function(){
    	var desktop = this.app.getDesktop();
        this.win = desktop.getWindow(this.moduleId);
        
        if(!this.win){
        	var winWidth = 610;
			var winHeight = 460;
			
			this.contentPanel = new Ext.Panel({
				activeItem: 0,
                border: false,
				id: 'pref-win-content',
				items: [
                	new QoDesk.QoPreferences.NavPanel({owner: this, id: 'pref-win-card-1'}),
                	new QoDesk.QoPreferences.Shortcuts({owner: this, id: 'pref-win-card-6'}),
                	new QoDesk.QoPreferences.AutoRun({owner: this, id: 'pref-win-card-5'}),
                	new QoDesk.QoPreferences.QuickStart({owner: this, id: 'pref-win-card-2'}),
                	new QoDesk.QoPreferences.Appearance({owner: this, id: 'pref-win-card-3'}),
                	new QoDesk.QoPreferences.Background({owner: this, id: 'pref-win-card-4'})
                ],
				layout: 'card',
				tbar: [{
					disabled: true,
                	handler: this.navHandler.createDelegate(this, [-1]),
                	id: 'back',
                	scope: this,
                	text: 'Назад'
                },{
                	disabled: true,
                	handler: this.navHandler.createDelegate(this, [1]),
                	id: 'next',
                	scope: this,
                	text: 'Вперед'
                }]
			});
			
            this.win = desktop.createWindow({
            	animCollapse: false,
                constrainHeader: true,
                id: this.moduleId,
                height: winHeight,
                iconCls: 'pref-icon',
                items: this.contentPanel,
                layout: 'fit',
                shim: false,
                taskbuttonTooltip: '<b>Настройки</b><br />Модификация рабочего стола',
                title: 'Настройки',
                width: winWidth
            });
            
			this.layout = this.contentPanel.getLayout();
        }
        
        this.win.show();
    },
    
    handleButtonState : function(){
    	var cards = this.cardHistory, activeId = this.layout.activeItem.id,
    		items = this.contentPanel.getTopToolbar().items, back = items.get(0), next = items.get(1);
    	
    	for(var i = 0, len = cards.length; i < len; i++){
    		if(cards[i] === activeId){
    			if(i <= 0){
    				back.disable();
    				next.enable();
    			}else if(i >= (len-1)){
    				back.enable();
    				next.disable();
    			}else{
    				back.enable();
    				next.enable();
    			}
    			break;
    		}
    	}
    },
    
    navHandler : function(index){
    	var cards = this.cardHistory,
    		activeId = this.layout.activeItem.id,
    		nextId;
    	
    	for(var i = 0, len = cards.length; i < len; i++){
    		if(cards[i] === activeId){
    			nextId = cards[i+index];
    			break;
    		}
    	}
    	
    	this.layout.setActiveItem(nextId);
    	this.handleButtonState();
    },
    
    save : function(params){    	
    	var desktop = this.app.getDesktop();
    	var notifyWin = desktop.showNotification({
			html: 'Сохранение данных...'
			, title: 'Информация'
		});
	    var callback = params.callback || null;
		var callbackScope = params.callbackScope || this;
		
		params.moduleId = this.moduleId;
		params.fileName = 'Preferences.php';
        params.uid = uidkey;
	    Ext.Ajax.request({
			url: this.app.connection,
			/* Could also pass moduleId and fileName in querystring like this
			 * instead of in the params config option.
			 *
			 * url: this.app.connection+'?moduleId='+this.id+'&fileName=Preferences.php', */
			params: params,
			success: function(o){
				if(o && o.responseText && Ext.decode(o.responseText).success){
					saveComplete('Информация', 'Данные сохранены');
				}else{
					saveComplete('Ошибка', 'Ошибка в данных.');
				}
			},
			failure: function(){
				saveComplete('Ошибка', 'Потеренно соединение с сервером.');
			},
			scope: this
		});
		
		function saveComplete(title, msg){
			notifyWin.setIconClass('x-icon-done');
			notifyWin.setTitle(title);
			notifyWin.setMessage(msg);
			desktop.hideNotification(notifyWin);
			
			if(callback){
				callback.call(callbackScope);
			}
		}
	},
    
    viewCard : function(card){
		this.layout.setActiveItem(card);
	    if(this.cardHistory.length > 1){
	    	this.cardHistory.pop();
	    }
	    this.cardHistory.push(card);
	    this.handleButtonState();
	}
});

//				<li> \
//					<img src="'+Ext.BLANK_IMAGE_URL+'" class="icon-pref-autorun"/> \
//					<a id="viewShortcuts" href="#">Shortcuts</a><br /> \
//					<span>Choose which applications appear in your shortcuts.</span> \
//				</li> \
//				<li> \
//					<img src="'+Ext.BLANK_IMAGE_URL+'" class="icon-pref-autorun"/> \
//					<a id="viewAutoRun" href="#">Auto Run Apps</a><br /> \
//					<span>Choose which applications open automatically once logged in.</span> \
//				</li> \
//				<li> \
//					<img src="'+Ext.BLANK_IMAGE_URL+'" class="icon-pref-quickstart"/> \
//					<a id="viewQuickstart" href="#">Quick Start Apps</a><br /> \
//					<span>Choose which applications appear in your Quick Start panel.</span> \
//				</li> \

QoDesk.QoPreferences.NavPanel = function(config){
	this.owner = config.owner;
	
	QoDesk.QoPreferences.NavPanel.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:15px',
		border: false,
		html: '<ul id="pref-nav-panel"> \
				<li> \
					<img src="'+Ext.BLANK_IMAGE_URL+'" class="icon-pref-appearance"/> \
					<a id="viewAppearance" href="#">Цвет и внешний вид окна</a><br /> \
					<span>Настройка окон, цвет и стиль вашего окна.</span> \
				</li> \
				<li> \
					<img src="'+Ext.BLANK_IMAGE_URL+'" class="icon-pref-wallpaper"/> \
					<a id="viewWallpapers" href="#">Фон рабочего стола</a><br /> \
					<span>Выбрать фоновый рисунок, цвет фона и шрифта.</span> \
				</li> \
			</ul>',
		id: config.id
	});
	
	this.actions = {
		'viewShortcuts' : function(owner){
			owner.viewCard('pref-win-card-6');
		},
		
		'viewAutoRun' : function(owner){
			owner.viewCard('pref-win-card-5');
		},
		
		'viewQuickstart' : function(owner){
	   		owner.viewCard('pref-win-card-2');
	   	},
	   	
	   	'viewAppearance' : function(owner){
	   		owner.viewCard('pref-win-card-3');
	   	},
	   	
	   	'viewWallpapers' : function(owner){
	   		owner.viewCard('pref-win-card-4');
	   	}
	};
};

Ext.extend(QoDesk.QoPreferences.NavPanel, Ext.Panel, {
	afterRender : function(){
		this.body.on({
			'mousedown': {
				fn: this.doAction,
				scope: this,
				delegate: 'a'
			},
			'click': {
				fn: Ext.emptyFn,
				scope: null,
				delegate: 'a',
				preventDefault: true
			}
		});
		
		QoDesk.QoPreferences.NavPanel.superclass.afterRender.call(this); // do sizing calcs last
	},
	
	doAction : function(e, t){
    	e.stopEvent();
    	this.actions[t.id](this.owner);  // pass owner for scope
    }
});



QoDesk.QoPreferences.AutoRun = function(config){
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var ms = this.app.modules,
		ids = this.app.desktop.config.launchers.autorun,
		nodes = expandNodes(ms, ids);
				
	QoDesk.QoPreferences.AutoRun.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: false,
		buttons: [{
			handler: onSave,
			scope: this,
			text: 'Сохранить'
		},{
			handler: onClose,
			scope: this,
			text: 'Закрыть'
		}],
		cls: 'pref-card pref-check-tree',
		id: config.id,
		lines: false,
		listeners: {
			'checkchange': {
				fn: onCheckChange,
				scope: this
			}
		},
		loader: new Ext.tree.TreeLoader(),
		rootVisible: false,
		root: new Ext.tree.AsyncTreeNode({
			text: 'Автозапуск',
			children: nodes
		}),
		title: 'Автозапуск'
	});
			
	function expandNodes(ms, ids){
		var nodes = [];
		
		for(var i = 0, len = ms.length; i < len; i++){
			var o = ms[i].launcher ? ms[i].launcher : ms[i];
			if(o.menu){
				/* nodes.push({
					leaf: false,
					text: o.text || o.menuText,
					children: this.expandNodes(o.menu.items, ids)
				}); */
			}else{
				nodes.push({
		           	checked: isChecked(ms[i].moduleId, ids) ? true : false,
		           	iconCls: ms[i].launcher.iconCls,
		           	id: ms[i].moduleId,
		           	leaf: true,
		           	selected: true,
		           	text: o.text || o.menuText
				});
			}
		}
		
		return nodes;
	}
	
	function isChecked(id, ids){
		for(var i = 0, len = ids.length; i < len; i++){
			if(id == ids[i]){
				return true;
			}
		}
	}

	function onCheckChange(node, checked){
		if(node.leaf && node.id){
    		if(checked){
				this.app.desktop.addAutoRun(node.id, true);
    		}else{
				this.app.desktop.removeAutoRun(node.id, true);
    		}
    	}
    	node.ownerTree.selModel.select(node);
    }
    
    function onClose(){
		this.owner.win.close();
	}
	
    function onSave(){
    	this.buttons[0].disable();
    	this.owner.save({
    		callback: function(){
    			this.buttons[0].enable();
    		}
    		, callbackScope: this
    		, task: 'save'
    		, what: 'autorun'
    		, ids: Ext.encode(this.app.desktop.config.launchers.autorun)
    	});
    }
};

Ext.extend(QoDesk.QoPreferences.AutoRun, Ext.tree.TreePanel);



QoDesk.QoPreferences.Shortcuts = function(config){
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var ms = this.app.modules,
		ids = this.app.desktop.config.launchers.shortcut,
		nodes = expandNodes(ms, ids);
	
	QoDesk.QoPreferences.Shortcuts.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: false,
		buttons: [{
			handler: onSave,
			scope: this,
			text: 'Сохранить'
		},{
			handler: onClose,
			scope: this,
			text: 'Закрыть'
		}],
		cls: 'pref-card pref-check-tree',
		id: config.id,
		lines: false,
		listeners: {
			'checkchange': {
				fn: onCheckChange,
				scope: this
			}
		},
		loader: new Ext.tree.TreeLoader(),
		rootVisible: false,
		root: new Ext.tree.AsyncTreeNode({
			text: 'Shortcuts',
			children: nodes
		}),
		title: 'Shortcuts'
	});
			
	function expandNodes(ms, ids){
		var nodes = [];
		
		for(var i = 0, len = ms.length; i < len; i++){
			var o = ms[i].launcher ? ms[i].launcher : ms[i];
			if(o.menu){
				/* nodes.push({
					leaf: false,
					text: o.text || o.menuText,
					children: this.expandNodes(o.menu.items, ids)
				}); */
			}else{
				nodes.push({
		           	checked: isChecked(ms[i].moduleId, ids) ? true : false,
		           	iconCls: ms[i].launcher.iconCls,
		           	id: ms[i].moduleId,
		           	leaf: true,
		           	selected: true,
		           	text: o.text || o.menuText
				});
			}
		}
		
		return nodes;
	}
	
	function isChecked(id, ids){
		for(var i = 0, len = ids.length; i < len; i++){
			if(id == ids[i]){
				return true;
			}
		}
	}

	function onCheckChange(node, checked){
		if(node.leaf && node.id){
    		if(checked){
				this.app.desktop.addShortcut(node.id, true);
    		}else{
				this.app.desktop.removeShortcut(node.id, true);
    		}
    	}
    	node.ownerTree.selModel.select(node);
    }
    
    function onClose(){
		this.owner.win.close();
	}
	
    function onSave(){
    	this.buttons[0].disable();
    	this.owner.save({
    		callback: function(){
    			this.buttons[0].enable();
    		}
    		, callbackScope: this
    		, task: 'save'
    		, what: 'shortcut'
    		, ids: Ext.encode(this.app.desktop.config.launchers.shortcut)
    	});
    }
};

Ext.extend(QoDesk.QoPreferences.Shortcuts, Ext.tree.TreePanel);



QoDesk.QoPreferences.QuickStart = function(config){
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var ms = this.app.modules,
		ids = this.app.desktop.config.launchers.quickstart,
		nodes = expandNodes(ms, ids);
				
    QoDesk.QoPreferences.QuickStart.superclass.constructor.call(this, {
    	autoScroll: true,
		bodyStyle: 'padding:10px',
		border: false,
		buttons: [{
			handler: onSave,
			scope: this,
			text: 'Сохранить'
		},{
			handler: onClose,
			scope: this,
			text: 'Закрыть'
		}],
		cls: 'pref-card pref-check-tree',
		id: config.id,
		lines: false,
		listeners: {
			'checkchange': {
				fn: onCheckChange,
				scope: this
			}
		},
		loader: new Ext.tree.TreeLoader(),
		rootVisible: false,
		root: new Ext.tree.AsyncTreeNode({
			text: 'Быстрый запуск',
			children: nodes
		}),
		title: 'Быстрый запуск'
    });
			
	function expandNodes(ms, ids){
		var nodes = [];
		
		for(var i = 0, len = ms.length; i < len; i++){
			var o = ms[i].launcher ? ms[i].launcher : ms[i];
			if(o.menu){
				/* nodes.push({
					leaf: false,
					text: o.text || o.menuText,
					children: this.expandNodes(o.menu.items, ids)
				}); */
			}else{
				nodes.push({
		           	checked: isChecked(ms[i].moduleId, ids) ? true : false,
		           	iconCls: ms[i].launcher.iconCls,
		           	id: ms[i].moduleId,
		           	leaf: true,
		           	selected: true,
		           	text: o.text || o.menuText
				});
			}
		}
		
		return nodes;
	}
	
	function isChecked(id, ids){
		for(var i = 0, len = ids.length; i < len; i++){
			if(id == ids[i]){
				return true;
			}
		}
	}
	
	function onCheckChange(node, checked){
		if(node.leaf && node.id){
    		if(checked){
				this.app.desktop.addQuickStartButton(node.id, true);
    		}else{
				this.app.desktop.removeQuickStartButton(node.id, true);
    		}
    	}
    	node.ownerTree.selModel.select(node);
    }
    
    function onClose(){
		this.owner.win.close();
	}
	
    function onSave(){
    	this.buttons[0].disable();
    	this.owner.save({
    		callback: function(){
    			this.buttons[0].enable();
    		}
    		, callbackScope: this
    		, task: 'save'
    		, what: 'quickstart'
    		, ids: Ext.encode(this.app.desktop.config.launchers.quickstart)
    	});
    }
};

Ext.extend(QoDesk.QoPreferences.QuickStart, Ext.tree.TreePanel);



QoDesk.QoPreferences.Appearance = function(config){
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var desktop = this.app.getDesktop();
	
	var store = new Ext.data.JsonStore({
		baseParams: {
			moduleId: this.owner.moduleId,
			fileName: 'Preferences.php',
			task: 'load',
			what: 'themes'
		},
		fields: ['id', 'name', 'pathtothumbnail', 'pathtofile'],
		id: 'id',
		root: 'images',
		url: this.app.connection
	});
	
	this.store = store;
	
	store.on('load', function(store, records){
		if(records){
			defaults.setTitle('Доступные темы (' + records.length + ')');
			
			var id = this.app.desktop.config.styles.theme.id;
			if(id){
				view.select('theme-'+id);
			}
		}				
	}, this);
	
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
			'<div class="pref-view-thumb-wrap" id="theme-{id}">',
				'<div class="pref-view-thumb"><img src="{pathtothumbnail}" title="{name}" /></div>',
			'<span>{shortName}</span></div>',
		'</tpl>',
		'<div class="x-clear"></div>'
	);

	var view = new Ext.DataView({
		autoHeight:true,
		cls: 'pref-thumnail-view',
		emptyText: 'Без темы',
		itemSelector:'div.pref-view-thumb-wrap',
		loadingText: 'Загрузка...',
		singleSelect: true,
		overClass:'x-view-over',
		prepareData: function(data){
			data.shortName = Ext.util.Format.ellipsis(data.name, 17);
			return data;
		},
		store: store,
		tpl: tpl
	});
	view.on('selectionchange', onSelectionChange, this);
	
	var defaults = new Ext.Panel({
		animCollapse: false,
		baseCls:'collapse-group',
		border: false,
		cls: 'pref-thumbnail-viewer',
		collapsible: true,
		hideCollapseTool: true,
		id: 'pref-theme-view',
		items: view,
		title: 'Тема по умолчанию',
		titleCollapse: true
	});
	
	var themes = new Ext.Panel({
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: true,
		cls: 'pref-card-subpanel',
		id: 'themes',
		items: defaults,
		margins: '10 15 0 15',
		region: 'center'
	});
	
	var checkBox = new Ext.form.Checkbox({
		checked: this.app.desktop.config.styles.transparency ? true : false,
		x: 150,
		y: 15
	});
	checkBox.on('check', toggleTransparency, this);
	
	var formPanel = new Ext.FormPanel({
		border: false,
		height: 70,
		items: [
			{x: 15, y: 15, xtype: 'label', text: 'Прозрачность'},
			checkBox
		],
		layout: 'absolute',
		split: false,
		region: 'south'
	});
	
	QoDesk.QoPreferences.Appearance.superclass.constructor.call(this, {
		border: false,
		buttons: [{
			handler: onSave,
			scope: this,
			text: 'Сохранить'
			},{
			handler: onClose,
			scope: this,
			text: 'Закрыть'
		}],
		cls: 'pref-card',
		id: config.id,
		items: [
			themes,
			formPanel
		],
		layout: 'border',
		title: 'Цвет окна и внешний вид'
	});
	
	function onClose(){
		this.owner.win.close();
	}
	
	function onSave(){
		var c = this.app.desktop.config.styles;
		
		this.buttons[0].disable();
    	this.owner.save({
    		callback: function(){
    			this.buttons[0].enable();
    		}
    		, callbackScope: this
    		, task: 'save'
    		, what: 'appearance'
    		, backgroundcolor: c.backgroundcolor
    		, fontcolor: c.fontcolor
    		, theme: c.theme.id
    		, transparency: c.transparency
    		, wallpaper: c.wallpaper.id
    		, wallpaperposition: c.wallpaperposition
    	});
	}
	
	function onSelectionChange(view, sel){
		if(sel.length > 0){
			var cId = this.app.desktop.config.styles.theme.id,
				r = view.getRecord(sel[0]),
				d = r.data;
			
			if(parseInt(cId) !== parseInt(r.id)){
				if(r && r.id && d.name && d.pathtofile){
					desktop.setTheme({
						id: r.id,
						name: d.name,
						pathtofile: d.pathtofile
					});
				}
			}
		}
	}
	
	function toggleTransparency(field, checked){
		desktop.setTransparency(checked);
	}
};

Ext.extend(QoDesk.QoPreferences.Appearance, Ext.Panel, {
	afterRender : function(){
		QoDesk.QoPreferences.Appearance.superclass.afterRender.call(this);
		
		this.on('show', this.loadStore, this, {single: true});
	},
	
	loadStore : function(){
		this.store.load();
	}
});



QoDesk.QoPreferences.Background = function(config){
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var desktop = this.app.getDesktop();
	
	var store = new Ext.data.JsonStore({
		baseParams: {
			moduleId: this.owner.moduleId,
			fileName: 'Preferences.php',
			task: 'load',
			what: 'wallpapers'
		},
		fields: ['id', 'name', 'pathtothumbnail', 'pathtofile'],
		id: 'id',
		root: 'images',
		url: this.app.connection
	});
	
	this.store = store;
	
	store.on('load', function(store, records){
		if(records){
			defaults.setTitle('Обои по умолчанию (' + records.length + ')');
			
			var id = this.app.desktop.config.styles.wallpaper.id;
			if(id){
				view.select('wallpaper-'+id);
			}
		}				
	}, this);

	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
			'<div class="pref-view-thumb-wrap" id="wallpaper-{id}">',
				'<div class="pref-view-thumb"><img src="{pathtothumbnail}" title="{name}" /></div>',
			'<span>{shortName}</span></div>',
		'</tpl>',
		'<div class="x-clear"></div>'
	);

	var view = new Ext.DataView({
		autoHeight:true,
		cls: 'pref-thumnail-view',
		emptyText: 'No wallpapers to display',
		itemSelector:'div.pref-view-thumb-wrap',
		loadingText: 'Загрузка...',
		singleSelect: true,
		overClass:'x-view-over',
		prepareData: function(data){
			data.shortName = Ext.util.Format.ellipsis(data.name, 17);
			return data;
		},
		store: store,
		tpl: tpl
	});
	view.on('selectionchange', onSelectionChange, this);
	
	var defaults = new Ext.Panel({
		animCollapse: false,
		baseCls:'collapse-group',
		border: false,
		cls: 'pref-thumbnail-viewer',
		collapsible: true,
		hideCollapseTool: true,
		id: 'pref-wallpaper-view',
		items: view,
		title: 'Обои по умолчанию',
		titleCollapse: true
	});
	
	var wallpapers = new Ext.Panel({
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: true,
		cls: 'pref-card-subpanel',
		id: 'wallpapers',
		items: defaults,
		margins: '10 15 0 15',
		region: 'center'
	});
	
	var wpp = this.app.desktop.config.styles.wallpaperposition;
	var tileRadio = createRadio('tile', wpp == 'tile' ? true : false, 90, 40);
	var centerRadio = createRadio('center', wpp == 'center' ? true : false, 200, 40);
	
	var position = new Ext.FormPanel({
		border: false,
		height: 140,
		id: 'position',
		items: [{
				border: false,
				items: {border: false, html:'Как расположить картинку?'},
				x: 15,
				y: 15
			},{
				border: false,
				items: {border: false, html: '<img class="bg-pos-tile" src="'+Ext.BLANK_IMAGE_URL+'" width="64" height="44" border="0" alt="" />'},
				x: 15,
				y: 40
			},
				tileRadio,
			{
				border: false,
				items: {border: false, html: '<img class="bg-pos-center" src="'+Ext.BLANK_IMAGE_URL+'" width="64" height="44" border="0" alt="" />'},
				x: 125,
				y: 40
			},
				centerRadio,
			{
				border: false,
				items: {border: false, html:'Выберите цвет фона'},
				x: 245,
				y: 15
			},{
				border: false,
				items: new Ext.ColorPalette({
					listeners: {
						'select': {
							fn: onColorSelect
							, scope: this
						}
					}
				}),
				/* items: new Ext.Button({
					handler: onChangeBgColor,
					scope: this,
					text: 'Background color'
				}), */
				x: 245,
				y: 40
			},{
				border: false,
				items: {border: false, html:'Выберите цвет текста'},
				x: 425,
				y: 15
			},{
				border: false,
				items: new Ext.ColorPalette({
					listeners: {
						'select': {
							fn: onFontColorSelect
							, scope: this
						}
					}
				}),
				x: 425,
				y: 40
				
		}],
		layout: 'absolute',
		region: 'south',
		split: false
	});

	QoDesk.QoPreferences.Background.superclass.constructor.call(this, {
		border: false,
		buttons: [{
			handler: onSave,
			scope: this,
			text: 'Сохранить'
			},{
			handler: onClose,
			scope: this,
			text: 'Закрыть'
		}],
		cls: 'pref-card',
		id: config.id,
		items: [
			wallpapers,
			position
		],
		layout: 'border',
		title: 'Цвет рабочего стола'
	});
	
	function createRadio(value, checked, x, y){
		if(value){
			radio = new Ext.form.Radio({
				name: 'position',
				inputValue: value,
				checked: checked,
				x: x,
				y: y
			});
			
			radio.on('check', togglePosition, radio);
			
			return radio;
		}
	}
    
    /* function onChangeBgColor(){
    	var dialog = Ext.getCmp('qo-color-picker');
    	
    	if(!dialog){
	    	dialog = new Ext.ux.ColorDialog({
				title: 'Background Color',
				closable: true,
				height:232,
				id: 'qo-color-picker',
				modal: false,
				shadow: true,
				width: 362,
				x: desktop.getWinX(362),
				y: desktop.getWinY(232)
			});
		}
		
		//dialog.on('pickcolor', onPickColor, this);
    	dialog.show();
    } */
    
	function onClose(){
		this.owner.win.close();
	}
	
	function onColorSelect(p, hex){
		desktop.setBackgroundColor(hex);
	}
	
	function onFontColorSelect(p, hex){
		desktop.setFontColor(hex);
	}
	
	function onSave(){
		var c = this.app.desktop.config.styles;
		
		this.buttons[0].disable();
    	this.owner.save({
    		callback: function(){
    			this.buttons[0].enable();
    		}
    		, callbackScope: this
    		, task: 'save'
    		, what: 'appearance'
    		, backgroundcolor: c.backgroundcolor
    		, fontcolor: c.fontcolor
    		, theme: c.theme.id
    		, transparency: c.transparency
    		, wallpaper: c.wallpaper.id
    		, wallpaperposition: c.wallpaperposition
    	});
	}
	
	function onSelectionChange(view, sel){
		if(sel.length > 0){
			var cId = this.app.desktop.config.styles.wallpaper.id,
				r = view.getRecord(sel[0]),
				d = r.data;
			
			if(parseInt(cId) !== parseInt(r.id)){
				if(r && r.id && d.name && d.pathtofile){
					desktop.setWallpaper({
						id: r.id,
						name: d.name,
						pathtofile: d.pathtofile
					});
				}
			}
		}
	}
	
	function togglePosition(field, checked){
		if(checked === true){
			desktop.setWallpaperPosition(field.inputValue);
		}
	}
};

Ext.extend(QoDesk.QoPreferences.Background, Ext.Panel, {
	afterRender : function(){
		QoDesk.QoPreferences.Background.superclass.afterRender.call(this);
		
		this.on('show', this.loadStore, this, {single: true});
	},
	
	loadStore : function(){
		this.store.load();
	}
});



/* 
 * Will ensure that the checkchange event is fired on 
 * node double click
 */
Ext.override(Ext.tree.TreeNodeUI, {
	toggleCheck : function(value){		
        var cb = this.checkbox;
        if(cb){
            cb.checked = (value === undefined ? !cb.checked : value);
            this.fireEvent('checkchange', this.node, cb.checked);
        }
    }
});

//таблица отчетов
QoDesk.GridWindow = Ext.extend(Ext.app.Module, {
	
	moduleType : 'demo',
    moduleId : 'demo-grid',
    
    init : function(){
        this.launcher = {
            handler : this.createWindow,
            iconCls: 'icon-grid',
            scope: this,
            shortcutIconCls: 'demo-grid-shortcut',
            text: 'Отчеты',
            tooltip: '<b>Grid Window</b><br />Отчеты по маршрутам'
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('grid-win');
        if(!win){        	
        	var sm = new Ext.grid.RowSelectionModel({singleSelect:true});
        	
        	var grid = new Ext.grid.GridPanel({
				//autoExpandColumn:'company',
				border:false,
				ds: new Ext.data.Store({
					reader: new Ext.data.ArrayReader({}, [
						{name: 'company'},
						{name: 'price', type: 'float'},
						{name: 'change', type: 'float'},
						{name: 'pctChange', type: 'float'}
					]),
					data: Ext.grid.dummyData
				}),
				cm: new Ext.grid.ColumnModel([
					new Ext.grid.RowNumberer(),
					{header: "Company", width: 120, sortable: true, dataIndex: 'company'},
					{header: "Price", width: 70, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'},
					{header: "Change", width: 70, sortable: true, dataIndex: 'change'},
					{header: "% Change", width: 70, sortable: true, dataIndex: 'pctChange'}
				]),
				shadow: false,
				shadowOffset: 0,
				sm: sm,
				tbar: [{
					text:'Add Something',
					tooltip:'Add a new row',
					iconCls:'demo-grid-add'
					}, '-', {
					text:'Options',
					tooltip:'Your options',
					iconCls:'demo-grid-option'
					},'-',{
					text:'Remove Something',
					tooltip:'Remove the selected item',
					iconCls:'demo-grid-remove'
				}],
				viewConfig: {
					forceFit:true
				}
			});
			
			// example of how to open another module on rowselect
			sm.on('rowselect',function(){
				var tabWin = this.app.getModule('demo-tabs');
				if(tabWin){
					tabWin.launcher.handler.call(this.scope || this);
				}
				
			}, this);
			
            win = desktop.createWindow({
                id: 'grid-win',
                title:'Grid Window',
                width:740,
                height:480,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
				layout: 'fit',
                items: grid,
                taskbuttonTooltip: '<b>Grid Window</b><br />A window with a grid'
            });
            
            // begin: modify top toolbar
	        var tb = grid.getTopToolbar();
				
			// example of getting a reference to another module's launcher object
	        var tabWin = this.app.getModule('demo-tabs');
	        
			if(tabWin){
				var c = tabWin.launcher;
				tb.add({
					// example button to open another module
					text: 'Open Tab Window',
					handler: c.handler,
					scope: c.scope,
					iconCls: c.iconCls
				});
			}
				
			tb.add({
				text: 'Toggle My Taskbutton Text/Icon',
				handler: this.updateTaskButton,
				scope: this
			});
	        // end: modify top toolbar
	        
	        // could modify this windows taskbutton tooltip here (defaults to win.title)
	        //win.taskButton.setTooltip('Grid Window');
        }
        
        win.show();
    },
    
    updateTaskButton : function(){
    	var desktop = this.app.getDesktop(),
    		win = desktop.getWindow('grid-win'),
    		btn = win.taskButton;
    	
    	if(btn.getText() === 'Toggled'){
    		btn.setText('Grid Window');
    		// can pass in an object
    		btn.setTooltip({title: 'Grid Window', text: 'A window with a grid'});
    		// or could pass in a string
    		//btn.setTooltip('Grid Window');
    		btn.setIconClass('icon-grid');
    	}else{
    		btn.setText('Toggled');
    		btn.setTooltip({title: 'Toggled', text: 'You have toogled me'});
    		btn.setIconClass('bogus');
    	}
    }
});

// Array data for the grid
Ext.grid.dummyData = [
    ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
    ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
    ['American Express Company',52.55,0.01,0.02,'9/1 12:00am'],
    ['American International Group, Inc.',64.13,0.31,0.49,'9/1 12:00am'],
    ['AT&T Inc.',31.61,-0.48,-1.54,'9/1 12:00am'],
    ['Caterpillar Inc.',67.27,0.92,1.39,'9/1 12:00am'],
    ['Citigroup, Inc.',49.37,0.02,0.04,'9/1 12:00am'],
    ['Exxon Mobil Corp',68.1,-0.43,-0.64,'9/1 12:00am'],
    ['General Electric Company',34.14,-0.08,-0.23,'9/1 12:00am'],
    ['General Motors Corporation',30.27,1.09,3.74,'9/1 12:00am'],
    ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
    ['Honeywell Intl Inc',38.77,0.05,0.13,'9/1 12:00am'],
    ['Intel Corporation',19.88,0.31,1.58,'9/1 12:00am'],
    ['Johnson & Johnson',64.72,0.06,0.09,'9/1 12:00am'],
    ['Merck & Co., Inc.',40.96,0.41,1.01,'9/1 12:00am'],
    ['Microsoft Corporation',25.84,0.14,0.54,'9/1 12:00am'],
    ['The Coca-Cola Company',45.07,0.26,0.58,'9/1 12:00am'],
    ['The Procter & Gamble Company',61.91,0.01,0.02,'9/1 12:00am'],
    ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am'],
    ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81,'9/1 12:00am']
];
Ext.ux.TabCloseMenu = function(){
    var tabs, menu, ctxItem;
    this.init = function(tp){
        tabs = tp;
        tabs.on('contextmenu', onContextMenu);
    }

    function onContextMenu(ts, item, e){
        if(!menu){ // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: tabs.id + '-close',
                text: 'Закр. вкладку',
                handler : function(){
                    tabs.remove(ctxItem);
                }
            },{
                id: tabs.id + '-close-others',
                text: 'Закр. остальные вкладки',
                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());
    }
};

  
QoDesk.TabWindow = Ext.extend(Ext.app.Module, {
	
	moduleType : 'demo',
    moduleId : 'demo-tabs',
    open: false,
    TP:{},
    
    init : function(){
        this.launcher = {
            handler : this.createWindow,
            iconCls:'tabs',
            scope: this,
            shortcutIconCls: 'demo-tab-shortcut',
            text: 'Маршруты',
            tooltip: '<b>Tab Window</b><br />A window with tabs'
        }
    },
    addTab : function (map,Carid){
            var dateMenu = new Ext.menu.DateMenu({
                handler : function(dp, date){
                      actiondate.setText('Просмотр за: '+date.format('d.m.Y'));
                      AllCarLines.CurrentDatef(Carid,date.format('m/d/Y'));
                      
                }
            });    
            var colorMenu = new Ext.menu.ColorMenu({
                handler : function(cm, color){
                   AllCarLines.SetColor(Carid,color);
                }
            });
            var actiondate = new Ext.Action({
              //  iconCls: 'calendar',
                text: 'Просмотр за: '+(new Date()).format('d.m.Y'),
                menu: dateMenu
            }); 
            var actioncolor = new Ext.Action({
                text: 'Цвет маршрута',
                menu: colorMenu
            });     
            var actiond = new Ext.Action({
                text: 'за день',
                handler: function(){
                  //  AllCarLines.CarLines[Carid].PlotTime.Plot.clearSelection();
                }
             //   ,iconCls: 'blist'
            });    
            var actioni = new Ext.Action({
                text: 'за интервал',
                handler: function(){
                    var tabs= Ext.getCmp('tabpan-win');
                    var tab=tabs.getActiveTab();
                    var c =tab.Carid;
                    
                }
             //   ,iconCls: 'blist'
            });
            var actiont = new Ext.Action({
                text: 'История ',
                handler: function(item,a){
                    alert(item.text);
                }
             //   ,iconCls: 'blist'
            });
            var actionUpdate = new Ext.Action({
                text: 'Обновить',
                handler: function(item,a){
                   AllCarLines.Draw(Carid);
                   treckbardraw(Carid);
                   AllCarLines.LoadDrawSpeed(Carid);
                }
           //    , iconCls: 'blist'
            });            
            var actionc = new Ext.Action({
                text: 'Цвет',
                menu: colorMenu
            });
            var tbspeedgr = new Ext.Action({
                text: 'Анализировать',
                handler: function(item,a){
                   AllCarLines.LoadDrawSpeed(Carid);
                   
                }
           //    , iconCls: 'blist'
            });
            var btLoadTreack = new Ext.Action({
                text: 'Загрузить трек',
                handler: function(item,a){
                   AllCarLines.CarLines[Carid].OnLoadtreack();
                }
           //    , iconCls: 'blist'
            });
            var btDelTreack = new Ext.Action({
                text: 'Удалить трек',
                handler: function(item,a){
                   AllCarLines.CarLines[Carid].Removetreack();
                }
           //    , iconCls: 'blist'
            });
        var commonChartStyle = {"margin": "17px 17px 17px 17px;"};

        this.TP.add({
            map: map,
            Carid:Carid,
            title: 'Карта:'+map+' авто:'+Carid,
            iconCls: 'tabs',
            tbar: [
                actiondate,'-',           
                {                  
                    text: 'Запрос данных',
                    menu: [ actiond, actioni ]
                },'-',
                actiont,actionUpdate
            ],
            html: '<div id="div'+Carid+'"></div>',
            closable:true
        }).show();
        
        var costContainer = new Ext.Panel({
            height: 50,
            margins:'7 7 7 7',
         //   cmargins:'7 7 7 7',
            id: 'placeholder'+Carid
        });
      //  var costContainerBar = new Ext.Panel({
      //      height: 50,
      //      id: 'placeholderBar'+Carid
      //  });        
        var costContainer2 = new Ext.Panel({
            height: 80,
            margins:'7 7 7 7',
          //  cmargins:'7 7 7 7',
            id: 'placeSpeed'+Carid
        });
       var p = new Ext.Panel({
            renderTo: 'div'+Carid,
        //    collapsible:true,
            bodyStyle: 'border: 0px',
           items: [
                {
                    bodyStyle: 'border: 0px',
                    items: [{            
                  //          style: commonChartStyle,
                            bodyStyle: 'border: 0px',  
                            margins:'17 17 17 17',                  
                            html: 'Индикация загруженных данных (выделите и загрузите):'
                        },{
                            bodyStyle: 'border: 0px',   
                  //          style: {"margin": "7px 7px 7px 7px;","font-size": "10px;", "font-variant": "normal;"},    
                            items: [costContainer]//,costContainerBar
                        },{
                            tbar: [tbspeedgr,btLoadTreack,btDelTreack,'->','-',
                                   {text: 'Настройки', menu: [ actioncolor ]}   ]
                        },{
                            bodyStyle: 'border: 0px',   
                  //          style: {"margin": "7px 7px 7px 7px;","font-size": "10px;", "font-variant": "normal;"},    
                            items: [costContainer2]
                        }
                    ]
                }
            ]
        });


    },
    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('tab-win');
        this.open=true;
        if(!win){
            this.TP = new Ext.TabPanel({
                        id: 'tabpan-win',
                        activeTab:0,
                        resizeTabs:true, // turn on tab resizing
                        minTabWidth: 135,
                        tabWidth:135,
                        shim:false,
                        animCollapse:false,
                        constrainHeader:true,                        
                        enableTabScroll:true,
                        defaults: {autoScroll:true},
                        margins:'3 3 3 3', 
                        plugins: new Ext.ux.TabCloseMenu()
            });
            this.TP.on('resize', function(tabs, w, h) {
                var tab=tabs.getActiveTab();
              //  if (tab!=null) if  (AllCarLines.CarLines[tab.Carid]!=null) AllCarLines.Draw(tab.Carid);
            }); 
            this.TP.on('tabchange', function(tabs,tab) {
//                if (tab!=null) 
//                    if  (AllCarLines.CarLines[tab.Carid]!=null)
//                        if (this.open) 
//                        AllCarLines.Draw(tab.Carid);
//                        else  setTimeout(function(){AllCarLines.Add(tab.Carid);}, 500);
            }); 

            win = desktop.createWindow({
                id: 'tab-win',
                title:'Окно маршрутов',
                width:740,
                height:350,
                iconCls: 'tabs',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                layout: 'fit',
                items:  this.TP,
                taskbuttonTooltip: '<b>Tab Window</b><br />A window with tabs'
            });
            win.on('close', function(h) {
                 this.open=false;
            });
        }
        win.show();
    }
});
         function save(tree,n,e){

//                 croot.expand(true) 
//                 var ch = getChildren(croot);
// 
//           Ext.get('main').mask('Sending data to server...', 'x-mask-loading');
// 
//                 new Ajax.Request('GetPoint.aspx',
//                 {method:'post', parameters:'data='+encodeURIComponent(Ext.encode(ch)), onSuccess:refresh, onFailure:refresh});
// 
         }
             function refresh(){
//                 Ext.get('main').unmask();
//                 croot.reload();
//                 croot.expand(true);
             }

QoDesk.AccordionWindow = Ext.extend(Ext.app.Module, {
    
	moduleType : 'demo',
	moduleId : 'demo-acc',

	init : function(){
		this.launcher = {
            handler : this.createWindow,
            iconCls:'accordion',
            scope: this,
            shortcutIconCls: 'demo-acc-shortcut',
            text: 'Объекты',
            tooltip: '<b>Accordion Window</b><br />A window with an accordion layout'
		}
	},

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('acc-win');
        if(!win){
                         var CarUserTree=new Ext.tree.AsyncTreeNode(CarUserList);
                        var CarUserTree2=new Ext.tree.AsyncTreeNode(CarUserList);
                        var Treepanel = new Ext.tree.TreePanel({
                        id:'im-tree',
                        title: 'Наблюдение в РВ',
                        loader: new Ext.tree.TreeLoader(),
                        rootVisible:false,
                        lines:false,
                        autoScroll:true,
                        enableDD:true,
                        useArrows: true,
                        tools:[{
                            id:'refresh',
                            on:{
                                click: function(){
                                    var tree = Ext.getCmp('im-tree');
                                    tree.body.mask('Loading', 'x-mask-loading');
                                    tree.root.reload();
                                    tree.root.collapse(true, false);
                                    setTimeout(function(){ // mimic a server call
                                        tree.body.unmask();
                                        tree.root.expand(true, true);
                                    }, 100);
                                }
                            }
                        }],
                        root: CarUserTree
                    });
                    onOpenAnket = function(Carid,mapid,tabWinAn){
    		            tabWinAn.launcher.handler.call(tabWinAn,Carid,mapid); 
                    };
                   
                    Treepanel.on("contextmenu", function(node,e) {
                            var mapid=node.attributes.id.substring(2,3);
                            var carid=node.attributes.id.substring(4);
                            var tabWinAn =  this.app.getModule('demo-Anketa');
                            var tabWinAnNew =  this.app.getModule('demo-AnketaNew');
                            var iframe =  this.app.getModule('demo-ViewAnket');
                         if (node.attributes.cls=='file'){   
                            var  contextMenu = new Ext.menu.Menu([{
                 
                                text: 'Редактировать',
                                handler : function(){
                                     onOpenAnket(carid,mapid,tabWinAn);
                                }
                            },{
                                text: 'Добавить',
                                handler : function(){
                                    onOpenAnket(carid,mapid,tabWinAnNew);
                                }
                            },{
                                text: 'Просмотр',
                                handler : function(){
                                    onOpenAnket(carid,mapid,iframe);
                                }
                            }]);
                            contextMenu.showAt(e.xy);
                         }
                         if (node.attributes.cls=='maps'){   
                            var  contextMenu = new Ext.menu.Menu([{
                                text: 'Добавить',
                                handler : function(){
                                    onOpenAnket(carid,mapid,tabWinAnNew);
                                }
                            }]);
                            contextMenu.showAt(e.xy);
                         }                         
                    },this); 
                    Treepanel.on('click',function(n){
                    //	$("#main").trigger('click');
    	                if (n.attributes.cls=='file'){
    	                        var mapid=n.id.substring(2,3);
    	                        var carid=n.id.substring(4);
    	                        
    	                        if (!CarMaps.OnOpenMap(mapid)){
    	                            var owner = this.app.getModule('demo-bogus');
    	                            owner.openDetail(mapid);
    	                        }    
                                CarMaps.SelectCar(mapid,carid);
                        }
			        },this);
			        Treepanel.on('enddrag', save);

                    var TreeCarTrack = new Ext.tree.TreePanel({
                        id:'CarTrack-tree',
                        title: 'Маршруты',
                        loader: new Ext.tree.TreeLoader(),
                        rootVisible:false,
                        lines:false,
                        autoScroll:true,
                        enableDD:true,
                        useArrows: true,
                        
                        tools:[{
                            id:'refresh',
                            on:{
                                click: function(){
                                    var tree = Ext.getCmp('CarTrack-tree');
                                    tree.body.mask('Loading', 'x-mask-loading');
                                    tree.root.reload();
                                    tree.root.collapse(true, false);
                                    setTimeout(function(){ // mimic a server call
                                        tree.body.unmask();
                                        tree.root.expand(true, true);
                                    }, 100);
                                }
                            }
                        }],
                        root: CarUserTree2
                    });
                    TreeCarTrack.on("contextmenu", function(node,e) {
                            var mapid=node.attributes.id.substring(2,3);
                            var carid=node.attributes.id.substring(4);
                            var tabWinAn =  this.app.getModule('demo-Anketa');
                            var tabWinAnNew =  this.app.getModule('demo-AnketaNew');
                            var iframe =  this.app.getModule('demo-ViewAnket');
                        if (node.attributes.cls=='file'){
                            var  contextMenu = new Ext.menu.Menu([{
                 
                                text: 'Редактировать',
                                handler : function(){
                                     onOpenAnket(carid,mapid,tabWinAn);
                                }
                            },{
                                text: 'Добавить',
                                handler : function(){
                                    onOpenView(carid,mapid,tabWinAnNew);
                                }
                            },{
                                text: 'Просмотр',
                                handler : function(){
                                    onOpenView(carid,mapid,iframe);
                                }
                            }]);
                            contextMenu.showAt(e.xy);
                        }
                        if (node.attributes.cls=='maps'){
                            var  contextMenu = new Ext.menu.Menu([{
                                text: 'Добавить',
                                handler : function(){
                                    onOpenView(carid,mapid,tabWinAnNew);
                                }
                            }]);
                            contextMenu.showAt(e.xy);
                        }                        
                    },this);       
                    TreeCarTrack.on('click',function(n){
				        var tabWin = this.app.getModule('demo-tabs');
    		            tabWin.launcher.handler.call(tabWin);  
				        if ((n.attributes.cls=='file')&&(tabWin.open)){
                            var mapid=n.id.substring(2,3);
                            var carid=n.id.substring(4);
                            var Name='Карта:'+mapid+' авто:'+n.text;
				            var title = 'Карта:'+mapid+' авто:'+carid;
				            var tab = tabWin.TP.items.find(function(i){return i.title === title;});
				            if (!CarMaps.OnOpenMap(mapid)){
    	                            var owner = this.app.getModule('demo-bogus');
    	                            owner.openDetail(mapid);
    	                        }    
 				            if(tab==null) {
                                tabWin.addTab(mapid,carid);
                                setTimeout(function(){AllCarLines.Add(mapid,carid,Name);treckbardraw(carid);}, 1000);	
                            }
                            else tabWin.TP.setActiveTab(tab);
    	                }
			        },this);

            win = desktop.createWindow({
                id: 'acc-win',
                title: 'Навигация',
                width:200,
                height:400,
                iconCls: 'accordion',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                maximizable: false,
                taskbuttonTooltip: '<b>Accordion Window</b><br />A window with an accordion layout',
                layout:'accordion',
                layoutConfig: {
                    animate:false
                },
                items: [Treepanel ,TreeCarTrack]
            });
        }
        win.show();
    }
});


QoDesk.LayoutWindow = Ext.extend(Ext.app.Module, {
	
	moduleType : 'demo',
	moduleId : 'demo-layout',
	
	init : function(){
		this.launcher = {
			handler : this.createWindow,
            iconCls:'bogus',
			scope: this,
			shortcutIconCls: 'demo-layout-shortcut',
			text: 'Помощь',
			tooltip: '<b>Layout Window</b><br />A window with a layout'
		}
	},

	createWindow : function(){
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('layout-win');
		if(!win){
			var winWidth = desktop.getWinWidth() / 1.1;
			var winHeight = desktop.getWinHeight() / 1.1;
			
			win = desktop.createWindow({
				id: 'layout-win',
				title:'Layout Window',
				width:winWidth,
				height:winHeight,
				x:desktop.getWinX(winWidth),
				y:desktop.getWinY(winHeight),
				iconCls: 'bogus',
				shim:false,
				animCollapse:false,
				constrainHeader:true,
				minimizable:true,
    			maximizable:true,

				layout: 'border',
				tbar:[{
					text: 'Button1'
				},{
					text: 'Button2'
				}],
				items:[/*{
					region:'north',
					border:false,
					elements:'body',
					height:30
				},*/{
					region:'west',
					autoScroll:true,
					collapsible:true,
					cmargins:'0 0 0 0',
					margins:'0 0 0 0',
					split:true,
					title:'Panel',
					width:parseFloat(winWidth*0.3) < 201 ? parseFloat(winWidth*0.3) : 200
				},{
					region:'center',
					border:false,
					layout:'border',
					margins:'0 0 0 0',
					items:[{
						region:'north',
						elements:'body',
						title:'Panel',
						height:winHeight*0.3,
						split:true
					},{
						autoScroll:true,
						elements:'body',
						region:'center',
						id:'mydiv',
						title:'Preview Panel',
						html: '<div id="mydiv">sadfsdds</div>'
					}]
				}/*,{
					region:'south',
					border:false,
					elements:'body',
					height:25
				}*/],
				taskbuttonTooltip: '<b>Layout Window</b><br />A window with a layout'
			});
		}
		win.show();
	//	setTimeout(function(){$("#mydiv").load("index.html");}, 1000);	
		
	}
});
//QoDesk.BogusMenu = Ext.extend(Ext.app.Module, {

//	moduleType : 'menu', // required appType for a menu module
//	moduleId : 'demo-menu', // must match id in module.xml
//	
//	menu : new Ext.menu.Menu(),

//	// id's of modules to add to this menu,  can't hard code them in directly.
//	// desktop needs to initialize them first
//	items : [
//		'demo-submenu',
//		'demo-bogus'
//	],

//	init : function(){
//		this.launcher = {
//			text: 'Bogus Menu',
//			iconCls: 'bogus',
//			handler: function(){
//				return false;
//			},
//			menu: this.menu
//		}
//	}
//});
//QoDesk.BogusSubMenu = Ext.extend(Ext.app.Module, {

//	moduleType : 'menu', // required appType for a menu module
//	moduleId : 'demo-submenu', // must match id in module.xml
//	
//	menu : new Ext.menu.Menu(),

//	// Id's of modules to add to this menu,  can't hard code them in directly.
//	// Desktop needs to initialize them first.
//	items : [
//		'demo-bogus'
//	],
//	init : function(){
//		this.launcher = {
//			text: 'Bogus Sub-menu',
//			iconCls: 'bogus',
//			handler: function(){
//				return false;
//			},
//			menu: this.menu
//		}
//	}
//});
QoDesk.BogusModule = Ext.extend(Ext.app.Module, {

	moduleType : 'demo',
	moduleId : 'demo-bogus',
	
	detailModule : null,
	
	init : function(){		
		this.launcher = {
			handler: this.createWindow,
			iconCls: 'bogus',
			scope: this,
			shortcutIconCls: 'demo-bogus-shortcut',
			text: 'Карты',
			tooltip: '<b>Карты</b><br />Список карт'
		}
		
		this.detailModule = new QoDesk.BogusDetailModule();
	},

	createWindow : function(){
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('bogus-win');

		if(!win){
            win = desktop.createWindow({
                autoScroll: true,
                id: 'bogus-win',
                title: 'Карты',
                width:640,
                height:480,
                iconCls: 'bogus',
                iconCls: 'bogus',
                items: new QoDesk.BogusModule.NavPanel({owner: this, id: 'nav-panel'}),
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                maximizable: false,
                tbar: [{
                	handler: this.showDialog,
                	scope: this,
                	text: 'Настройки'
                }],
                taskbuttonTooltip: '<b>Настройки</b><br />Настройки карт'
            });
        }
        
        win.show();
    },
    
    openDetail : function(id){
		this.detailModule.createWindow(this.app, id);
    },
    
    showDialog : function(){
    	if(!this.dialog){
            this.dialog = new Ext.Window({
            	bodyStyle:'padding:10px',
                layout:'fit',
                width:500,
                height:300,
                closeAction:'hide',
                plain: true,
                html: 'В разработке',
                buttons: [{
                    text:'Submit',
                    disabled:true
                },{
                    text: 'Close',
                    handler: function(){
                        this.dialog.hide();
                    },
                    scope: this
                }],
                modal: true
            });
        }
        this.dialog.show();
    }
});



QoDesk.BogusModule.NavPanel = function(config){
	this.owner = config.owner;
	
	QoDesk.BogusModule.NavPanel.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:15px',
		border: false,
		html: '<ul id="bogus-nav-panel"> \
				<li> \
					<a id="openDetailOne" href="#">Отрыть карту 1</a><br /> \
					<span>Данные по 1й группе</span> \
				</li> \
				<li> \
					<a id="openDetailTwo" href="#">Отрыть карту 2</a><br /> \
					<span>Данные по 2й группе</span> \
				</li> \
				<li> \
					<a id="openDetailThree" href="#">Отрыть карту 3</a><br /> \
					<span>Данные по 3й группе</span> \
				</li> \
			</ul>',
		id: config.id
	});
	
	this.actions = {
		'openDetailOne' : function(owner){
			owner.openDetail(1);
		},
		
		'openDetailTwo' : function(owner){
			owner.openDetail(2);
		},
		
		'openDetailThree' : function(owner){
	   		owner.openDetail(3);
	   	}
	};
};

Ext.extend(QoDesk.BogusModule.NavPanel, Ext.Panel, {
	afterRender : function(){
		this.body.on({
			'mousedown': {
				fn: this.doAction,
				scope: this,
				delegate: 'a'
			},
			'click': {
				fn: Ext.emptyFn,
				scope: null,
				delegate: 'a',
				preventDefault: true
			}
		});
		
		QoDesk.BogusModule.NavPanel.superclass.afterRender.call(this); // do sizing calcs last
	},
	
	doAction : function(e, t){
    	e.stopEvent();
    	this.actions[t.id](this.owner);  // pass owner for scope
    }
});

QoDesk.BogusDetailModule = Ext.extend(Ext.app.Module, {

	moduleType : 'demo',
	moduleId : 'demo-bogus-detail',
	
	init : function(){
		this.launcher = {
			handler: this.createWindow,
			iconCls: 'bogus',
			scope: this,
			shortcutIconCls: 'demo-bogus-shortcut',
			text: 'Bogus Detail Window',
			tooltip: '<b>Bogus Detail Window</b><br />A bogus detail window'
		}
	},

	createWindow : function(app, id){
		this.moduleId = 'demo-bogus-detail-'+id;
		
		var desktop = app.getDesktop();
		var win = desktop.getWindow('bogus-detail'+id);
        if(!win){
            win = desktop.createWindow({
                id: 'bogus-detail'+id,
                title: 'Карта '+id,
                width: 540,
                height: 380,
                html : '<body><div  id="map_canvas'+id+'" style="BACKGROUND-COLOR: yellow; width: 100%; height: 100%">Карта не доступна</div></body>',
                iconCls: 'bogus',
                shim:false,
                animCollapse:false,
                constrainHeader:true
            });
        }
        win.show();
        if (GBrowserIsCompatible()) {
          CarMaps.InitMap(document.getElementById('map_canvas'+id),id,win.width,win.height);
       }

        win.on('resize', function(win, w, h) {
                  var mapdiv = CarMaps.Maps[id].Map.getContainer();
                  mapdiv.style.width = w + "px";
                  mapdiv.style.height= h + "px";
                  CarMaps.Maps[id].Map.checkResize();
        });
        win.on('close', function(h) {
            CarMaps.Maps[id]=null;
            var ok=0;
            for (var i=0; i<CarMaps.Maps.length; i++) if (CarMaps.Maps[i]!=null) ok=1;
            if (ok==0) CarCurrent.Stop();
        });
    }
});



QoDesk.AnketaWindow = Ext.extend(Ext.app.Module, {
	
	moduleType : 'demo',
	moduleId : 'demo-Anketa',
	
	init : function(){
		this.launcher = {
			handler : this.createWindow,
            iconCls:'bogus',
			scope: this,
			shortcutIconCls: 'demo-layout-shortcut',
			text: 'Анкета',
			tooltip: '<b>Layout Window</b><br />A window with a layout'
		}
	},

	createWindow : function(Carid,mapid){
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('layout-Anketa');
		if(!win){

	var desktop = this.app.getDesktop();
    var tab2  = new Ext.FormPanel({
        url:'FormAnketa', 
      //  labelAlign: 'top',
        frame:true,
        labelWidth: 65,
        defaults: {width: 100},        
      //  title: 'Multi Column, Nested Layouts and Anchoring',
        bodyStyle:'padding:3px 3px 0',
        items: [{
                    xtype:'textfield',
                    fieldLabel: 'Ник',
                    name: 'Nik',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'Имя',
                    name: 'first',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'Фамилия',
                    name: 'last',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'Номер ТС',
                    name: 'NCar',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'IMEI',
                    name: 'IMEI',
                    anchor:'100%'
                  //  ,disabled: true
                },{
                  //  xtype:'textarea',
                    xtype:'htmleditor',
                    name: 'bio',
                    fieldLabel:'Заметки',
                    height:150,
                    anchor:'100%'
                }]
    });
         tab2.load({
         url:'FormAnketa',
         params:{cmd:'load',Maps:mapid,CarId:Carid, uid:uidkey}
         });
         // any additional load click processing here
  
			win = desktop.createWindow({
			    id: 'layout-Anketa',
                title: 'Редактирование карточки',
                width: 620,
                height:370,
                resizable: false,
                layout: 'fit',
                plain:true,
                items: [tab2],
				minimizable:true,
    			maximizable:false,

        buttons:[{
                text:'Обновить',
                handler: function(){
                     tab2.load({
                     url:'FormAnketa',
                     waitMsg:'Загрузка...',
                     params:{cmd:'load',Maps:mapid,CarId:Carid, uid:uidkey}
                     });                    
                }
             },{ 
                text:'Сохранить',
              //  formBind: true,	 
                // Function that fires when user clicks the button 
                handler:function(){ 
                    tab2.getForm().submit({ 
                        method:'POST',
                        params:{cmd:'save',Maps:mapid,CarId:Carid, uid:uidkey}, 
                        waitTitle:'Соединение', 
                        waitMsg:'Отправка данных...',
                        success:function(form, action){ 
	    	                obj = Ext.util.JSON.decode(action.response.responseText); 
    	                    var notifyWin = desktop.showNotification({
			                    html: obj.info.text,
			                    title: 'Информация'
		                    });
		                    desktop.hideNotification(notifyWin);
                            win.close();
                            CarCurrent.Update();
                        },

                        failure:function(form, action){ 
                            if(action.failureType == 'server'){ 
                                obj = Ext.util.JSON.decode(action.response.responseText); 
    	                        var notifyWin = desktop.showNotification({
			                        html: obj.errors.reason,
			                        title: 'Ошибка!'
		                        });                                
                            }else{ 
                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText ); 
                            } 
                            tab2.getForm().reset(); 
                        } 
                    }); 
                } 
            }] 

    			
            });
		}
		win.show();
	//	setTimeout(function(){$("#mydiv").load("index.html");}, 1000);	
		
	}
});


QoDesk.AnketaWindowNew = Ext.extend(Ext.app.Module, {
	
	moduleType : 'demo',
	moduleId : 'demo-AnketaNew',
	
	init : function(){
		this.launcher = {
			handler : this.createWindow,
            iconCls:'bogus',
			scope: this,
			shortcutIconCls: 'demo-layout-shortcut',
			text: 'Новая карточка',
			tooltip: 'Добавление нового пользователя.'
		}
	},

	createWindow : function(Carid,mapid){
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('layout-AnketaNew');
		if(!win){

	var desktop = this.app.getDesktop();
    var tab2  = new Ext.FormPanel({
        url:'FormAnketa', 
      //  labelAlign: 'top',
        frame:true,
        labelWidth: 65,
        defaults: {width: 100},        
      //  title: 'Multi Column, Nested Layouts and Anchoring',
        bodyStyle:'padding:3px 3px 0',
        items: [{
                    xtype:'textfield',
                    fieldLabel: 'Ник',
                    name: 'Nik',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'Имя',
                    name: 'first',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'Фамилия',
                    name: 'last',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'Номер ТС',
                    name: 'NCar',
                    anchor:'100%'
                },{
                    xtype:'textfield',
                    fieldLabel: 'IMEI',
                    name: 'IMEI',
                    anchor:'100%'
                },{
                  //  xtype:'textarea',
                    xtype:'htmleditor',
                    name: 'bio',
                    fieldLabel:'Заметки',
                    height:150,
                    anchor:'100%'
                }]
    });
  
			win = desktop.createWindow({
			    id: 'layout-AnketaNew',
                title: 'Добавление карточки',
                width: 620,
                height:370,
                resizable: false,
                layout: 'fit',
                plain:true,
                items: [tab2],
				minimizable:true,
    			maximizable:false,

            buttons:[{ 
                text:'Сохранить',
              //  formBind: true,	 
                // Function that fires when user clicks the button 
                handler:function(){ 
                    tab2.getForm().submit({ 
                        method:'POST',
                        params:{cmd:'new',uid:uidkey , Maps:mapid,CarId:Carid}, 
                        waitTitle:'Соединение', 
                        waitMsg:'Отправка данных...',
                        success:function(form, action){ 
	    	                obj = Ext.util.JSON.decode(action.response.responseText); 
    	                    var notifyWin = desktop.showNotification({
			                    html: obj.info.text,
			                    title: 'Информация'
		                    });
		                    desktop.hideNotification(notifyWin);
                            win.close();
                            CarCurrent.Update();
                        },

                        failure:function(form, action){ 
                            if(action.failureType == 'server'){ 
                                obj = Ext.util.JSON.decode(action.response.responseText); 
    	                        var notifyWin = desktop.showNotification({
			                        html: obj.errors.reason,
			                        title: 'Ошибка!'
		                        });                                
                            }else{ 
                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText ); 
                            } 
                            tab2.getForm().reset(); 
                        } 
                    }); 
                } 
            }] 

    			
            });
		}
		win.show();
	//	setTimeout(function(){$("#mydiv").load("index.html");}, 1000);	
		
	}
});


QoDesk.ViewAnket = Ext.extend(Ext.app.Module, {
	
	moduleType : 'demo',
	moduleId : 'demo-ViewAnket',
	
	init : function(){
		this.launcher = {
			handler : this.createWindow,
            iconCls:'bogus',
			scope: this,
			shortcutIconCls: 'demo-layout-shortcut',
			text: 'Просмотр',
			tooltip: '<b>Layout Window</b><br />A window with a layout'
		}
	},

	createWindow : function(Carid,mapid){
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('layout-ViewAnket');
		if(!win){
			win = desktop.createWindow({
			    id: 'layout-ViewAnket',
                width: 400,
                height:300,
                resizable: false,
                plain:true,
				minimizable:true,
    			maximizable:false,
                autoLoad:{
                 url:'ViewAnket.aspx'
                },
                title:'Просмотр'
                ,listeners:{show:function() {
                    this.loadMask = new Ext.LoadMask(this.body, {
                        msg:'Loading. Please wait...'
                    });
                }}
           });
		}
		win.show();
	}
});

QoDesk.IframeWindow= Ext.extend(Ext.app.Module, {
	
	moduleType : 'demo',
	moduleId : 'demo-iframe',
	
	
    init : function(){
        this.launcher = {
            text: 'Справка',
            iconCls: 'icon-grid',
            handler : this.createWindow,
            shortcutIconCls: 'demo-grid-shortcut',
            scope: this
        }
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
		var win = desktop.getWindow('tab-iframe');
        if(!win){
            win = desktop.createWindow({
                id: 'tab-iframe',
                title:'Справка',
                width:740,
                height:480,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                border:false,
                constrainHeader:true,

                layout: 'fit',
                items:
                    new Ext.TabPanel({
                        activeTab:'igrid',
                        deferredRender:true,
                        plain:true,
                        layoutOnTabChange:true,
			            defaults:{
			               autoScroll: true
			              ,border:false
			              ,loadMask:true
			              },
                                    items: [{
                                        title: 'Справка по SQL',
                                        id:'igoogle',
                                        xtype:'iframepanel',
                                        defaultSrc:'http://www.microsoft.com/express/'
                                     
                                    }]
                                })
                    });
        }
        win.show();
    }
});
