
//test only -> the Layout as JSON 

var rLayout = [ 
               {Name: "left", XPos:"2", YPos: "110", Width: "200", Height: "800"},
               {Name: "center", XPos:"205", YPos: "110", Width: "600", Height: "250"}, 
               {Name: "right", XPos:"RightMost", YPos: "110", Width: "600", Height: "250"},
               {Name: "top", XPos:"0", YPos: "0", Width: "1200", Height: "100", Layout: "brick"}
               //{Name: "nowhereman", XPos:"0", YPos: "0", Width: "0", Height: "0", Layout: "brick"}
              ]; 

/*This is the SnapDef Registry (which should be dynamically be loaded somehow)*/
var rSnapIns = null ;

   var SnapDef = function(strURL, strTitle, strName,  strSIM, bIsChild, strID, strType) 
   {
      this.URL   = strURL ;
      this.ID    = strID ; //strID would usually not set on construction but later when snap is instantiated.
      this.Type  = strType //adapter.snap, adapter.uwa, Content...
      this.Name  = strName ; 
      this.Title = strTitle ;       
      this.SIM   = strSIM ; 
      this.XPos  = 0 ;
      this.YPos  = 0 ;
      this.Width = 0 ;
      this.Height = 0 ;
      this.FreeFloat = false ;
      this.IsChild = bIsChild ; //can be null or undefined
   }


   getSnapInDefinition = function (strName) 
   {
      var snapDef = null ;
      //it may occur that parseJSON remove spaces - so do we
      var strNameCondensed = strName.replace(/ /g, "");
      for(var i=0; i<rSnapIns.length; i++) //calling all SnapIns
      {
         if( rSnapIns[i].Name == strName || rSnapIns[i].Name == strNameCondensed)     //match
         {            
            if( null == rSnapIns[i].SIM) rSnapIns[i].SIM = '';
            snapDef = rSnapIns[i] ;
         }
      }
      return snapDef;  //can be null   
   }

   /*this is for sorting the boot array - do not confuse pos with snapIn.POS!*/
   function posSort (a, b) {
      
      return (a.Pos - b.Pos);  //reverse since we are a stack
   }

/*
   The snapIn12 primordial Class, where all custom snapIns should inherit from.
*/

NS2112.namespace('masterControl') ;

NS2112.CONST_CAT_INFO = 'info' ;
NS2112.CONST_CAT_WARN = 'warn' ;
NS2112.CONST_CAT_ERR = 'error' ;
NS2112.NOWHEREMAN = 'nowhereman'; //a special sim identifier for floating windows.


