Ext.ux.PortletPlugin= {
	activeWindow:null,
    AUTO_IDs : {},
    init: function(panel) {
        //if you rely on auto-id's, then the ID in initComponent is invalid
        //the reason for this is that the ID is reset here during the init of the plugin, which
        //happens after initComponent is called.
        //The issue is, as your page grows, or if people simply come to the portal later from
        //another portion of the application, then the ext-comp id's may have already surpassed
        //the ids for the stored portlets.  This implementation gives the control an id of xtype-n
        //allowing you to use multiple portlets of the same type, but allowing them to save state
        //without risk of duplicating ids.
        //If you need to use auto-ids in initComponent, just copy this block of code to your
        //initComponent, changing this to Ext.ux.PortletPlugin
        //You may have issues if you have multiple portals using the same portlets.  If this is the
        //case, you will need to design your own ID system to handle it.  This is necessarily external
        //to the Portlet, because Portlets are created before being added to any particular portal,
        //and the best id system is probably something like PortalID-PortletXType-N
        
    	if (!this.AUTO_IDs[panel.xtype])
            this.AUTO_IDs[panel.xtype] = 0;
        if (panel.id.substring(0, 8) == 'ext-comp')
            panel.id = panel.xtype + '-' + (++this.AUTO_IDs[panel.xtype]);
        else if (panel.id.substring(0, panel.xtype.length) == panel.xtype)
            this.AUTO_IDs[panel.xtype] = Math.max(this.AUTO_IDs[panel.xtype], parseInt(panel.id.substr(panel.xtype.length+1)) + 1);
		
        panel.on('hide',function(){
			var myXtype = panel.getXType();
			panel.cascade(function() {
				if(myXtype==this.getXType())return;
				else if(this.stopPoll && this.isVisible()) {
					this.stopPoll();
				}
				
					
			});
		});
		panel.on('show',function(){
			
			var myXtype = panel.getXType();
			panel.cascade(function() {
				if(myXtype==this.getXType())return;
				else if(this.startPoll && this.isVisible())
					this.startPoll();
			});
		});
        
        //required settings - these will override anything set up in config or initComponent of extension
        //these attributes are required to make a portlet a portlet
        Ext.apply(panel, {
            anchor: '100%',
            frame:true,
            draggable: {ddGroup:'portal',beforeDragDrop:function(target,e,id){return panel.draggable;}},
            hideBorders:true,
            cls:'x-portlet'
        });
        panel.on('render',function(){
			var obj = Kelda.Info.ObjectMgr.getInstance().get('portletsMenuBtn');
			obj[this.getXType()] = true;
			
		},panel);
		panel.on('destroy',function() {
			var obj = Kelda.Info.ObjectMgr.getInstance().get('portletsMenuBtn');
			obj[this.getXType()] = false;
			/*
			var objMgr = Kelda.Info.ObjectMgr.getInstance();
			var menuhelper = objMgr.get('keldan-menu-help');
			var btn = menuhelper.mainMenuButtons.get(this.getXType());
			var btn2 = Ext.getCmp(this.getXType());
			if(btn) {
				btn.toggle();
			}else {
				console.log('No btn');
			}*/
		},panel);
        //optional settings
        Ext.applyIf(panel, {
            collapsible:false,
            settings: false,
            settingHandler: Ext.emptyFn,
            closeable: true,
            resizeable: true, 
            tools: []
        });
        if(!panel.nohelp) {
        	panel.tools.push({
        	 id:'help',
        	 qtip:keldan_lang_text('help'),
        	 handler:function(e,target,panel){
        		var win = Ext.get(panel.id+"_help");
        		if(!win) {
        		win = new Ext.Window({
        			id:panel.id+"_help",
        			constrainHeader:true,
        			title:keldan_lang_text('help').toUpperCase(),
        			width:500,
        			autoHeight:true,
        			maximizable:false,
        			bodyStyle:{
						'background-color':'#dcdcdc',
						color:'black',
						'font-family':'helvetica'
					},
        			renderTo:Ext.getBody()
        		});
        		win.on('move',function(){
        			if(this.getPosition()[1] <= 108) {
        				this.suspendEvents();
        				this.setPosition(win.getPosition()[0],108);
        				this.resumeEvents();
        			}
        		},win);
        		win.load({
        			url:window.location.protocol+"//"+window.location.hostname+"/"+basePath+"feedconnect/getHelp?portlet="+panel.xtype+"&lang="+keldan_lang,
        			callback:function() {
        			
    				},
    				scope: this, // optional scope for the callback
    				timeout: 30,
    				scripts:false
        		});
        		win.show();
        	}else if(win.isVisible()) {
        		 win.destroy();
        	}
        	/*
        	if(Ext.MessageBox.isVisible())
        		return;
        	*/
        	/*	
        	if(!this.helpMenu) {
        			this.helpMenu = new Ext.menu.Menu({
        				id:'portletHelpMenu',
        				items:[{
        					text:'Add'
        				},{
        					text:'Graph Intraday',
        					handler: function(e) {
        					alert('in graphRow');
    						alert('row index is '+this.view.findRowIndex(e.getTarget()));
    						}
        				}]
        			});
        		}
        		var xy = e.getXY();
        		this.helpMenu.showAt(xy);
        		*/
        		/*
        		Ext.Ajax.request({
        			url:window.location.protocol+basePath+"/feedconnect/getHelp?portlet="+panel.xtype,
        			success:function(response,obj) {
        				var m = response.responseText;
        				//console.log('displaying help text');
        				
        				Ext.MessageBox.show({
        		 	           title:'HJÁLP',
        		 	           msg:m,
        		 	           autoWidth:true,
        		 	           closable:true,
        		 	           resizeable:true,
        		 	           modal:false,
        		 	           animEl: panel.getEl(),
        		 	           fn:function(btnId,txt,opt) {
        		 					//this.enable();
        		 				},
        		 				scope:this
        		 	    });
        			},
        			failure:function(){
        				Ext.MessageBox.show({
        		 	           title: 'Hjálp',
        		 	           msg:'Engin hjálp til staðar',
        		 	           autoWidth:true,
        		 	           closable:true,
        		 	           modal:false,
        		 	           animEl: panel.getEl(),
        		 	           fn:function(btnId,txt,opt) {
        		 					//this.enable();
        		 				},
        		 				scope:this
        		 	   });
        			}
        		});
        		*/
        	},
        	scope:this
        });
        }
        
        if (panel.settings)
            panel.tools.push({
                id:'gear',
                handler: panel.settingHandler,
                scope: panel
            });
        if (panel.maximizable)
        	panel.tools.push({
        		id:'maximize',
        		qtip:'Breyta í glugga',
        		handler: handleMaximize 
        	});
        if (panel.closeable)
            panel.tools.push({
                id:'close',
                qtip:keldan_lang_text('close'),
                handler: function(e, target, panel){
                panel.ownerCt.remove(panel, true);
                var mini = Ext.getCmp(panel.id+'_mini');
                if(mini) {
                	mini.ownerCt.remove(mini,true);
                }
            }
            });
        

        //tell the Portal to doLayout after expanding or collapsing in case scrollbars appeared/disappeared
        panel.on('expand', function() {
            panel.initialConfig.collapsed = false;
            panel.ownerCt.ownerCt.saveState();
            panel.ownerCt.ownerCt.doLayout();
        });

        //the collapse event is deferred because panels that start collapsed fire the collapse event before rendering
        panel.on.defer(50, panel, ['collapse', function() {
            panel.initialConfig.collapsed = true;
            panel.ownerCt.ownerCt.saveState();
            panel.ownerCt.ownerCt.doLayout();
        }]);
        
        
        
        if (panel.resizeable)
        {
            panel.on('render', function() {
                panel.resizer = new Ext.Resizable(panel.el, {
                    handles: 's',
                    minHeight: 100,
                    maxHeight:800,
                    pinned: true,
                    resizeElement: function() {
                		if(!panel.ownerCt.ownerCt)
                			return
                        var box = this.proxy.getBox();
                        panel.setSize(box);
                        panel.initialConfig.height = box.height;
                        //remove and reappend element to fix IE6 bug
                        //var parent = this.south.el.parent();
                        //this.south.el.remove();
                        //parent.appendChild(this.south.el);
                        panel.ownerCt.ownerCt.saveState();
                        return box;
                    }
                });
                
                //bug fix - Resizers place their proxy in the same container with the panel, messing with layouts
                //this removes the proxy from the container and moves it to the end of the document. fixed in 2.2
                if (Ext.version < 2.2)
                {
                    panel.resizer.proxy.remove();
                    panel.resizer.proxy.appendTo(Ext.getBody());
                }
            });
        }
        function handleMaximize(event, toolEl, panel/*the portlet*/){
        	
        	panel.originalDD = panel.draggable;
        	panel.draggable = false;
        	var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
        	panel.originalOwnerCt = panel.ownerCt;
            panel.originalPosition = panel.ownerCt.items.indexOf(panel);
            panel.originalSize=panel.getSize();
            panel.originalChild = panel.getComponent(0);
            var iconClass = '';
            if(panel.header.hasClass('greenlight'))
            	iconClass = 'greenlight';
            else if(panel.header.hasClass('redlight'))
            	iconClass = 'redlight';
            //toolEl.window = null;
            if (!toolEl.window) {
            	//alert('window is null');
                var defaultConfig = {
                    id: (panel.getId() + '-MAX'),
                    name:panel.name,
                    listeners:panel.listeners,
                    title:panel.title,
                    autoHeight:panel.autoHeight,
                    width:panel.winWidth,
                    headerCfg:panel.headerCfg,
                    iconCls:iconClass,
                    //height: (480),
                    //autoHeight:true,
                    resizable: true,
                    draggable: true,
                    closable: false,
                    //closeAction: 'hide',
                    hideBorders: true,
                    minimizable:true,
                    maximizable:false,
                    plain: true,
                    layout: 'fit',
                    //autoScroll: true,
                    border: false,
                    bodyBorder: false,
                    frame: true,
                    pinned: true,
                    tools:[{
                    	id:'pin',
                    	handler: function(event,tool,panel) {
                    		removeWin(panel);
                    	}
                    }],
                    closeWinPortlet:removeWin,
                    manager:null,
                    bodyStyle: 'background-color: #ffffff;',
                    shadow:false,
                    taskButton:null,
                    animateTarget:null,
                    cmenu : new Ext.menu.Menu({
                        items: [
                                ]
                    })
                };
                toolEl.window = new Ext.Window(defaultConfig);
               // alert('created new one');
                /*toolEl.window.tools.push({
                	id:'pin',
                	handler:removeWin
                });*/
                
                toolEl.window.on({
                	'activate': {
                		fn: markActive
                	},
                	'beforeshow': {
                		fn: markActive
                	},
                	'deactivate': {
                		fn: markInactive
                	},
                	'minimize': {
                		fn: minimizeWin
                	},
                	'close': {
                		fn: removeWin
                	},
                	'maximize' : {
                		fn: maximizeWin
                	}
                });
                // toolEl.window.animateTarget = toolEl.window.taskButton.el;
                
                //toolEl.window.on('hide', handleMinimize, panel);
            }
            toolEl.window.manager = desktop.windows;
            toolEl.window.taskButton = desktop.taskbar.addTaskButton(toolEl.window);
            toolEl.window.animateTarget = toolEl.window.taskButton.el;
            if (!panel.dummyComponent) {
                var dummyCompConfig = {
                    title: panel.title,
                    width: panel.getSize().width,
                    height: panel.getSize().height,
                    html: '&nbsp;'
                };
                panel.dummyComponent = new Ext.Panel(dummyCompConfig);
            }
            
            
            toolEl.window.add(panel.originalChild);
            
            
            toolEl.window.portlet = panel;
            if (panel.tools['toggle']) panel.tools['toggle'].setVisible(false);
            panel.tools['maximize'].setVisible(false);
            panel.tools['close'].setVisible(false);
            

            /*
            panel.originalOwnerCt.insert(panel.originalPosition, panel.dummyComponent);
            panel.originalOwnerCt.doLayout();
            panel.dummyComponent.setSize(panel.originalSize);
            panel.dummyComponent.setVisible(false);
            */
            
            //panel.dummyComponent.getEl().mask('This is maximized.');
            
            panel.hide();
            //toolEl.window.fireEvent('resize',0,0,panel.getSize().width,panel.getSize().height);
           // alert('showing window');
           
            toolEl.window.on('show',function(comp){
            	if(panel.preferredWinSize) {
            		toolEl.window.setSize(panel.preferredWinSize.width,panel.preferredWinSize.height);
            	}
            	//set market open/close
            	
            });
            
            toolEl.window.setPosition(0,160);
            toolEl.window.show(this);
           
            
        };
        function handleClose(window) {
        	var panel = window.portlet;
        	var panelChild = window.getComponent(0);
        	panel.insert(0,panelChild);
        	panel.draggable = true;
        	panel.draggable = panel.originalDD;
            //panel.dummyComponent.getEl().unmask();
            //panel.dummyComponent.setVisible(true);
            //panel.originalOwnerCt.insert(panel.originalPosition, panel);
            //panel.originalOwnerCt.doLayout(); 
            //panel.setSize(panel.originalSize);
            panel.tools['maximize'].setVisible(true);
            panel.tools['close'].setVisible(true);
            if (panel.tools['toggle']) panel.tools['toggle'].setVisible(true);
            //panel.dummyComponent.ownerCt.remove(panel.dummyComponent);
            //window.removeAll();
            //window.destroy();
            
            //panel.insert(panelChild.originalPosition,panelChild);
            /*panel.insert(0,{
            	xtype:panel.getXType()+"_Child"
            });
            */
            window.hide();
            //window.destroy();
            panel.show();
            panel.doLayout();
            panel.fireEvent('resize',this,0,0,panel.getSize().width,panel.getSize().height);
        };
        function minimizeWin(win){
            win.minimized = true;
            win.hide();
        }
        function maximizeWin(win) {
        	win.maximized = true;
        	
        }
        function markActive(win){
        	
        	var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
            if(this.activeWindow && this.activeWindow != win){
                markInactive(this.activeWindow);
            }
            desktop.taskbar.setActiveButton(win.taskButton);
            this.activeWindow = win;
            Ext.fly(win.taskButton.el).addClass('active-win');
            win.minimized = false;
        }
        function markInactive(win){
        	
            if(win == this.activeWindow){
                this.activeWindow = null;
                Ext.fly(win.taskButton.el).removeClass('active-win');
            }
        }
        function removeWin(win){
        	
        	var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
            desktop.taskbar.removeTaskButton(win.taskButton);
            handleClose(win);
        }
    }
};

