/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.app.App = function(cfg) {
	this.portletXTypes = [],
	Ext.apply(this, cfg);
	this.addEvents( {
		'ready' : true,
		'beforeunload' : true
	});

	Ext.onReady(this.initApp, this);
};

Ext.extend(Ext.app.App, Ext.util.Observable, {
	id:'main-app',
	isReady : false,
	startMenu : null,
	modules : null,	

	getStartConfig : function() {
		
	},

	initApp : function() {
		
		this.announceTask = {
			run : function() {
				Ext.Ajax.request({
					url:window.location.protocol+"//"+window.location.hostname+"/"+basePath+"feedconnect/getAnnounce",
					success:function(response,opt) {
						var res = Ext.decode(response.responseText).result;
						if(!res)return;
						var last = parseInt(Keldan_Get_Cookie('keldan_announce'));
						var bodyTxt = '';
						for(i=0,j=res.length;i<j;i++) {
							
							if(res[i].id <= last) {
								//alert('res id is '+res[i].id+' last is '+last+' continuing');
								continue;
							}
							else {
								//alert('res id is '+res[i].id+' last is '+last+' adding text');
								bodyTxt += '<p>'+res[i].body+'</p>';
							}
						}
						if(bodyTxt.length > 1) {
							//alert('bodyTxt.length is '+bodyTxt.length);
							Kelda.Info.Message.msg('Tilkynningar',bodyTxt);
						}
						Keldan_Set_Cookie('keldan_announce',res[res.length-1].id,1000);
					}
				});
			},
			interval : 20000
		};
		
		//Ext.TaskMgr.start(this.announceTask);
		
		/*
		(function() {
			Kelda.Info.Message.msg("Tilkynning","<p>Bla bla bla bla bla bla kdfjkdfk fkdjfkdjfkjdf kdjfkdjfkdjfkjdkf kdjf</p>" +
					"<p>Ble ble ble ble ble ble  fdkjjkjdkjfdkfdfjkdfjdf dkj dkj kjdf;wkej ;jwekg kwjei</p>" +
					"<p><b>Pruff</b></p>");
		}).defer(5000);
		*/
		
		
		if(!Ext.QuickTips.isEnabled())
			Ext.QuickTips.init();
		//try to fix notorius IE DOM-JS memory leaks. 
		if(Ext.isIE)
			Ext.enableListenerCollection = true;
		var hfdepo = Ext.get('depo-link');
		var loginlinks = Ext.get('ux-tasklinks');
		if(keldan_lang=='is') {
			if(hfdepo) {
				hfdepo.setVisible(true);
			}
			if(loginlinks)
				loginlinks.setVisible(true);
			Ext.MessageBox.buttonText = {
				ok:keldan_lang_text('ok') ,
				cancel:keldan_lang_text('cancel') ,
				yes:keldan_lang_text('yes'),
				no:keldan_lang_text('no')
			};
		}else {
			if(hfdepo) {
				hfdepo.setVisible(false);
			}
			if(loginlinks)
				loginlinks.setVisible(false);
		}
		
		/*
		var loadingMask = Ext.get('loading-mask');
	     var loading = Ext.get('loading');
	     loading.fadeOut({ duration: 0.2, remove: true });
	     loadingMask.setOpacity(0.9);
	     loadingMask.ghost();
	     */
	     /*
	     loadingMask.shift({
	          xy: loading.getXY(),
	          width: loading.getWidth(),
	          height: loading.getHeight(),
	          remove: true,
	          duration: 3,
	          opacity: 0.1,
	          easing: 'none' //bounceOut
	     });
	     */
		if(Ext.isIE6) {
			this.displayIE6Warning();
		}/*else if(Ext.isIE7) {
			this.displayIE7Warning();
		}*/
		if(keldan_lang=='en')
			pageTracker._trackEvent('Keldan.com','Loaded','App keyrt upp.');
		else
			pageTracker._trackEvent('Keldan.is','Loaded','App keyrt upp.');
		/*var langicon = Ext.get('keldan-lang');
		langicon.set({src:'themes/hfvtheme/images/currencies/'+(keldan_lang=='is'?'GBP.png':'ISK.png')});
		var langa = Ext.get('keldan-lang-a');
		langa.set({href:(keldan_lang=='is'?'http://www.keldan.com':'http://www.keldan.is')});
		if(keldan_lang=='en') {
			var hficon = Ext.get('keldan-hfvlogo');
			hficon.set({src:'themes/hfvtheme/images/taskbar/black/'+'hflogo-en.png'});
		}*/
		var hflink = Ext.get('hflink');
		hflink.set({href:(keldan_lang=='is'?'http://www.hfv.is':'http://www.hfv.is/en')});
		var dateTxtEl = Ext.get("date-text-pre");
		var keldansave = Ext.get('keldan-save');
		var keldanrefresh = Ext.get('keldan-reset');
		var saveDt = new Ext.util.DelayedTask();
		if(keldansave) {
			keldansave.set({'ext:qtip':keldan_lang_text('savedesktop'),'qclass':'savettstyle'});
			keldansave.on('click',function(){
				saveDt.delay(700,function(){
				var sm = new Kelda.Info.Statemanager();
	        	sm.setApp(this);
	        	sm.persistState();
			});
			});
		}
		if(keldanrefresh) {
			keldanrefresh.set({'ext:qtip':keldan_lang_text('refreshdesktop')});
			keldanrefresh.on('click',function(){
				Ext.Msg.show({
					title:keldan_lang_text('refreshdesktop'),
					msg: keldan_lang_text('refreshdesktopconfirm'),
					buttons: Ext.Msg.OKCANCEL,
					fn: function(btnId){
						if(btnId=='ok') {
							//delete the cookie and start anew.
							Keldan_Set_Cookie('wsid','',0,'/');
							if(Keldan_hasLocalStore()) {
								delete localStorage.workspace;
							}
							location.reload(true);
						}
					},
					modal:false,
					icon: Ext.MessageBox.QUESTION
				});
				
				
			});
		}
		this.desktop = new Ext.Desktop(this);
		var desk = this.desktop;
		var loginlink = Ext.get('keldan-login-link');
		var logoutlink = Ext.get('keldan-logout-link');
		var mykeldalink = Ext.get('keldan-mykelda-link');
		var aboutlink = Ext.get('keldan-about-link');
		var pricelink = Ext.get('keldan-pricelist-link');
		if(pricelink) {
			pricelink.on('click',function(){
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var winman = objMgr.get('toolbox-win-manager');
				
				var win = Ext.getCmp('pricelist-win');
				if(!win) {
				
					win = desk.createStandAloneIWin({
						id:'pricelist-win',
						title:keldan_lang_text('pricelist').toUpperCase(),
						name:keldan_lang_text('pricelist'),
						bodyStyle:{
							'background-color':'white',
							color:'black'
						},
						manager:winman.manager,
						maximizable:false,
						//constrainHeader:true,
						//autoScroll:true,
						width:650,
						height:Ext.getCmp('main-portal').getSize().height-100,
						resizeable:true,
						//autoWidth:true,
						//autoHeight:true,
						layout:'fit',
						loadMask:true,
			            defaultSrc :window.location.protocol+"//"+window.location.hostname+"/"+basePath+"keldan/pricelist"
					});
					win.on('move',function(){
	        			if(this.getPosition()[1] <= 108) {
	        				this.suspendEvents();
	        				this.setPosition(win.getPosition()[0],108);
	        				this.resumeEvents();
	        			}
	        		},win);	
				}
				win.setPosition(100,0);
				win.show();
				win.toFront();
				
			});
		}
		if(logoutlink) {
			logoutlink.on('click',function(){
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var act = objMgr.get('mykelda-logout-action');
				act.action();
			});
		}
		if(mykeldalink) {
			mykeldalink.on('click',function(){
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var act = objMgr.get('mykelda-action');
				act.action();
			});
		}
		if(aboutlink) {
			aboutlink.on('click',function(){
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var winman = objMgr.get('toolbox-win-manager');
				var win = Ext.getCmp('about-us-win');
				if(!win) {
					win = desk.createStandAloneWin({
						id:'about-us-win',
						title:keldan_lang_text('aboutkeldan').toUpperCase(),
						name:keldan_lang_text('aboutkeldan'),
						autoLoad:window.location.protocol+"//"+window.location.hostname+"/"+basePath+"keldaconnect/getAboutUs?lang="+keldan_lang,
						header:false,
						//autoLoad : {
						//	url: window.location.protocol+"//"+window.location.hostname+"/"+basePath+"keldaconnect/getAboutUs?lang="+keldan_lang
						//},
						bodyStyle:{
							'background-color':'white',
							color:'black'
						},
						//maximizable:false,
						//constrainHeader:true,
						autoScroll:true,
						manager:winman.manager,
						//autoWidth:true,
						width:700,
						height:(Ext.getCmp('main-viewport').getHeight() - 140) < 730 ? Ext.getCmp('main-viewport').getHeight() - 140:730 
					});
					/*
					win.on('move',function(){
	        			if(this.getPosition()[1] <= 108) {
	        				this.suspendEvents();
	        				this.setPosition(win.getPosition()[0],108);
	        				this.resumeEvents();
	        			}
	        		},win);
	        		*/
				}
				win.setPosition(100,0);
				
				win.show();
			});
		}
		if(loginlink) {
			loginlink.alignTo('keldan-pricelist-link','r-l',[-12,0]);
			loginlink.on('click',function(){
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var act = objMgr.get('login-action');
				act.action('/user/');
			});
			
		}
		dateTxtEl.on({
			'click': { 
				fn : function(ev,el,o){
					var dPicker = new Ext.DatePicker({
						cancelText:keldan_lang_text('quit'),
						dayNames:(keldan_lang=='is'?clock_days_is:clock_days_en),
						monthNames:(keldan_lang=='is'?clock_months_is:clock_months_en),
						monthYearText:keldan_lang_text('pickmonth'),
						okText:keldan_lang_text('ok'),
						todayText:keldan_lang_text('today')
					});
					//var elDate = Ext.get('clock_day_month_text');
					var dateWin = Ext.getCmp('dateWin');
					if(!dateWin) {
						dateWin = new Ext.Window({
							id:'dateWin',
							//x:elDate.getX()-40,
							//y:elDate.getY()+20,
							title:keldan_lang_text('calendar'),
							closeAction:'close',
							frame:true,
							width:190,
							height:222,
							resizable:false,
							border:true,
							layout:'fit',
							items:[new Ext.Panel({
								//width:100,
								//height:100,
								items:[dPicker]
							})
							]
						});
						var el = Ext.get("date-text-pre");
						dateWin.on('move',function(){
		        			if(this.getPosition()[1] <= 108) {
		        				this.suspendEvents();
		        				this.setPosition(this.getPosition()[0],108);
		        				this.resumeEvents();
		        			}
		        		},dateWin);
						dateWin.setPosition(el.getX()-44,el.getY()+20);
						dateWin.show(el);
					}else {
						if(dateWin.isVisible()) {
							dateWin.hide(el);
						}
						else {
							dateWin.show(el);
						}
					}
				},
				scope:this
			},
			'mouseover' : {
				fn : function() {
					
				}
			}
		});
	
		
		this.startConfig = this.startConfig || this.getStartConfig();

		
		
		this.viewport = new Ext.Viewport( {
			id : 'main-viewport',
			cls : 'mainviewport',
			layout : 'border',
			items : [
			  this.desktop.taskbar.container,
			  {
			  region:'center',
			  xtype : 'main-portal'
			}]
			//renderTo : Ext.getBody()
		});
		
		var objMgr = Kelda.Info.ObjectMgr.getInstance();
		objMgr.reg(this.desktop);
		
		
		
		
		this.launcher = this.desktop.taskbar.startMenu;
		
		this.desktop.taskbar.setDesktop(this.desktop);

		this.initActions();
		this.initKeyMaps();
		this.initMisc();

		
		
		this.modules = this.getModules();
		if (this.modules) {
			this.initModules(this.modules);
		}
		this.init();
		this.registerXTypes();
		Ext.EventManager.on(window, 'beforeunload', this.onUnload, this);
		this.fireEvent('ready', this);
		this.isReady = true;
		//console.log(document.cookie);
		if(Keldan_hasState()) {
			var sm = new Kelda.Info.Statemanager();
	    	sm.setApp(this);
	    	sm.loadState();
		}else {
			this.defaultPortlets();
		}
		
		objMgr.reg(this);
	
	},
	getModules : Ext.emptyFn,
	init : Ext.emptyFn,
	getStartupDefaults : Ext.emptyFn,
	initModules : function(ms) {
		for ( var i = 0, len = ms.length; i < len; i++) {
			var m = ms[i];
			
			this.launcher.add(m.launcher);
		
			m.app = this;
		}
	},
	setVersionCheck : function() {
		/*var task = {
				run : function() {
			  Ext.Ajax.request({
				url:window.location.protocol+"//"+window.location.hostname+"/"+basePath+"keldaconnect/getVersion",
				success: function(res,opts) {
				  	var vers = res.responseText;
				  	if(vers != keldan_version && vers.length > 4 && vers.length < 6) {
				  		//console.log('versions match');
				  	
				  		//console.log('version mismatch our ver is '+keldan_version+" ext vers is "+vers);
				  		Ext.Msg.show({
				  			title:keldan_lang_text('newversion'),
				  			msg:keldan_lang_text('newversion-text'),
				  			buttons:Ext.Msg.OKCANCEL,
				  			modal:false,
				  			fn:function(bId,txt,opts) {
				  				if(bId=='ok') {
				  					location.reload(true);
				  				}else {
				  					
				  				}
				  			},
				  			icon:Ext.Msg.INFO
				  		});
				  	}
					
				},
				error: function() {
					
				}
			  });
			},
			//interval : 7200000
			interval : 3000
			
		};
		Ext.TaskMgr.start(task);
		*/
	},
	firstTimeCheck : function() {
		
	},
	getModule : function(name) {
		var ms = this.modules;
		for ( var i = 0, len = ms.length; i < len; i++) {
			if (ms[i].id == name || ms[i].appType == name) {
				return ms[i];
			}
		}
		return '';
	},
	initActions : function() {
		var logoutAction = new Kelda.Info.Action({
			id : "logoutAction",
			msg : "User logged out",
			action : new Ext.Action({
				text:"Logout",
				handler: function() {
					
					Ext.Ajax.request({
						url:window.location.protocol+"/logout",
						success: function() {
							Kelda.Info.Message.msg("Útskráning tókst","Notandi er skráður út.");
							//disable bank timers if any
							
							desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
							
							Ext.removeNode(Ext.get('logout-button'));
							Ext.destroy(Ext.getCmp('logout-button'));
							Ext.getCmp('login-form-id').setVisible(true);
							var kd = Ext.getCmp('kelda-depo');
							if(kd){ 
								kd.destroy();
								desktop.removeWin(kd);
							}
							Ext.getCmp('sett-depo').disable();
							//Ext.getCmp('sett-depo').hide();
							Ext.getCmp('sett-overview').disable();
							//Ext.getCmp('sett-overview').hide();
							if(window.depo_bank !== undefined) {
								depo_bank.disableTimers();
							}
						},
						error: function() {
							Kelda.Info.Message.msg("Log out failed","");
						}
					});
					
				}
			})
			
		});
		Kelda.Info.ObjectMgr.getInstance().reg(logoutAction);
		var plotRowAction = new Kelda.Info.Action({
			id : 'plotRowAction',
			action : new Ext.Action({
				text:"Graf",
				handler:function(rec) {
					var winctrl = Ext.getCmp('main-graph-ctrl');
					var d = new Date();
					var today = d.format('Y-m-d');
					winctrl.setAndPlot(rec.data.name,today+' 00:00:00',today+' 23:59:59');
					Ext.getCmp('graph-win').show();
				}
			})
		});
		Kelda.Info.ObjectMgr.getInstance().reg(plotRowAction);
		/*var loginAction = new Kelda.Info.Action( {
			id : "loginAction",
			action : new Ext.Action( {
				text : "Login",
				handler : function(usr, pwd) {
					Ext.Ajax.request({
						url:window.location.protocol+"/node?destination=node",
						params:{form_id:'user_login_block',name:usr,op:'Log in',pass:pwd,type:'ajax'},
						callback: function(opts,succ,xhrRes) {
							
							if(xhrRes.status != 200) {
								//Kelda.Info.Message.msg("Log in failed!","");
							}
							if(xhrRes.responseText.length < 150) {
								if(xhrRes.responseText.indexOf("login") >= 0) {
									var res = eval("("+xhrRes.responseText+")");
									if(res.login == 1) {
										
										Kelda.Info.Message.msg("Innskráning tókst","Notandi "+usr+" er skráður inn");
										Ext.getCmp('login-form-id').setVisible(false);
										
											
										Ext.getCmp('sett-depo').enable();
										Ext.getCmp('sett-overview').enable();
										var logoutBtn = new Ext.Button({
								            text: usr,
								            id: 'logout-button',
								            iconCls:'logout-button-icon',
								            menu: this.startMenu,
								            renderTo: 'ux-taskbar-start',
								            handler: function() {
												Kelda.Info.ObjectMgr.getInstance().get('logoutAction').action.execute();
											},
								            template: new Ext.Template(
													'<table border="0" cellpadding="0" cellspacing="0" class="logout-button-table" style="width:160px"><tbody><tr>',
													'<td style="width:120px"><b><font id="username" color="white">{0}</font></b></td><td><em unselectable="on"><button class="logout-button" type="{1}"></button></em></td>',
									            	'</tr></tbody></table>')
												
								        });
										if(res.keldatype=='bank') {
											dwin = Ext.getCmp('kelda-depo') ;
											if(!dwin) {
										        dwin = Kelda.Info.ObjectMgr.getInstance().get('main-desktop').createWindow({
													id:'kelda-depo',
													cls:'kelda-depo-win',
										        	title : 'Depo',
													width:700,
													height:600
												});
										        dwin.addListener('beforeclose',function(panel){
										        	this.hide();
										        	this.taskButton.hide();
										        	return false;
										        });
										        
										        dwin.addListener('show',function(comp){
										        	this.taskButton.show();
										        	
										        });
										        dwin.load({
											    	url: window.location.protocol+"keldaconnect/getDepoClient",
											        callback: function(){
										        		depo_bank.init();
										        	},
											        scope: this, // optional scope for the callback
											        discardUrl: false,
											        nocache: false,
											        text: "Hleð inn...",
											        timeout: 30,
											        scripts: true
											    });
										    }
										    
										}
										
									}
								}
							}else{
								Kelda.Info.Message.msg("Innskráning mistókst","Rangt notandanafn eða lykilorð.Vinsamlegat reynið aftur.");
							}
							
						}
					});
				}
			})
		});
		Kelda.Info.ObjectMgr.getInstance().reg(loginAction);
		*/
	},
	initMisc : function() {
		Ext.apply(Ext.form.VTypes, {
		    daterange : function(val, field) {
		        var date = field.parseDate(val);

		        if(!date){
		            return;
		        }
		        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
		            var start = Ext.getCmp(field.startDateField);
		            start.setMaxValue(date);
		            start.validate();
		            this.dateRangeMax = date;
		        } 
		        else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
		            var end = Ext.getCmp(field.endDateField);
		            end.setMinValue(date);
		            end.validate();
		            this.dateRangeMin = date;
		        }
		        /*
		         * Always return true since we're only using this vtype to set the
		         * min/max allowed values (these are tested for after the vtype test)
		         */
		        return true;
		    },

		    password : function(val, field) {
		        if (field.initialPassField) {
		            var pwd = Ext.getCmp(field.initialPassField);
		            return (val == pwd.getValue());
		        }
		        return true;
		    },

		    passwordText : 'Passwords do not match'
		});
		
	    //win.hide();

	},
	initKeyMaps : function() {
		var taskSwitch = new Ext.KeyMap(Ext.get(document), [{
			key:'q',
			alt:true,
			fn:function(e){
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				//console.log('Alt-q');
				
				//console.log('Alt was down!');
				var win = Ext.getCmp('task-switch');
				if(!win) {
				 win = new Ext.Window({
					id:'task-switch',
					cls:'TaskSwitchWin',
					border:true,
					modal:true,
					manager:desk.windows,
					layout:'border',
					height:80,
					items:[]
				});
				Ext.apply(win,{
					selectBtnIdx:0
				});
				win.on('beforerender',function(winComp) {
					var tsPanel = new Ext.Panel({
						region:'center',
						border:false,
						layout:'table',
						height:40,
						layoutConfig : {
							columns:5
						},
						items:[]
					});
					var btns = desk.taskbar.getTaskButtons();
					if(btns.length===0)return false;
					for(i = 0; i < btns.length;i++) {
						var btn = btns[i];
						var newBtn = new Ext.Panel({
							id:btn.id+'_ts',
							cls:'task-switch-btn',
							width:36,
							height:36,
							//iconCls:'task-switch-btn-iconn',
							//text:'',
							winText:btn.text,
							border:false,
							html:'<table><tbody>'+
									'<tr><td><img src="/themes/hfvtheme/images/taskbar/taskswitch.png"></td></tr>'+
									'</tbody></table>'
							
						});
						tsPanel.add(newBtn);
						//winComp.add(newBtn);
					}
					winComp.add(tsPanel);
					/*winComp.add(new Ext.Panel({
						border:false,
						region:'south',
						html:'<p id="task-switch-text">Prufa</p>'
					}));
					*/
					
				});
				  win.show();
				  desk.windows.bringToFront(win);
				  
				  var btn = win.getComponent(0).getComponent(win.selectBtnIdx);
				  btn.addClass('task-switch-btn-over');
				  win.selectBtnIdx++;
			  }else {
				  if(win.selectBtnIdx >= win.items.length)
						win.selectBtnIdx = 0;
				  btn = win.getComponent(win.selectBtnIdx);
				  if(win.selectBtnIdx > 0) {
					  oldBtn = win.getComponent(win.selectBtnIdx - 1);
					  oldBtn.removeClass('task-switch-btn-over');
				  }else if(win.selectBtnIdx === 0) {
					  oldBtn = win.getComponent(win.items.length - 1);
					  oldBtn.removeClass('task-switch-btn-over');
				  }
				  btn.addClass('task-switch-btn-over');
				  win.selectBtnIdx++; 
				  win.show();
				  desk.windows.bringToFront(win);
			  }
			  
			    
			},
			stopEvent:true,
			scope:this
			}]);
		var altUp = new Ext.KeyMap(Ext.get(document),{
				key:Ext.EventObject.ALT,
				fn:function() {
					var win = Ext.getCmp('task-switch');
					if(win) {
						//ok TaskSwitch is up, bring it down;
						//win.destroy();
					}
				}
			},'keyup');
		
	},
	onReady : function(fn, scope) {
		if (!this.isReady) {
			this.on('ready', fn, scope);
		} else {
			fn.call(scope, this);
		}
	},
	getDesktop : function() {
		return this.desktop;
	},
	getViewport: function() {
		return this.viewport;
	},/*
	startAutoRefreshTimer : function() {
		this.autoRefresh = {
			run : function() {
				var d = new Date();
				console.log(d.getDay()+" "+d.getHours());
				if(d.getDay()==0 && d.getHours() >= 15 && d.getHours() <= 17 ) {
					window.location.reload();
					fresh = false;
				}
			},
			interval : 30000//7200000
		};
		//Ext.TaskMgr.start(autoRefresh);
		setTimeout("Ext.TaskMgr.start(this.autoRefresh)",30000);
	},*/
	portlets : {
		news : {
			name:'nfp',
			title:keldan_lang_text('news'),
			headerCfg : {
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('news').toUpperCase()
				}]
			},
			item : {
					xtype:'tabpanel',
					activeTab:(keldan_lang=='is'?6:0),
					//id:'newstabpanel_'+Math.random()*1001,
					listeners :{ 
						'tabchange' : function(tpanel,thetab) {
							pageTracker._trackEvent('News','TabOpen',thetab.title);
						}
					},
					enableTabScroll:true,
					plugins: new Ext.ux.TabCloseMenu(),
					items:(keldan_lang=='is'?[{
						xtype:'nfp_Child',
						id:'news-domestic_'+Math.random()*1000,
						title:keldan_lang_text('news-domestic'),
						domesticOnly:true,
						foreignOnly:false,
						//closable:true,
						newscategory:'DOM_GEN'
						
					},{
						xtype:'nfp_Child',
						id:'news-foreign_'+Math.random()*1000,
						title:keldan_lang_text('news-foreign'),
						domesticOnly:false,
						foreignOnly:true,
						//closable:true,
						newscategory:'FOR_GEN'
					},{
						xtype:'nfp_Child',
						id:'news-forbus_'+Math.random()*1000,
						title:keldan_lang_text('news-forbus'),
						domesticOnly:false,
						foreignOnly:true,
						//closable:true,
						newscategory:'FOR_BUS'
					},{
						xtype:'nfp_Child',
						id:'news-forbus_'+Math.random()*1000,
						title:keldan_lang_text('news-forice-short'),
						domesticOnly:false,
						foreignOnly:true,
						//closable:true,
						newscategory:'ICE_ABR'
					},{
						xtype:'nfp_Child',
						id:'news-domspo_'+Math.random()*1000,
						title:keldan_lang_text('news-sports'),
						domesticOnly:false,
						foreignOnly:true,
						//closable:true,
						newscategory:'DOM_SPO'
					},{
						xtype:'nfp_Child',
						id:'news-forbus_'+Math.random()*1000,
						title:keldan_lang_text('news-domfun'),
						domesticOnly:false,
						foreignOnly:true,
						//closable:true,
						newscategory:'DOM_FUN'
					},{
						xtype:'nfp_Child',
						id:'news-dombus_'+Math.random()*1000,
						title:keldan_lang_text('news-dombus'),
						domesticOnly:false,
						foreignOnly:true,
						//closable:true,
						newscategory:'DOM_BUS',
						loadMask:{msg:keldan_lang_text('loading'),removeMask:true}
					}]:[{
						xtype:'nfp_Child',
						id:'news-domestic_'+Math.random()*1000,
						title:keldan_lang_text('news-domestic'),
						domesticOnly:true,
						foreignOnly:false,
						//closable:true,
						newscategory:'ICE_BUS',
						loadMask:{msg:keldan_lang_text('loading'),removeMask:true}
					},{
						xtype:'nfp_Child',
						id:'news-dombus_'+Math.random()*1000,
						title:keldan_lang_text('news-forbus'),
						domesticOnly:false,
						//closable:true,
						foreignOnly:true,
						newscategory:'FOR_BUS'
					}])
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
	    				this.title,
	    				this.headerCfg,
	    				this.item
				);
			}
		},
		bonds : {
			name:'ISBP',
			title:keldan_lang_text('bonds'),
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('bonds').toUpperCase()
				},{
					tag:'pre',
					cls:'header-text-delayed',
					html:keldan_lang_text('delayed')+" 15 "+keldan_lang_text('minutes')
				}]
			},
			item : {
					xtype:'ISBTabsPanel',
					listeners :{ 
						'tabchange' : function(tpanel,thetab) {
							pageTracker._trackEvent('Bonds','TabOpen',thetab.title);
						}
					},
					//id:'bondstabpanel_'+Math.random(),
					items:[{
						xtype:'ISBP_Child',
						title:keldan_lang_text('treasurynotes')+"/"+keldan_lang_text('treasurybills'),
						loadMask:{msg:keldan_lang_text('loading'),removeMask:true}
						//id:'bonds_'+Math.random()*100000
						//stateEvents:['hiddenchange']
						//region:'center',
						//autoHeight:true
					}/*,{
						xtype:'Bonds_Child',
						title:keldan_lang_text('treasurybills'),
						id:'bonds_'+Math.random()*1000,
						feedType:'ISBV'
					}*/,{
						xtype:'Bonds_Child',
						title:keldan_lang_text('calculator')
					},{
						xtype:'panel',
						id:'fruss',
						layout:'fit',
						title:keldan_lang_text('yieldcurve'),
						height:370,
						items :[{
						
							id:'isb-flot-graph1',
							xtype:'ISBGP_Child',
							title:'Rass'
							//height:400
							
							//region:'center',
							//autoWidth:true,
							//autoHeight:true
							//height:200
							//width:380
						}]
					}]
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg,
						this.item);
			}
				
		
		},
		
		stocks : {
			name:'ISSP',
			title:keldan_lang_text('stocks'),
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('stocks').toUpperCase()
				},{
					tag:'span',
					cls:'header-text-delayed',
					html:keldan_lang_text('delayed')+" 15 "+keldan_lang_text('minutes')
				}]
			},
			item : {
					xtype:'ISSTabsPanel',
					listeners :{ 
						'tabchange' : function(tpanel,thetab) {
							pageTracker._trackEvent('Stocks','TabOpen',thetab.title);
						}
					},
					//id:'stockstabpanel_'+Math.random(),
					items:[{
						xtype:'ISSP_Child',
						stateId:'stocks_'+Math.random()*1000,
						category:'OMXI6',
						title:'OMXI6',
						loadMask:{msg:keldan_lang_text('loading'),removeMask:true}
					},{
						xtype:'ISSP_Child',
						stateId:'stocks_'+Math.random()*1000,
						category:'FN',
						title:'First North'
					},{
						xtype:'ISSP_Child',
						stateId:'stocks_'+Math.random()*1000,
						category:'ALL',
						title:keldan_lang_text('allstocks')
					}]
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg,
						this.item);
			}
		},
		worldindex : {
			name:'WIndexPortlet',
			is:'Erlendir markaðir',
			en:'World Indexes',
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:'ERLENDIR MARKAÐIR'
				},{
					tag:'pre',
					cls:'header-text-delayed',
					html:'Seinkun 15 min.'
				}]
			}
		},
		rsfaf : {
			name:'RSFAFPortlet',
			title:keldan_lang_text('fishmarket'),
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('fishmarket').toUpperCase()
				}]
			},
			item : {
					xtype:'tabpanel',
					activeTab:0,
					stateId:'fxtabpanel_'+Math.random()*1000,
					stateEvents:['tabchange'],
					getState : function() {
						return {
							activeTab:this.items.indexOf(this.getActiveTab())
						};
					},
					items:[/*{
						xtype:'FSPortlet_Child',
						title:keldan_lang_text('fishquota')
					},*/{
						xtype:'RSFAFPortlet_Child',
						//id:'rsfgutt_'+Math.random()*100,
						rsfafType:'GUTTED',
						title:keldan_lang_text('gutted')
			
					},{
						xtype:'RSFAFPortlet_Child',
						//id:'rsfgutt_'+Math.random()*100,
						rsfafType:'UNGUTTED',
						title:keldan_lang_text('ungutted')
						
					}]
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg,
						this.item);
			}
		},
		iceabroad : {
			name:'ICEAbroadPortlet',
			id:'iceabrd_'+Math.random()*1000,
			title:keldan_lang_text('iceland-abroad'),
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('iceland-abroad').toUpperCase()
				}]
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg);
			}
		},
		cbirates : {
			name:'CBIRatesPortlet',
			title:keldan_lang_text('icecbrates'),
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('icecbrates').toUpperCase()
				}]
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg);
			}
		},
		bankrates : {
			name:'BankRatesPortlet',
			title:keldan_lang_text('depositrates'),
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('depositrates').toUpperCase()
				}]
			},
			item : {
					xtype:'tabpanel',
					listeners :{ 
						'tabchange' : function(tpanel,thetab) {
							pageTracker._trackEvent('DepositRates','TabOpen',thetab.title);
						}
					},
					activeTab:3,
					stateId:'fxtabpanel_'+Math.random()*1000,
					stateEvents:['tabchange'],
					getState : function() {
						return {
							activeTab:this.items.indexOf(this.getActiveTab())
						};
					},
					items:[{
						xtype:'BankRatesPortlet_Child',
						id:'br_a_'+Math.random()*100,
						category:'0A',
						title:'1 '+keldan_lang_text('million-short')
					},{
						xtype:'BankRatesPortlet_Child',
						id:'br_b_'+Math.random()*100,
						category:'0B',
						title:'10 '+keldan_lang_text('million-short')
					},{
						xtype:'BankRatesPortlet_Child',
						id:'br_c_'+Math.random()*100,
						category:'0C',
						title:'50 '+keldan_lang_text('million-short')
					},{
						xtype:'BankRatesPortlet_Child',
						id:'br_d_'+Math.random()*100,
						category:'0D',
						title:'100 '+keldan_lang_text('million-short'),
						loadMask:{msg:keldan_lang_text('loading'),removeMask:true}
					},{
						xtype:'BankRatesPortlet_Child',
						id:'br_e_'+Math.random()*100,
						category:'0E',
						title:keldan_lang_text('indexed')
					}]
				
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg,
						this.item);
			}
		},
		centralBankRates : {
			name:'ReiborPortlet',
			id:'reiborlibor_'+Math.random()*100,
			title:keldan_lang_text('interbankrates'),
			headerCfg:{
				tag:'div',
				cls:'x-panel-header',
				children:[{
					tag:'pre',
					cls:'header-text-title',
					html:keldan_lang_text('interbankrates').toUpperCase()
				}]
			},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg);
			}
		},
		currency : {
			name:'CP',
			title:keldan_lang_text('currencies'),
			en:'',
			headerCfg:{
			tag:'div',
			cls:'x-panel-header',
			children:[{
				tag:'pre',
				cls:'header-text-title',
				html:keldan_lang_text('currencies').toUpperCase()
			}/*,{
				tag:'div',
				cls:'reuters-logo'
			}*/]
			},
			footerCfg : {
				tag:'div',
				cls:'x-panel-footer',
				children:[{
					tag : 'div',
					cls:'reuters-logo'
				}]
			},
			item: {
				  xtype:'tabpanel',
				  listeners :{ 
						'tabchange' : function(tpanel,thetab) {
							pageTracker._trackEvent('Currencies','TabOpen',thetab.title);
						}
					},	
				  activeTab:0,
				  stateId:'fxtabpanel_'+Math.random()*1000,
				  stateEvents:['tabchange'],
				  getState : function() {
					return {
						activeTab:this.items.indexOf(this.getActiveTab())
					};
				  },
				  items:[       
				{
					xtype:'CP_Child'
					//id:'cp_'+Math.random()*100
				},{
					xtype:'FxMatrix'
					//id:'fxmatrix_'+Math.random()*100
				},{
					xtype:'ISCBFXGrid'
					//id:'iscbfx_'+Math.random()*100
				},{
					xtype:'ISCGrid'
					//id:'isc_'+Math.random()*100
				},{
					xtype:'Valitor'
					//id:'creditfx_'+Math.random()*100
				}]},
			startup : function() {
				var objMgr = Kelda.Info.ObjectMgr.getInstance();
				var desk = objMgr.get('main-desktop');
				desk.createPortlet(this.name,
						this.title,
						this.headerCfg,
						this.item);
			}
			},
			bensin : {
				name:'BensinPortlet',
				title:keldan_lang_text('bensin'),
				headerCfg:{
					tag:'div',
					cls:'x-panel-header',
					children:[{
						tag:'pre',
						cls:'header-text-title',
						html:keldan_lang_text('bensin')
					}]
				},
				item : {
						xtype:'tabpanel',
						activeTab:0,
						stateId:'bensintabpanel_'+Math.random()*1000,
						stateEvents:['tabchange'],
						getState : function() {
							return {
								activeTab:this.items.indexOf(this.getActiveTab())
							};
						},
						items:[{
							xtype:'BensinPortlet_Child',
							id:'ben_a_'+Math.random()*100,
							region:'city',
							title:'Rvk. ',
							loadMask:{msg:keldan_lang_text('loading'),removeMask:true}
						},{
							xtype:'BensinPortlet_Child',
							id:'ben_b_'+Math.random()*100,
							region:'south',
							title:'Suðurland '
						},{
							xtype:'BensinPortlet_Child',
							id:'ben_c_'+Math.random()*100,
							region:'east',
							title:'Austurland'
						},{
							xtype:'BensinPortlet_Child',
							id:'ben_d_'+Math.random()*100,
							region:'north',
							title:'Norðurland'
						},{
							xtype:'BensinPortlet_Child',
							id:'ben_e_'+Math.random()*100,
							region:'westfjords',
							title:'Vestfirðir'
						},{
							xtype:'BensinPortlet_Child',
							id:'ben_e_'+Math.random()*100,
							region:'west',
							title:'Vesturland'
						}]
				},
				startup : function() {
					var objMgr = Kelda.Info.ObjectMgr.getInstance();
					var desk = objMgr.get('main-desktop');
					desk.createPortlet(this.name,
							this.title,
							this.headerCfg,
							this.item);
				}
			},
			dm : {
				name:'DmPortlet',
				id:'reiborlibor_'+Math.random()*100,
				title:keldan_lang_text('ecosizescol'),
				headerCfg:{
					tag:'div',
					cls:'x-panel-header',
					children:[{
						tag:'pre',
						cls:'header-text-title',
						html:keldan_lang_text('ecosizescol')
					}]
				},
				startup : function() {
					var objMgr = Kelda.Info.ObjectMgr.getInstance();
					var desk = objMgr.get('main-desktop');
					desk.createPortlet(this.name,
							this.title,
							this.headerCfg);
				}
			},
		about : {
			name:'about',
			startup:function() {
				var win = Ext.getCmp('about-us-win');
				if(!win) {
					var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
					win = desktop.createWindow({
					id:'about-us-win',
					title:keldan_lang_text('aboutkeldan').toUpperCase(),
					name:keldan_lang_text('aboutkeldan'),
					manager:desktop.windows,
					bodyStyle:{
						'background-color':'white',
						color:'black'
					},
					maximizable:false,
					constrainHeader:true,
					width:520,
					height:410
				});
				win.load({
					url: window.location.protocol+"//"+window.location.hostname+"/"
					+basePath+"keldaconnect/getAboutUs?lang="+keldan_lang ,
					callback:function() {
						
					},
					scope: this, // optional scope for the callback
			        discardUrl: false,
			        nocache: false,
			        timeout: 30,
			        scripts: false
				});
				}
				win.setPosition(100,120);
				win.on('move',function(){
        			if(this.getPosition()[1] <= 108) {
        				this.suspendEvents();
        				this.setPosition(win.getPosition()[0],108);
        				this.resumeEvents();
        			}
        		},win);
				win.show();
			}
		}
			
		
		
	},
	registerXTypes : function() {
		var portletsMenuBtn = {
				id:'portletsMenuBtn'
		};
		for(var a in this.portlets) {
			//console.log(this.portlets[a].name);
			this.portletXTypes[this.portlets[a].name] = this.portlets[a];
			portletsMenuBtn[this.portlets[a].name] = false;
			
		}
		var objMgr = Kelda.Info.ObjectMgr.getInstance();
		objMgr.reg(portletsMenuBtn);
	},
	defaultPortlets : function() {
		//if( document.cookie.indexOf("ys-main-portal")<0) {
		if(keldan_lang=='is') {
			this.desktop.createPortlet(this.portlets['currency'].name,
					this.portlets['currency'].title,
					this.portlets['currency'].headerCfg,
					this.portlets['currency'].item,-1);
			this.desktop.createPortlet(this.portlets.news.name,
					this.portlets.news.title,
					this.portlets.news.headerCfg,
					this.portlets.news.item,1);
			this.desktop.createPortlet(this.portlets.bensin.name,
                	this.portlets.bensin.title,
                	this.portlets.bensin.headerCfg,
                	this.portlets.bensin.item,1);
			this.desktop.createPortlet(this.portlets.centralBankRates.name,
                	this.portlets.centralBankRates.title,
                	this.portlets.centralBankRates.headerCfg,
                	false,1);
			
			this.desktop.createPortlet(this.portlets.bonds.name,
					this.portlets.bonds.title,
					this.portlets.bonds.headerCfg,
					this.portlets.bonds.item,2);
			this.desktop.createPortlet(this.portlets.dm.name,
                	this.portlets.dm.title,
                	this.portlets.dm.headerCfg,false,2);
			this.desktop.createPortlet(this.portlets.stocks.name,
					this.portlets.stocks.title,
					this.portlets.stocks.headerCfg,
					this.portlets.stocks.item,0);
			this.desktop.createPortlet(this.portlets.bankrates.name,
                	this.portlets.bankrates.title,
                	this.portlets.bankrates.headerCfg,
                	this.portlets.bankrates.item);
			
			this.desktop.createPortlet(this.portlets.iceabroad.name,
                	this.portlets.iceabroad.title,
                	this.portlets.iceabroad.headerCfg,false,0);
			this.desktop.createPortlet(this.portlets.cbirates.name,
                	this.portlets.cbirates.title,
                	this.portlets.cbirates.headerCfg,false,0);
			
			
		}else {
			this.desktop.createPortlet(this.portlets['currency'].name,
					this.portlets['currency'].title,
					this.portlets['currency'].headerCfg,
					this.portlets['currency'].item);
			this.desktop.createPortlet(this.portlets.news.name,
					this.portlets.news.title,
					this.portlets.news.headerCfg,
					this.portlets.news.item,1);
			this.desktop.createPortlet(this.portlets.bonds.name,
					this.portlets.bonds.title,
					this.portlets.bonds.headerCfg,
					this.portlets.bonds.item,2);
			this.desktop.createPortlet(this.portlets.iceabroad.name,
                	this.portlets.iceabroad.title,
                	this.portlets.iceabroad.headerCfg,false,0);
			this.desktop.createPortlet(this.portlets.stocks.name,
					this.portlets.stocks.title,
					this.portlets.stocks.headerCfg,
					this.portlets.stocks.item,0);
			this.desktop.createPortlet(this.portlets.bankrates.name,
                	this.portlets.bankrates.title,
                	this.portlets.bankrates.headerCfg,
                	this.portlets.bankrates.item);
			this.desktop.createPortlet(this.portlets.centralBankRates.name,
                	this.portlets.centralBankRates.title,
                	this.portlets.centralBankRates.headerCfg,
                	false,2);
			this.desktop.createPortlet(this.portlets.cbirates.name,
                	this.portlets.cbirates.title,
                	this.portlets.cbirates.headerCfg,false,0);
			this.desktop.createPortlet(this.portlets.dm.name,
                	this.portlets.dm.title,
                	this.portlets.dm.headerCfg,
                	this.portlets.dm.item,1);
		}
			
		//}
		
	},
	displayIE6Warning : function() {
		alert("Athugið! Þú ert að nota Internet Explorer 6 sem er mjög gamall vafri." +
		"Keldan.is styður ekki þessa útgáfu. Keldan.is mælir með Google Chrome eða Mozilla Firefox.");
	},
	displayIE7Warning : function() {
		alert("Athugið! Þú ert að nota Internet Explorer 7 sem er gamall vafri." +
		"Virkni Keldunnar gæti skerst sökum þess. Keldan.is mælir með Google Chrome eða Mozilla Firefox. ");
	},
	onUnload : function(e) {
		if (this.fireEvent('beforeunload', this) === false) {
			e.stopEvent();
		}
	},
	initActions : function() {
		
		var toolbarWinManager = new Ext.WindowGroup();
		var objMgr = Kelda.Info.ObjectMgr.getInstance();
		objMgr.reg({
			id:'toolbox-win-manager',
			manager:toolbarWinManager
		});
		var loginlogout = new Kelda.Info.Action({
			id:'loginlogout',
			action:function(login,destroy,destroyallbutme_id) {
				var loginlink = Ext.get('keldan-login-link');
				var logoutlink = Ext.get('keldan-logout-link');
				var mykeldalink = Ext.get('keldan-mykelda-link');
				if(login) {
					if(loginlink)loginlink.hide(true);
					if(mykeldalink)mykeldalink.show(true);
					if(logoutlink)logoutlink.show(true);
					KeldanIn=true;
				}else {
					if(logout)logoutlink.hide(true);
					if(mykeldalink)mykeldalink.hide(true);
					if(loginlink)loginlink.show(true);
					KeldanIn=false;
				}
				if(destroyallbutme_id) {
					
					toolbarWinManager.each(function(win){
						//console.log('allbutme is '+destroyallbutme_id+' win.id is '+win.id);
						if(win.id!=destroyallbutme_id)
							win.destroy();
					});
				}
				if(destroy)
					toolbarWinManager.each(function(win){
						win.destroy();
					});
				
			}
		});
		objMgr.reg(loginlogout);
		var registerUser = new Kelda.Info.Action({
			id:'registerUser',
			action:function() {
    		var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
    		var win = new desktop.createStandAloneWin({
    			id:'keldan-user-register',
    			title:'User register',
    			name:'userreg',
    			manager:desktop.windows,	
    			layout:'fit',
    			width:Ext.get('main-portal').getComputedWidth(),
    			height:Ext.get('main-portal').getComputedHeight(),
    			//autoHeight:false,
    			items :[{
    				xtype:'iframepanel',
    				id: 'user_register_panel',
                    header:false,
                    defaultSrc :window.location.protocol+"//"+window.location.hostname+"/"+basePath+"registerUser"
                }]
    		});
    		win.show();
    		//win.alignTo(Ext.get('ux-taskbar-ribbon'),'tl-bl',[0,0]);
			}
		});
		objMgr.reg(registerUser);
		var fmr = this.buildToolbarAction('fmr',toolbarWinManager);
		objMgr.reg(fmr);
		var hlut = this.buildToolbarAction('hlutafelog',toolbarWinManager);
		objMgr.reg(hlut);
		var part = this.buildToolbarAction('thatttaka',toolbarWinManager);
		objMgr.reg(part);
		var legalpub = this.buildToolbarAction('legalpub',toolbarWinManager)
		objMgr.reg(legalpub);
		var thjodskra = this.buildToolbarAction('natreg',toolbarWinManager);
		objMgr.reg(thjodskra);
		var car = this.buildTabbedToolbarAction('cars',toolbarWinManager);
		objMgr.reg(car);
		var ars = this.buildToolbarAction('arsreikningar',toolbarWinManager);
		objMgr.reg(ars);
		var mykelda = new Kelda.Info.Action({
			id:'mykelda-action',
			action : function() {
				
				var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
				var win = Ext.getCmp('keldan-mykelda');
				if(win){win.show();return;}
				win = Ext.getCmp('keldan-mykelda');
				win = desktop.createStandAloneIWin({
					id:'keldan-mykelda',
					title:'Min Kelda',
					name:'mykelda',
					manager:toolbarWinManager,
					minimizable:false,
					layout:'fit',
					width:Ext.get('main-portal').getComputedWidth(),
					height:Ext.get('main-portal').getComputedHeight(),
					header:false,
					defaultSrc :window.location.protocol+"//"+window.location.hostname+"/"+basePath+"keldan/mykelda",
					listeners : {
						'documentloaded' : {
							fn : function(frameEl) {
								var lstat = frameEl.get('lstat');
								var objMgr = Kelda.Info.ObjectMgr.getInstance();
								if(lstat && lstat.getValue()=='1' && !KeldanIn) {
									objMgr.get('loginlogout').action(true,false,this.id);
								}
								else if((!lstat || lstat.getValue()!='1') && KeldanIn) {
									objMgr.get('loginlogout').action(false,true,null);
									Ext.getCmp('start-btn').toggle(true);
								}
							}
						}
					}
					//	autoHeight:false,
				
						
				
				});
				win.show();
			}
		});
		objMgr.reg(mykelda);
		var login =  new Kelda.Info.Action({
			id:'login-action',
			action:function() {
				//console.log('action, link is '+link);
				var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
				var win = Ext.getCmp('keldan-login-win');
				if(win && win.isVisible()) {
					win.hide();
					Ext.getCmp('start-btn').toggle(true);
					//win.show(Ext.get('ux-taskbar-ribbon'));
					return;
				}else if(win && !win.isVisible()) {
					win.show(Ext.get('ux-taskbar-ribbon'));
					return;
				}
				win = new desktop.createStandAloneWin({
    			 id:'keldan-login-win',
    			 //title:keldan_lang_text(idpostfix),
    			 header:false,
    			 name:'keldan-login-win',
    			 manager:toolbarWinManager,
    			 closable:false,
    			 resizable:true,
    			 draggable:false,
    			 //minimizable:false,
    			 maximized:true,
    			 layout:'fit',
    			width:Ext.get('main-portal').getComputedWidth(),
    			//height:Ext.get('main-portal').getComputedHeight(),
    			//autoHeight:true,
    			//autoHeight:false,
    			items :[{
    				xtype:'iframepanel',
    				id: 'keldan-login-win_panel',
                    header:false,
                    loadMask:true,
                    defaultSrc :window.location.protocol+"//"+window.location.hostname+'/user',
                    listeners : {
    					'domready' : {
    						fn : function(frameEl) {
    							var as = Ext.query('.profile',frameEl.getFrameDocument());
    							var objMgr = Kelda.Info.ObjectMgr.getInstance();
    							if(as && as.length > 0) {
    								objMgr.get('loginlogout').action(true,true);
    								//frameEl.remove();
    								win.destroy();
    								Ext.getCmp('start-btn').toggle(true);
    							}
    							/*else {
    								objMgr.get('loginlogout').action(false);
    								
    							}*/
    							
    						},
    						scope:this
    						
    					}
    				}
                }]
    		});
				win.on('beforeshow',function() {
					this.manager.hideAll();
					//mainp = Ext.getCmp('main-portal');
					//mainp.setVisibleChildren(false);
					Ext.getCmp('start-btn').toggle(false);
				});
				Ext.EventManager.onWindowResize(function(neww,newh){
					win.setWidth(neww);
					//win.setHeight(newh);
					win.alignTo(Ext.get('ux-taskbar-ribbon'),'tl-bl',[0,-10]);
				},win);
			
    		win.show();
    		win.alignTo(Ext.get('ux-taskbar-ribbon'),'tl-bl',[0,-10]);
			}
		});
		objMgr.reg(login);
		var logout = new Kelda.Info.Action({
			id:'mykelda-logout-action',
			action:function() {
				Ext.Ajax.request({
					disableCaching:false,
					url:window.location.protocol+"//"+window.location.hostname+"/"+basePath+"logout",
					params:{type:'ajax'},
					success : function() {
						objMgr.get('loginlogout').action(false,true);
						Kelda.Info.ObjectMgr.getInstance().get('toolbox-win-manager').manager.each(function(w) {
							if(w)
								w.destroy();
						});
						Ext.getCmp('start-btn').toggle(true);
						/*Ext.Msg.show({
						title:'Útskráning',
						msg:'Útskráning tókst',
						buttons:Ext.Msg.OK,
						icon:Ext.Msg.INFO
						});*/
    				},
    				failure : function() {
    					/*
    					Ext.Msg.show({
    						title:'Útskráning',
    						msg:'Útskráning mistókst, vinsamlegast endurhlaðið síðu.',
    						buttons:Ext.Msg.OK,
    						icon:Ext.Msg.INFO
    					});
    					*/
    				}
				});
			}	
		});
		objMgr.reg(logout);
	},
	buildToolbarAction : function(idpostfix,toolbarWinManager) {
		var act = new Kelda.Info.Action({
			id:idpostfix+'action',
			action:function(link) {
				var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
				var win = Ext.getCmp('keldan-'+idpostfix);
				if(win && link){
					win.get(0).setLocation((!Ext.isIE7 ? window.location.protocol+"//"+window.location.hostname+link:link));
					win.show(Ext.get('ux-taskbar-ribbon'));
					return;
				}else if(win) {
					win.show(Ext.get('ux-taskbar-ribbon'));
					return;
				}
				if(!link && !Ext.isIE7) 
					link = '/'+basePath+'keldan/'+idpostfix;
				else if(!link) {
					link = window.location.protocol+"//"+window.location.hostname+'/'+basePath+'keldan/'+idpostfix;
				}
				//alert('link is '+link);
				win = new desktop.createStandAloneIWin({
    			 id:'keldan-'+idpostfix,
    			 //title:keldan_lang_text(idpostfix),
    			 header:false,
    			 name:idpostfix,
    			 manager:toolbarWinManager,
    			 closable:false,
    			 resizable:true,
    			 draggable:false,
    			 //minimizable:false,
    			 maximized:true,
    			 //layout:'fit',
    			width:Ext.get('main-portal').getComputedWidth(),
    			header:false,
                defaultSrc :(!Ext.isIE7 ? window.location.protocol+"//"+window.location.hostname+link:link),
                //defaultSrc :'https://beta.keldan.is',
                listeners : {
					'documentloaded' : {
						fn : function(frameEl) {
							var lstat = frameEl.get('lstat');
							
							var objMgr = Kelda.Info.ObjectMgr.getInstance();
							if(lstat && lstat.getValue()=='1' && !KeldanIn) {
								objMgr.get('loginlogout').action(true,false,this.id);
								
							}
							else if((!lstat || lstat.getValue()!='1') && KeldanIn) {
								//objMgr.get('loginlogout').action(false,false,null);
								//console.log('Is logged in : '+KeldanIn);
								//console.log(lstat);
								objMgr.get('loginlogout').action(false,true,null);
								Ext.getCmp('start-btn').toggle(true);
								
							}
							
							var as = Ext.query('.keldan-redir',frameEl.getFrameDocument());
							for(i=0,ii=as.length;i<ii;i++) {
								var d = as[i];
								var el = Ext.get(d);
								//console.log(Ext.get(d));
								if(el) {
									el.on('click',function(e){
										e.stopEvent();
										var href = this.dom.getAttribute('href');
										var splits = href.split('/',10);
										if(splits.length < 1) {
											return false;
										}
										var type = splits[2];
										if(Ext.isIE7)
											type = splits[4];
										var objMgr = Kelda.Info.ObjectMgr.getInstance();
										//console.log('type is '+type+' href '+href);
										var act = objMgr.get(type+'action');
										if(act) {
											var btn = Ext.getCmp(type+'-btn');
											if(btn) {
												btn.toggle(true,true);
												btn.getEl().replaceClass('keldanmenu-toolbox-btn-normal','keldanmenu-toolbox-btn-pressed');
												var mybtn = Ext.getCmp(idpostfix+'-btn');
												mybtn.toggle(false);
												act.action(href);
												
											}//else 
												//console.log('no button');
										}
										//else console.log('no act');
										return false;
									},el);
								}
							}
						},
						scope:win
					},
					'domready' : {
						fn : function(frameEl) {
							var as2 = Ext.query('.profile',frameEl.getFrameDocument());
							if(as2 && as2.length > 0) {
								frameEl.setSrc();
							}
						}	
					},
					scope:win
					
				}
    			
    		});
				win.on('beforeshow',function() {
					//var p = Ext.getCmp(idpostfix+'_panel');
					//if(p)
					//	p.setLocation();
					this.manager.hideAll();
					mainp = Ext.getCmp('main-portal');
					mainp.setVisibleChildren(false);
					var pwin = Ext.getCmp('pricelist-win'); 
					if(pwin)pwin.destroy();
				});
				Ext.EventManager.onWindowResize(function(neww,newh){
					win.setWidth(neww);
					//win.setHeight(newh);
					win.alignTo(Ext.get('ux-taskbar-ribbon'),'tl-bl',[0,-10]);
				},win);
			
    		win.show();
    		win.alignTo(Ext.get('ux-taskbar-ribbon'),'tl-bl',[0,-10]);
			}
		});
		return act;
	},
	buildTabbedToolbarAction : function(idpostfix,toolbarWinManager) {
		var act = new Kelda.Info.Action({
			id:idpostfix+'action',
			action:function(links) {
				var win = Ext.getCmp('keldan-'+idpostfix);
				if(win) {
					win.show(Ext.get('ux-taskbar-ribbon'));
					return;
				}
				items = [];
				for(i=0;i<links.length;i++) {
					items[i] = {
		    				 xtype:'iframepanel',
		    				 id:'iframep_'+links[i].type,
		    				 title:links[i].title,
		        			 name:idpostfix,
		        			 lIn:false,
		        			 defaultSrc :window.location.protocol+"//"+window.location.hostname+links[i].url,
		                    //defaultSrc :'https://beta.keldan.is',
		                    listeners : {
		    					'documentloaded' : {
		    						fn : function(frameEl) {
		    							//alert('document loaded');
		    							var lstat = frameEl.get('lstat');
		    							var objMgr = Kelda.Info.ObjectMgr.getInstance();
		    							if(lstat && lstat.getValue()=='1' && !KeldanIn) {
		    								objMgr.get('loginlogout').action(true,false,'keldan-'+idpostfix);
		    								
		    							}
		    							else if((!lstat || lstat.getValue()!='1') && KeldanIn) {
		    								//objMgr.get('loginlogout').action(false,false,null);
		    								//console.log('Is logged in : '+KeldanIn);
		    								//console.log(lstat);
		    								
		    								objMgr.get('loginlogout').action(false,true,null);
		    								Ext.getCmp('start-btn').toggle(true);
		    								
		    							}
		    							this.lIn = KeldanIn;
		    							var as = Ext.query('.keldan-redir',frameEl.getFrameDocument());
		    							//alert('got as ');
		    							for(i=0,ii=as.length;i<ii;i++) {
		    								var d = as[i];
		    								var el = Ext.get(d);
		    								//console.log(Ext.get(d));
		    								
		    								if(el) {
		    									
		    									el.on('click',function(e){
		    										
		    										e.stopEvent();
		    										
		    										var href = this.dom.getAttribute('href');
		    										var splits = href.split('/',10);
		    										if(splits.length < 1) {
		    											return false;
		    										}
		    										var type = splits[2];
		    										if(Ext.isIE7)
		    											type = splits[4];
		    										var objMgr = Kelda.Info.ObjectMgr.getInstance();
		    										//console.log('type is '+type+' href '+href);
		    										var act = objMgr.get(type+'action');
		    										
		    										for(k=0,kk=links.length;k<kk;k++) {
		    											
		    											if(links[k].type==type) {
		    												//alert('My link is '+window.location.protocol+"//"+window.location.hostname+href);
		    												//this.ownerCt.setTab(type,'');
		    												//alert('got type');
		    												Ext.getCmp('iframep_'+type)
		    												.ownerCt.setTab(type,
		    														(!Ext.isIE7?window.location.protocol+"//"+window.location.hostname+href:href));
		    												return false;
		    											}
		    										}
		    										
		    										if(act) {
		    											var btn = Ext.getCmp(type+'-btn');
		    											if(btn) {
		    												btn.toggle(true,true);
		    												btn.getEl().replaceClass('keldanmenu-toolbox-btn-normal','keldanmenu-toolbox-btn-pressed');
		    												var mybtn = Ext.getCmp(idpostfix+'-btn');
		    												mybtn.toggle(false);
		    												act.action(href);
		    												
		    											}//else 
		    												//console.log('no button');
		    										}
		    										//else console.log('no act');
		    										return false;
		    									},el);
		    								}
		    							}
		    						}
		    						//scope:this
		    					},
		    					'domready' : {
		    						fn : function(frameEl) {
		    							var as2 = Ext.query('.profile',frameEl.getFrameDocument());
		    							if(as2 && as2.length > 0) {
		    								frameEl.setSrc();
		    							}
		    						}	
		    					}
		    					//scope:win
		    					
		    				}
		    			 };
				
				}
				
				var desktop = Kelda.Info.ObjectMgr.getInstance().get('main-desktop');
				var win = new desktop.createStandAloneWin({
    			 id:'keldan-'+idpostfix,
    			 width:Ext.get('main-portal').getComputedWidth(),
    			 manager:toolbarWinManager,
    			 closable:false,
    			 resizable:true,
    			 draggable:false,
    			 //minimizable:false,
    			 maximized:true,
    			 layout:'fit',
    			header:false,
                loadMask:true,
    			 items:[{
    				 xtype:'tabpanel',
        			 activeTab:0,
        			 items : items,
        			 listeners : {
    				 	'tabchange' : {
    				 		fn : function(tp,p) {
    				 			if(p.lIn!=KeldanIn) {
    				 				p.setSrc();
    				 			}
    			 			}
    			 		}
    			 	 },
    			 	 setTab : function(type,url) {
    			 		 //alert('setting tab');
    			 		 var t = this.get('iframep_'+type);
    			 		 if(t) {
    			 			 this.activate(t);
    			 			t.setSrc(url);
    			 		 }
    			 	 }
    			 }]
				});
				
				win.on('beforeshow',function() {
					//var p = Ext.getCmp(idpostfix+'_panel');
					//if(p)
					//	p.setLocation();
					this.manager.hideAll();
					mainp = Ext.getCmp('main-portal');
					mainp.setVisibleChildren(false);
					var pwin = Ext.getCmp('pricelist-win'); 
					if(pwin)pwin.destroy();
				});
				Ext.EventManager.onWindowResize(function(neww,newh){
					win.setWidth(neww);
					//win.setHeight(newh);
					win.alignTo(Ext.get('ux-taskbar-ribbon'),'tl-bl',[0,-10]);
				},win);
			
    		win.show();
    		win.alignTo(Ext.get('ux-taskbar-ribbon'),'tl-bl',[0,-10]);
				
			}
		});
		return act;
	}
});
Ext.override(Ext.grid.ColumnModel, {
    destroy : function(){
        for(var i = 0, len = this.config.length; i < len; i++){
            Ext.destroy(this.config[i]);
        }
        this.purgeListeners();
    }
});