NS2112.masterControl = function() {
    //var m_coordinates = ToolMan.coordinates() ;
    var m_Loader = null;
    var m_iContainerID = 0;
    var m_rIntrinsics = new Object();  //the intrinsic snapins (Layout, logger...)
    var m_rSIMRegistry = null; // new Object() ; //associate SIM-Name - Snap
    var m_rSnapRegistry = new Object(); //an array of slots
    var m_BugPrison = null;   //singleton
    var m_DragShim = null;    //singleton drag shim for enhanced drag performance
    var m_silo = null; //the snapin loader
    var m_snapNum = 0;   //for generating a snapin element Id
    // no more used - eliminate all YUI - Stuff... var m_OverlayManager = new YAHOO.widget.OverlayManager(); 
    var m_BugPrisonName = 'bugprison';
    var strSourceSIMName; //holds the sims name to prevent overwriting.
    var bDragInProgress = false;
    var m_strCustomHeader = null;
    var m_systemWindow = null ; //system message box singleton

    this.onIntrinsicReady = new NS2112.CustomEvent("onIntrinsicReady");
    this.onCreatePanel = new NS2112.CustomEvent("onPanelCreate");       //client may not want a panel - can veto this
    this.beforeSnapInCreate = new NS2112.CustomEvent("beforeSnapInCreate");
    this.beforeSnapContainerCreate = new NS2112.CustomEvent("onSnapContainerCreate");
    this.onSnapInContentLoaded = new NS2112.CustomEvent("onSnapInContentLoaded");  //after .load
    this.onSnapInLoaded = new NS2112.CustomEvent("onSnapInLoaded");
    this.onSnapInUnload = new NS2112.CustomEvent("onSnapInUnload");
    this.onSnapInRecycle = new NS2112.CustomEvent("onSnapInRecycle");
    this.onClipboardCut  = new NS2112.CustomEvent("onClipboardCut"); //clipboard event


    YAHOO.widget.Module.textResizeEvent.subscribe(function() {
        var iDelta = 0;
        var currentSnap = null;
        var mc = NS2112.portalMan.getMasterControl();

        if (!mc) {
            NS2112.masterControl.Log("textResizeEvent - failed to get mc.", NS2112.CONST_CAT_ERROR);
            return;
        }

        for (var X in m_rSnapRegistry) //calling all SIMS
        {
            currentSnap = m_rSnapRegistry[X];

            currentSnap.Width = currentSnap.m_Panel.body.firstChild.clientWidth;

            if (currentSnap.Width > m_rSIMRegistry[m_rSnapRegistry[X].m_responsibleSIM].Width) {
                NS2112.masterControl.Log(currentSnap.Name + "/" + m_rSIMRegistry[m_rSnapRegistry[X].m_responsibleSIM].Width + "/"
                           + m_rSnapRegistry[X].m_Panel.body.firstChild.clientWidth, NS2112.CONST_CAT_INFO);
                iDelta = currentSnap.Width - m_rSIMRegistry[currentSnap.m_responsibleSIM].Width;

                //if the Snap Width gets wider than the SIMS width we need to adjust the layout and the SIMS width

                var l = mc.getIntrinsic('layout');
                var s = null;
                if (l) {
                    m_rSIMRegistry[currentSnap.m_responsibleSIM].Width = currentSnap.Width;
                    s = l.getIntrinsicObject().get(currentSnap.m_responsibleSIM);
                    if (s) {
                        s.setWidth(currentSnap.Width);
                        NS2112.masterControl.Log("textResizeEvent - adjustLayout [" + currentSnap.m_responsibleSIM.Name + "] [" + currentSnap.Width + "]",
                    NS2112.CONST_CAT_INFO);

                    }
                }
            }
        }
        mc.adjustLayout();
        mc.hideDragShim();  //just to make sure

    });

    this.enumSnapIns = function() {
        return m_rSnapRegistry;
    }

    this.getIntrinsic = function(strName) {
        var ret = m_rIntrinsics[strName];
        if (typeof ret == 'undefined') ret = null;
        return ret;
    }

   //Messagebox.
   this.getSystemWindow = function(strTitle, strContent, iWidth, iHeight){
		var wm = NS2112.portalMan.getWindowManager();
  
		if(!m_systemWindow)
			m_systemWindow = this.contentRequested( 'content', strContent, strTitle, iWidth, iHeight, 0, 0, true, true) ;
        m_systemWindow.setTitle(strTitle) ;
        this.recycle(m_systemWindow);
		wm.bringToTop(m_rSnapRegistry, m_systemWindow.m_Panel.getWindow());        
		return  m_systemWindow ;
   }


    this.createSnapIn = function(strUniqueName, strTitle, theContent,
                        iWidth, strUnitW, iHeight, strUnitH, windowStyle, elParentContainer) {
        var si = this.getIntrinsic('adapter.snap');  //this is the overall host for any content... the hull, container
        var myPanel = null;
        //Since we are loading through ajax and eval, we absolutely make sure that no
        //'undefined' values travel the wire - since this would lead to a 
        // 'not wellformed' error.
        if (typeof theContent == 'undefined') theContent = '';
        if (typeof strUniqueName == 'undefined') strUniqueName = '';
        if (typeof strTitle == 'undefined') strTitle = '';

        if (typeof iWidth == 'undefined') iWidth = 0;
        if (typeof strUnitW == 'undefined') strUnitW = 'px';
        if (typeof iHeight == 'undefined') iHeight = 0;
        if (typeof strUnitH == 'undefined') strUnitH = 'px';
        if (typeof bNoBorder == 'undefined') bNoBorder = false;
        if (typeof bCanClose == 'undefined') bCanClose = true;
        if (si) {
            myPanel = si.getIntrinsicObject().create
           (this.queryDrag, this.queryDrop, this.queryGrow, this.queryUnload,
             theContent, strUniqueName, strTitle,
                        iWidth, iHeight,
                        NS2112.portalMan.getHeaderHeight(),
                        NS2112.portalMan.getFooterHeight(),
                        windowStyle, m_strCustomHeader, elParentContainer);    //cust Header for clients
            myPanel.setStartResizeListener(this.onSnapStartResize);
            myPanel.setEndResizeListener(this.onSnapEndResize);
            myPanel.setResizeListener(this.onSnapResize);
            si.getIntrinsicObject().show(myPanel);
            this.registerOverlay(myPanel);  //eliminate this plz, someday
        }
        return myPanel;
    }
    /*------------------------*/


    /*The function is a bit of a simplification and should get more refined.*/
    /*take care: since this is an event that was fired - oSnap is an Array*/

    this.onContentReady = function(strEventName, rSnap, mySnapDef) {
        //alert("onContentReady " + strURL) ;      
        var mc = NS2112.portalMan.getMasterControl();
        mc.onSnapInLoaded.unsubscribe(this.onContentReady, mySnapDef);
        if (!rSnap) return;
        /*
        Must display the content SnapIn here: since it is intrinisic it will not be shown yet!00
        */
        rSnap[0].m_responsibleSIM = 'center';
        if (true == mySnapDef.FreeFloat) {
            rSnap[0].WindowStyle |= NS2112.windowStyle.WS_FREEFLOAT;
            rSnap[0].m_responsibleSIM = NS2112.NOWHEREMAN; //a special (non existing) SIM
        }

        if (typeof mySnapDef.Height == 'undefined' || null == mySnapDef.Height || 0 == mySnapDef.Height) {
            rSnap[0].Height = NS2112.portalMan.getContentWndExtY(); //load from settings
        }
        else
            rSnap[0].Height = mySnapDef.Height;

        if (typeof mySnapDef.Width != 'undefined' && null != mySnapDef.Width && 0 != mySnapDef.Width) {
            rSnap[0].Width = mySnapDef.Width;
        }
        else {  //no width set - set FITTOHOST
            rSnap[0].Width = NS2112.portalMan.getContentWndExtX(); //load from settings ;      
            //the FitToHost is set for all standard content windows - but may be cleared in later.
            rSnap[0].WindowStyle |= NS2112.windowStyle.WS_FITTOHOST;
        }

        rSnap[0].FreeFloat = mySnapDef.FreeFloat;

        m_rSnapRegistry[rSnap[0].Name] = rSnap[0];

        m_rSIMRegistry['center'].showSnapIn(rSnap[0], mc.createContainer(rSnap[0].Name, rSnap[0].ID),
                rSnap[0].Name, 0);
        rSnap[0].Title = mySnapDef.Title;

        rSnap[0].m_Panel.setTitle(mySnapDef.Title);
        rSnap[0].m_Panel.setNavBackListener(rSnap[0].queryNavBack);
        rSnap[0].m_Panel.setNavForthListener(rSnap[0].queryNavForth);
        rSnap[0].m_Panel.setReloadListener(rSnap[0].queryNavReload);
        //rSnap[0].m_Panel.resize(rSnap[0].Width, rSnap[0].Height);
        rSnap[0].m_Panel.resizeWindowStation(rSnap[0].Width, rSnap[0].Height);
        if (rSnap[0].FreeFloat) {
            rSnap[0].m_Panel.moveTo(mySnapDef.XPos, mySnapDef.YPos);
            rSnap[0].X = mySnapDef.XPos; //X/Y only relevant for FreeFloat
            rSnap[0].Y = mySnapDef.YPos;
        }



        rSnap[0].m_Panel.setBody(rSnap[0].loadContent(rSnap[0].Name, mySnapDef.URL, mySnapDef.Type));
        //alert(rSnap[0].m_responsibleSIM) ;
        //    if( NS2112.NOWHEREMAN == rSnap[0].m_responsibleSIM ) return  ;
        m_rSIMRegistry['center'].rebuild();

    }


    //contentRequested can be called by any snap in, but usually from a menu to show 
    //content from a URL.
    //strObject is the URL


    /*
    !!strObject can be a URL or Code!!
    This Method would load content or snapins (uwa etc.)
    REMARK on bNewWindow: Currently under development. But, this would decide wether to reuse a content window (false)
                          or start a new WindowStation (true).
    */
    this.contentRequested = function(strIntrinsicName, strObject, strTitle, iWidth,
                                    iHeight, iXPos, iYPos, bNewWindow, bFreeFloat, strSIM, bIsChild) {
        //strIntrinsic could be 'content', 'embedded', 'adapter.snap', 'adapter.uwa', 'tabview'
        var snapContainer = null; //for show snapIn
        var l = this.getIntrinsic(strIntrinsicName); //try to find a carrier for the request.
        if (null == l) {
            NS2112.onConsoleOut.fire('Cannot load intrinsic [' + strIntrinsicName + ']');
            return;
        }

        if (null == strSIM || typeof strSIM == 'undefined') strSIM = 'center';
        l.WindowStyle |= NS2112.windowStyle.WS_CANRELOAD | NS2112.windowStyle.WS_CANGROW ; //| NS2112.windowStyle.WS_CANNAVIGATE;

        //user requested a new window and it is not a snap
        if( true == bNewWindow ) { //Loading IFRAME SRC into a Window that is not bound to our grid.
            //reset focus on all overlays. So we can float on top. Jun.6.08
            //subscribe to the loading function
            var mySnapDef = new SnapDef(strObject);  //create a definition object (properties only)
            mySnapDef.FreeFloat = bFreeFloat;
            mySnapDef.Title = strTitle;
            mySnapDef.XPos = iXPos;
            mySnapDef.YPos = iYPos;
            mySnapDef.Width = iWidth;
            mySnapDef.Height = iHeight;
            mySnapDef.SIM = strSIM;
            mySnapDef.Type = strIntrinsicName ;
            this.onSnapInLoaded.subscribe(this.onContentReady, mySnapDef);            
            lCloned = l.clone(); //this would start a chain of actions   - calling registerSnap, postRegisterSnap, fire onContentReady          
            return lCloned;
        }

        //1.4  
        if (strIntrinsicName.indexOf('adapter') == 0 && true == bIsChild) //loading a snap as child window
        {
            l = l.copyBlueprint();
            //the content will be a child of the adapter.
   //         l.WindowStyle = NS2112.windowStyle.WS_CHILD;
        }
        

        //else -> hm...


        //not a new window - show content in our std window (recycle it if neccessary.
        //workaround for SAFARI - usually it would be sufficient to just reset the body.
        //...
        //hopefully removing this someday
        if (strIntrinsicName == 'content' && null != l.m_Panel) {
            l.m_Panel.destroy();
            l.m_Panel = null;  //set null the panel will be set up by showSnapIn later again...
        }


        //which SIM would host this snap?
        //currently we would simply put the content into the center SIM
        l.m_responsibleSIM = bFreeFloat==false?m_rSIMRegistry['center'].Name:m_rSIMRegistry[NS2112.NOWHEREMAN];  //important to set
        
        //showSnapIn will create a new Panel.
        //From V1.4 we have Container snapIns, that have only a panel and host other snapIns
        //Here we need to ask if the container panel is already created.
        //since these are not cloned, we can easily check their panel.

        //showSnapIn will call createSnapIn to create the panel.
        //if the container does not have a panel yet - create one
        if (!l.m_Panel   ) {            
            snapContainer = this.createContainer(l.Name, l.ID);  //creates a DOM DIV Element      
            //1.5: we need a new name in anycase to support other types of containers.
            if(  NS2112.WIDGET.HOSTSINGLE == l.Hosting )
				l = l.copyBlueprint();   
            m_rSIMRegistry[strSIM].showSnapIn(l, snapContainer, l.Name, null);            
            l.Title = strTitle;
            l.m_Panel.setTitle(strTitle);
            l.m_Panel.setBody(l.loadContent(l.Name, strObject));
            l.m_Panel.setNavBackListener(l.queryNavBack);
            l.m_Panel.setNavForthListener(l.queryNavForth);
            l.m_Panel.setReloadListener(l.queryNavReload);
            m_rSIMRegistry[strSIM].rebuild();
        }
        //*1.5 moved here since the snap could have gotten a new name
		//copy the intrinsic over to the snapin array so SIMs could manage it. If already inserted then just overwrite.
        m_rSnapRegistry[l.Name] = l;
        this.recycle(l);
        this.onSnapInRecycle.fire(l);
        //1.5 loading defaults... 
        if( typeof iWidth == 'undefined' )  iWidth = NS2112.portalMan.getContentWndExtX() ;
        if( typeof iHeight == 'undefined' ) iHeight = NS2112.portalMan.getContentWndExtY() ;
        
        //usually we do not resize CHILD but on single hosting parents we do.
        if( NS2112.WIDGET.HOSTMULTIPLE == l.Hosting ){
          ;  }
        else{
         l.Width = iWidth ;
		 l.Height = iHeight ;
         l.m_Panel.resizeWindowStation(iWidth, iHeight);
        }
        return l ; //1.5 - need whole snap not only .m_Panel;
    }




    //theDiv could be a string or an element
    this.hookDiv = function(theDiv, strTitle, iWidth, iHeight, strSIM) {
        var oCloned = null;
        var l = this.getIntrinsic('divHook'); //try to find a carrier for the request.
        if (null == l) {
            return;
        }
        //make copy of this snap
        oCloned = l.clone(); //this would start a chain of actions by calling registerSnapIn     
        //which SIM would host this snap?
        //currently we would simply put the content into the center SIM
        l.m_responsibleSIM = strSIM;  //important to set
        //copy the intrinsic over to the snapin array so SIMs could manage it.
        m_rSnapRegistry[l.Name] = l;
        l.Width = iWidth;
        l.Height = iHeight;
        l.Title = strTitle;
        m_rSIMRegistry[strSIM].showSnapIn(l, theDiv, l.Name);
        this.registerOverlay(l.m_Panel);
        m_rSIMRegistry[strSIM].rebuild();
    }




    this.getLayout = function() //unitname is top/left/bottom/right
    {

        var l = this.getIntrinsic('layout');
        if (l)
            return l.getIntrinsicObject().getSizes();
        else
            return null;
    }

    this.changeSkin = function(strCustomExt,
                              iHeaderHeight,
                              iFooterHeight,
                              strCSSUrl,
                              strCustomHeaderURL) {
        alert(strCustomHeaderURL);
        if (strCustomHeaderURL && strCustomHeaderURL.length > 0) {
            m_strCustomHeader = NS2112.masterControl.loadModule(strURL, false, false);
        }
        else
            m_strCustomHeader = null;
        //sync
        if (null != strCSSUrl && typeof strCSSUrl != 'undefined')
            NS2112.masterControl.loadCSS(strCSSUrl);

        for (var X in m_rSnapRegistry) //calling all SIMS
        {
            m_rSnapRegistry[X].m_Panel.changeSkin(strCustomExt,
                              iHeaderHeight,
                              iFooterHeight,
                              m_rSnapRegistry[X].Title,
                              m_strCustomHeader);
        }
        for (var X in m_rSIMRegistry) //calling all SIMS
        {
            m_rSIMRegistry[X].rebuild();
        }

    }

    this.recycle = function(theSnap) {
        if (!theSnap)
            return;
        var si = this.getIntrinsic('adapter.snap');
        if (si) si.getIntrinsicObject().show(theSnap.m_Panel);
        this.onSnapInRecycle.fire(theSnap);
        m_rSnapRegistry[theSnap.Name] = theSnap;
        if (m_rSIMRegistry[theSnap.m_responsibleSIM])  //check if it has a SIM (like FreeFloat doesn't)
            m_rSIMRegistry[theSnap.m_responsibleSIM].rebuild();
    }
    
    this.setClipboardData = function(strName, oData){
		this.onClipboardCut.fire(strName, oData);
    }

    //check our SIMReg - 
    this.dumpLayout = function() //debug functionality only - ignore
    {

        for (var X in m_rSIMRegistry) //calling all SIMS
        {
            //alert(X) ;

            NS2112.masterControl.Log('SIM [' + X + '] X [' + m_rSIMRegistry[X].XPos
                   + '] Y [' + m_rSIMRegistry[X].YPos + ' W [' + m_rSIMRegistry[X].Width
                   + '] H [' + m_rSIMRegistry[X].Height + ']'
                   , NS2112.CONST_CAT_INFO);

        }
    }

    //called on resize
    this.adjustLayout = function() {
        var size = this.getLayout();
        var maxHeight = YAHOO.util.Dom.getViewportHeight();
        if (!size) {
            NS2112.masterControl.Log("***************  adjustLayout size is undefined");
            return 0;
        }


        for (var X in m_rSIMRegistry) //calling all SIMS
        {
            if (typeof size[X].l == 'undefined') {
                size[X].l = null;
                NS2112.masterControl.Log("***************  adjustLayout size.left of  [" + X + "] is undefined");
            }
            if (typeof size[X].t == 'undefined') {
                NS2112.masterControl.Log("***************  adjustLayout size.top of  [" + X + "] is undefined");
                size[X].t = null;
            }
            m_rSIMRegistry[X].XPos = size[X].l == null ? 0 : size[X].l;
            m_rSIMRegistry[X].YPos = size[X].t == null ? 0 : size[X].t; ;
            m_rSIMRegistry[X].Width = size[X].w;
            m_rSIMRegistry[X].Height = size[X].h;
            m_rSIMRegistry[X].rebuild();
            if (m_rSIMRegistry[X].CurrentHeight > maxHeight) maxHeight = m_rSIMRegistry[X].CurrentHeight;
        }


        //I adjust the height of the doc - since backgrounds else would not appear when scrolled down...         

        if (maxHeight > 0) {
            document.body.style.height = maxHeight;
        }
        this.hideDragShim();
        NS2112.onConsoleOut.fire('adjustLayout');
    }
   //1.5 Drag Drop - find the 
   this.findDropTarget = function(x,y){ 
		var mySnapTarget = null ;
		for (var X in m_rSIMRegistry) //calling all SIMS
        {
			mySnapTarget =m_rSIMRegistry[X].hitTest(x, y);
			if(mySnapTarget) break ;
		}
		return mySnapTarget ; //can be null
   }

    this.findSnapByName = function(snapName) {
        var myCurrentSnap = null;
        var myTargetSnap = null;

        for (var X in m_rSnapRegistry) //calling all SIMS
        {
            myCurrentSnap = m_rSnapRegistry[X];

            if (myCurrentSnap.m_Panel && myCurrentSnap.m_Panel.getWindowName() == snapName) { //found 
                myTargetSnap = myCurrentSnap;
                break; //cannot be source and target at once.
            }
        }
        return myTargetSnap; //can be null
    }
    //1.5
    this.findSnapById = function(snapID) {
        var myCurrentSnap = null;
        var myTargetSnap = null;

        for (var X in m_rSnapRegistry) //calling all SIMS
        {
            myCurrentSnap = m_rSnapRegistry[X];

            if (myCurrentSnap && myCurrentSnap.ID == snapID) { //found 
                myTargetSnap = myCurrentSnap;
                break; //cannot be source and target at once.
            }
        }
        return myTargetSnap; //can be null
    }
    
    
    /*  obsolete - moved to snapIn12
    this.queryReload = function(snapID)
    {  
    var strIFrameID = 'IF_' + snapID ;   //IFRAME IDs are assembled by Prefix IF_ plus snapID  
    var f = document.getElementById(strIFrameID);
    if(f)
    f.src = f.src;
    }

*/



    //this would run as callback, so  
    //d o  n o t   r e l y   o n   a   v a l i d   t h i s   -    p  o i n t e r
    //A window wants to be displayed bigger or be resized to original extents.
    this.queryGrow = function(snapID) {
        var mySnap = NS2112.portalMan.getMasterControl().findSnapByName(snapID);
        var wm = NS2112.portalMan.getWindowManager();
        var iWidth;
        var iHeight;
        if (!mySnap ) return;
        if( null ==  mySnap.IsMaximized ){ 
			mySnap.IsMaximized = false ;
			return ;
        }
        
        wm.bringToTop(m_rSnapRegistry, mySnap.m_Panel.getWindow());
        

        if (true == mySnap.IsMaximized) { //already maxed? then set back to org size

            //it may occur that the snap has no SIM (FreeFloat).
            mySnap.restoreWnd();  //does a resize 
            if (m_rSIMRegistry[mySnap.m_responsibleSIM])
                m_rSIMRegistry[mySnap.m_responsibleSIM].rebuild();

            mySnap.IsMaximized = false;
            return;

        }

        if (false == mySnap.onMaximize()) //vetoed
            return; //do nothing

        mySnap.backupWnd();    //store attributes for restoring
        mySnap.m_Panel.moveTo(0, 0);
        iWidth = YAHOO.util.Dom.getViewportWidth();
        iHeight = YAHOO.util.Dom.getViewportHeight() - 72;
        mySnap.Width = iWidth;   //update extent
        mySnap.Height = iHeight;
        mySnap.X = 0;
        mySnap.Y = 0;
        mySnap.m_Panel.resizeWindowStation(iWidth, iHeight); //72 is arbitrary
        mySnap.IsMaximized = true;

    }

    this.activateWindow = function(thePanelName) {
        var mc = NS2112.portalMan.getMasterControl();
        var wm = NS2112.portalMan.getWindowManager();
        var theSnap = null;
        if (null != thePanelName && typeof thePanelName != 'undefined')
            theSnap = mc.findSnapByName(thePanelName);
        if (theSnap) wm.bringToTop(m_rSnapRegistry, theSnap.m_Panel.getWindow());

    }

    this.showDragShim = function() {

        var dragAccel = this.getDragShim();
        if (null != dragAccel) {
            dragAccel.style.zIndex = 65535; //bring to front
            dragAccel.style.left = '0px';
            dragAccel.style.top = '0px';
            dragAccel.style.width = YAHOO.util.Dom.getViewportWidth() + 'px';
            // ;YAHOO.util.Dom.getViewportHeight() + 'px' ;
            dragAccel.style.height = '1280px'; //use some big value (else would need to implement logic for scrolled windows) 
            dragAccel.style.display = 'block';
        }

    }

    this.hideDragShim = function() {
        var dragAccel = this.getDragShim();
        if (null != dragAccel) {
            dragAccel.style.height = YAHOO.util.Dom.getViewportHeight() + 'px';
            dragAccel.style.zIndex = -1;
            dragAccel.style.display = 'none';
        }

    }



    //Called once when dragging starts
    this.queryDrag = function(thePanelName) {
        //reset focus on all overlays. So we can float on top. Jun.6.08
        var mc = NS2112.portalMan.getMasterControl();
        if (bDragInProgress) return;
        var l = mc.getIntrinsic('layout');
        mc.showDragShim();
        if (l) {
            l.drawGrid();
        }
        mc.activateWindow(thePanelName);
        bDragInProgress = true;



    }

    //called once when resize is finished (mouse release on resize handle).
    this.onSnapStartResize = function(thePanelName, x, y, width, height) {
        var mc = NS2112.portalMan.getMasterControl();
        if (!mc) return;
        var l = mc.getIntrinsic('layout');
        if (l) l.drawGrid();
    }

    //called once when resize is finished (mouse release on resize handle).

    //TODO: on Layout 'brick' we need to check height constraint.
    this.onSnapEndResize = function(thePanelName, x, y) {

        var mc = NS2112.portalMan.getMasterControl();
        if (!mc) return;

        var theSnap = mc.findSnapByName(thePanelName);
        var theSIM = null;
        var bForceResize = true; ;
        if (theSnap) //rebuild stack
        {
            theSIM = m_rSIMRegistry[theSnap.m_responsibleSIM]; //this may result in a null (freeFloat).         
            if (theSIM) {
            
                if (theSnap.Width > theSIM.Width) {
                    theSnap.Width = theSIM.Width; 
                    bForceResize = false;
                    theSnap.m_Panel.resize( theSnap.Width, theSnap.Height );
                } //do not exceed boundaries
            
                
                if (theSnap.Width < 50) { theSnap.Width = 50; bForceResize = true }
                if (theSnap.Height < 50) { theSnap.Height = 50; bForceResize = true }
                
                
 //1.5 resize should no more be required, since rebuild does the job anyway.
                //if (true == bForceResize)
                //    theSnap.m_Panel.resizeWindowStation(theSnap.Width, theSnap.Height);
                // Do call rebuild only when window is not maximized (1.4RC)
                if (false == theSnap.IsMaximized) {
                    theSIM.rebuild();
                }
            }
        }

        var l = mc.getIntrinsic('layout');
        if (l) l.hideGrid();
        mc.hideDragShim();
    }
    //fires constantly while resize handle is dragged.
    //A word from the author:
    //For absolute performance, we do next to no boundary checking here
    //but let onSnapEndResize decide to check the constraints
    this.onSnapResize = function(thePanelName, x, y) {

        var mc = NS2112.portalMan.getMasterControl();
        if (!mc) return;
        var theSnap = mc.findSnapByName(thePanelName);
        if (!theSnap || !theSnap.m_Panel) return;
        //The new dimensions will be calculated and some logic applied to it (minSize/MaxSize)
        var iOffsY = NS2112.scrollOffsetY();
        var iOffsX = NS2112.scrollOffsetX();
        var iHeight = (y - theSnap.Y) + iOffsY;
        var iWidth = (x - theSnap.X); // iOffsX;

        mc.showDragShim();
        NS2112.onConsoleOut.fire('resizeWindowStation X/Y [' + theSnap.X + '/' + theSnap.Y + ']', NS2112.CONST_CAT_INFO);
        NS2112.onConsoleOut.fire('resize mouse x/y [' + x + '/' + y + ']', NS2112.CONST_CAT_INFO);

        NS2112.onConsoleOut.fire('resizeWindowStation w/h [' + iWidth + '/' + iHeight + ']');
        theSnap.m_Panel.resizeWindowStation(iWidth, iHeight);
        theSnap.Height = theSnap.m_Panel.getBodyHeight();  //The Width/Height Props are not the windows extensions.
        theSnap.Width = theSnap.m_Panel.getBodyWidth();   //They need to be re-calculated.
        window.status = 'ScrollY: ' + NS2112.scrollOffsetY() + ' X:' + x + '/' + theSnap.X + 'Y: ' + y + '/' + theSnap.Y + ' New Dims   [' + iWidth + '/' + iHeight + ']';

    }

    this.queryDrop = function(thePanelName, x, y, width, height) {  //check which sim was hit and inform it           
        var mySnapSource = null;
        var mySnapTarget = null;
        var myCurrentSnap = null;
        var mySourceSIM = null;
        var bFoundHost = false;

        
        var mc = NS2112.portalMan.getMasterControl();
        //debugger;  //ie
        bDragInProgress = false;
        var l = NS2112.portalMan.getMasterControl().getIntrinsic('layout');
        if (l) {
            l.hideGrid();
        }
       
        mc.hideDragShim();
        
        var iOffsY = NS2112.scrollOffsetY();
        var iOffsX = NS2112.scrollOffsetX();
        //translate position
        x += iOffsX;
        y += iOffsY;
      
        NS2112.onConsoleOut.fire("mc.queryDrop");
        //search the snap
        mySnapSource = mc.findSnapByName(thePanelName) ;
         //1.5. reset maximized
     
        if( true == mySnapSource.IsMaximized ){
			mySnapSource.IsMaximized = null ;  //is a tristate true/false/null
			mySnapSource.restoreWnd();						 
		}        
        
       
        //alert(myCurrentSnap.m_Panel.getWindowName()) ;

        if (mySnapSource != null && mySnapSource.m_Panel != null) {
            if (mySnapSource.FreeFloat) //return but set X/Y before leaving.
            {

                var el = mySnapSource.m_Panel.getWindow();
                if (el) {
                    mySnapSource.X = parseInt(el.style.left);
                    mySnapSource.Y = parseInt(el.style.top);
                }
                return;
            }
            //set snap to limbo state
            NS2112.onConsoleOut.fire("mc.queryDrop - Limbo", NS2112.CONST_CAT_INFO);
            mySourceSIM = mySnapSource.m_responsibleSIM; //must save this
            mySnapSource.m_responsibleSIM = '';      //unlink  

        }

        //search the sim-target
        for (var X in m_rSIMRegistry) //calling all SIMS
        {
            if (true == m_rSIMRegistry[X].queryDrop(x, y)) {
                if (true == m_rSIMRegistry[X].canHost(mySnapSource.Width, mySnapSource.Height) ||
                  (m_rSIMRegistry[X].Layout == NS2112.snapIn12Constraint.layoutColumn
                      && (mySnapSource.WindowStyle & NS2112.windowStyle.WS_FITTOHOST))) {
                    mySnapSource.m_responsibleSIM = X;  //set new SIM
                    NS2112.masterControl.Log("mc.queryDrop found SIM [" + mySnapSource.m_responsibleSIM + "]", NS2112.CONST_CAT_INFO);
                }
                else //no host
                {
                    NS2112.masterControl.Log("mc.queryDrop - found no host - resnapping", NS2112.CONST_CAT_INFO);
                    mySnapSource.m_responsibleSIM = mySourceSIM; //back to the origin.
                }

                break;
            }
        }

        //1.2.1
        var targetPos = 0;
        var sourcePos = 0;
        
       
        
        mySnapTarget = m_rSIMRegistry[mySnapSource.m_responsibleSIM].hitTest(x, y);
        
        
        if ( mySnapTarget ) {			
            targetPOS = mySnapTarget.POS;
            sourcePOS = mySnapSource.POS;
            mySnapSource.POS = -1;
            //dropped from another SIM 
            //dropper from same SIM 
            if (mySnapSource.m_responsibleSIM == mySnapTarget.m_responsibleSIM
         && targetPOS < sourcePOS) //dropped up
                m_rSIMRegistry[mySnapSource.m_responsibleSIM].incPos(targetPOS, sourcePOS);
            else if (mySnapSource.m_responsibleSIM == mySnapTarget.m_responsibleSIM
         && targetPOS > sourcePOS)  //different SIM
                m_rSIMRegistry[mySnapSource.m_responsibleSIM].decPos(sourcePOS, targetPOS);
            else //dropped from a different sim
            {

                m_rSIMRegistry[mySnapSource.m_responsibleSIM].incPos(targetPOS, 9999); // all
            }

            mySnapSource.POS = targetPOS; //take over position
            m_rSIMRegistry[mySnapSource.m_responsibleSIM].reposV2();
        }
        else {  //no target, simply set coords and let the SIM reorder
            mySnapSource.X = x;
            mySnapSource.Y = y;
        }
        //1.2.1 END      




        //just in case - revert back to orignating SIM when no host was found.
        if ('' == mySnapSource.m_responsibleSIM) mySnapSource.m_responsibleSIM = mySourceSIM;


        m_rSIMRegistry[mySnapSource.m_responsibleSIM].rebuild();
        m_rSIMRegistry[mySnapSource.m_responsibleSIM].closeGap(); //just in case
        m_rSIMRegistry[mySourceSIM].rebuild();
        m_rSIMRegistry[mySourceSIM].closeGap();
    }



    this.queryUnload = function(thePanelName) {
        //find the Panel and unload the snap.
        for (var X in m_rSnapRegistry) //calling all SIMS
        {
            if (!m_rSnapRegistry[X].m_Panel) continue;
            if (m_rSnapRegistry[X].m_Panel.getWindowName() == thePanelName)     //match
            {
                m_rSnapRegistry[X].unload(); //call the snap and ask it to leave 
                //NS2112.portalMan.getMasterControl().garbageCollect(m_rSnapRegistry[X]) ;
                NS2112.portalMan.getMasterControl().onSnapInUnload.fire(m_rSnapRegistry[X]); //to those who care
                theSIM = m_rSIMRegistry[m_rSnapRegistry[X].m_responsibleSIM];
                //m_rSnapRegistry[X].m_Panel.destroy() ;  //hm, this would lead to a runtime error...
                //m_rSnapRegistry[X].m_Panel = null ;
                delete (m_rSnapRegistry[X]);
                if (null != theSIM) {//Ask the associated SIM to regroup
                    theSIM.rebuild();
                    //theSIM.closeGap(m_rSnapRegistry[X]);
                }
                break;
            }
        }
        //tbi -> if not found?
    }


    this.getNewID = function(strName) //SIMs would call this to generate a Id
    {
        m_snapNum++;
        return strName + '.' + m_snapNum.toString();
    }

    this.registerOverlay = function(thePanel, bOnTop) {
        var wm = NS2112.portalMan.getWindowManager();
        wm.register(thePanel.getWindow());
        if (true == bOnTop)
            wm.bringToTop(m_rSnapRegistry, thePanel.getWindow());
        //set the titlebar listener to bring clicked windows to top
        thePanel.setTitlebarClickListener(this.activateWindow);

        //thePanel.ToolTip = new YAHOO.widget.Tooltip("tt1", { context:thePanel.getHeader(), text:"Red: Hide" });
    }

    this.getBugPrisonName = function() {
        return m_BugPrisonName;
    }

    this.getBugPrison = function() {
        if (null == m_BugPrison) //singleton
        {
            m_BugPrison = document.createElement("div");
            var a = document.createAttribute("id");
            a.nodeValue = "bugprison";
            m_BugPrison.setAttributeNode(a);
            document.body.appendChild(m_BugPrison);
            m_BugPrison.style.display = 'block';
        }
        else {
            m_BugPrison = document.getElementById(m_BugPrisonName);
        }
        return m_BugPrison;
    }


    this.getDragShim = function() {
        var strName = NS2112.portalMan.getDragShimName();

        if (strName == 'none') return null;
        if (!strName) strName = 'dragshim_2112'; //Default

        if (null == m_DragShim) //singleton
        {
            m_DragShim = document.createElement("div");
            var a = document.createAttribute("id");
            a.nodeValue = strName;
            m_DragShim.setAttributeNode(a);
            document.body.appendChild(m_DragShim);
            m_DragShim.style.zIndex = -1;
            m_DragShim.style.position = 'absolute';
            m_DragShim.style.left = '0px';
            m_DragShim.style.top = '0px';
            m_DragShim.style.backgroundColor = 'silver';
            m_DragShim.style.opacity = ".50";
            m_DragShim.style.filter = "alpha(opacity=50)";
        }
        else {
            m_DragShim = document.getElementById(strName);
        }
        return m_DragShim;
    }
    // containers will be created in the bugPrison first, to host the snapIn on creation.
    this.createContainer = function(strSnapName, strSnapID) {
		//fire Event that allows the caller to override the elContainer...
		//This call would set the snapIn's container in some cases (tabView)
		var theSnap = this.findSnapById(strSnapID) ;		
        if( theSnap && false == this.onCreatePanel.fire(theSnap) ) //someone has created an own container - leave this then.
           return null ; //theSnap.ParentContainerID ;               
        
        var myContainer = document.createElement("div");
        var a = document.createAttribute("id");
        a.nodeValue = strSnapName + m_iContainerID;
        m_iContainerID++;
        myContainer.setAttributeNode(a);
        this.getBugPrison().appendChild(myContainer);
        return myContainer;
    }



    this.countSnapIns = function(strSIMName) //result array
    {
        var iCount = 0;
        for (var X in m_rSnapRegistry) //calling all SIMS
        {
            if (m_rSnapRegistry[X].m_responsibleSIM == strSIMName)     //match
            {
                iCount++;
            }
        }
        return iCount;
    }



    //Deliver a list of snapins for a SIM
    //choose wether to receive an array or an object list
    this.getSnapIns = function(strSIMName, r_SnapIns, bAsArray) //result array
    {
        var iCount = 0;
        for (var X in m_rSnapRegistry) //calling all SIMS
        {
            if (m_rSnapRegistry[X].m_responsibleSIM == strSIMName)     //match
            {
                if (bAsArray)
                    r_SnapIns.push(m_rSnapRegistry[X]);
                else
                    r_SnapIns[X] = m_rSnapRegistry[X];
                iCount++;
            }
        }
        return iCount;
    }

    this.loadLayout = function() {
        if (!m_rSIMRegistry) m_rSIMRegistry = new Object();
        for (var i = 0; i < rLayout.length; i++) {
            var objSIM = new NS2112.snapInMan();
            objSIM.Name = rLayout[i].Name;
            objSIM.Width = parseInt(rLayout[i].Width, 10);
            objSIM.Height = parseInt(rLayout[i].Height, 10); //makes sense only for 'Bricks'.
            objSIM.XPos = parseInt(rLayout[i].XPos, 10);
            objSIM.YPos = parseInt(rLayout[i].YPos, 10);

            if (null != rLayout[i].Layout)
                objSIM.Layout = rLayout[i].Layout;
            else
                objSIM.Layout = NS2112.snapIn12Constraint.layoutColumn;
            //Add to the SIMS
            m_rSIMRegistry[objSIM.Name] = objSIM;
        }
    }

    this.loadCustomLayout = function() {
        units = this.getLayout();
        for (var X in units)  //this will provide a flexible mirror of configured layout
        {        //layout cells not configured will not create a snapInMan
            if (X == 'doc') continue; //ignore
            //alert(X) ;
            var objSIM = new NS2112.snapInMan();
            objSIM.Name = X;
            objSIM.Width = units[X].w;
            objSIM.Height = units[X].h; //makes sense only for 'Bricks'.
            objSIM.XPos = units[X].l + 1;
            objSIM.YPos = units[X].t + 1;

            if (X == 'bottom' || X == 'top')
                objSIM.Layout = NS2112.snapIn12Constraint.layoutBrick;
            //Add to the SIMS
            m_rSIMRegistry[objSIM.Name] = objSIM;
        }
        return (units != null);

    }
    //called on success
    this.loaderCallback = function(o) {
        var oAssocModule = null ;
        var i ;
        var strModuleName = '' ;
        var bLoadQueued = true ;


        NS2112.masterControl.Log('~~~~~loaderCallback ready: ' + o.data.theSnap.Name + '~~~~~~~~~~~~~~~~~~~~~') ;
//if( 'Repository' == o.data.theSnap.Name )
//if( 'Semitary' == o.data.theSnap.Name )
//    debugger ;
        //set load complete on all modules of this load.                
         //----  14.07.2009  ----if (NS2112.LoadControl.LoadComplete != NS2112.loadHistory[o.data.arTheLib]) {  //not in the load history yet    
           
            for(i=0; i<o.data.arTheLib.length;i++){ 
               if (NS2112.LoadControl.LoadComplete != NS2112.loadHistory[o.data.arTheLib[i]] ){
                 NS2112.onConsoleOut.fire('~~Set Complete~~~ ' + o.data.theSnap.Name + '~~~~~~~~' + o.data.arTheLib[i] + '~~~~~~~~~~~~~') ;
                 NS2112.loadHistory[o.data.arTheLib[i]] = NS2112.LoadControl.LoadComplete; //just insert a little bit with this key
               }
             }
         //}

         
   
         

                  
         //check wether we are complete
         for(i=0;  i < o.data.m_rWaitForMultipleObjects.length ; i++){         
             strModuleName = o.data.m_rWaitForMultipleObjects[i] ;
             
            //does this module have the LoadComplete? - if not, we cannot proceed - but have to wait.
            if( NS2112.loadHistory[strModuleName] != NS2112.LoadControl.LoadComplete){
               NS2112.onConsoleOut.fire(  '!!!!!!!! ' + o.data.theSnap.Name + ' will be deferred...') ;
               NS2112.loadQueue.push(o.data) ;  //for later checks
               NS2112.onConsoleOut.fire(  o.data.theSnap + ' -------  waiting for ------------' + strModuleName) ; 
               return ;
            }
         }

    
         //Start regular snapIn loading.
         o.data.mc.postRegisterSnap(o.data.theSnap, o.data.strSnapID);
         
         
         //do we have queued loads that are complete now?         
         //1.4 RC: release all assiociated when ready (NS2112.loadQueue)
         for( i = 0; i< NS2112.loadQueue.length; i++){
            bLoadQueued = true ;  //default to true 
            oAssocModule = NS2112.loadQueue[i] ;
            if(null == oAssocModule ) continue ;
            //debugger ;
            for(var k = 0; k < oAssocModule.m_rWaitForMultipleObjects.length; k++){
               if(NS2112.loadHistory[oAssocModule.m_rWaitForMultipleObjects[k]] != NS2112.LoadControl.LoadComplete){
                  bLoadQueued = false ;
                  break ;
               }
            }
               if( true == bLoadQueued  ){
                  //debugger ;
                  NS2112.onConsoleOut.fire('~~~~~~~~~!!!!~~~~~~loaderCallback: ' + oAssocModule.theSnap.Name + ' is ready for loading now.') ;
                  //temporary disabled: 
                  oAssocModule.mc.postRegisterSnap(oAssocModule.theSnap, oAssocModule.strSnapID);
                  NS2112.loadQueue[i] = null ;
                  oAssocModule = null ;
               }
              
            }
         
    }


    this.registerSnap = function(theSnap, strSnapID, rDependencyLibs) {
        var iInsertState = NS2112.LoadControl.Limbo  ; //Loader Control
        var rDependencyLibs_remain = new Array() ; //these are left from rDependencyLibs
        if (null == rDependencyLibs) {  //no libs required -> call postRegister              
            this.postRegisterSnap(theSnap, strSnapID);
            return;
        }

        NS2112.onConsoleOut.fire('registerSnap: ' + theSnap.Name) ;        
         var Loader = new NS2112.Loader(); 
         
         Loader.data["mc"] = this;
        //YUI! - snapIn requested dependecy libs.        
        for (var i = 0; i < rDependencyLibs.length; i++) {
              //loaderCallback will use this to keep a history updated
             
            iInsertState = Loader.require(rDependencyLibs[i]);  
            if( NS2112.LoadControl.LoadInsert == iInsertState ) //only take over modules that are not already loading.
               rDependencyLibs_remain.push(rDependencyLibs[i]) ;                      
            NS2112.loadHistory[rDependencyLibs[i]] = NS2112.LoadControl.LoadPending ; //just insert a little bit with this key
            NS2112.onConsoleOut.fire('Setting ' + rDependencyLibs[i] + ' to ' +  NS2112.LoadControl.LoadPending );
        }
        Loader.data["arTheLib"] = rDependencyLibs_remain ; //store what is left       
        
        if (null != rDependencyLibs && rDependencyLibs.length > 0) {
            //alert(strSnapID + " needs libs") ;
            Loader.data["theSnap"] = theSnap;
            Loader.data["strSnapID"] = strSnapID;
            Loader.onSuccess = this.loaderCallback; //this would fire postRegisterSnap
            Loader.insert();
        }
    }


    //on initial registering the snap would alway be displayed on slot Zero (TopMost/LeftMost)
    this.postRegisterSnap = function(theSnap, strSnapID) {
        var bFoundHost = false;
        var iWidth = 0;
        var iHeight = 7;

        //on registering we try to find a host for this snap
        //alert(theSnap.Name + '/' + theSnap.Intrinsic) ;
        if (true == theSnap.Intrinsic) //is it an intrinsic? No panel will be created for intrinsics, but load is called.
        {
			NS2112.onConsoleOut.fire('loading Intrinsic [' + theSnap.Name + ']') ;
            m_rIntrinsics[theSnap.IntrinsicType] = theSnap;
            theSnap.load(this.createContainer(theSnap.Name, theSnap.ID));
            this.onIntrinsicReady.fire(theSnap);
            this.onSnapInLoaded.fire(theSnap);   //need this for content snap... will call onContentReady
            return;
        }
        //1.4 RC - uniqueness of SnapIDs and Names
        if (null != m_rSnapRegistry && typeof m_rSnapRegistry[strSnapID] != 'undefined') {
            strSnapID = this.getNewID(strSnapID);
            theSnap.Name = this.getNewID(theSnap.Name); //must update the name also
        }

        NS2112.onConsoleOut.fire('registerSnap[' + theSnap.Name + '] Width  [' + theSnap.Width + ']', NS2112.CONST_CAT_INFO);
        NS2112.onConsoleOut.fire('registerSnap[' + theSnap.Name + '] Height  [' + theSnap.Height + ']', NS2112.CONST_CAT_INFO);


        //singleton: our simRegistry is fueled by an intrinisc snapin -> create it if not already
        if (null == m_rSIMRegistry) {
            m_rSIMRegistry = new Object();             //SINGLETON
            var theLayout = this.loadCustomLayout();   //Try to load a custom layout

            if (false == theLayout) {
                this.loadLayout();  //Standard
                NS2112.onConsoleOut.fire("No Layout snapIn found, loading Defaults.", NS2112.CONST_CAT_ERR);
            }
            else {
                NS2112.onConsoleOut.fire("Layout snapIn found, loaded custom.", NS2112.CONST_CAT_INFO);
                this.dumpLayout();
            }
        }

        '%' == theSnap.UnitW ? iWidth = YAHOO.util.Dom.getViewportWidth() / (theSnap.Width / 100) : iWidth = theSnap.Width;
        theSnap.UnitW = 'px';
        NS2112.onConsoleOut.fire('UnitW [' + theSnap.UnitW + '] vpwidth [' + YAHOO.util.Dom.getViewportWidth() + '] [' + theSnap.Width + ']', NS2112.CONST_CAT_INFO);
        NS2112.onConsoleOut.fire('[' + theSnap.Name + '] width was calculated to [' + iWidth + ']', NS2112.CONST_CAT_INFO);

        '%' == theSnap.UnitH ? iHeight = YAHOO.util.Dom.getViewportHeight() / (theSnap.Height / 100) : iHeight = theSnap.Height;
        theSnap.UnitH = 'px';
        NS2112.onConsoleOut.fire('[' + theSnap.Name + '] height was calculated to [' + iHeight + ']', NS2112.CONST_CAT_INFO);

        //?Where should we put the snap?
        //This function will be enhanced by respecting the snapins user - preference for a distinct sim.

        //first of all ask the prefferred sim to host - if it does not we have a small redundance in the for-loop, well...

        //!!!!!  Make sure you match the the Name
        //This is a name from the snapIn Object
        var mySnapDef = getSnapInDefinition(theSnap.Name);
        if (null != mySnapDef)
            NS2112.onConsoleOut.fire("###################### Search Def for [" +
                theSnap.Name + "] Found [" + mySnapDef.Name + "]",
                NS2112.CONST_CAT_INFO);
        else
            NS2112.onConsoleOut.fire("####################SNAPDEF is null for [" + theSnap.Name + "]", NS2112.CONST_CAT_INFO);


        //Does the snap has a preferrence for a specific SIM? - then ask to host
        if (null != mySnapDef && null != mySnapDef.SIM
          && typeof m_rSIMRegistry[mySnapDef.SIM] != 'undefined'
          && typeof mySnapDef.SIM != 'undefined' && mySnapDef.SIM.length > 0) {
            NS2112.onConsoleOut.fire("####################  The SNAP [" + theSnap.Name + "] wants SIM [" + mySnapDef.SIM + "]");

            if (m_rSIMRegistry[mySnapDef.SIM].canHost(iWidth, iHeight) ||
                  (m_rSIMRegistry[mySnapDef.SIM].Layout == NS2112.snapIn12Constraint.layoutColumn
                      && (theSnap.WindowStyle & NS2112.windowStyle.WS_FITTOHOST))) {
                theSnap.m_responsibleSIM = mySnapDef.SIM;
                theSnap.ID = strSnapID ;
                NS2112.onConsoleOut.fire("####################  ShowSnapIn [" + theSnap.Name + "]");
                //1.4. RC SIMReg now storing strSnapID as key else it would be possible to create duplicates -> SIM would not repos.
                m_rSnapRegistry[strSnapID] = theSnap;   //do not add the Snap before showSnapIn!         
                m_rSIMRegistry[mySnapDef.SIM].showSnapIn(theSnap, this.createContainer(strSnapID), strSnapID);                  
                this.adjustLayout();
                this.onSnapInLoaded.fire(theSnap); //to those who care
                return;
            }
            NS2112.onConsoleOut.fire("####################  SIM Rejected [" + theSnap.Name + "]");
        }
        //try to find a suitable SIM
        for (var X in m_rSIMRegistry) //calling all SIMS
        {
            NS2112.onConsoleOut.fire('canHost Asking SIM [' + X + ']', NS2112.CONST_CAT_INFO);
            if (m_rSIMRegistry[X].canHost(iWidth, iHeight)) {  //found a host
                bFoundHost = true;
                NS2112.onConsoleOut.fire('canHost SIM [' + X + '] will host [' + theSnap.Name + ']'
                 , NS2112.CONST_CAT_INFO);
                //set the SIMName into the Snap
                theSnap.m_responsibleSIM = X;
                theSnap.ID = strSnapID ;
                m_rSnapRegistry[strSnapID] = theSnap; 
                m_rSIMRegistry[X].showSnapIn(theSnap, this.createContainer(theSnap.Name, theSnap.ID), theSnap.Name);
                  //do not add the Snap before showSnapIn!
                this.onSnapInLoaded.fire(theSnap); //to those who care
                break;
            }
            if (!bFoundHost) //need to force insertion on any host.
            {
                //tbi
                NS2112.onConsoleOut.fire('canHost SIM [' + X + '] rejected.', NS2112.CONST_CAT_INFO);
            }
        }
        this.adjustLayout();
        this.onSnapInLoaded.fire(theSnap);
    }

    //Loading a single Snap
    this.loadSnapIn = function(strURL, strName, strTitle, strSIM, parentSnapID) {
        var rSnap = new Array();
        var mySnap = new SnapDef(strURL, strName, strTitle, strSIM, parentSnapID);
        /*
        if( true == NS2112.sandboxMode )
        {
        //  NS2112.include(mySnap.URL) ;

         var r_URLs = [ strURL ]; 

        return ;
        }
        */
        rSnap.push(mySnap);
        silo = new NS2112.snapInLoader();
        silo.loadSnap(rSnap);    //
    }

    //Calling all snapIns - by using our silo

    this.loadSnapIns = function() {
        rSnapIns.sort(posSort);
        //snapInLoader      

        //load the snapin table
        //when in sanbox mode then do a simple include, to allow debugging
        if (true == NS2112.sandboxMode) {
            var r_SnapIns = new Array();
            for (var i = 0; i < rSnapIns.length; i++) {
                //NS2112.include(rSnapIns[i].URL) ;
                r_SnapIns.push(rSnapIns[i].URL);

            }
            NS2112.snapInLoaderGlobals.embedScript(r_SnapIns, null);
            return;
        }
        var verb = NS2112.portalMan.getLoadMethod();
        if (!verb) verb = 'GET';
        silo = new NS2112.snapInLoader();
        silo.loadSnap(rSnapIns, verb);    //rSnapIns, currently global above.  
    }

    this.includeModule = function(strModuleName, bLoadMin, bLoadBeta) {
        //snapInLoader  
        if (true == NS2112.sandboxMode) {
            var strPath = NS2112.aPortalSettings['YUI_PATH'] + '/' + strModuleName + '/' + strModuleName;
            if (true == bLoadBeta) strPath += '-beta';
            bLoadMin == true ? strPath += '-min.js' : strPath += '.js';
            NS2112.include(strPath);
            return;
        }
        silo = new NS2112.snapInLoader();
        silo.loadModule(strModuleName, true, false, bLoadMin, bLoadBeta);
    }

    this.inlineModule = function(strModuleName) {
        //snapInLoader  
        if (true == NS2112.sandboxMode) {
            NS2112.include(NS2112.aPortalSettings['YUI_PATH'] + '/' + strModuleName + '/' + strModuleName + '.js');
            return;
        }
        silo = new NS2112.snapInLoader();
        return silo.loadModule(strModuleName, false, false);
    }

    //load the SIMS from the Layout definition

    /*INTRINSICS*/
    m_rIntrinsics['adapter.snap'] = null;
    m_rIntrinsics['logger'] = null;
    m_rIntrinsics['layout'] = null;

    m_silo = new NS2112.snapInLoader();
    strConfig = m_silo.loadBootConfig(NS2112.portalMan.getBootConfigURL());    //rSnapIns, currently global above.
    //set the global Array
    rSnapIns = YAHOO.lang.JSON.parse(strConfig); //this would yield an array with snapIn Modules.

    var strURL = NS2112.portalMan.getCustomCSS_URL();
    if (strURL)
        NS2112.masterControl.loadCSS(strURL);
    strURL = NS2112.portalMan.getCustomHeaderURL();
    if (strURL)
        m_strCustomHeader = NS2112.masterControl.loadModule(strURL, false, false);

}                            //END OF MC


