// Copyright 2001 by Mike Hall.
// See http://www.brainjar.com for terms of use.


var oOverlay=null;
// Determine browser and version.
var _is_ie = (navigator.userAgent.indexOf('MSIE')>=0)?true:false;

//=============================================================================
// Window Object
//=============================================================================

function Window(el) {

  var i, mapList, mapName;

  // Get window components.

  this.frame           = el;
  this.titleBar        = winFindByClassName(el, "titleBar");
  this.titleBarText    = winFindByClassName(el, "titleBarText");
  //this.titleBarButtons = winFindByClassName(el, "titleBarButtons");
  this.clientArea      = winFindByClassName(el, "clientArea");
  this.iframe          = winFindByClassName(el, "winFrame");
	
	this.fixPadding=(_is_ie)?10:9;
		
  this.clientArea.style.height=(this.frame.offsetHeight-(this.titleBar.offsetHeight+this.fixPadding))+"px";

  
  // Set flags.

  this.isOpen      = false;
  this.isMinimized = false;

  // Set methods.

  this.open       = winOpen;
  this.close      = winClose;
  this.minimize   = winMinimize;
  this.restore    = winRestore;
  this.makeActive = winMakeActive;

  // Set up event handling.

  this.frame.parentWindow = this;
  this.frame.onmousemove  = winResizeCursorSet;
  this.frame.onmouseout   = winResizeCursorRestore;
  this.frame.onmousedown  = winResizeDragStart;
	
																					
  this.titleBar.parentWindow = this;
  this.titleBar.onmousedown  = winMoveDragStart;

													
  this.clientArea.parentWindow = this;
  this.clientArea.onclick      = winClientAreaClick;
	
	// Calculate the minimum width and height values for resizing
  // and fix any initial display problems.

  var initLt, initWd, w, dw;

  // Save the inital frame width and position, then reposition
  // the window.

  initLt = this.frame.style.left;
  initWd = this.frame.offsetWidth;

  
  // Find the difference between the frame's style and offset widths. 
  //For IE, adjust the client area/frame width difference accordingly.

  
  w = this.frame.offsetWidth;
  this.frame.style.width = w + "px";
  dw = this.frame.offsetWidth - w;
  w -= dw;     
  this.frame.style.width = w + "px";
  
  if (_is_ie)
    this.widthDiff -= dw;

  // Find the minimum width for resize.

  this.isOpen = true;  // Flag as open so minimize call will work.
  this.minimize();
  // Get the minimum width.
  
  // For later versions of Gecko.
  this.minimumWidth = 300;

  // Set the minimum height.
  this.minimumHeight=(_is_ie)?300:293;


			//add button
			var img = document.createElement('IMG');
				img.src = 'scripts/window/images/winClose.png';
				img.id='imgClose';
				img.style.verticalAlign='middle';
				img.style.position='absolute';
				img.style.right='8px';
				img.style.top='16px';
				img.style.zIndex='1';
				img.style.cursor='pointer';
 				img.style.width  = '16px';
  			img.style.height = '16px';
  			img.style.display = 'block';
  			img.onclick=new Function ("winCtrl.active.close();return false;");
  			
			
		el.insertBefore(img,this.clientArea);
  	
  // Restore window. For IE, set client area width.

  this.restore();
  this.isOpen = false;  // Reset flag.
  initWd = Math.max(initWd, this.minimumWidth);
  
  // Restore the window to its original position.

  this.frame.style.left = initLt;
}

//=============================================================================
// Window Methods
//=============================================================================

function winOpen(w,h,t,l) {

  if (this.isOpen)
    return;

  // Restore the window and make it visible.
	this.frame.style.display = 'block';

	positionWin(this.frame,w,h,t,l);

  this.makeActive();
  this.isOpen = true;
  if (this.isMinimized)
  this.restore();
  
  this.clientArea.style.height=(this.frame.offsetHeight-(this.titleBar.offsetHeight+this.fixPadding))+"px";
  
  this.frame.style.visibility='visible';
  
}

function winClose() {

  // Hide the window.

	//this.frame.style.visibility='hidden';
  this.frame.style.display = "none";
  this.isOpen = false;
}

