/* Ext JS Library 2.0
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://www.extjs.com/license
 */



// Use our blank image
Ext.BLANK_IMAGE_URL = 'appsrv/media/images/blank.png';

Ext.MessageBox.buttonText.yes     = "Ja";
Ext.MessageBox.buttonText.no      = "Nein";
Ext.MessageBox.buttonText.ok      = "OK";
Ext.MessageBox.buttonText.cancel  = "Abbrechen";


// Desktop
Ext.Desktop = function() {

  var desktop   = Ext.get('DESKTOP');
  this.desktop  = desktop;

  var windows   = new Ext.WindowGroup();
  windows.zseed = 100;
  var activeWindow;

  function minimizeWin(win){
    win.minimized = true;
    win.hide();
  }

  function markActive(win){
    if(activeWindow && activeWindow != win){
        markInactive(activeWindow);
    }
    activeWindow = win;
    win.minimized = false;
  }

  function markInactive(win){
    if(win == activeWindow){
      activeWindow = null;
      //Ext.fly(win.taskButton.el).removeClass('active-win');
    }
  }

  function removeWin(win){
  	//taskbar.removeTaskButton(win.taskButton);
    layout();
  }

  function layout(){
    desktop.setHeight(Ext.lib.Dom.getViewHeight() - 36);
  }
  Ext.EventManager.onWindowResize(layout);

  this.layout = layout;

  this.createWindow = function(config, cls) {
  	var win = new (cls||Ext.Window)(
        Ext.applyIf(config||{}, {
          manager: windows,
          minimizable: false,
          maximizable: true
        })
      );
      win.render(desktop);
      //win.taskButton = taskbar.addTaskButton(win);

      win.cmenu = new Ext.menu.Menu({
          items: [
          ]
      });

      //win.animateTarget = win.taskButton.el;

      win.on({
      	'activate': {
      		fn: markActive
      	},
      	'beforeshow': {
      		fn: markActive
      	},
      	'deactivate': {
      		fn: markInactive
      	},
      	'minimize': {
      		fn: minimizeWin
      	},
      	'close': {
      		fn: removeWin
      	}
      });

      layout();
      return win;
  };

  this.getManager = function(){
      return windows;
  };

  this.getWindow = function(id){
      return windows.get(id);
  }

  this.getWinWidth = function(){
		var width = Ext.lib.Dom.getViewWidth();
		return width < 200 ? 200 : width;
	}

	this.getWinHeight = function(){
		var height = (Ext.lib.Dom.getViewHeight() - 302);
		return height < 100 ? 100 : height;
	}

	this.getWinX = function(width){
		return (Ext.lib.Dom.getViewWidth() - width) / 2
	}

	this.getWinY = function(height){
		return (Ext.lib.Dom.getViewHeight() - height) / 2;
	}

  this.removeWin = removeWin;

  layout();
};


// Application
Ext.app.App = function(cfg){
  Ext.apply(this, cfg);
  this.addEvents({
    'ready' : true,
    'beforeunload' : true,
    'sessionexpire': true
  });
  Ext.onReady(this.initApp, this);
};

Ext.extend(Ext.app.App, Ext.util.Observable, {
  isReady: false,
  startMenu: null,
  modules: null,

  initApp : function(){
  	this.desktop  = new Ext.Desktop();
    this.modules  = this.getModules();
    if(this.modules){
      this.initModules(this.modules);
    }
    this.init();
    Ext.EventManager.on(window, 'beforeunload', this.onUnload, this);
    this.fireEvent('ready', this);
    this.isReady = true;
  },

  getModules : Ext.emptyFn,
  init : Ext.emptyFn,

  initModules : function(ms){
    for(var i = 0, len = ms.length; i < len; i++){
      var m = ms[i];
      m.app = this;
    }
  },

  getModule : function(name){
  	var ms = this.modules;
  	for(var i = 0, len = ms.length; i < len; i++){
  		if(ms[i].appType == name){
  			return ms[i];
	    }
    }
    return '';
  },

  onReady : function(fn, scope){
    if(!this.isReady){
      this.on('ready', fn, scope);
    } else{
      fn.call(scope, this);
    }
  },

  getDesktop : function(){
    return this.desktop;
  },

  onUnload : function(e){
    if(this.fireEvent('beforeunload', this) === false){
      e.stopEvent();
    }
  }
});