//returns the portalman windowmanager.
//snapins should use this function and not access the windowManager instance directly
NS2112.masterControl.getWindowManager = function()
{
   return NS2112.portalMan.getWindowManager() ;
}
/*get all registered snapins*/
NS2112.masterControl.enumSnapIns = function(){
   return NS2112.portalMan.getMasterControl().enumSnapIns() ;
}

//Load all registered snapIns
NS2112.masterControl.loadSnapIns = function()
{
   NS2112.portalMan.getMasterControl().loadSnapIns() ;
}

NS2112.masterControl.getIntrinsic = function(strIntrinsicName)
{
   return NS2112.portalMan.getMasterControl().getIntrinsic(strIntrinsicName) ;
}


/*loads a snapins configuration file*/
/**/
NS2112.masterControl.getConfig = function(strSnapID)
{
   var mySnapDef = getSnapInDefinition(strSnapID) ;
   var strConfig ;
   
   if(!mySnapDef){
         
       return strConfig ;
   }

   silo = new NS2112.snapInLoader() ;
   if ( strSnapID )
   {
      strConfig = silo.loadSnapConfig (mySnapDef.URL + '.cfg') ;    //rSnapIns, currently global above.
   }
   return strConfig ;
}


/*change skin on the fly*/
NS2112.masterControl.changeSkin = function(strCustomExt, 
                              iHeaderHeight,
                              iFooterHeight,
                              strCSSUrl,
                              strHeaderUrl)
{

   NS2112.portalMan.getMasterControl().changeSkin(strCustomExt, 
                              iHeaderHeight,
                              iFooterHeight,
                              strCSSUrl,
                              strHeaderUrl) ;

}

