/**
 * @fileoverview
 * Atoolo - Cynapsis Kommunikationsagentur
 * @author Holger Veltrup
 * @version 0.9.3
 */

/**
 * Konstruktor
 * @class
 * AtooloDesktop bildet die oberste Klasse von Atoolo. Hier enthalten ist die {@link AtooloDesktop#main}-Methode,
 * die von <code>&lt;body onload=".." ..&gt;</code> aufgerufen wird um den Desktop zu starten.
 */
function AtooloDesktop() {
	AtooloDesktop.instance = this;
}

AtooloDesktop = {

	/**
	 * Session Id;
	 * @private
	 */
	sessionId: null,

///**
// * Atoolo Konfiguration
// * @private
// */
//	config: null,

/**
 * Atoolo Desktop Umgebung des Nutzers
 * @private
 */
	environment: null,

/**
 * Atoolo Desktop Notifier
 * @private
 */
	notifier: null,

/**
 * Atoolo Desktop Window-Manager
 * @private
 */
	windowManager: null,

///**
// * Atoolo Desktop Notifier
// * @private
// */
//	loadingBar: null,

/**
 * Atoolo Desktop login
 * @private
 */
	loginWindow: null,

/**
 * Atoolo Desktop registration
 * @private
 */
	registrationWindow: null,

/**
 * Atoolo Startmenue
 * @private
 */
	startMenu: null,

/**
 * Atoolo Icons
 * @private
 */
	icons: [],

/**
 * BestFit-Berechnung
 * @private
 */
	bgOffsetWidth: null,
	bgOffsetHeight: null,


/**
 * Atoolo Debug-Level
 * @private
 */
	debug: 0,

/**
 * Cobranding
 * @private
 */
	isSpec: false,

/**
 * Variablen fuer Dragging von DesktopIcons
 * @private
*/
	actIcon: null,
	actIconPosX: null,
	actIconPosY: null,
	iconDragging: false,

/**
 * Liefert die Desktop-Instanz
 * @return Desktop-Instanz
 * @type AtooloDesktop
 */
	getInstance: function () {
		return AtooloDesktop;
	},

/**
 * Einstiegspunkt fuer atoolo. Nach Aufruf diese Methode wird der Desktop gestartet
 * @param {JSONObject} parameter Uebergabe-Parameter fuer den Desktop. Das <code>parameter</code>-Objekt
 *	hat folgende Struktur:<br>
 *	<pre>
 *		{<br>
 *			"session" : ,<br>
 *			"debug" : 0,<br>
 *			"mode" : "standard",<br>
 *			"registration" : {<br>
 *				"firstName" : "Peter",<br>
 *				"lastName" : "Mustermann",<br>
 *				"email" : "peter@mustermann.de",<br>
 *				"salutation" : "gent", (bzw. "female")<br>
 *				"sender" : "?" (TODO: wer weiss was darueber?)<br>
 *			}<br>
 *	 	}<br>
 *	</pre>
 * @type void
 */
	main: function(parameter) {

	  	var pub = window.location.href;
	  	var stage = "dev";
	  	if(pub.indexOf("atoolo.com") > -1){
	  		stage = "live";
	  	}else if(pub.indexOf("atoolo.cynapsis.com") > -1){
	  		stage = "test";
	  	}

	  	var linaConfig = {};

	  	Lina.setConfig({
	  		systemColors: {
		      ButtonFace:        "#F2F2F2",
		      ButtonText:        "#000000",
		      GrayText:          "#808080",
		      HighlightText:     "#FFFFFF",
		      Highlight:         "#656565",
		      ThreeDDarkShadow:  "#F2F2F2",
		      ThreeDLightShadow: "#F2F2F2"
		    },
		   	stage: stage,
		   	i18n: {
		   		lang: parameter.lang,
		   		bundle: "application",
		   		serverActionPath: "/json/getResourceBundle.jsp"
		   	}
			,lrm: {
				"widget/overlay/window.css": "/css/lina_rewrite/window.css"
			}

	  	});


		if (parameter.debug > 0 && typeof(console) != "object") {
	//		AT.log("create debug-console: debug=" + debug + ", console=" + typeof(console));
			var debugConsole = document.createElement("div");
			debugConsole.id = "debugConsole";

			debugConsole.innerHTML = 	'<div id="clearDebug"><input type="button" value="clear" onclick="Lina.get(\'debug\').innerHTML = \'\'; " /></div>\n' +
										'<div id="debug"></div>\n';
			document.body.appendChild(debugConsole);

	  	}
	  // Hintergrund-Geflacker bei Flash-Objekten fuer MSIE abschalten
	  	try {
	    	document.execCommand('BackgroundImageCache', false, true);
	  	} catch(e) { e = null; }

		var t1 = new Date().getTime();
		this.init(parameter);

		var t2 = new Date().getTime();
		AT.log("desktop started in " + (t2 - t1) + "ms");
	},

/**
 * Wird bei einem unload des Desktop augerufen
 * @type void
 */
	destroy: function() {
		if (this.windowManager != null) {
			myWinMgr.destroy();
		}
		AT.log("desktop destroyed");
	},

	configurated: function(mode, registration, error, warning) {
		AtooloLoadingBar.init();
//		this.loadingBar = AtooloLoadingBar.init();
//	  	error   = decodeURIComponent(error);
//	  	warning = decodeURIComponent(warning);
		AT.log("init desktop with: " + mode + ":" + parameter.registration + ":" + error + ":" + warning);

		ResourceLoader.detectLoadedResouces();


		if (mode != null && mode == 'registration') {
			this.loadRegistrationScreen(parameter.registration);
		} else {
			if (AtooloConfig.getUser() != null) {
				this.loadDesktop();
			} else {
				this.loadLoginScreen();
			}
		}
	  if((error != "undefined") || (warning != "undefined")) {
	    if (error != null) {
	      alert(error);
	    } else if (warning != null) {
	      alert(warning);
	    }
	  }
	},

/**
 * Initialisiert den Desktop. Hier werden noch alle noetigen Resourcen wie JavaScript und
 * Cascading Stylesheets geladen, sowie ueber DHTML der Desktop eingerichtet
 * @type void
 */
	init: function(parameter) {

		this.debug = parameter.debug;
		this.sessionId = parameter.sessionId;
		AtooloConfig.load();
//		this.config = AtooloConfig;
	//  var flater = "AtooloDesktop.getInstance().configurated('"+parameter.mode+"', '"+parameter.registration+"', '"+encodeURIComponent(parameter.error)+"', '"+encodeURIComponent(parameter.warning)+"')";
	////  AT.log("this.config:"+this.config);
	//  window.setTimeout(flater, 100);
//		this.configurated(parameter.mode, parameter.registration, encodeURIComponent(parameter.error), encodeURIComponent(parameter.warning));
		this.configurated(parameter.mode, parameter.registration, parameter.error, parameter.warning);

	},

/**
 * Ist das Login-Fenster aktiviert wird mit dessen Daten die Anmeldung vorgenommen.
 * War die Anmeldung erfolgreich, wird das Login-Fenster geschlossen und der Desktop geladen.
 * Bei ungueltiger Anmeldung wird der Nutzer darueber informiert.
 * @type void
 */
	login: function() {
		if (this.loginWindow != null) {
			var success = this.loginWindow.login();
			if (success) {
				this.loginWindow.destroy();
				this.loginWindow = null;
				this.loadDesktop();
			}
		}
	},

	confirmAGBandTerms: function(agb, terms) {
		this.loginWindow.destroy();
		this.loginWindow = null;
		this.confirmWindow(agb, terms);
	},

	confirmWindow: function(agb, terms) {
		var loginDiv = document.createElement("div");
		loginDiv.id = "loginDialog";
		if(document.all) {
			loginDiv.setAttribute("className", "login", "false");
		} else {
			loginDiv.setAttribute("class", "login", "false");
		}
		var html = [];
		html.push("<div class=\"bg\"></div>\n");
		html.push("<div class=\"loginClicker\" onclick=\"window.open('http://atoolo.blogspot.com'); return false;\"></div>\n");
		html.push("<div class=\"inner\">\n");
		html.push("\t<a href=\"javascript:var windowId = AtooloDesktop.getInstance().openWindow('myHelp', 'helpWindow', 'Login Hilfe', '/myHelp/loginHelp.jsp');\"><div class=\"help\">Hilfe</div></a>\n");
		//html.push("\t<form id=\"form_login\" action=\"\" method=\"post\" onsubmit=\"AtooloLogin.getInstance().login(); return false;\">\n");
		html.push("\t<form id=\"form_login\" action=\"\" method=\"post\" onsubmit=\"AtooloDesktop.getInstance().confirm_AGBaT(); return false;\">\n");
		html.push("\t\t<div>\n");
		html.push("\t\t\t<input name=\"sys_mt_user_action\" value=\"login\" type=\"hidden\" />\n");
		html.push("\t\t\t<input name=\"sys_mt_jsp_Handler\" value=\"com.cynapsis.myTools.http.handler.HttpUserHandler\" type=\"hidden\" />\n");
		html.push("\t\t\t<input name=\"sys_mt_login\" id=\"sys_mt_login\" type=\"hidden\" style=\"z-index:500000;\" /><br/>\n");
		html.push("\t\t\t<input name=\"sys_mt_password\" id=\"sys_mt_password\" type=\"hidden\" /><br/>\n");
		html.push("\t\t\t<div class=\"login_checkbox\">\n");
		html.push("\t\t\t\t<input type=\"checkbox\" name=\"sys_mt_agb\" value=\"true\" class=\"chkRadio\" id=\"login_agb_check\"");
	  if(agb == "true") {
	    html.push(" checked=\"checked\" ");
	  }
	  html.push("/>\n");
		html.push("\t\t\t</div>\n");
	//	html.push("\t\t\t<label for=\"login_agb_check\" class=\"radiochecklabel\">" + Lina.translate("js.AtooloLogin.text4", null, "application") + "</label>\n");
		html.push("\t\t\t<label for=\"login_agb_check\" class=\"radiochecklabel\">Ich akzeptiere die AGBs</label><br />\n");
		html.push("\t\t\t<div class=\"login_checkbox\" style=\"clear:both\">\n");
		html.push("\t\t\t\t<input type=\"checkbox\" name=\"sys_mt_terms\" value=\"true\" class=\"chkRadio\" id=\"login_terms_check\"");
	  if(terms == "true") {
	    html.push(" checked=\"checked\" ");
	  }
	  html.push("/>\n");
	  html.push("\t\t\t</div>\n");
		html.push("\t\t\t<label for=\"login_terms_check\" class=\"radiochecklabel\">Ich akzeptiere die Beta-Test-Nutzungsbedingungen</label>\n");

	  html.push("\t\t\t<button type=\"submit\" id=\"loginButton\" >" + Lina.translate("login", null, "common") + "</button>\n");
		html.push("\t\t</div>\n");
		html.push("\t</form>\n");
		html.push("\t<div class=\"stoerer\">" + Lina.translate("js.AtooloLogin.text7", null, "application") + "</div>\n");
		html.push("\t<div class=\"banderole\"><a href=\"/public/free.jsp\">" + Lina.translate("js.AtooloLogin.text8", null, "application") + "</a></div>\n");
		html.push("</div>\n");

		loginDiv.innerHTML = html.join("");
		document.body.appendChild(loginDiv);

		if (AtooloConfig.getInstance().getRoot().scheme == "https") {
			Lina.get("login_ssl_check").checked = true;
		}
	  Lina.get("sys_mt_login").focus();
	},

/**
 * Ist das Registrierungs-Fenster aktiviert, wird mit dessen Daten die Registrierung vorgenommen.
 * War die Registrierung erfolgreich, wird das Registrierungs-Fenster geschlossen und der Desktop geladen.
 * Bei ungueltiger Registrierung wird der Nutzer darueber informiert.
 * @type void
 */
	register: function() {
		if (this.registrationWindow != null) {
			var success = this.registrationWindow.register();
			if (success) {
				this.registrationWindow.destroy();
				this.loadDesktop();
			}
		}
	},

/**
 * Ueber diese Methode wird der angemeldete Nutzer abgemeldet. Es werden alle Desktop-Elemente
 * entfernt und das Login-Fenster angezeigt.
 * @type void
 */
	logout: function() {

		try {
	//    	Lina.get("start_menu_iframe").style.visibility = 'hidden';
			this.windowManager.closeAll();

			this.destroyIcons();
			this.destroyTop();
			this.destroyBottom();
			this.startMenu.destroy();
			this.startMenu = null;
			this.notifier.destroy();
			this.notifier = null;
			this.environment = null;
			AtooloConfig.reset();

			var param = "?";
			param += "sys_mt_jsp_Handler=com.cynapsis.myTools.http.handler.HttpUserHandler&";
			param += "sys_mt_user_action=logout";
			var response = ResourceLoader.getContent("/control/doNothing.jsp" + param);

			this.sessionId = null;

			this.loadLoginScreen();
		} catch (e) {
			AT.log("logout incomplete: " + e, "error", e);
		}
	},

/**
 * Zeigt den Login-Screen
 * @type void
 */
/*
	loadLoginScreen: function() {

		this.disable();

		if (this.registrationWindow != null) {
			this.registrationWindow.destroy();
			this.registrationWindow = null;
		}
		if (this.loginWindow == null) {
			var resources = [];
			resources = resources.concat(AtooloConfig.getResources("main"));
			resources = resources.concat(AtooloConfig.getResources("login"));
			this.loadResourceList("base", resources, function() {
		  		AtooloDesktop.loginWindow = new AtooloLogin();
			  	AtooloDesktop.loginWindow.init();
			});
		}

	},
*/

	loadLoginScreen: function(isCallback) {

		if (!isCallback) {
			this.disable();

			if (this.registrationWindow != null) {
				this.registrationWindow.destroy();
				this.registrationWindow = null;
			}
			if (this.loginWindow == null) {
				var resources = new Array();
				resources = resources.concat(AtooloConfig.getResources("main"));
				resources = resources.concat(AtooloConfig.getResources("login"));
				this.loadResourceList("base", resources, function() { AtooloDesktop.loadLoginScreen(true); });
			}
		} else {
		    if(typeof AtooloLogin != "undefined") {
		  		this.loginWindow = new AtooloLogin();
			  	this.loginWindow.init();
		    } else {
		      	window.setTimeout("AtooloDesktop.loadLoginScreen(true)", 100);
		    }
		}
	},




//	loadLoginScreen: function(isCallback) {

//		if (isCallback == null || !isCallback) {
//			this.disable();
//
//			if (this.registrationWindow != null) {
//				this.registrationWindow.destroy();
//				this.registrationWindow = null;
//			}
//			if (this.loginWindow == null) {
//				var resources = [];
//				resources = resources.concat(AtooloConfig.getResources("main"));
//				resources = resources.concat(AtooloConfig.getResources("login"));
//				this.loadResourceList("base", resources, function() { 	AtooloDesktop.loadLoginScreen(true); });
//			}
//		} else {
//		    if(typeof AtooloLogin != "undefined") {
//		  		this.loginWindow = new AtooloLogin();
//			  	this.loginWindow.init();
//		    } else {
//		      	window.setTimeout("AtooloDesktop.getInstance().loadLoginScreen(true)", 100);
//		    }
//		}
//	},

/**
 * Zeigt den Registrations-Screen
 * @type void
 */
	loadRegistrationScreen: function(user, isCallback) {

		if (isCallback == null || !isCallback) {
			this.disable();

			if (this.loginWindow != null) {
				this.loginWindow.destroy();
				this.loginWindow = null;
			}
			if (this.registrationWindow == null) {
				var resources = [];
				resources = resources.concat(AtooloConfig.getResources("main"));
				resources = resources.concat(AtooloConfig.getResources("registration"));
				this.loadResourceList("base", resources, function() { AtooloDesktop.getInstance().loadRegistrationScreen(user, true)} );
			}
		} else {
	    if(typeof AtooloRegistration != "undefined") {
	  		this.registrationWindow = new AtooloRegistration();
		  	this.registrationWindow.init(parameter.registration);
	    } else {
	      window.setTimeout("AtooloDesktop.getInstance().loadRegistrationScreen('"+user+"', true)", 100);
	    }
		}
	},

/**
 * Zeigt den Desktop
 * @type void
 */
	loadDesktop: function(isCallback) {

		if (isCallback == null || !isCallback) {

			if (this.loginWindow != null) {
				this.loginWindow.destroy();
				this.loginWindow = null;
			}

			this.enable();

			var resources = new Array();
			resources = resources.concat(AtooloConfig.getResources("main"));
			resources = resources.concat(AtooloConfig.getResources("desktop"));
			resources = resources.concat(AtooloConfig.getResources("windowManager"));
			this.loadResourceList("base", resources, function() { window.setTimeout("AtooloDesktop.loadDesktop(true)", 300); });
		} else {

	//		AT.log("load desktop");

			if (this.windowManager != null) {
				myWinMgr.getInstance().closeAll();
			} else {
				this.windowManager = myWinMgr.getInstance();
			}

			// FIXME: Nutzerdaten nicht im WindowManager halten
			var tu = AtooloConfig.getUser();

			this.windowManager.setUser(
					tu.name,
					tu.salutation,
					tu.id,
					tu.login,
					tu.session);

			this.environment = new AtooloDesktopEnvironment(AtooloConfig.getUser().id);

			myLanguages.getInstance();
		    var em = AtooloConfig.getInstance().getRoot()["user"].email;
		    this.isSpec = (em.search("gehoerlos.de") + em.search("cynapsis.") + em.search("sitepark.de") );
		//    this.isSpec = em.search("gehoerlos.de");
		    this.isSpec = (this.isSpec == (-3)) ? false : true;
			draginit();
			this.startMenu = new AtooloStartMenu();
			this.startMenu.init();
			this.windowManager.setAdvertising();
		    this.initTop();
			this.initBottom();
			this.autoStart();
			this.initIcons();
		    this.initBG();
		    this.environmentalStart();
		    Lina.requireOnce("common/lina/widget/grid/scrollable.js");
			zeit();
		}
	},
/*
	loadDesktop: function() {


//		if (isCallback == null || !isCallback) {

			if (this.loginWindow != null) {
				this.loginWindow.destroy();
				this.loginWindow = null;
			}

			this.enable();

			var resources = [];
			resources = resources.concat(AtooloConfig.getResources("main"));
			resources = resources.concat(AtooloConfig.getResources("desktop"));
			resources = resources.concat(AtooloConfig.getResources("windowManager"));
			this.loadResourceList("base", resources, Lina.Utils.Function.bind(function() {
//		} else {

	//		AT.log("load desktop");

				if (this.windowManager != null) {
					myWinMgr.getInstance().closeAll();
				} else {
					this.windowManager = myWinMgr.getInstance();
				}


				// FIXME: Nutzerdaten nicht im WindowManager halten
				var tu = AtooloConfig.getUser();

				this.windowManager.setUser(
						tu.name,
						tu.salutation,
						tu.id,
						tu.login,
						tu.session);

				this.environment = new AtooloDesktopEnvironment(AtooloConfig.getUser().id);

				myLanguages.getInstance();
		    	var em = AtooloConfig.getInstance().getRoot()["user"].email;
		    	this.isSpec = (em.search("gehoerlos.de") + em.search("cynapsis."));
		//    this.isSpec = em.search("gehoerlos.de");
		    	this.isSpec = (this.isSpec == (-1)) ? false : true;

				draginit();
				this.startMenu = new AtooloStartMenu();
				this.startMenu.init();
				this.windowManager.setAdvertising();
		    	this.initTop();
				this.initBottom();
				this.autoStart();
				this.initIcons();
		    	this.initBG();
		    	this.environmentalStart();
		    	Lina.requireOnce("common/lina/widget/grid/scrollable.js");
				zeit();
//		}
		 }, this));

	},
*/
/**
 * Zeigt die StartUp-Fenster des Desktop an
 * Beispiel: myTips
 * @type void
 */
	environmentalStart: function() {
	  var isShown = this.environment.getProperty("myTipsOpen");
	  if(isShown == null) {
	    this.environment.setProperty("myTipsOpen", "true");
	    myWinMgr.getInstance().open("myTips", "main");
	  }
	  if(isShown == "true") {
	    myWinMgr.getInstance().open("myTips", "main");
	  }
	},


/**
 * Zeigt die Top des Desktop an
 * @type void
 */
	initTop: function() {

		var topinfo = document.createElement("div");
		topinfo.id = "topinfo_full";
	  var pub = AtooloConfig.getRoot().host;
	  if(pub.indexOf("https") != (-1)) { pub = pub.replace("https", "http"); }
	  if(pub.indexOf("http://") == (-1)) { pub = "http://"+pub; }
	  var html = [];
		html.push("<div class=\"topinfo_rund\">\n");
		html.push("</div>\n");
		html.push("<div class=\"topinfo\">\n");
		html.push("\t<div id=\"dt\">&nbsp;</div>\n");
		html.push("\t<div id=\"user\">\n");
		html.push("\t\t<div class=\"userdata " + AtooloConfig.getUser().salutation + "\">\n");
		html.push("\t\t\t<a href=\"#\" onclick=\"AtooloDesktop.getInstance().openWindow('myProfile', 'main'); return false;\">" + AtooloConfig.getUser().name + "</a>\n");
		html.push("\t\t</div>\n");
		html.push("\t</div>\n");
		html.push("\t<img id=\"userr\" src=\"/img/topinfo/user_right.gif\" class=\"userdata_abschluss\" alt=\"" + Lina.translate( "js.AtooloDesktop.text1" ) + "\" />\n");
	  if(this.isSpec) {
	    html.push("\t<div class=\"about_gehoerlos\">about gehoerlos</a></div>\n");
	  }
	  html.push("\t<div class=\"about_atoolo\"><a href=\"" + pub +"/\" onclick=\"window.open(this.href); return false\">about atoolo</a></div>\n");
	  html.push("\t<div class=\"logout\">\n");
		html.push("\t\t<a href=\"javascript:AtooloDesktop.getInstance().logout();\"><img src=\"/img/btn_logout.gif\" alt=\"" + Lina.translate( "js.AtooloDesktop.text2" ) + "\"/></a>\n");
		html.push("\t</div>\n");
		html.push("</div>\n");

		topinfo.innerHTML = html.join("");
		document.body.appendChild(topinfo);
	},

/**
 * Entfernt den Top des Desktop an
 * @type void
 */
	destroyTop: function() {
		var topinfo = Lina.get("topinfo_full");
		if (topinfo != null) {
			document.body.removeChild(topinfo);
		}
	},

/**
 * Zeigt die Bottom des Desktop an
 * @type void
 */
	initBottom: function() {

		var bottom = document.createElement("div");
		bottom.id = "bottom";

		var html = [];
		html.push("<div id=\"start\"><a href=\"javascript:AtooloDesktop.getInstance().switchStartMenu();\"><img src=\"/img/bottom_start.gif\" alt=\"" + Lina.translate( "js.AtooloDesktop.text3" ) + "\" /></a></div>\n");
		html.push("<div id=\"short\">\n");
		html.push("\t<div>");
		var systembar = AtooloConfig.getRoot().systembar;
		for (var i = 0;  i < systembar.length; i++) {
			html.push("\t\t\t<a id=\"Systembar_icon_" + systembar[i].id + "\" class=\"" + systembar[i].id + "\" href=\"javascript: void(0);\" onclick=\"myWinMgr.getWindow('" + systembar[i].id + "').onIconClick();\" ondblclick=\"myWinMgr.getWindow('" + systembar[i].id + "').onIconDblClick();\">\n");
			html.push("\t\t\t\t<span>" + systembar[i].title + "</span>\n");
			html.push("\t\t\t</a>\n");
		}
		html.push("\t</div>\n");
		// FIXME: Sollte auch auch Tool sein. Immer diese Extrawuerste ;-)
		html.push("\t<div id=\"systembarClock\"></div>\n");
		html.push("\t<div class=\"systembarCloser\"></div>\n");
		html.push("</div>\n");

		bottom.innerHTML = html.join("");
		document.body.appendChild(bottom);
	},

/**
 * Startet alle Tools die beim Start automatisch gestartet werden sollen.
 * @type void
 */
	autoStart: function(isCallback) {

		// Tools, die automatisch gestartet werden sollen
		var tools = [
			{
				toolId : "myPostAt",
				windowId : "main"
			},
			{
				toolId : "myMessageCenter",
				windowId : "main"
			}
		];

		if (isCallback == null || !isCallback) {
			var resources = [];
			for (var i = 0; i < tools.length; i++) {
				try {
					var windowConf = AtooloConfig.getInstance().getWindowConfig(tools[i].toolId, tools[i].windowId);
					if (windowConf != null) {
						resources = resources.concat(windowConf.resources);
					}
				} catch(e) {
					AT.log("get window config:" + e, "error", e);
				}
			}
	//		AT.log("auto start resouces " + resources.length);
			AtooloDesktop.getInstance().loadResourceList("dependent", resources, function() { window.setTimeout("AtooloDesktop.getInstance().autoStart(true)", 300); } );
		} else {
	//		AT.log("start auto");
			for (var i = 0; i < tools.length; i++) {
				myWinMgr.getInstance().open(tools[i].toolId, tools[i].windowId, null, null, null, true);
			}
	//		AT.log("create notifier old: " + this.notifier);
	    window.setTimeout("AtooloDesktop.getInstance().notifier = new AtooloNotifier();	AtooloDesktop.getInstance().notifier.start();", 500);
		}
	},

/**
 * Entfernt den Bottom des Desktop an
 * @type void
 */
	destroyBottom: function() {
		var bottom = Lina.get("bottom");
		if (bottom != null) {
			document.body.removeChild(bottom);
		}
	},

/**
 * Zeigt die Desktop-Icons
 * @type void
 */
	initIcons: function() {
	  AtooloDesktopIconMan.getInstance().start();
	},

	initBG: function() {
	  if(this.isSpec) {
	    var dt = Lina.get("desktop");
	    var img = document.createElement("div");
	    dt.appendChild(img);
	    img.className = "specialBrand";
	  }

	  var hgId    = AtooloDesktop.getInstance().environment.getProperty("desktopBackground");
	  var hgAlign = AtooloDesktop.getInstance().environment.getProperty("desktopBackgroundAlign");
	  if(Lina.get("desktopBackground") != null) {
	    Lina.get("desktopBackground").parentNode.removeChild(Lina.get("desktopBackground"));
	  }
	  var ddiv    = document.createElement("div");
	  document.body.appendChild(ddiv);
	  ddiv.style.height = "100%";
	  ddiv.style.width  = "100%";
	  ddiv.id = "desktopBackground";
	  ddiv.style.position = "absolute";
	  ddiv.style.top  = "0";
	  ddiv.style.left = "0";
	  ddiv.style.zIndex = 400;
	  if((hgAlign != null) && (hgId != null)) {

	//    var url = "/control/?mt_storage_loadContentType=application%2Foctet-stream&sys_mt_storage_action=load&mt_storage_id="+hgId+"&sys_mt_jsp_Handler=com.cynapsis.myTools.http.handler.HttpStorageHandler";
	//    url = ResourceLoader.rewriteUrl(url);

	    var hgProof = [];
	    hgProof = hgId.split(":");
	    if(hgProof.length != 2) {
	      hgProof[0] = "none";
	      hgProof[1] = "none";
	    }

	    var url = "/img/themes/blue/bg.gif";
	    if((hgProof[0] != "none") && (hgProof[1] != "none")) {
	      url = "/dt/img/background/atoolo_wp_"+hgProof[0]+hgProof[1]+".jpg";

	      if(hgAlign == "center") {
	        var hgImg = document.createElement("img");
	        ddiv.appendChild(hgImg);
	        hgImg.id = "desktopBackgroundImage";
	        hgImg.src = url;
	        var todo = "AtooloDesktop.getInstance().centerBG()";
	        window.setTimeout(todo, 1500);
	      }
	      if(hgAlign == "juxtaposing") { // nebeneinander
	        ddiv.style.backgroundImage = "url('"+url+"')";
	      }
	      if(hgAlign == "stretched") {
	        var hgImg = document.createElement("img");
	        hgImg.id = "desktopBackgroundImage";
	        ddiv.appendChild(hgImg);
	        hgImg.style.width  = "100%";
	        hgImg.style.height = "100%";
	        hgImg.src = url;
	      }
	      if(hgAlign == "bestFit") {
	        //TODO:!!!
	        var t = document.createElement("table");
	        var tb = document.createElement("tbody");
	/*
	        var tr = document.createElement("tr");
	        t.appendChild(tr);
	        var td = document.createElement("td");
	        tr.appendChild(td);
	*/
	        ddiv.appendChild(t);
	        t.appendChild(tb);
	        tb.insertRow(0);
	        tb.rows[0].insertCell(0);
	        t.style.position = "absolute";
	        t.style.width = "1000%";
	        t.style.height = "1000%";
	        t.style.left = "-450%";
	        t.style.top = "-450%";
	        tb.rows[0].cells[0].style.textAlign = "center";
	/*
	        td.style.verticalAlign = "middle";
	        td.style.textAlign = "center";
	*/
	        var hgImg = document.createElement("img");
	        tb.rows[0].cells[0].appendChild(hgImg);
	        hgImg.style.visibility = "hidden";
	        hgImg.id = "desktopBackgroundImage";
	        hgImg.src = url;
	        var todo = "AtooloDesktop.getInstance().findBest()";
	        window.setTimeout(todo, 1500);
	      }
	    }
	  }
	},

	centerBG: function() {
	  hgImg = Lina.get("desktopBackgroundImage");
	  hgImg.style.position = "absolute";
	  hgImg.style.left   = "50%";
	  hgImg.style.top    = "50%";
	  hgImg.style.marginLeft = (-(hgImg.offsetWidth)/2)+"px";
	  hgImg.style.marginTop  = (-(hgImg.offsetHeight)/2)+"px";
	},

	findBest: function() {

	  hgImg = Lina.get("desktopBackgroundImage");
	//  hgImg.style.position = "absolute";
	  var w = hgImg.offsetWidth;
	  var h = hgImg.offsetHeight;
	  this.bgOffsetWidth  = w;
	  this.bgOffsetHeight = h;
	//  hgImg.style.marginLeft = "auto";
	//  hgImg.style.marginRight  = "auto";

	  var ww = document.body.offsetWidth;
	  var wh = document.body.offsetHeight;
	  var wq = w/ww;
	  var hq = h/wh;
	  wq = wq-1;
	  hq = hq-1;
	  if(hq < wq) {
	    hgImg.style.height = "11%";
	    hgImg.style.width  = "auto";
	/*    w = hgImg.offsetWidth;
	    if(w > ww) {
	      hgImg.style.left = (-((w-ww)/2))+"px";
	    }
	*/
	  } else {
	    hgImg.style.width  = "11%";
	    hgImg.style.height = "auto";
	/*
	    h = hgImg.offsetHeight;
	    if(h > wh) {
	      hgImg.style.top = (-((h-wh)/2))+"px";
	    }
	*/
	  }
	  hgImg.style.visibility = "visible";

	},

/**
 * Entfernt die Icons des Desktop an
 * @type void
 */
	destroyIcons: function() {
		var desktopItems = Lina.get("desktopItems");
		if (desktopItems != null) {
			document.body.removeChild(desktopItems);
		}
	},

/**
 * Deaktiviert den Desktop, so das keine Aktionen mehr ausgeloest werden koennen. Der
 * Desktop kann mit {@link AtooloDesktop#enable()} wieder aktiviert werden.
 * @type void
 */
	disable: function() {

		var offOver = Lina.get("off_over");
		if (offOver == null) {
			offOver = document.createElement("div");
			offOver.id = "off_over";
			offOver.appendChild(document.createElement("div"));
			document.body.appendChild(offOver);
		} else {
			offOver.style.visibility = "visible";
		}
	},

/**
 * Deaktiviert den Desktop, so das keine Aktionen mehr ausgeloest werden koennen
 * @return Liefert <code>true</code>, wenn der Desktop deaktiviert wurde, sonst <code>false</code>
 * @type boolean
 */
	isDisabled: function() {
		var offOver = Lina.get("off_over");
		if (offOver == null || offOver.style.visibility == "hidden") {
			return false;
		} else {
			return true;
		}
	},

/**
 * Aktiviert den Desktop nach einem {@link AtooloDesktop#disable()} wieder
 * @type true
 */
	enable: function() {
		var offOver = Lina.get("off_over");
		if (offOver != null) {
			offOver.style.visibility = "hidden";
		}
	},

/**
 * Liefert den Debug-Level
 * @return Debug-Level
 * @type int
 */
	getDebugLevel: function() {
		return this.debug;
	},

/**
 * Liefert den Aktuell angemeldeten Nutzer
 * @return Aktuell angemeldeter Nutzer
 * @type JSONObject
 */
	getUser: function() {
		return AtooloConfig.getUser();
	},

/**
 * Liefert den Desktop-Umgebung des Nutzers
 * @return Desktop-Umgebung des Nutzers
 * @type AtooloDesktopEnvironment
 */
	getEnvironment: function() {
		return this.environment;
	},

///**
// * Liefert den LadeBalken des Desktop
// * @return Ladebalken
// * @type AtooloLoadingBar
// */
//	getLoadingBar: function() {
//		return this.loadingBar;
//	},

/**
 * Liefert den Notifier
 * @return Notifier
 * @type AtooloDesktopEnvironment
 */
	getNotifier: function() {
		return this.notifier;
	},

/**
 * Liefert die SessionId der HTTP-Session
 * @return SessionId
 * @type String
 */
	getSessionId: function() {
		return this.sessionId;
	},

/**
 * Setzt die SessionId der HTTP-Session
 * @param {String} sessionId SessionId
 * @type void
 */
	setSessionId: function(sessionId) {
		this.sessionId = sessionId;
	},

/**
 * Oeffnet das Startmenu, wenn es geschlossen und schliesst es, wenn es geoeffnet
 * @type void
 */
	switchStartMenu: function() {
		if (this.startMenu != null) {
			this.startMenu.switchMenu();
		}
	},
/**
 * Schliesst das Startmenu
 * @type void
 */
	closeStartMenu: function() {
		if (this.startMenu != null) {
			this.startMenu.closeMenu();
		}
	},
/**
 * oeffnet das Startmenu
 * @type void
 */
	openStartMenu: function() {
		if (this.startMenu != null) {
			this.startMenu.openMenu();
		}
	},

/**
 * Liefert den Notifier
 * @return Notifier
 * @type void
 */
	openWindow: function(toolId, windowId, title, url, id, isCallback) {

		try {
			if (this.windowManager == null) {
				if (isCallback == null || !isCallback) {
					var res = AtooloConfig.getResources("windowManager");
					this.loadResourceList("base", AtooloConfig.getResources("windowManager"), function() { AtooloDesktop.getInstance().openWindow(toolId, windowId, title, url, id, true); } );
				} else {
					draginit();
					this.windowManager = myWinMgr.getInstance();
					this.windowManager.open(toolId, windowId, title, url, id);
				}
			} else {
					this.windowManager.open(toolId, windowId, title, url, id);
			}
		} catch (e) {
			AT.log("AtooloDesktop.openWindow: " + e, "error" ,e);
		}
	},

/**
 * laed eine ResourceListe
 * @param {String} loadingLevel (base|dependent)
 * @param {Array} list Resourceliste aus der Konfiguration
 * @param {Function} callback Funktion die aufgerufen werden soll, wenn die Resoucen geladen sind.
 * @type void
 * @private
 */
	loadResourceList: function(loadingLevel, list, callback) {

		var loader = ResourceLoader.loadResourceList(loadingLevel, list, callback);
		if (loader != null) {
			AtooloLoadingBar.addLoader(loader);
		}
	}
}