function winMinimize() {

  if (!this.isOpen || this.isMinimized)
    return;

  this.makeActive();

  // Save current frame and title bar text widths.

  this.restoreFrameWidth = this.frame.style.width;
  //this.restoreTextWidth = this.titleBarText.style.width;

  // Disable client area display.

  this.clientArea.style.display = "none";

  // Minimize frame and title bar text widths.

  if (this.minimumWidth)
    this.frame.style.width = this.minimumWidth + "px";
  else
    this.frame.style.width = "";
  //this.titleBarText.style.width = winCtrl.minimizedTextWidth + "px";

  this.isMinimized = true;
}

function winRestore() {

  if (!this.isOpen || !this.isMinimized)
    return;

  this.makeActive();

  // Enable client area display.
  this.clientArea.style.display = "";

  // Restore frame and title bar text widths.
  this.frame.style.width = this.restoreFrameWidth;
  //this.titleBarText.style.width = this.restoreTextWidth;

  this.isMinimized = false;
}

function winMakeActive() {

  if (winCtrl.active == this)   return;
  winCtrl.active = this;
}

//=============================================================================
// Event handlers.
//=============================================================================

function winClientAreaClick(event) {

  // Make this window the active one.

  this.parentWindow.makeActive();
}

//-----------------------------------------------------------------------------
// Window dragging.
//-----------------------------------------------------------------------------

function winMoveDragStart(event) {

  var target;
  var x, y;
  var evt=(_is_ie)?window.event:event;
  target = (_is_ie)?evt.srcElement.tagName:evt.target.tagName;
  if (target == "AREA") return;

  oOverlay.className = "overlayShow";
  this.parentWindow.makeActive();
	
	
  // Get cursor offset from window frame.
  x = (_is_ie)?evt.x:evt.pageX;
  y = (_is_ie)?evt.y:evt.pageY;
  
  winCtrl.xOffset = winCtrl.active.frame.offsetLeft - x;
  winCtrl.yOffset = winCtrl.active.frame.offsetTop  - y;
	
	
  // Set document to capture mousemove and mouseup events.
	  
  if (_is_ie) {
    document.onmousemove = winMoveDragGo;
    document.onmouseup   = winMoveDragStop;
  } else {
    document.addEventListener("mousemove", winMoveDragGo,   true);
    document.addEventListener("mouseup",   winMoveDragStop, true);
    event.preventDefault();
  }
	
  winCtrl.inMoveDrag = true;
}