//Used to manipulate the style of the Window for the Panel factory.
//Maybe this method should be replaced by a anonymous function (created on the fly).
NS2112.masterControl.beforeChildSnapPanelCreate = function(strEventName, rSnap, oCustom)
{
   mc.beforeSnapInCreate.unsubscribe(NS2112.masterControl.beforeChildSnapPanelCreate) ;
   if(!rSnap[0]) return ;
   var theSnap = rSnap[0] ;
   theSnap.WindowStyle = NS2112.windowStyle.WS_CHILD  ;
   theSnap.ParentContainerID = oCustom ;
}


NS2112.masterControl.requestSnap = function(strURL, strName, strTitle, strSIM, elParentContainer)
{
   var mc = NS2112.portalMan.getMasterControl() ;

   NS2112.onConsoleOut.fire('requestSnap [' + strName + ']');
   if(typeof strURL == 'undefined') return ; 
   if(typeof strName == 'undefined') return ; 
   if(typeof strTitle == 'undefined') strTitle = 'untitled' ;
   if(typeof strSIM == 'undefined') strSIM = null ; 
   if(elParentContainer != null && typeof elParentContainer != 'undefined')
   {  //Client wants to load this as a child window.
      mc.beforeSnapInCreate.subscribe( NS2112.masterControl.beforeChildSnapPanelCreate, elParentContainer) ;
   }
   mc.loadSnapIn(strURL, strName, strTitle, strSIM) ;
}  


