/*	(c) 2007 Real Estate Data X-Change, Inc.
*	@author Everett Morse
*	Adapted from code by CodeLifter.com (c) 2003
*	(Since I don't care about Netscape 4, the show/hide methods don't support it, and maybe a few features don't either.)
*
*	A Popup Div as a JS object.
*	Handles the creation of the div itself and has methods to make interaction easier.
*	Can have multiple such divs on a page.
*/

//Browser compatibility -- detect which we have
isIE=document.all;
isNN=!document.all&&document.getElementById;
isN4=document.layers;

//Static vars
popupDivNextId = 0;			//each popup gets a unique id like "popup0"
popupDivCloseImg = "/images/close.gif";
popupDivDDEnabled = false;	//is dragging a popup
popupDivDDWhich = null;		//which popup is being dragged
popupDivs = [];				//the list of all popups (only needed by the close button to call the hide() method)

//On Load Handler -- Cannot finish the init until document.body has been fully loaded in IE.  So here we finish anything left undone
var popupPrevOnLoad = window.onload;
var popupBodyLoaded = false;
window.onload = function() {

//Event.observe(window,'load', function() {
	if( popupBodyLoaded ) return;
	popupBodyLoaded = true;
	
	document.onmousedown = ddInit;
	document.onmouseup = Function("popupDivDDEnabled=false");
	
	popupNumScroll = 0;
	
	for(c = 0; c < popupDivs.length; c++) {
		if( popupDivs[c].elemToAdd != null ) {
			document.body.appendChild(popupDivs[c].elemToAdd);
			popupDivs[c].elemToAdd = null;	//added
			if( popupDivs[c].onLoad ) popupDivs[c].onLoad();
		}
		if( popupDivs[c].scrollLock ) popupNumScroll++;
	}
	
	if( popupNumScroll > 0 ) popupScrollAttach();	//have at least one
	
	if( popupPrevOnLoad != null && typeof(popupPrevOnLoad) == 'function')
		popupPrevOnLoad();
};
//});

function PopupDiv()
{
	var isHot = false;	//if the title bar is being dragged (N4 only, so ignored)
	var id = null;		//the id of the master div.  TitleBar, TitleContent and Content are this id + "_TitleBar", "_TitleContent", and "_Content"
	var elemToAdd;		//the DIV element, if it has been created but not added (which happens when calling init before the document body is loaded)
	
	//Events
	var onShow = null;
	var onHide = null;
	var scrollLock = false;	//lock in position regardless of window scroll
	var onLoad = null;
	
	//Settings
	var bgColor;
	var titleColor;
	
	//Default Values (the above are nulls and falses, so doesn't matter)
	
	//this.bgColor = "#0055ee";
	//this.titleColor = "#ffffff";
	this.bgColor = "#000000";
	this.titleColor = "#ffffff";
}