Ext.override(Ext.menu.Item, {
    onRender : function(container, position){
        if (!this.itemTpl) {
            this.itemTpl = Ext.menu.Item.prototype.itemTpl = new Ext.XTemplate(
                '<a id="{id}" class="{cls}" hidefocus="true" unselectable="on" href="{href}"',
                    '<tpl if="hrefTarget">',
                        ' target="{hrefTarget}"',
                    '</tpl>',
                 '>',
                     '<img src="{icon}" class="x-menu-item-icon {iconCls}"/>',
                     '<span class="x-menu-item-text">{text}</span>',
                 '</a>'
             );
        }
        var a = this.getTemplateArgs();
        this.el = position ? this.itemTpl.insertBefore(position, a, true) : this.itemTpl.append(container, a, true);
        this.iconEl = this.el.child('img.x-menu-item-icon');
        this.textEl = this.el.child('.x-menu-item-text');
        if (this.tooltip) {
            this.tooltip = new Ext.ToolTip(Ext.apply({
                target: this.el
            }, (this.tooltip && typeof this.toolip == 'object' )? this.toolTip : { html: this.tooltip }));
        }
        Ext.menu.Item.superclass.onRender.call(this, container, position);
    },
    getTemplateArgs: function() {
		var result = {
				//id: this.id,
				cls: this.itemCls + (this.menu ?  ' x-menu-item-arrow' : '') + (this.cls ?  ' ' + this.cls : ''),
				href: this.href || '#',
				tooltip: this.tooltip,
				hrefTarget: this.hrefTarget,
				icon: this.icon || Ext.BLANK_IMAGE_URL,
				iconCls: this.iconCls || '',
				text: this.itemText || this.text || ' '
				};
		return result;
	}
});
//For IE8 to stop it drawing the search field in the wrong spot
Ext.override(Ext.form.TwinTriggerField, {
    afterRender: function() {
        Ext.form.TwinTriggerField.superclass.afterRender.call(this);
        if (Ext.isIE && !this.hideTrigger) {
            this.el.position();  
            this.el.applyStyles("top: 1px;");
        } 
    }
});
Ext.Panel.prototype.afterRender = Ext.Panel.prototype.afterRender.createInterceptor(

        function() {
		this.body.dom.style.cursor='default';	
	        if (this.autoScroll) {
		
		            this.body.dom.style.position = 'relative';
			    
			            }
				    
}); 
Ext.override(Ext.ToolTip, {
    onTargetOver : function(e){
        if(this.disabled || e.within(this.target.dom, true)){
            return;
        }
        var t = e.getTarget(this.delegate);
        if (t) {
            this.triggerElement = t;
            this.clearTimer('hide');
            this.targetXY = e.getXY();
            this.delayShow();
        }
    },
    onMouseMove : function(e){
        var t = e.getTarget(this.delegate);
        if (t) {
            this.targetXY = e.getXY();
            if (t === this.triggerElement) {
                if(!this.hidden && this.trackMouse){
                    this.setPagePosition(this.getTargetXY());
                }
            } else {
                this.hide();
                this.lastActive = new Date(0);
                this.onTargetOver(e);
            }
        } else if (!this.closable && this.isVisible()) {
            this.hide();
        }
    },
    hide: function(){
        this.clearTimer('dismiss');
        this.lastActive = new Date();
        delete this.triggerElement;
        Ext.ToolTip.superclass.hide.call(this);
    }
});
Ext.grid.GridView.override({
    
    syncFocus : false,
    
    removeRow : function(row){
        Ext.removeNode(this.getRow(row));
        this.syncFocusEl(row);
    },
    removeRows : function(firstRow, lastRow){
        var bd = this.mainBody.dom;
        for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
            Ext.removeNode(bd.childNodes[firstRow]);
        }
        this.syncFocusEl(firstRow);
    },
    insertRows : function(dm, firstRow, lastRow, isUpdate){
        if(!isUpdate && firstRow === 0 && lastRow == dm.getCount()-1){
            this.refresh();
        }else{
            if(!isUpdate){
                this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
            }
            var html = this.renderRows(firstRow, lastRow);
            var before = this.getRow(firstRow);
            if(before){
                Ext.DomHelper.insertHtml('beforeBegin', before, html);
            }else{
                Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html);
            }
            if(!isUpdate){
                this.fireEvent("rowsinserted", this, firstRow, lastRow);
                this.processRows(firstRow);
            }
        }
        this.syncFocusEl(firstRow);
    },
    onDataChange : function(){
        this.refresh();
        this.updateHeaderSortState();
        this.syncFocusEl(0);
    },
    onClear : function(){
        this.refresh();
        this.syncFocusEl(0);
    },
    focusCell : function(row, col, hscroll){
        this.syncFocusEl(row, col, hscroll, true)
        if(Ext.isGecko){
            this.focusEl.focus();
        }else{
            this.focusEl.focus.defer(1, this.focusEl);
        }
    },
    syncFocusEl : function(row, col, hscroll, /*private*/ force){
        if(force || this.syncFocus){
            row = Math.min(row, Math.max(0, this.getRows().length-1));
            var xy = this.ensureVisible(row, col, hscroll);
            this.focusEl.setXY(xy||this.scroller.getXY());
        }
    }
});