/*TODO: when containerWidget is not present, we should try to load it from the net...*/
//types: currently only 'uwa', 'snap'. future: igoogle...
//CONTAINERWIDGET can be a literal - currently only 'tabview' is supported
NS2112.masterControl.requestWidget = function(strURL, strTitle, iWidth, iHeight, 
                  strType, strPreferredSIM, strContainerWidget)  
{
   var mc = NS2112.portalMan.getMasterControl() ;
   var containerWidget = null ;
   var bNewWindow = true ; //default
   var strWidgetType =  'adapter.' + strType.toLowerCase() ;
   var theSnap = null ;
   
   NS2112.onConsoleOut.fire('requestWidget [' + strURL + ']');


   if( null != strContainerWidget && typeof strContainerWidget != 'undefined'){
      //client want to be contained in another widget...
      //check if this widget exists
      containerWidget = mc.getIntrinsic(strContainerWidget) ;  //are we loaded?
      if(containerWidget) strWidgetType = strContainerWidget ;
   }   

   if(!containerWidget){
      NS2112.onConsoleOut.fire('Parent Widget not available: ' + strContainerWidget);      
   }

   //when no container found or none is requested then open a new Window
   bNewWindow = ( !containerWidget && strContainerWidget != '_SELF_') ;

   if ( true == bNewWindow && strWidgetType.indexOf('adapter.snap') == 0){ //load regular snap
      NS2112.masterControl.requestSnap(strURL, 'strName', strTitle, strPreferredSIM)
      return ;
   }


//Try to either load the container or the widget itself
   //containerWidget might be another instance now - (grid control).
   theSnap = mc.contentRequested( strWidgetType, strURL, strTitle, iWidth, iHeight, 0, 0, bNewWindow, 
                                                         false,   //no free float
                                                         strPreferredSIM) ;
   
   //now load the contained widget...
   //if we have found a container  then use it
   
   
   
   
   if( containerWidget ){
     //sure no one ever will love this code - containers can be host single (grid) or multiple snapIns (tabview).
     //when single then the container is the grid itself.
	 if(NS2112.WIDGET.HOSTSINGLE == theSnap.Hosting ){
		containerWidget = theSnap ; //itself
     }
     containerWidget.loadChild(strURL, strTitle, iWidth, iHeight, 
                  strType, strPreferredSIM, strContainerWidget) ;
   }
  /*1.5 DO NOT RETURN OBJECTS HERE! it would break the  client return theSnap ;*/
 
}


