/**
 * Main system class, get some login information and shows the login window
 * or init the desktop and load all module files.
 */
Ext.ns('Uwd');
Uwd.System = function() {
	/**
	 * on window close
	 */
	Ext.get(document).on('unload', function() {
		//alert('weg bist du');									 
	});									 
											 
											 
	
	
	
	/**
	 * setup quick tips and place form errors globally
	 */
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
	Ext.Ajax.timeout = 300000;
	/**
	 * set the default backend url and some internal properties of Uwd.System
	 */
	var config = {
		backendUrl: '../jsonInterface.php',
		isLoading: false,
		isLoggedIn: null,
		config: null,
		desktop: null,
		user: null,
		autostart : null,
		desktopIcons : null,
		login: null
	};
	
	Ext.apply(this, config);
    // call parent constructor
	Uwd.System.superclass.constructor.call(this);
	this.isFisheye = null;
	this.programs = null;
	this.allowedLanguages = null;

};

Ext.extend(Uwd.System, Ext.util.Observable, {
	
	/**
	 * Method init wich is called from Ext.onReady, to found in index.php
	 */
	init : function() {
		// set up the main loading mask
		this.mask = new Uwd.System.LoadMask();
		this.mask.show();
		// call config request
		this.requestConfig();
		this.requestSystemLanguage();
		this.requestLoginLanguage();
		// is logged in?
		this.requestLoggedIn();
		
		
		// wait till isLoggedIn is loaded
		var timer;
		var f = function(){
			if(this.isLoading === false && this.isLoggedIn !== null && (Uwd.System.SystemLanguage && Uwd.System.LoginLanguage)) { // done login loading
				window.clearInterval(timer);
				// if the user is logged in go on in application loading
				if (this.isLoggedIn === true) {
					this.buildDesktop();
				// else show the login form and hide the mask
				} else {
					this.mask.hide();
					this.login = new Uwd.System.Login();
					this.login.show();
				}
				return false;
			}
		}.createDelegate(this);
		timer = window.setInterval(f, 200);
	},
	
	/**
	 * Build the desktop
	 */
	buildDesktop : function() {
		Ext.get('loginForm').remove();
		
		Ext.get('x-desktop').removeClass('x-hidden');
				
		this.requestPrograms();
		this.requestDesktopIcons();
		this.requestAutostart();
		
		var timer;
		var f = function(){
			if(this.isLoading === false && this.programs !== null && this.user !== null && this.userDetails !== null && this.isFisheye !== null) { // done login loading
				window.clearInterval(timer);
				// if the user is logged in go on in application loading

				
				this.desktop = new Uwd.System.Desktop();
				
				this.fisheyeMenu = new Uwd.System.Fisheye();
				this.fisheyeMenu.initStartmenu();
	
				this.programMenu = new Uwd.System.Startmenu();
				this.programMenu.initStartmenu();
				
				if (this.isFisheye == true) {
					// do osx startmenu
					this.setFisheyeMenu();
				} else {
					// do windows startmenu
					this.setProgramMenu();
				}
				this.mask.hide();
			}
		}.createDelegate(this);
		timer = window.setInterval(f, 200);
	},
	
	getUser : function() {
		return this.user;
	},
	
	getUserDetails : function() {
		return this.userDetails;
	},
	
	/**
	 * Returns the desktop object
	 */
	getDesktop : function() {
		return this.desktop;
	},
	
	getTheme : function() {
		return 'default';	
	},
	
	/**
	 * Returns the backend url
	 */
	getBackendUrl : function() {
		if (this.config !== null) {
			// just return it
			return this.config.getBackendUrl();
		}
		return this.backendUrl;	
	},
	
	/**
	 * Returns the config object
	 */
	getConfigObject : function() {
		return this.config;	
	},
	
	/**
	 * Does a login request
	 * and stores the result in this.isLoggedIn
	 */
	requestLoggedIn : function() {
		// if the value is already loaded
		if (this.isLoggedIn !== null) {
			// just return it
			return this.isLoggedIn;
		}
		
		var doRequest = function() {
			this.isLoading = true;
			this.mask.setText('check login');
			// do the request
			Ext.Ajax.request({
				url: this.getBackendUrl(),
				method:'post',
				params: {
					controller: 'System',
					basePath: 'system/',
					action: 'getLoggedIn'
				},
				scope: this,
				success: function (result, request) { 
					var jsonData = Ext.decode(result.responseText);
					// if not logged in
					this.isLoading = false;
					if (jsonData.success === false) {
						// show form
						this.isLoggedIn = false;
					} else {
						// set this.loggedIn on true for every call after
						this.user = new Uwd.System.User(jsonData.data.user);
						this.isFisheye = jsonData.data.user.menuType;
						this.userDetails = new Uwd.System.UserDetails(jsonData.data.details);
						// test for ie6 crashes
						/*alert('ok, ie6 is not crashed');
						return;
						// here it is the shit*/
						if (!Ext.isIE6) {
							this.loadExtLanguage(jsonData.data.details.defaultLanguage);
						}
						this.setTheme(jsonData.data.themeName);
						this.isLoggedIn = true;
					}
					// set loading on false
				}.createDelegate(this),
				failure: function (result, request) { 
					// set this.loggedIn on false for every call after
					this.isLoading = false;
					this.requestSystemLanguage();
					this.requestLoginLanguage();
				}.createDelegate(this) 
			});
		}.createDelegate(this);
		
		// if the value is unloaded and loading the call is still unprocessing
		if (this.isLoading === false) {
			// system now is loading some data from backend
			doRequest();
		} else {
			var timer;
			var f = function(){
				if(this.isLoading === false){ // done loading
					window.clearInterval(timer);
					doRequest();
				}
			}.createDelegate(this);
			timer = window.setInterval(f, 200);
		}
	},
	
	/**
	 * Get the config from backend
	 * and set up Uwd.System.Config object with this data
	 */
	requestConfig : function() {
		// if the value is already loaded
		if (this.config !== null) {
			// just return it
			return this.config;
		}
		
		var doRequest = function() {
			this.isLoading = true;
			this.mask.setText('read configuration');
			Ext.Ajax.request({
				url: this.getBackendUrl(),
				method:'post',
				params: {
					controller: 'System',
					basePath: 'system/',
					action: 'getConfig'
				},
				scope: this,
				success: function (result, request) { 
					var jsonData = Ext.decode(result.responseText);
					// if not logged in
					if (jsonData.success === false) {
						// show form
						this.config = null;
					} else {
						// set this.loggedIn on true for every call after
						this.config = new Uwd.System.Config(jsonData.data);
						this.loadExtLanguage(jsonData.data.UWD_DEFAULT_LANGUAGE);
						this.allowedLanguages = jsonData.data.UWD_ALLOWED_LANGUAGES;
					}
					this.isLoading = false;
					// set loading on false
				}.createDelegate(this),
				failure: function (result, request) { 
					// set this.loggedIn on true for every call after
					this.isLoading = false;
					Ext.MessageBox.alert(Uwd.System.SystemLanguage.error, Uwd.System.SystemLanguage.connectionError);
				}.createDelegate(this) 
			});
		}.createDelegate(this);
		
		// if the value is unloaded and loading the call is still unprocessing
		if (this.isLoading === false) {
			// system now is loading some data from backend
			doRequest();
			// do the request
		} else {
			var timer;
			var f = function(){
				if(this.isLoading === false){ // done loading
					window.clearInterval(timer);
					doRequest();
				}
			}.createDelegate(this);
			timer = window.setInterval(f, 200);
		}
	},
	
	/**
	 * Get the config from backend
	 * and set up Uwd.System.Config object with this data
	 */
	requestSystemLanguage : function() {
		// if the language is already loaded
		if (Uwd.System.SystemLanguage) {
			// just return
			return;
		}
		
		var doRequest = function() {
			this.isLoading = true;
			this.mask.setText('load system language');
			Ext.Ajax.request({
				url: this.getBackendUrl(),
				method:'post',
				params: {
					controller: 'System',
					basePath: 'system/',
					action: 'getFrontendSystemLanguage'
				},
				scope: this,
				success: function (result, request) { 
					var jsonData = Ext.decode(result.responseText);
					
					if (jsonData.success === true) {
						Uwd.System.SystemLanguage = jsonData.data;
						if (Ext.ux.grid.Search) {
							Ext.ux.grid.Search.searchText = Uwd.System.SystemLanguage.gridSearch;	
						}
						//this.loadAdditionalScripts();
					} else {
						Uwd.System.SystemLanguage = null;
					}
					
					
					this.isLoading = false;
					// set loading on false
				}.createDelegate(this),
				failure: function (result, request) { 
					// set this.loggedIn on true for every call after
					this.isLoading = false;
					Ext.MessageBox.alert(Uwd.System.SystemLanguage.error, Uwd.System.SystemLanguage.connectionError);
				}.createDelegate(this) 
			});
		}.createDelegate(this);
		
		// if the value is unloaded and loading the call is still unprocessing
		if (this.isLoading === false) {
			// system now is loading some data from backend
			doRequest();
		} else {
			// wait till current load is over
			var timer;
			var f = function(){
				if(this.isLoading === false){ // done loading
					window.clearInterval(timer);
					doRequest();
				}
			}.createDelegate(this);
			timer = window.setInterval(f, 200);
		}
	},
	
	/**
	 * Get the config from backend
	 * and set up Uwd.System.Config object with this data
	 */
	requestLoginLanguage : function() {
		// if the language is already loaded
		if (Uwd.System.LoginLanguage) {
			// just return
			return;
		}
		
		var doRequest = function() {
			this.isLoading = true;
			this.mask.setText('load system language');
			Ext.Ajax.request({
				url: this.getBackendUrl(),
				method:'post',
				params: {
					controller: 'System',
					basePath: 'system/',
					action: 'getFrontendLoginLanguage'
				},
				scope: this,
				success: function (result, request) { 
					var jsonData = Ext.decode(result.responseText);
					
					if (jsonData.success === true) {
						Uwd.System.LoginLanguage = jsonData.data;
					} else {
						Uwd.System.LoginLanguage = null;
					}
					
					
					this.isLoading = false;
					// set loading on false
				}.createDelegate(this),
				failure: function (result, request) { 
					// set this.loggedIn on true for every call after
					this.isLoading = false;
					Ext.MessageBox.alert(Uwd.System.SystemLanguage.error, Uwd.System.SystemLanguage.connectionError);
				}.createDelegate(this) 
			});
		}.createDelegate(this);
		
		// if the value is unloaded and loading the call is still unprocessing
		if (this.isLoading === false) {
			// system now is loading some data from backend
			doRequest();
		} else {
			// wait till current load is over
			var timer;
			var f = function(){
				if(this.isLoading === false){ // done loading
					window.clearInterval(timer);
					doRequest();
				}
			}.createDelegate(this);
			timer = window.setInterval(f, 200);
		}
	},
	
	/**
	 * Get allowed programs of this user
	 */
	requestPrograms : function() {
		// if the value is already loaded
		if (this.programs !== null) {
			// just return it
			return this.programs;
		}
		
		var doRequest = function() {
			this.isLoading = true;
			this.mask.setText('load program permissions');
			// do the request
			Ext.Ajax.request({
				url: this.getBackendUrl(),
				method:'post',
				params: {
					controller: 'System',
					basePath: 'system/',
					action: 'getPrograms'
				},
				scope: this,
				success: function (result, request) { 
					var jsonData = Ext.decode(result.responseText);
					// if not logged in
					this.isLoading = false;
					if (jsonData.success === true) {
						// set this.loggedIn on true for every call after
						this.programs = jsonData.data;
						Uwd.System.ProgramStack.init(this.programs);
					}
					// set loading on false
				}.createDelegate(this),
				failure: function (result, request) { 
					// set this.loggedIn on false for every call after
					this.isLoading = false;
					Ext.MessageBox.alert(Uwd.System.SystemLanguage.error, Uwd.System.SystemLanguage.connectionError);
				}.createDelegate(this) 
			});
		}.createDelegate(this);
		
		// if the value is unloaded and loading the call is still unprocessing
		if (this.isLoading === false) {
			// system now is loading some data from backend
			doRequest();
		} else {
			var timer;
			var f = function(){
				if(this.isLoading === false){ // done loading
					window.clearInterval(timer);
					doRequest();
				}
			}.createDelegate(this);
			timer = window.setInterval(f, 200);
		}
	},
	
	/**
	 * Get autostart programs of this user
	 */
	requestAutostart : function() {
		// if the value is already loaded
		if (this.autostart !== null) {
			// just return it
			return this.autostart;
		}
		
		var doRequest = function() {
			this.isLoading = true;
			this.mask.setText('get autostart programs');
			// do the request
			Ext.Ajax.request({
				url: this.getBackendUrl(),
				method:'post',
				params: {
					controller: 'System',
					basePath: 'system/',
					action: 'getAutostart'
				},
				scope: this,
				success: function (result, request) { 
					var jsonData = Ext.decode(result.responseText);
					// if not logged in
					this.isLoading = false;
					if (jsonData.success === true) {
						// set this.loggedIn on true for every call after
						this.autostart = jsonData.data;
						Ext.each(this.autostart, function(id) {
							var prog = Uwd.System.ProgramStack.getProgramById(id);
							if (prog !== null) {
								
								var desk = this.getDesktop();
								if (desk !== null) {
									prog.openWindow();									
								} else {
									var timer;
									var f = function(){
										desk = this.getDesktop();
										if(desk !== null){ // done loading
											window.clearInterval(timer);
											prog.openWindow();
										}
									}.createDelegate(this);
									timer = window.setInterval(f, 100);
								}
							}
						}.createDelegate(this));
					}
					// set loading on false
				}.createDelegate(this),
				failure: function (result, request) { 
					// set this.loggedIn on false for every call after
					this.isLoading = false;
					Ext.MessageBox.alert(Uwd.System.SystemLanguage.error, Uwd.System.SystemLanguage.connectionError);
				}.createDelegate(this) 
			});
		}.createDelegate(this);
		
		// if the value is unloaded and loading the call is still unprocessing
		if (this.isLoading === false) {
			// system now is loading some data from backend
			doRequest();
		} else {
			var timer;
			var f = function(){
				if(this.isLoading === false){ // done loading
					window.clearInterval(timer);
					doRequest();
				}
			}.createDelegate(this);
			timer = window.setInterval(f, 200);
		}
	},
	
	getAutostartIds : function() {
		return this.autostart;	
	},
	
	setAutostartIds : function(ids) {
		this.autostart = ids;
		return true;
	},
	
	setTheme : function() {
		var fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("id", "changeStyleSheet");
		fileref.setAttribute("href", './themes/' + this.user.getThemeName() + '/css/' + this.user.getThemeName() + '.css');
		document.getElementById('changeStyleSheet').parentNode.replaceChild(fileref, document.getElementById('changeStyleSheet'));		
	},
	
	/**
	 * Get desktop icons of this user
	 */
	requestDesktopIcons : function() {
		// if the value is already loaded
		if (this.desktopIcons !== null) {
			// just return it
			return this.desktopIcons;
		}
		
		var doRequest = function() {
			this.isLoading = true;
			this.mask.setText('get autostart programs');
			// do the request
			Ext.Ajax.request({
				url: this.getBackendUrl(),
				method:'post',
				params: {
					controller: 'System',
					basePath: 'system/',
					action: 'getDesktopIcons'
				},
				scope: this,
				success: function (result, request) { 
					var jsonData = Ext.decode(result.responseText);
					// if not logged in
					this.isLoading = false;
					if (jsonData.success === true) {
						// set this.loggedIn on true for every call after
						this.desktopIcons = jsonData.data;
						if (this.desktop) {
							this.desktop.setUpDeskButtons(this.desktopIcons);	
						} else {
							
							var timer;
							var f = function(){
								if(this.desktop) { // done login loading
									window.clearInterval(timer);
									this.desktop.setUpDeskButtons(this.desktopIcons);	
								}
							}.createDelegate(this);
							timer = window.setInterval(f, 200);
						}
					}
					// set loading on false
				}.createDelegate(this),
				failure: function (result, request) { 
					// set this.loggedIn on false for every call after
					this.isLoading = false;
					Ext.MessageBox.alert(Uwd.System.SystemLanguage.error, Uwd.System.SystemLanguage.connectionError);
				}.createDelegate(this) 
			});
		}.createDelegate(this);
		
		// if the value is unloaded and loading the call is still unprocessing
		if (this.isLoading === false) {
			// system now is loading some data from backend
			doRequest();
		} else {
			var timer;
			var f = function(){
				if(this.isLoading === false){ // done loading
					window.clearInterval(timer);
					doRequest();
				}
			}.createDelegate(this);
			timer = window.setInterval(f, 200);
		}
	},
	
	getDesktopIconIds : function() {
		return this.desktopIcons;	
	},
	
	setDesktopIconIds : function(ids) {
		this.desktopIcons = ids;
		this.desktop.setUpDeskButtons(this.desktopIcons);
		return true;
	},
	
	getAllowedLanguages : function() {
		return this.allowedLanguages;
	},
	
	isAllowdLanguage : function(l) {
		var ret = false;
		Ext.each(this.allowedLanguages, function(lang) {
			if (lang[0] === l) {
				ret = true;	
			}
		});
		
		return ret;
	},
	
	loadExtLanguage : function(lang) {
		//lang = lang.substring(0, 2);
		var extLocaleFile = './ext-3.0.0/src/locale/ext-lang-' + lang + '.js';
		var scriptTag = window.document.createElement('script');
		scriptTag.setAttribute('language', 'javascript');
		scriptTag.setAttribute('type', 'text/javascript');
		scriptTag.setAttribute('src', extLocaleFile);
		window.document.getElementsByTagName('head')[0].appendChild(scriptTag);
	},
	
	/**
	 * Returns the loading state of Uwd.System
	 */
	isLoading : function() {
		return this.isLoading === true;	
	},
	
	setFisheyeMenu : function() {
		Ext.get('x-windows').addClass('x-hidden');
		Ext.get('dock2').removeClass('x-hidden');
		/*Ext.get('dock2').setHeight(50);
		Ext.get('x-windows').setHeight(3);*/
		this.startmenu = this.fisheyeMenu;
	},
	
	setProgramMenu : function() {
		Ext.get('dock2').addClass('x-hidden');
		Ext.get('x-windows').removeClass('x-hidden');
		/*Ext.get('dock2').setHeight(0);
		Ext.get('x-windows').setHeight(30);*/
		this.startmenu = this.programMenu;
	},
	
	showUser : function(id) {
		alert('show user details of user id ' + id);	
	}
	
});