// Modules
Ext.app.Module = function(config){
  Ext.apply(this, config);
  Ext.app.Module.superclass.constructor.call(this);
  this.init();
}
Ext.extend(Ext.app.Module, Ext.util.Observable, {
  init : function(){ }
});


// Plugins
var App = App || {};

App = new Ext.app.App({
	init :function(){
		Ext.QuickTips.init();
    this.loadedLibs   = [];
    this.requiredLibs = [];
	},

	getModules : function(){
		return [];
	},

  loadUrl: function(url) {
    document.location.href = url;
  },

  load: function(url, params, callback, scope) {
    Ext.Ajax.request({
      url: url,
      success: function(response) {
        eval(response.responseText);
      },
      callback: callback,
      scope: scope,
      params: params
    });
  },

  // require needed libs
  require: function() {
    var argv    = this.require.arguments;
    var argc    = argv.length;
    var append  = "?_dc=" + (new Date().getTime());
    for (var i = 0; i < argc; i++) {
      //alert("Include " + i + " = " + argv[i]);
      this.include(argv[i], append);
    }
    if(this.requiredLibs.length == 0) {
      this.fireEvent('ready', this);
    }
  },

  // include lib (add script to head)
  include: function(lib, append) {
    if(this.loadedLibs[lib]) {
      return false;
    }
    var js  = document.createElement('script');
    js.type = 'text/javascript';
    js.src  = this.getSrc(lib) + append;
    var head=document.getElementsByTagName('head')[0];
    head.appendChild(js);
    this.requiredLibs[lib]  = true;
    this.loadedLibs[lib]    = true;
  },

  // get src (AppCmsMediaLib -> appsrv/apps/cms/media/media.js)
  getSrc: function(lib) {
    split = lib.match(/[A-Z]+[a-z]*/g);
    path  = 'appsrv/apps/' + split[1].toLowerCase() + '/media/js/lib.' + split[2].toLowerCase() + '.js';
    return path;
  },

  // register lib
  register: function() {
    var argv = this.register.arguments;
    var argc = argv.length;
    for (var i = 0; i < argc; i++) {
      //alert("Is registered " + i + " = " + argv[i]);
      this.requiredLibs[argv[i]] = null;
    }
    if(this.requiredLibs.length == 0) {
      this.fireEvent('ready', this);
    }
  },

  // get dependencies from ini
  // appsrv/apps/[module]/[controller].[action].ini
  getDependencies: function(url) {
    u = url.replace(/\//gi, ".");
    u = (u.slice(-1)=='.') ? u.slice(0,-1) : u;
    r = 'appsrv/default/lib/loadDependencies/request/'+u;
    Ext.Ajax.request({
      url: r,
      success: function(response) {
        a = eval(response.responseText);
        if(a) {
          for (var i=0; i<a.length; i++) {
            App.require(a[i]);
          }
        }
      }
    });
  },

  // add js file to header
  requireOld: function(filename) {
    if(this.loadedDeps[filename]) {
      return false;
    }
    var js = document.createElement('script');
    js.type = 'text/javascript';
    js.src = filename;
    var head=document.getElementsByTagName('head')[0];
    if(/WebKit|Khtml/i.test(navigator.userAgent)) {
      head.appendChild(js);
    } else {
      js.onload = js.onreadystatechange = function() {
        if (js.readyState && js.readyState != 'loaded' && js.readyState != 'complete') return;
        js.onreadystatechange = js.onload = null;
      };
      head.appendChild(js);
    }
    this.loadedDeps[filename] = true;
  },

  // open window
  open: function(url, params) {
    if(!Ext.get('TempUpdater')) {
      Ext.getBody().createChild({id:'TempUpdater', style: 'display:none'});
    }
    // get dependencies
    //this.getDependencies(url);
    // request
    Ext.get('TempUpdater').load({
        url: url,
        scripts:true,
        showLoadIndicator: true,
        params: params,
        text: "Loading Foo..."
    });
  }

});