NS2112.masterControl.getSystemMessageWindow = function(strTitle, strContent, iWidth, iHeight){ 
	var mc = NS2112.portalMan.getMasterControl();	
    return mc.getSystemWindow(strTitle, strContent, iWidth, iHeight) ;
}

  

NS2112.masterControl.requestContent = function(strURL, strTitle, iWidth, iHeight, bNewWindow)
{
   NS2112.portalMan.getMasterControl().contentRequested( 'content', strURL, strTitle, iWidth, iHeight, 0, 0, bNewWindow, false) ;
}  


NS2112.masterControl.requestContentFloat = function( strURL, strTitle, iWidth, iHeight,  X, Y)
{
   return NS2112.portalMan.getMasterControl().contentRequested('content', strURL, strTitle, iWidth, iHeight, X, Y, 
                                                   true, true) ;  //newWindow = true, float = true
}  

NS2112.masterControl.embedObject = function( strObjectString, strTitle, iWidth, iHeight, bNewWindow, strPreferredSIM)
{
   if(typeof strPreferredSIM == 'undefined') strPreferredSIM = 'center' ;
   return NS2112.portalMan.getMasterControl().contentRequested('embedded', strObjectString, strTitle, iWidth, iHeight, 0,0,
                                       bNewWindow, false, strPreferredSIM) ;  //newWindow = true, float = true
}  

NS2112.masterControl.hookDiv = function(theDiv, strTitle, iWidth, iHeight, strSIM)
{
   return NS2112.portalMan.getMasterControl().hookDiv(theDiv, strTitle, iWidth, iHeight, strSIM) ;
}



NS2112.masterControl.doResize = function()
{
   NS2112.onConsoleOut.fire("beforeResize");   
   NS2112.portalMan.getMasterControl().adjustLayout() ;
   
}

NS2112.masterControl.Log = function(strMsg, strCategory)
{
   var l = NS2112.portalMan.getMasterControl().getIntrinsic('logger') ; //lowercase
   //if(l && l.IntriniscObject)
   //   l.getIntrinsicObject().Log(strMsg) ;
   YAHOO.log(strMsg, strCategory) ;
}


//no error checking - dev
NS2112.masterControl.registerSnapIn = function (theSnapIn, strUniqueID, rDependencies) 
{
   //1,4 RC - check uniqueness of the id and create a new one if not.
   
   NS2112.portalMan.getMasterControl().registerSnap(theSnapIn, strUniqueID, rDependencies) ;  
}

//Loaddup can override the check for single load only
NS2112.masterControl.loadModule = function(strURL, bEval, bAsync, cbCallback, bLoadDuplicates)
{
   silo = new NS2112.snapInLoader() ;
   
   if( typeof bLoadDuplicates == 'undefined' ) bLoadDuplicates = false ;
   
   if( false == bLoadDuplicates && 
      (null != NS2112.loadHistory[strURL] || typeof NS2112.loadHistory[strURL] != 'undefined')
      ) //the we have loaded already
	return ;
   NS2112.loadHistory[strURL] = NS2112.LoadControl.LoadComplete ;
   return silo.loadModule2(strURL, bEval, bAsync, cbCallback) ;    
}

NS2112.masterControl.requires = function (YUI_MODULE_NAME, bLoadMin, bLoadBeta) //yahoo, dom, event, dragdrop....
{
   //check if not already loaded
   if( null == YAHOO.env.getVersion(YUI_MODULE_NAME) ) //not loaded
   {
      NS2112.portalMan.getMasterControl().includeModule(YUI_MODULE_NAME, bLoadMin, bLoadBeta) ;
   }
}

NS2112.masterControl.inline = function (YUI_MODULE_NAME) //yahoo, dom, event, dragdrop....
{
   //check if not already loaded
   if( null == YAHOO.env.getVersion(YUI_MODULE_NAME) ) //not loaded
   {
      return NS2112.portalMan.getMasterControl().inlineModule(YUI_MODULE_NAME) ;
   }
}



NS2112.masterControl.loadCSS = function (strURI) //yahoo, dom, event, dragdrop....
{
   
   //TODO: (1.5) check the nod for existence first...
   m_styles =  document.getElementsByTagName("link");
   
   for(var i = 0; i<m_styles.length;i++)
   {
      if(m_styles[i].href == strURI){
         NS2112.masterControl.Log('NS2112.masterControl.loadCSS already loaded [' + strURI + ']') ;
         return ;
      }
   }


   var theCSS = document.createElement("link");   
/*
   theCSS.setAttribute("rel", "stylesheet");
   theCSS.setAttribute("type", "text/css");
   theCSS.setAttribute("href", file);
*/


   var a = document.createAttribute("rel");
   a.nodeValue = "stylesheet";
   theCSS.setAttributeNode(a);

    a = document.createAttribute("type");
   a.nodeValue = "text/css";
   theCSS.setAttributeNode(a);

    a = document.createAttribute("href");
   a.nodeValue = strURI;
   theCSS.setAttributeNode(a);

   document.getElementsByTagName('head').item(0).appendChild(theCSS);    

   //document.body.appendChild ( theCSS );
   
}








NS2112.namespace("snapIn12Constraint") ; //Precreate

