// xFenster, Copyright 2004-2006 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xFenster(eleId, iniX, iniY, barId, resBtnId, maxBtnId, closeBtnId) // object prototype
{
  // Private Properties
  var me = this;
  var ele = xGetElementById(eleId);
  
  if(resBtnId != null)
  {
	var rBtn = xGetElementById(resBtnId);
  }
  
  if(maxBtnId != null)
  {
	  var mBtn = xGetElementById(maxBtnId);
  }
  
  if(closeBtnId != null)
  {
	   var cBtn = xGetElementById(closeBtnId);
  }
  
  
  var x, y, w, h, maximized = false;
  // Public Methods
  this.onunload = function()
  {
    if (!window.opera) { // clear cir refs
      xDisableDrag(barId);
	  if(rBtn != null)
	  {
      	xDisableDrag(rBtn);
		rBtn = null;
	  }
	  
	  if(mBtn != null)
	  {
		  mBtn.onclick = ele.onmousedown = null;
		  mBtn = null;
	  }
	  
	  if(cBtn != null)
	  {
		cBtn.onclick = ele.onmousedown = null;
		cBtn = null;
	  }
      
	 
      me = ele = null;
    }
  };
  this.paint = function()
  {
		if(rBtn)
		{
			xMoveTo(rBtn, xWidth(ele) - xWidth(rBtn), xHeight(ele) - xHeight(rBtn));
		}
		
		if(mBtn)
		{
			if(cBtn)
			{
				xMoveTo(mBtn, xWidth(ele) - (xWidth(mBtn) + xWidth(cBtn)), 0);
			}
			else xMoveTo(mBtn, xWidth(ele) - xWidth(mBtn), 0);
		}
		
		if(cBtn)
		{
			xMoveTo(cBtn, xWidth(ele) - xWidth(cBtn)- 10, 0);
		}
  };
  // Private Event Listeners
  function barOnDrag(e, mdx, mdy)
  {
    // Thanks to Jen for this feature:
    var x = xLeft(ele) + mdx;
    var y = xTop(ele) + mdy;
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    xMoveTo(ele, x, y);
  }
  function resOnDrag(e, mdx, mdy)
  {
    xResizeTo(ele, xWidth(ele) + mdx, xHeight(ele) + mdy);
    me.paint();
  }
  function fenOnMousedown()
  {
    xZIndex(ele, xFenster.z++);
  }
  function maxOnClick()
  {
    if (maximized) {
      maximized = false;
      xResizeTo(ele, w, h);
      xMoveTo(ele, x, y);
    }
    else {
      w = xWidth(ele);
      h = xHeight(ele);
      x = xLeft(ele);
      y = xTop(ele);
      xMoveTo(ele, xScrollLeft(), xScrollTop());
      maximized = true;
      xResizeTo(ele, xClientWidth(), xClientHeight());
    }
    me.paint();
  }
  
  function closeOnClick()
  {
	  xHide(ele);
  }
  
  function show()
  {
	  xShow(ele);
  }
  
  function hide()
  {
	  xHide(ele);
  }
  
  // Constructor Code
  xFenster.z++;
  xMoveTo(ele, iniX, iniY);
  this.paint();
  xEnableDrag(barId, null, barOnDrag, null);
  if(rBtn != null)
  {
	xEnableDrag(rBtn, null, resOnDrag, null);
  }
  
  if(mBtn != null)
  {
	mBtn.onclick = maxOnClick;
  }
  
  if(cBtn != null)
  {
	  cBtn.onclick = closeOnClick;
  }
  
  ele.onmousedown = fenOnMousedown;
  //xShow(ele); 
} // end xFenster object prototype

xFenster.z = 0; // xFenster static property