PopupDiv.prototype = 
{
	//Creates the div
	init : function() {
		if( isN4 ) return;	//not supported
		if( this.id != null ) return;	//already has been inited
		
		var num = popupDivNextId++;
		
		var div = document.createElement('DIV');
		//date = new Date();
		//num = String(date.getSeconds()) + String(date.getMinutes()) + String(date.getHours()) + String(date.getDay());
		div.id = 'popup' + num;
		this.id = div.id;
		div.style.position = "absolute";
		div.style.width = "250px";
		div.style.left = "100px";
		div.style.top = "100px";
		div.style.visibility = "hidden";
		
		
		
		
		//onMouseover='isHot=true;if (isN4) ddN4("+this.id+")' onMouseout='isHot=false'
		
		//Title Content is width - 30, content is width - 10
		
		div.innerHTML = 
		"<div style='background-color:"+this.bgColor+";'>"+
		"	<div id='"+this.id+"_TitleBar' popupDiv='"+this.id+"' style='background-color: #000; height: 20px'>"+
		"		<div id='"+this.id+"_TitleContent' style='font-face: Arial; color: "+this.titleColor+"; cursor: move; padding: 2px 0 2px 10px; float: left; width: 220px; text-align: center;'></div>"+
		"		<div style='cursor:default; float:right; width:20px;'>"+
		"			<a href='#' onClick=\"popupDivs["+num+"].hide();return false\">"+
		"				<img src='"+popupDivCloseImg+"' border='0' style='padding: 2px 3px 0 0;'>"+
		"			</a>"+
		"		</div>"+
		" 	</div>"+
		"	<div id='"+this.id+"_Content' style='text-align: left;border-left: solid 1px #333; border-right: solid 1px #333; border-bottom: solid 1px #333; background-color: #fff; padding: 4px; overflow:auto'>"+
		"	</div>"+
		"</div>"
		;
		
		if( popupBodyLoaded ) {
			document.body.appendChild(div);
		} else {
			this.elemToAdd = div;	//can't add to the body until it has been loaded.  So let the onload handler do it
		}
		popupDivs[num] = this;
		
		//Need to add these to make it work - Dallin & eam - July 2008
		this._getElem(this.id+'_TitleBar').onmousedown = ddInit;
		this._getElem(this.id+'_TitleBar').onmouseup = function(){ popupDivDDEnabled = false; };
		
		//Give default Z-Index
		this._getElem(this.id).style.zIndex = 10;
	}
	,
	show : function() {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		$(this.id).style.visibility="visible";
		if( this.onShow != null && typeof(this.onShow) == 'function' )
			this.onShow(this);
	}
	,
	hide : function() {
		if( this.id == null ) return;	//nothing to hide
		$(this.id).style.visibility="hidden";
		if( this.onHide != null && typeof(this.onHide) == 'function' )
			this.onHide(this);
	}
	,
	// Position the popup to be centered on elem
	centerOn : function(elem) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		
		elem = $(elem);	//make sure I have an element vs id
		var div = $(this.id);
		var pt = this._getElementPosition(elem);
		
		div.style.top = ((elem.offsetHeight - div.offsetHeight)/2 + pt.y) + "px";
		div.style.left = ((elem.offsetWidth - div.offsetWidth)/2 + pt.x) + "px";
	}
	,
	// Position the popup centered on elem, then scoot it to be above (so it doesn't cover).  This will adjust the div so it is not off the top of the screen.
	centerAbove : function(elem) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		
		elem = $(elem);	//make sure I have an element vs id
		var div = $(this.id);
		var pt = this._getElementPosition(elem);
		
		var y = pt.y - div.offsetHeight - 2;
		var scrollY = this._getPageScrollY();
		if( y < scrollY ) y = scrollY;	//I don't like it off the top
		div.style.top = y + "px";
		div.style.left = ((elem.offsetWidth - div.offsetWidth)/2 + pt.x) + "px";
	}
	,
	// Position the popup to be centered in the browser window (accounts for scrolling, and doesn't place the top of the popup off the top of the screen)
	centerOnScreen : function() {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		var div = $(this.id);
		var scrollY = this._getPageScrollY();
		var y = (this._getPageHeight() - div.offsetHeight)/2 + scrollY;
		if( y < scrollY ) y = scrollY;	//I don't like it off the top
		
		var scrollX = this._getPageScrollX();
		var width = div.firstChild.offsetWidth + 20; //div.offsetWidth; doesn't work, need actual width.  So using the Table's width + padding
		var x = (this._getPageWidth() - width)/2 + scrollX;
		
		div.style.top = y + "px";
		div.style.left = x + "px";
	}
	,
	//Position the top-left of the popup on the top-left of the elem
	positionOn : function(elem) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		var pt = this._getElementPosition(elem);
		$(this.id).style.top = pt.y + "px";
		$(this.id).style.left = pt.x + "px";
	}
	,
	//position below like a dropdown
	positionDropDown : function(elem) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		var pt = this._getElementPosition(elem);
		var ptY = $(elem).getHeight() + pt.y;		
		$(this.id).style.top = ptY + "px";
		$(this.id).style.left = pt.x + "px";
	}
	,
	//Position the div at the full top-left of the screen
	positionLeft : function() {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		
		var div = $(this.id);
		var scrollX = this._getPageScrollX();
		var width = div.firstChild.offsetWidth + 20; //div.offsetWidth; doesn't work, need actual width.  So using the Table's width + padding
		
		div.style.left = ((this._getPageWidth() - width) - scrollX) + "px";
		div.style.top = (this._getPageScrollY()) + "px";	//at top
	}
	,
	// Keeps the div on the screen, so if it is off any of the sides, this scoots it back into the visible area.
	keepOnScreen : function() {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		
		var div = $(this.id);
		var scrollY = this._getPageScrollY();
		var scrollX = this._getPageScrollX();
		var y = Number(div.style.top.substr(0,div.style.top.length-2));
		var x = Number(div.style.left.substr(0,div.style.left.length-2));
		
		if( y + div.offsetHeight > scrollY + this._getPageHeight() ) {	//check bottom first, so if this scoots top off, we fix top next
			y = scrollY + this._getPageHeight() - div.offsetHeight;
		}
		if( y < scrollY )
			y = scrollY;
		
		if( x + div.offsetWidth > scrollX + this._getPageWidth() ) {
			x = scrollX + this._getPageWidth() - div.offsetWidth;
		}
		if( x < scrollX )
			x = scrollX;
		
		div.style.top = y + "px";
		div.style.left = x + "px";
	}
	,
	setScrollLock : function(lock) {
		this.scrollLock = lock;
		if( popupBodyLoaded ) {
			if( lock )
				popupScrollAdded();
			else
				popupScrollRemoved();
		}
	}
	,
	setWidth : function(width) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		width = new String(width).replace(/[^0-9]/gi,'');
		this._getElem(this.id).style.width = width + "px";
		this._getElem(this.id+'_TitleContent').style.width = (width-30) + "px";
	}
	,
	// If not null, sets a hieght and sets contents to scroll.  Otherwise clears the hieght and overflow properties
	setHeight : function(height) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		if( height == null ) {	//clear
			this._getElem(this.id).style.height = "";
			this._getElem(this.id).style.overflowY = "";
		} else {	//set up
			this._getElem(this.id).style.height = new String(height).replace(/[^0-9]/gi,'') + "px";
			this._getElem(this.id).style.overflowY = "auto";
		}
	}
	,
	setZ : function(z) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		this._getElem(this.id).style.zIndex = z;
	}
	,
	setPosition : function(x, y) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		this._getElem(this.id).style.top = y;
		this._getElem(this.id).style.left = x;
	}
	,
	//Returns a Point object { x : ..., y : ... }
	getPosition : function() {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		var div = this._getElem(this.id);
		var y = Number(div.style.top.substr(0,div.style.top.length-2));
		var x = Number(div.style.left.substr(0,div.style.left.length-2));
		var pt = { x : x, y : y };
		return pt;
	}
	,
	setScrollX : function(scrollX) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		if( scrollX ) {
			this._getElem(this.id).style.overflowX = "scroll";
		} else {
			this._getElem(this.id).style.overflowX = "";
		}
	}
	,
	setTitle : function(title) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		var elem = this._getElem(this.id+'_TitleContent').innerHTML = title;
	}
	,
	setContent : function(content) {
		if( this.id == null ) this.init();	//haven't been initted yet, so do so now.
		this._getElem(this.id+'_Content').innerHTML = content;
	}
	
	,
	//Returns a Point object with properties x and y
	_getElementPosition : function(elem) {
		elem = $(elem);	//make sure we have an element vs id
		var pt = { x : elem.offsetLeft, y : elem.offsetTop };
		//Some browsers give offset relative to containing elem, vs page
		while( elem.offsetParent != null ) {
			elem = elem.offsetParent;
			pt.x += elem.offsetLeft;
			pt.y += elem.offsetTop;
		}
		return pt;
	}
	,
	
	//Since there are cases where init doesn't add to the DOM yet, use this to always get the element we want
	_getElem : function(findId) {
		if( this.id == null ) {
			this.init();	//haven't been initted yet, so do so now.
			findId = findId.replace('undefined',this.id);
		}
		
		if( this.elemToAdd != null ) {
			//Need to search through a non-added element
			if (findId == "heightSet"){	alert("not null"); }
			if( findId == this.id ) {
				return this.elemToAdd;
			} else {
				//A div beneath
				var divs = this.elemToAdd.getElementsByTagName('DIV');
				for(c = 0; c < divs.length; c++) {
					if( divs[c].id == findId ) {
						return divs[c];
					}
				}
			}			
			return null;
		} else {
			return $(findId);
		}
	}
	,
	
	// Browser Window Size and Position
	// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
	// you may copy these functions but please keep the copyright notice as well
	// Modified 2007 by Everett Morse
	_getPageWidth : function() {
		return window.innerWidth != null? 
			window.innerWidth :
			document.documentElement && document.documentElement.clientWidth ?
				document.documentElement.clientWidth : 
				document.body != null ? 
					document.body.clientWidth : 
					null;
	}
	,
	_getPageHeight : function() {
		return  window.innerHeight != null? 
			window.innerHeight : 
			document.documentElement && document.documentElement.clientHeight ?
				document.documentElement.clientHeight : 
				document.body != null? 
					document.body.clientHeight : 
					null;
	}
	,
	_getPageScrollX : function () {
		return typeof window.pageXOffset != 'undefined' ? 
			window.pageXOffset :
			document.documentElement && document.documentElement.scrollLeft ? 
				document.documentElement.scrollLeft : 
				document.body.scrollLeft ? 
					document.body.scrollLeft : 
					0;
	}
	,
	_getPageScrollY : function() {
		return typeof window.pageYOffset != 'undefined' ?  
			window.pageYOffset : 
			document.documentElement && document.documentElement.scrollTop ? 
				document.documentElement.scrollTop : 
				document.body.scrollTop ? 
					document.body.scrollTop : 
					0;
	}
}