NS2112.snapIn12Constraint.preferredWidth  = 200 ;
NS2112.snapIn12Constraint.preferredHeight = 150 ;
NS2112.snapIn12Constraint.layoutBrick = 'brick' ;
NS2112.snapIn12Constraint.layoutColumn = 'column' ;

//to be refined:
//must depend on the column/rowset
NS2112.snapIn12Constraint.maxExtX  = 700 ;
NS2112.snapIn12Constraint.maxExtY = 700 ;





NS2112.snapIn12 = function()
{  //Preset some stuff
   var m_responsibleSIM = '';
   var m_LoadPos = 0; 
   this.Title = 'I have no name!';
   this.Name =  '2112';
   this.ID   =   null ; //1.5
   this.Width =  NS2112.snapIn12Constraint.preferredWidth  ;
   this.UnitW  = 'px' ;
   this.Height = NS2112.snapIn12Constraint.preferredHeight ;
   this.UnitH  = 'px';
   this.X = 0;
   this.Y = 0;
   this.IsContainer = false ; //some Intrinsics may set this to true
   this.IsMaximized = false ; //init
   this.WindowStyle = NS2112.windowStyle.WS_VANILLA  ; //canclose, titlebar 
   this.CanClose = true ;
   this.ParentContainerID = null ; //when WS_CHILD is used we need a ParentContainer.
   this.Intrinsic = false ;
   this.IntrinsicType = null ; //internal use only
   this.IntrinsicObject = null ;
   this.FreeFloat = false ,
   this.Layout = NS2112.snapIn12Constraint.layoutBrick ; //there are two Layouts for a SnapIn: brick or pillar    
   this.CurrentSlot = 0 ; //the Slot in the SIM      
   this.AdjustHeight = false ; //let mc recalc height - not always what you want (useful for joomla module box).
   this.m_Panel  = null ;   
   this.makeHey = function(){alert("Hey");}
   this.load = function() {/*empty override this*/}; //called from mc to load the snap
   this.unload = function() {/*empty override this*/};
   this.clientContext = null ; //for clientData

   var m_prevWidth = this.Width ;   //for maximize/restore
   var m_prevHeight = this.Height ;
   var m_prevX = 0 ;
   var m_prevY = 0 ;
   //before maximze operation the previous window state must be saved
   this.backupWnd =function(){
      m_prevWidth = this.Width ;   //for maximize/restore
      m_prevHeight = this.Height ;
      m_prevX = this.X ;  //for free floating windows
      m_prevY = this.Y ;
   }

   this.restoreWnd = function(){
      this.Width = m_prevWidth ;
      this.Height = m_prevHeight ;
      this.m_Panel.resize(this.Width, this.Height) ;
      if( this.WindowStyle & NS2112.windowStyle.WS_FREEFLOAT ) {
         this.m_Panel.moveTo(m_prevX, m_prevY) ;         
         this.m_Panel.X = m_prevX
         this.m_Panel.Y = m_prevY ;
      }
   }
   
   this.onDrop = function(strContractName, oData){
	alert(strContractName + ' was dropped onto ' + this.Name) ;
   }
   
   
   //copy a snapIn
   this.copyBlueprint = function()
   {
      var oClone = NS2112.clone(this) ;
      var id = NS2112.portalMan.getMasterControl().getNewID(this.Name) ;
      oClone.Name =  id ;
      oClone.ParentContainerID = null ;
      oClone.m_Panel = null ;      
      return oClone ;
   }

   //clone would not only copy the object, but exec register also...
   this.clone = function()
   {
      var oClone = NS2112.clone(this) ;
      var id = NS2112.portalMan.getMasterControl().getNewID(this.Name) ;
      oClone.Name =  id ;
      //com._2112_.intrinsics_ - which is nonsense, since it does not an intrinsic - but it would work.
      NS2112.masterControl.registerSnapIn(oClone, "com._2112_.intrinsics_" + id) ;  
      return oClone ;
   }
   
   this.setTitle = function(strNewTitle){
		this.Title = strNewTitle ;
		this.m_Panel.setTitle(strNewTitle) ; 
	
   } ;

   //The standard IFRAME Loader for snapIns - see 'embedded' snap as a sample different behaviour.
   this.loadContent = function(strIFrameID, strURL, strType)
   {//standard overridable for content snapins to load an iframe
      var myIFrameSrc ; 
      
      if( null == strURL ) return ; //this might be intended by the caller
      
      //if (null == strType || typeof strType == 'undefined')     
      {
         myIFrameSrc = "\"" + strURL + "\" frameborder=\"0\"  width=\"100%\" height=\"100%\"" +
						   "  align=\"center\"" ;
         return "<div><iframe id=IF_" + strIFrameID + " src=" + myIFrameSrc + ">.</iframe></div>" ;      
      }      
   }
   this.onMaximize = function() //override this.
   {
      //return false to veto the operation.
      return true ;
   }  
   /*
      The navigation handlers - only executed when set from a content window.
   */
   this.queryNavReload = function(snapID)
   {  
      var strIFrameID = 'IF_' + snapID ;   //IFRAME IDs are assembled by Prefix IF_ plus snapID  
      var f = document.getElementById(strIFrameID);
      if(f)
         f.src = f.src;
   }

   this.queryNavBack = function(snapID)
   {  
      history.back() ;
   }

   this.queryNavForth = function(snapID)
   {  
      history.forward() ;
   }
   
   
   this.getIntrinsicObject = function()
   {
      return this.IntrinsicObject ;
   }

   this.setIntrinsicObject = function(objIntrinsic)
   {
      this.IntrinsicObject = objIntrinsic;
   }
   //append a div to a specific parent, or when NULL to the snapin content node
   
   this.appendChild = function(elParent, strID, strClass){
	  var theElement = document.createElement("div");         
	  var theParent = elParent ;
	  if( null == theParent && m_Panel )
	      theParent = m_Panel.getContentNode() ;
	      
	  if( null == theParent ) return ;
      a = document.createAttribute("id");
      a.nodeValue = strID ;
      theElement.setAttributeNode(a);
      
      if(typeof strClass != 'undefined' ){
		 a = document.createAttribute("class");
         a.nodeValue = strClass ;
         theElement.setAttributeNode(a);
      }
      
      theParent.appendChild( theElement ) ;
   }
     
}


   
/*
   The core SnapIn Manager
   Keeps Track of the Position of snapIns
   Handles Drag and Drop Operations
   Handles Serialization/Deserialization (someday)
*/