function winMoveDragGo(event) {

  var x, y;
	var evt=(_is_ie)?window.event:event;

  if (!winCtrl.inMoveDrag)
    return;

	hideWinFrame();
	
  // Get cursor position.

  if (_is_ie) {
    x = evt.x;
    y = evt.y;
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else {
    x = evt.pageX;
    y = evt.pageY;
    event.preventDefault();
  }

  // Move window frame based on offset from cursor.
  winCtrl.active.frame.style.left = (x + winCtrl.xOffset) + "px";
  winCtrl.active.frame.style.top  = (y + winCtrl.yOffset) + "px";
}

function winMoveDragStop(event) {

  winCtrl.inMoveDrag = false;
	oOverlay.className = "overlayHidden";
	
  showWinFrame();
	
	// Remove mousemove and mouseup event captures on document.

  if (_is_ie) {
    document.onmousemove = null;
    document.onmouseup   = null;
  } else {
    document.removeEventListener("mousemove", winMoveDragGo,   true);
    document.removeEventListener("mouseup",   winMoveDragStop, true);
  }
}

//-----------------------------------------------------------------------------
// Window resizing.
//-----------------------------------------------------------------------------

function winResizeCursorSet(event) {

  var target;
  var xOff, yOff;
	var evt=(_is_ie)?window.event:event;

  if (this.parentWindow.isMinimized || winCtrl.inResizeDrag)
    return;

  // If not on window frame, restore cursor and exit.
  target = (_is_ie)?evt.srcElement:evt.target;
  if (target != this.parentWindow.frame) return;

  // Find resize direction.
  xOff = (_is_ie)?evt.offsetX:evt.layerX;
  yOff = (_is_ie)?evt.offsetY:evt.layerY;
  
  
  winCtrl.resizeDirection = "";
  if (yOff <= winCtrl.resizeCornerSize) 
  	winCtrl.resizeDirection += "n";
  else if (yOff >= this.parentWindow.frame.offsetHeight - winCtrl.resizeCornerSize)
    winCtrl.resizeDirection += "s";
  if (xOff <= winCtrl.resizeCornerSize)
    winCtrl.resizeDirection += "w";
  else if (xOff >= this.parentWindow.frame.offsetWidth - winCtrl.resizeCornerSize)
    winCtrl.resizeDirection += "e";

  // If not on window edge, restore cursor and exit.

  if (winCtrl.resizeDirection == "") {
    this.onmouseout(event);
    return;
  }

  // Change cursor.

  if (_is_ie){
    document.body.style.cursor = winCtrl.resizeDirection + "-resize";
    oOverlay.style.cursor=document.body.style.cursor;
  } else {
    this.parentWindow.frame.style.cursor = winCtrl.resizeDirection + "-resize";
    oOverlay.style.cursor=this.parentWindow.frame.style.cursor;
  }
}

function winResizeCursorRestore(event) {

  if (winCtrl.inResizeDrag) return;

  // Restore cursor.
  if (_is_ie) 	document.body.style.cursor = "";
  else  			this.parentWindow.frame.style.cursor = "";
  
  oOverlay.style.cursor="";
}

function winResizeDragStart(event) {

  var target;
	var evt=(_is_ie)?window.event:event;
  // Make sure the event is on the window frame.

  target = (_is_ie)?evt.srcElement:evt.target;
  if (target != this.parentWindow.frame) return;
	oOverlay.className = "overlayShow";
  this.parentWindow.makeActive();
	
  if (this.parentWindow.isMinimized) return;
  
  // Save cursor position.
  winCtrl.xPosition = (_is_ie)?evt.x:evt.pageX;
  winCtrl.yPosition = (_is_ie)?evt.y:evt.pageY;
  

  // Save window frame position and current window size.
  
  winCtrl.oldLeft   =this.parentWindow.frame.offsetLeft;
  winCtrl.oldTop    =this.parentWindow.frame.offsetTop;
  winCtrl.oldWidth  =this.parentWindow.frame.offsetWidth;
  winCtrl.oldHeight =this.parentWindow.frame.offsetHeight;
  
  // Set document to capture mousemove and mouseup events.

  if (_is_ie) {
    document.onmousemove = winResizeDragGo;
    document.onmouseup   = winResizeDragStop;
  } else {
    document.addEventListener("mousemove", winResizeDragGo,   true);
    document.addEventListener("mouseup"  , winResizeDragStop, true);
    event.preventDefault();
  }

  winCtrl.inResizeDrag = true;
}

function winResizeDragGo(event) {

 	var north, south, east, west;
 	var dx, dy;
 	var w, h;
	
	var evt=(_is_ie)?window.event:event;
  if (!winCtrl.inResizeDrag) return;

	hideWinFrame();
	
  // Set direction flags based on original resize direction.

  north = false;
  south = false;
  east  = false;
  west  = false;
  if (winCtrl.resizeDirection.charAt(0) == "n")	north = true;
  if (winCtrl.resizeDirection.charAt(0) == "s")	south = true;
  if (winCtrl.resizeDirection.charAt(0) == "e" 
  ||	winCtrl.resizeDirection.charAt(1) == "e")	east = true;
  if (winCtrl.resizeDirection.charAt(0) == "w" 
  ||  winCtrl.resizeDirection.charAt(1) == "w")	west = true;

  // Find change in cursor position.
  dx = ((_is_ie)?evt.x:evt.pageX) - winCtrl.xPosition;
  dy = ((_is_ie)?evt.y:evt.pageY) - winCtrl.yPosition;

  // If resizing north or west, reverse corresponding amount.

  if (west)  dx = -dx;
  if (north) dy = -dy;

  // Check new size.

  w = winCtrl.oldWidth  + dx;
  h = winCtrl.oldHeight + dy;
  if (w <= winCtrl.active.minimumWidth) {
    w = winCtrl.active.minimumWidth;
    dx = w - winCtrl.oldWidth;
  }
  if (h <= winCtrl.active.minimumHeight) {
    h = winCtrl.active.minimumHeight;
    dy = h - winCtrl.oldHeight;
  } 

  // Resize the window. For IE, keep client area and frame widths in synch.

  if (east || west) 
    winCtrl.active.frame.style.width = w + "px";
  
  if (north || south){
  	try{
  		winCtrl.active.frame.style.height = h + "px";
  		winCtrl.active.clientArea.style.height=(winCtrl.active.frame.offsetHeight-(winCtrl.active.titleBar.offsetHeight+winCtrl.active.fixPadding))+"px";
  	} catch(e) { }
  }
  
  // Clip the title bar text, if necessary.
  /*if (east || west) {
    if (w < winCtrl.active.clipTextMinimumWidth)
      winCtrl.active.titleBarText.style.width = (winCtrl.minimizedTextWidth + w - winCtrl.active.minimumWidth) + "px";
    else
      winCtrl.active.titleBarText.style.width = "";
  }
  */

  // For a north or west resize, move the window.

  if (west)
    winCtrl.active.frame.style.left = (winCtrl.oldLeft - dx) + "px";
  if (north)
    winCtrl.active.frame.style.top  = (winCtrl.oldTop  - dy) + "px";

  if (_is_ie) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else{
    event.preventDefault();
  }
}

function winResizeDragStop(event) {

  winCtrl.inResizeDrag = false;
	oOverlay.className = "overlayHidden";

  showWinFrame();


  // Remove mousemove and mouseup event captures on document.

  if (_is_ie) {
    document.onmousemove = null;
    document.onmouseup   = null;
  } else {
    document.removeEventListener("mousemove", winResizeDragGo,   true);
    document.removeEventListener("mouseup"  , winResizeDragStop, true);
  }
}

//=============================================================================
// Utility functions.
//=============================================================================

function winFindByClassName(el, className) {

  var i, tmp;

  if (el.className == className)
    return el;

  // Search for a descendant element assigned the given class.

  for (i = 0; i < el.childNodes.length; i++) {
    tmp = winFindByClassName(el.childNodes[i], className);
    if (tmp != null)
      return tmp;
  }

  return null;
}

function showWinFrame() {
  winCtrl.active.frame.style.background="#d2e8ff";
  winCtrl.active.frame.style.border='#083c84 3px solid';
  winCtrl.active.titleBar.style.visibility='visible';
	winCtrl.active.clientArea.style.display='block';
	document.getElementById('imgClose').style.display='block';
  
}	

function hideWinFrame() {
	winCtrl.active.frame.style.background=winCtrl.ResizeDragBg;
	winCtrl.active.frame.style.border=winCtrl.ResizeDragBorder;
	winCtrl.active.titleBar.style.visibility='hidden';
	winCtrl.active.clientArea.style.display='none';
	document.getElementById('imgClose').style.display='none';
}	
	

// Initialization code.
var winList = new Array();
var winCtrl = new Object();

function winInit(overlay) {

  var elList;

  // Initialize window control object.

	oOverlay = document.getElementById(overlay);

  winCtrl.maxzIndex                        = 1024;
  winCtrl.resizeCornerSize                 = 10;
  winCtrl.minimizedTextWidth               = 100;
  
  winCtrl.inMoveDrag                       = false;
  winCtrl.inResizeDrag                     = false;
	winCtrl.ResizeDragBg					 					 = "transparent";
	winCtrl.ResizeDragBorder					 			 = "2px solid #666666";
	
  // Initialize windows and build list.

  elList = document.getElementsByTagName("DIV");
  for (var i = 0; i < elList.length; i++)
    if (elList[i].className == "window")
      winList[elList[i].id] = new Window(elList[i]);
}


function positionWin(el,w,h,t,l){
	
 		var _w=window.innerWidth || document.documentElement.clientWidth || document.body.offsetWidth || 0;
 		var _h=window.innerHeight || document.documentElement.clientHeight || document.body.offsetHeight || 0;
		
		el.style.width=((typeof w !='undefined')?w:_w-200)+'px';
		el.style.height=((typeof h !='undefined')?h:_h-100)+'px';
	
		
		if ((typeof(t) =='undefined') ||(typeof(l) =='undefined') ) {
			// Center the BusyBox in the window regardless of the scroll positions
			el.style.top = (_h - el.offsetHeight) / 2+'px';
			el.style.left = (_w - el.offsetWidth) / 2 +'px';
			
		} else {
			// if both top and left positions specified
			el.style.top = t+'px';
			el.style.left = l+'px';
		}
		
}


function openWin(page,pageTitle,w,h,t,l){
	if (winList['win']){

		winList['win'].iframe.src='about:blank';
		winList['win'].iframe.src='scripts/window/wait.asp';
		winList['win'].titleBarText.innerHTML=pageTitle;
		
		setTimeout(
			function(){
				winList['win'].open(w,h,t,l); 
				winList['win'].iframe.src=page;
			}, 200); //wait a sec
	}
}