function ddInit(e){
	topElem = isIE? "BODY" : "HTML";
	elem = isIE? event.srcElement : e.target;  
	while( elem.getAttribute('popupDiv') == null && elem.tagName != topElem ) {
		elem = isIE? elem.parentElement : elem.parentNode;
	}
	if(elem.getAttribute('popupDiv') != null) {
		popupDivDDWhich = $(elem.getAttribute('popupDiv'));
		offsetx = isIE? event.clientX : e.clientX;
		offsety = isIE? event.clientY : e.clientY;
		nowX = parseInt(popupDivDDWhich.style.left);
		nowY = parseInt(popupDivDDWhich.style.top);
		popupDivDDEnabled = true;
		document.onmousemove = dd;
	}
}

function dd(e){
	if (!popupDivDDEnabled) return;
	popupDivDDWhich.style.left = (isIE ? nowX+event.clientX-offsetx : nowX+e.clientX-offsetx) + "px"; 
	popupDivDDWhich.style.top = (isIE ? nowY+event.clientY-offsety : nowY+e.clientY-offsety) + "px";
	return false;  
}

function ddN4(whatDog){ // unused, but if you fix the show/hide methods, then b/c of this, the div will work just fine
  if (!isN4) return;
  N4=eval(whatDog);
  N4.captureEvents(Event.MOUSEDOWN|Event.MOUSEUP);
  N4.onmousedown=function(e){
    N4.captureEvents(Event.MOUSEMOVE);
    N4x=e.x;
    N4y=e.y;
  }
  N4.onmousemove=function(e){
    if (isHot){
      N4.moveBy(e.x-N4x,e.y-N4y);
      return false;
    }
  }
  N4.onmouseup=function(){
    N4.releaseEvents(Event.MOUSEMOVE);
  }
}

var popupNumScroll = 0;
function popupScrollAdded() {
	popupNumScroll++;
	if( popupNumScroll == 1 )
		popupScrollAttach();	//first one
}
function popupScrollRemoved() {
	popupNumScroll--;
	if( popupNumScroll == 0 )
		popupScrollRemove();	//last one
}
function popupScrollAttach() {
	window.onscroll = popupScroll;
}
function popupScrollRemove() {
	window.onscroll = null;
}
function popupScroll() {
	for(c = 0; c < popupDivs.length; c++) {
		if( popupDivs[c].scrollLock ) {
			var div = $(popupDivs[c].id);
			div.style.top = popupDivs[c]._getPageScrollY();	//at top
		}
	}
}