/**snapInMan or SIM in */
NS2112.snapInMan = function(theWindowMan, strName)
{     
   var m_rSnapIns = new Object() ;
   this.Name = strName ;
   this.XPos ;
   this.YPos ;
   this.CurrentHeight = 0 ;
   this.Layout = NS2112.snapIn12Constraint.layoutColumn ; //default layout is column

   //Width and Height are constraints to be checked
   //No Snap may exceed these bounds.
   //On queries form mc the SIM decides from these 
   //properties wether it could host the snap.
   this.Width ;    
   this.Height ;

   this.posSortY = function(a, b) {
      return (a.Y - b.Y);
   }

   //sort by POS property
   this.posSort = function  (a, b) {
      return (a.POS - b.POS);
   }

   /**
    * Rebuilding the stack of snapIns.
    * First all snapIns for this SIM are gathered from the MasterControl
    * Afterwards the snapIns are sorted by position and then
    * re-organized by the SIMs reposV method.
   */
   this.rebuild = function() 
   {
      m_rSnapIns = new Object () ;
      var wm = NS2112.portalMan.getWindowManager();
      var iCount = NS2112.portalMan.getMasterControl().getSnapIns(this.Name, m_rSnapIns) ;      
      var rWorkItems = new Array() ;
      var el = null ;
      
      var _spacing_x = NS2112.portalMan.getNumericSetting('WINDOWS', 'SPACING_X', NS2112.WINDOWSPACING_X) ; //dyn load       
      
      for( var X in m_rSnapIns)  //copy into slots
      {   
         //do not process WS_CHILD
         if(m_rSnapIns[X].WindowStyle & NS2112.windowStyle.WS_CHILD ){
            continue ;
         }
         //m_rSnapIns[X].IsMaximized = false ; //reset if maximzed.
         if( m_rSnapIns[X].WindowStyle & NS2112.windowStyle.WS_FITTOHOST ) 
         {
             m_rSnapIns[X].Width = this.Width - 2 * _spacing_x;
          
         }
         
        
         //1.5 DO NOT USE resizeWindowStation.
          if( m_rSnapIns[X].WindowStyle & NS2112.windowStyle.WS_MANAGECONTENT )
           {
           /* 1.5 Disabled...
            el = m_rSnapIns[X].m_Panel.getContentNode() ; 
            if(el) { el.style.height =  '96%' ; 
                     el.style.width = '98%'; el.style.overflow = 'auto' } ;   
             */
           }
           if( !(m_rSnapIns[X].WindowStyle & NS2112.windowStyle.WS_CHILD) )
            m_rSnapIns[X].m_Panel.resize(m_rSnapIns[X].Width, m_rSnapIns[X].Height) ;
         
         NS2112.masterControl.Log(this.Name + "+++++++++++++ EXT  " + X + "[" + m_rSnapIns[X].Width + "/" + m_rSnapIns[X].Height + "]");  
            
/*
        if( true === m_rSnapIns[X].AdjustHeight )  //if snap want's to get it's size managed
        {        
        }
*/
          
         rWorkItems.push(m_rSnapIns[X]) ;
      }
      rWorkItems.sort(this.posSortY);      
      this.CurrentHeight = this.reposV(rWorkItems) ;      
      wm.blurAll(m_rSnapIns) ; //1.5
   }

   this.hitTest = function (x, y){
      var iCount = NS2112.portalMan.getMasterControl().getSnapIns(this.Name, m_rSnapIns) ;      
      for( var X in m_rSnapIns)  //copy into slots
      {
         if( x >= m_rSnapIns[X].X && x <= (m_rSnapIns[X].X + m_rSnapIns[X].Width) &&
             y >= m_rSnapIns[X].Y && y <= (m_rSnapIns[X].Y + m_rSnapIns[X].Height) )
         return m_rSnapIns[X] ;
      }
      return null ;
   }
   //increment all snap Pos that are equal or higher the one in iPos (used for drop)
   //dropped up
   //alle inkrementieren, die grösser oder gleich dem Target sind
   this.incPos = function(iFrom, iTo)
   {
      var iCount = NS2112.portalMan.getMasterControl().getSnapIns(this.Name, m_rSnapIns) ;      
      for( var X in m_rSnapIns)  //copy into slots
      {         
        if( m_rSnapIns[X].POS >= iFrom &&  m_rSnapIns[X].POS <= iTo  )
           m_rSnapIns[X].POS+= 1 ;
      }
   }

/*shift up (but to lower Positions)*/
//dropped down
   this.decPos = function(iFrom, iTo)
   {
      var iCount = NS2112.portalMan.getMasterControl().getSnapIns(this.Name, m_rSnapIns) ;      
      for( var X in m_rSnapIns)  //copy into slots
      {         
        if(  m_rSnapIns[X].POS >= iFrom && m_rSnapIns[X].POS <= iTo )
           m_rSnapIns[X].POS-= 1 ;
      }
   }

   

   this.canHost = function(snapWidth, snapHeight) 
   { //decide, if we have capacity left to add another control  
         

      NS2112.masterControl.Log('canHost [' + this.Name + '] myLayout [' + this.Layout + ']', NS2112.CONST_CAT_INFO);
      NS2112.masterControl.Log('canHost [' + this.Name + '] SnapWidth [' + snapWidth + ']', NS2112.CONST_CAT_INFO);
      NS2112.masterControl.Log('canHost [' + this.Name + '] SnapHeight [' + snapHeight + ']', NS2112.CONST_CAT_INFO);
      NS2112.masterControl.Log('canHost [' + this.Name + '] my Width [' + this.Width + ']', NS2112.CONST_CAT_INFO);
      NS2112.masterControl.Log('canHost [' + this.Name + '] my Height [' + this.Height + ']', NS2112.CONST_CAT_INFO);
      if ( this.Layout == NS2112.snapIn12Constraint.layoutColumn)
      {            
         return (snapWidth <= this.Width) ;      
      }
      else  
         return  (snapHeight <= this.Height);         
   }

   this.queryDrop = function(x, y) //
   {
      NS2112.onConsoleOut.fire('queryDrop [' + x + '/' + y + ']');    
       if ( this.Layout == NS2112.snapIn12Constraint.layoutColumn)
         return ( x >= this.XPos && x <= this.XPos + this.Width) ;
      else
         return (x >= this.XPos && x <= this.XPos + this.Width) 
              && ( y >= this.YPos && y <= this.YPos + this.Height) ;
   }

   

   this.queryResize = function(newWidth)
   {
      var bRet = true;
      NS2112.portalMan.getMasterControl().getSnapIns(this.Name, m_rSnapIns) ;
      //we compare the new Value to the widest snapIn that has not 'FitToHost' set.
      for(var X in m_rSnapIns)
      {
          if( m_rSnapIns[X].WindowStyle & NS2112.windowStyle.WS_FITTOHOST ) continue ;
          if( newWidth < m_rSnapIns[X].Width ) return false ;
       }
       NS2112.onConsoleOut.fire('queryResize');    
      return bRet ;
   }

   


   this.reposSnapInsV = function(theSnap)
   {
      //Algorithmus:
      //gehe alle snaps durch, wenn du das Snap triffst, das auf iPos positioniert ist
      //übernehme dessen Y Pos 
      //Setze alle YPos der Snaps, die groesser oder gleiche der iPos sind auf Y + meine Höhe.

      theSnap.X = this.XPos + 1 ;
      theSnap.Y = this.YPos + 1;

      for(var X in m_rSnapIns)
      {
       
       if(m_rSnapIns[X].WindowStyle & NS2112.windowStyle.WS_CHILD )
         continue ;
       if( m_rSnapIns[X].POS == theSnap.POS )
          theSnap.Y = m_rSnapIns[X].Y ;     //simply take over this snaps Y0
       if( m_rSnapIns[X].POS >= theSnap.POS ) 
       {
         m_rSnapIns[X].POS++ ;
         m_rSnapIns[X].Y += theSnap.m_Panel.getWindowExtY() ; //theSnap.Height ;
         m_rSnapIns[X].m_Panel.moveTo(this.XPos, m_rSnapIns[X].Y) ; //YPos of this SIM
       }
      }  
      //finally move theSnap
      theSnap.m_Panel.moveTo(this.XPos, theSnap.Y) ;
   }

   this.reposSnapInsH = function(theSnap)
   {
      
   }
   //on relocation, we need to find a slot for this.
   this.relocSnap = function(theSnapIns, theSnap, POS, isNew) //handling is a bit different, when a new one arrives
   {
      
      if( true == isNew )
      {
         return ;
      }
      var tmpSnap = theSnapIns[POS] ; //save the old element

      //if null then there is no old element.
      if(null == tmpSnap) return ;


      iGap = theSnap.POS ;  //save gap where the old snap was
      theSnapIns[theSnap.POS] = null ; //empty the slot
      
      
      
      //now reloc all
      //Target (tmpSnap) and all following snaps will move one slot up
      //except we hit the tail, where no target is

      //Alle elemente vor der GAP rutschen jeweils eins hoch bis zur gap.
      
      for(var i = iGap; i>POS;i--) 
      {
         //the Gap will be filled - a new Gap is created
         theSnapIns[i] = theSnapIns[i-1];
         theSnapIns[i].POS = i ;
      }
      
      // alle Elemente hinter der Gap rutschen eins nach vorne
      for(var i = iGap; i<POS;i++) 
      {
         //the Gap will be filled - a new Gap is created
         theSnapIns[i] = theSnapIns[i+1];
         theSnapIns[i].POS = i ;
      }


      theSnap.POS = POS ;        //set the new position
      theSnapIns[POS] = theSnap ;//set at desired position.
   }


   //the elements are ordered - display from 0 to length-1
   this.reposV = function(theSnapArray)
   {
      var iOffsY = this.YPos ;
      var iHeight = 0 ;

      var _spacing_x = NS2112.portalMan.getNumericSetting('WINDOWS', 'SPACING_X', NS2112.WINDOWSPACING_X) ; //dyn load 
      var _spacing_y = NS2112.portalMan.getNumericSetting('WINDOWS', 'SPACING_Y', NS2112.WINDOWSPACING_Y) ;
      
      for(var i = 0; i< theSnapArray.length;i++)
      {
         if(null == theSnapArray[i].m_Panel) continue ;
         NS2112.masterControl.Log("+++++++++++++" + theSnapArray[i].m_Panel.getWindowName() + ' moveTo ' + (this.XPos + _spacing_x) + '/' + iOffsY);
      //alert(theSnapArray[i].m_Panel.getWindowName() + ' moveTo ' + (this.XPos + _spacing_x) + '/' + iOffsY) ;
         theSnapArray[i].m_Panel.moveTo(this.XPos + _spacing_x, iOffsY) ; //YPos of this SIM
         var element = document.getElementById(theSnapArray[i].m_Panel.getWindowName()) ;
         theSnapArray[i].X = this.XPos + _spacing_x;
         theSnapArray[i].Y = iOffsY + _spacing_y ;
         iOffsY +=  theSnapArray[i].m_Panel.getWindowExtY() + _spacing_y; //theSnapArray[i].Height ;         
         iHeight += theSnapArray[i].m_Panel.getWindowExtY() ; //theSnapArray[i].Height ;
      }
      return iHeight ;
   }

   this.reposV2 = function()
   {//like reposV but selecting snapArray first
      var myArray = new Array() ;
      NS2112.portalMan.getMasterControl().getSnapIns(this.Name, myArray, true) ;
      myArray.sort(this.posSort);       
      this.reposV(myArray) ;
   }

   this.closeGap = function()  //reorder after deleting or dropping away
   {
      var myArray = new Array() ;
      NS2112.portalMan.getMasterControl().getSnapIns(this.Name, myArray, true) ;
      myArray.sort(this.posSort);       
      for( var i = 0; i<myArray.length;i++){ //start over from index 0
         myArray[i].POS = i ;
      }

   }


 
   this.onContentLoaded = function (theSnap) 
   {
      //alert(myPanel.getWindowExtY() ) ;
      /*
      var newHeight = myPanel.getWindowExtY() ;
      xpRepos (theSnap.m_Panel, theSnap.Width, newHeight);
      theSnap.Height = newHeight;
      */
   }



   this.showSnapIn = function(theSnap, elContainer, strElementName, iPreferredPos) //optional: Position to insert, Default: Zero.
   {
     if (null == iPreferredPos || typeof iPreferredPos == 'undefined') iPreferredPos = 0; //Top or Leftmost Position
     applyConstraints(theSnap) ;
     //get all my snaps to check where to add this one
     var mc = NS2112.portalMan.getMasterControl()
     var elCustomContainer = null ; //a client provided container that overrides elContainer.
     mc.getSnapIns(this.Name, m_rSnapIns) ;
     theSnap.POS = iPreferredPos ;     
     //ask the snapIn to load itself 
	     //fire Event that allows the caller to override the elContainer...
//This call would set the snapIn's container
     mc.beforeSnapContainerCreate.fire(theSnap) ; 
    
     if( theSnap.ParentContainerID)
     {
         //alert('listener provides container [' + theSnap.ParentContainer.id + ']') ;
         elCustomContainer = document.getElementById(theSnap.ParentContainerID) ;
     }
     myEl = theSnap.load(null!=elCustomContainer?elCustomContainer:elContainer) ; //use bugPrison to first create hidden. 

     

     
     if(null == myEl) myEl = "<b>not loaded</b>" ; //do not display 
//alert('showSnapIn creating...') ;
     //V 1.4 - before creating via the panel factory a callback is called that could
     //set up things a bit differently.
     var bRet = mc.onCreatePanel.fire(theSnap) ;     

     myPanel = mc.createSnapIn(theSnap.Name, theSnap.Title,
                        myEl,  
                        theSnap.Width, theSnap.UnitW, theSnap.Height, theSnap.UnitH,                         
                        theSnap.WindowStyle, elCustomContainer) ; 
     
     theSnap.m_Panel = myPanel ; //store
	 mc.onSnapInContentLoaded.fire(theSnap, myEl) ;
     if( false == bRet ){ //client does not want a panel of its own! (i.e childWindows)
         //alert('Client vetoed panel creation - panel is: ' + theSnap.ParentContainerID) ;
         return ;
     }


     //adjust extend
     //theSnap.Width  = theSnap.m_Panel.getWindowExtX() ;      
     //theSnap.Height = theSnap.m_Panel.getWindowExtY() ;

     //reposSnapIns would set the initial X/Y Coords which is neccessary to sort the panels.

     if( this.Layout == NS2112.snapIn12Constraint.layoutColumn )
      this.reposSnapInsV(theSnap, iPreferredPos, true) ;  //Vertical repositioning. true -> a new snap is inserted
     else
      this.reposSnapInsH(theSnap, true) ;  //Horizontal repositioning. true -> a new snap is inserted   
    
}
     

//alert(theSnap.Name + "/" + myPanel.body.firstChild.clientHeight) ;

     

   
   this.showSnapIns = function(elBugPrison)
   { //load all registered
      NS2112.portalMan.getMasterControl().getSnapIns(this.Name, m_rSnapIns) ;
      for(var X in m_rSnapIns)
      {         
         snap = m_rSnapIns[X] ;
         if( null != snap )
         {
            //Show on the Canvas
            this.showSnapIn(snap) ;            
         }
         //else {} //todo - load error snap
      }
   }



//do not allow to rave on the canvas
//needs to be enhanced:
//The constraints depend on the layout...
   applyConstraints = function(theSnap)
   {
      if (typeof theSnap.Width == 'undefined' || null == theSnap.Width ) 
          theSnap.Width = NS2112.snapIn12Constraint.preferredWidth ;
      if (typeof theSnap.Height == 'undefined' || null == theSnap.Height ) 
         theSnap.Height = NS2112.snapIn12Constraint.preferredHeight ;
      if (theSnap.Width > this.Width )
           theSnap.Width = this.Width ;
      //if (theSnap.Height > this.Height ) //? this we should think over since Height may be endless
      //     theSnap.Height = this.Height ;
   }  

   this.unloadSnapIn = function(strSnapInName)
   {
      var si = NS2112.portalMan.getMasterControl().getSnapIn(strSnapInName) ;
      if( null != si)
         si.unload() ;
   }

   this.snapToSlot = function()
   {
      
   }   
   
} 
 //SIM Ends








