//class layout manager
function layoutMng(oSystem){
  //objects
  this.oSystem = oSystem;
  //properties
  this.defaultLayout;
  this.previousLayout;
  this.currentLayout;
  this.layoutChange = false;
  //methods
  this.loadLayout = loadLayout;
  this.parseLayoutConfig = parseLayoutConfig;
  this.manageLayoutChange = manageLayoutChange;
  this.displayLayout = displayLayout;
}

function loadLayout(layoutName){
  //this.oSystem.oDebug.dm('loading layout '+layoutName);
  this.previousLayout = this.currentLayout;
  this.currentLayout = layoutName ? layoutName : this.defaultLayout;
  this.layoutChange = (this.previousLayout != this.currentLayout);
  if(!this[this.currentLayout]){
    //this.oSystem.oDebug.dm('new layout '+layoutName);
    this.oSystem.oConnection.loadFile('./systems/'+this.oSystem.systemName+'/layouts/l_'+layoutName+'.xml','oSystem.oLayoutMng.parseLayoutConfig',[layoutName]);
  }else{
    //this.oSystem.oDebug.dm('layout '+layoutName+' already loaded');
    this.displayLayout();
  }
}

function parseLayoutConfig(xCode,layoutName){
  //this.oSystem.oDebug.dm('parsing layout '+layoutName+' config file');
  var oXml = this.oSystem.oConnection.generateXDoc('xml',xCode);
  var oLayout = new layout();
  var aBlocks = oXml.getElementsByTagName('block');
  var nBlock;
  var nName;
  var blockName;
  for(i=0;i<aBlocks.length;i++){
    nBlock = aBlocks.item(i);
    nName = nBlock.getElementsByTagName('name')[0];
    blockName = this.oSystem.oConnection.getNodeValue(nName);
    this.oSystem.oBlockMng.loadBlock(blockName);
    oLayout.addBlockToLayout(blockName);
  }
  this[layoutName] = oLayout;
  this.manageLayoutChange();
}

function manageLayoutChange(){
  if(!this.previousLayout) this.oSystem.oHtmlMng.createLayoutContainer();
  if(this.previousLayout && this.layoutChange){
    //this.oSystem.oDebug.dm('switching layout from '+this.previousLayout+' to '+this.currentLayout);
    this.oSystem.oHtmlMng.switchLayoutContainer();
    var oldBlock;
    for(i in this[this.previousLayout].aBlocks){
      oldBlock = this[this.previousLayout].aBlocks[i];
      if(!this.oSystem.inArray(this[this.currentLayout].aBlocks,oldBlock)){
        //this.oSystem.oDebug.dm('removing block '+oldBlock);
        //this.oSystem.oHtmlMng.deleteBlock(oldBlock);
        //this.oSystem.oBlockMng.removeBlock(oldBlock);
        this.oSystem.oBlockMng[oldBlock].close();
      }
    }
  }
}

function displayLayout(){
  this.manageLayoutChange();
  //loop over blocks
  for(i in this[this.currentLayout].aBlocks){
    this.oSystem.oBlockMng.loadBlock(this[this.currentLayout].aBlocks[i]);
  }
}

//class layout
function layout(){
  //properties
  this.aBlocks = new Array();
  //methods
  this.addBlockToLayout = addBlockToLayout;
}

function addBlockToLayout(blockName){
  this.aBlocks.push(blockName);
}
