function $(elementId) {
	return document.getElementById(elementId);
}

function hideElement(elementId) {
	document.getElementById(elementId).style.display = "none";
}

function showElement(elementId, displayStyle) {
	document.getElementById(elementId).style.display = displayStyle;
}

var clientWindowWidth, clientWindowHeight;
var scrOfX, scrOfY;

function getWindowSize() {
	clientWindowWidth = 0; clientWindowHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		clientWindowWidth = window.innerWidth; clientWindowHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
		clientWindowWidth = document.documentElement.clientWidth; clientWindowHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		clientWindowWidth = document.body.clientWidth; clientWindowHeight = document.body.clientHeight;
	}
	return { w : clientWindowWidth, h : clientWindowHeight };
}

function getScrollXY() {
	scrOfX = 0; scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset; scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop; scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		scrOfY = document.documentElement.scrollTop; scrOfX = document.documentElement.scrollLeft;
	}
	return { left : scrOfX, top : scrOfY };
}

function cancel(e) {
	if( e && e.preventDefault ) {
		e.preventDefault();		// DOM style
	}

	//if( e && e.returnValue )
	//	e.returnValue = false;	// IE style

	return false;			// IE style
}

function displayAlert(alertElement, alertText) {
	$(alertElement).innerHTML = alertText;
	$(alertElement).style.display = "block";	
	window.setTimeout("$(alertElement).style.display = 'none';", 5000);
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); }
String.prototype.ltrim = function() { return this.replace(/^\s+/g,""); }
String.prototype.rtrim = function() { return this.replace(/\s+$/g,""); }

function swapZIndex(e1, e2) {
	var zIndex = e1.style.zIndex;
	e1.style.zIndex = e2.style.zIndex;
	e2.style.zIndex = zIndex;
}

function addListener(eventSource, eventName, eventHandler, capturing) {
	eventSource.addEventListener ? eventSource.addEventListener(eventName, eventHandler, capturing) : eventSource.attachEvent ?
	eventSource.attachEvent("on" + eventName, eventHandler) : eventSource["on" + eventName] = eventHandler;
}

function centerElement(elementId, w, h) {
	var offset = getScrollXY();
	var windowSize = getWindowSize();
	$(elementId).style.left = (offset.left + ((windowSize.w * 0.5) - (w * 0.5))) + "px";
	$(elementId).style.top = (offset.top + ((windowSize.h * 0.5) - (h * 0.5))) + "px";
}


function grayOut(vis, options) {
	// Pass true to gray out screen, false to ungray
	// options are optional.  This is a JSON object with the following (optional) properties
	// opacity:0-100         // Lower number = less grayout higher = more of a blackout 
	// zindex: #             // HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx)    // Standard RGB Hex color code
	// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order.  Pass only the properties you need to set.
	
	var options = options || {}; 
	var zindex = options.zindex || 50;
	var opacity = options.opacity || 70;
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || "#000000";
	var lockBackground = options.lockBackground || false;
	var dark = $("darkenScreenObject");

	var pageOffset = getScrollXY();
	
	if( !dark ) {
		// The dark layer doesn't exist, it's never been created.  So we'll
		// create it here and apply some basic styles.
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917

		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement("div");		// Create the layer.
		tnode.style.position = "absolute";				// Position absolutely
		tnode.style.top  = pageOffset.top + "px";		// In the top
		tnode.style.left = pageOffset.left + "px";		// Left corner of the page
		tnode.style.display = "none";					// Start out Hidden
		tnode.id = "darkenScreenObject";				// Name it so we can find it later
		tbody.appendChild(tnode);					// Add it to the web page
		dark = $("darkenScreenObject");				// Get the object.
	}
	
	document.getElementsByTagName("body")[0].style.overflow = (lockBackground && vis) ? "hidden" : "auto";	

	if( vis ) {
		// set the shader to cover the entire page and make it visible.
		var windowSize = getWindowSize();

		dark.style.opacity = opaque;                      
	    	dark.style.MozOpacity = opaque;                   
	    	dark.style.filter = "alpha(opacity="+opacity+")"; 
	    	dark.style.zIndex = zindex;        
	    	dark.style.backgroundColor = bgcolor;
		dark.style.top		= pageOffset.top + "px";
		dark.style.left	= pageOffset.left + "px";
	    	dark.style.width	= windowSize.w + "px";
	    	dark.style.height	= windowSize.h + "px";
	    	dark.style.display	= "block";
	} else {
	     dark.style.display = "none";
	}			 
}


/*

The initHandler object allows modules to specify initialization functions that will be called
when a certain event is fired.

Use the following code at module level to add a function to the list:

initHandler.add(myFunc);  // myFunc is the name of a function

Use the initHandler.run() to call each function in the list:

<body onload="initHandler.run();">

*/

initHandler = {
	handler : new Array(),

	add : function(func) {
		this.handler.push(func);
	},

	run : function() {
		for(var i=0; i<this.handler.length; i++ ) {
			this.handler[i]();
		}
	}
}




// ---------------- limiting textarea length ------------------- //

var bName = navigator.appName;
 
function taAllowKeyPress(e) {
	if (!e) e = window.event;

	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;

	var source = e.target ? e.target : e.srcElement;

	var maxLength = source.getAttribute("maxlength");
	if( !maxLength )	
		maxLength = 300;

	if( source.value.length >= maxLength ) {
		cancel(e);
		return false;
	}

	return true;
}
 
function taCount(e) { 
	if (!e) e = window.event;
	var source = e.target ? e.target : e.srcElement;

	var maxLength = source.getAttribute("maxlength");

	if( !maxLength )	
		maxLength = 300;

	if( source.value.length > maxLength )
		source.value = source.value.substring(0, maxLength);

	var label = source.getAttribute("uselabel");
	var objLabel = getObject(label);

	if( objLabel ) {
		var textLength = maxLength - source.value.length;
		if( bName == "Netscape" ) {	
			objLabel.textContent = textLength.toString();
		} else {
			objLabel.innerHTML = textLength.toString();
		}
	}
}

function getObject(objId) {
	if (document.getElementById) return document.getElementById(objId);
	else if (document.layers) return eval("document." + objId);
	else if (document.all) return eval("document.all." + objId);
	else return eval("document." + objId);
}

// add event handlers to text-areas that have a 'maxlength' attributes 

function addLimitToTextAreas() {
	var allTextAreas = document.getElementsByTagName("textarea");
	for( var i = 0; i < allTextAreas.length; i++ ) {
		//alert(allTextAreas[i].id);
		var maxLength = allTextAreas[i].getAttribute("maxlength");
		if( !maxLength ) continue;

		var label = allTextAreas[i].getAttribute("uselabel");
		var objLabel = getObject(label);

		if( objLabel ) {
			var textLength = maxLength - allTextAreas[i].value.length;
			if( bName == "Netscape" ) {	
				objLabel.textContent = textLength.toString();
			} else {
				objLabel.innerHTML = textLength.toString();
			}
		}

		addListener(allTextAreas[i], "keyup", taCount, false);
		addListener(allTextAreas[i], "paste", taCount, false);
		addListener(allTextAreas[i], "keypress", taAllowKeyPress, false);
	}
}

initHandler.add(addLimitToTextAreas);




//----------------- pop up window -----------------//


var windowTopFixedWidth = 16;
var windowBottomFixedWidth = 16;
var windowSidesFixedHeight = 128;
var windowSidesPadding = 16;
var windowTopBottomPadding = 34;

var windowPercentHeight = 0.95;
var windowPercentWidth = 0.95;

function Window(w, h) {

	var me = this;
	var i = 0;
	while(1) {
		if( $("popUpWindow" + i) == null ) 
			break;
	
		i++;
	}

	this.contentWidth = 0;
	this.contentHeight = 0;

	this.popUpWindowDiv = document.createElement("div");
	this.popUpWindowDiv.id = "popUpWindow" + i;
	this.popUpWindowDiv.style.zIndex = 1100;
	this.popUpWindowDiv.style.display = "none";
	this.popUpWindowDiv.style.position = "absolute";

	this.popUpWindowDiv.innerHTML = getPopUpWindowHTML();

	this._width = w;
	this._height = h;

	this.onCloseWindow = null;

	document.body.appendChild(this.popUpWindowDiv);

	this.windowVisible = false;

	addListener(getChildElementById(this.popUpWindowDiv, "img", "closePopUp"), "click", function(e) {
		if( me.windowVisible == true ) {
			if (!e) e = window.event;

			me.popUpWindowDiv.style.display = "none";
			grayOut(false);
			me.windowVisible = false;
			//cancel(e);
			if( me.onCloseWindow )
				me.onCloseWindow();
		}
	}, false);

	//addListener(window, "resize", handleClientWindowResize, false);

	this.showWindow = function() {
		if( this.windowVisible == false ) {		
			grayOut(true, { lockBackground:true });

			this.resizeWindow(this._width, this._height);
			this.popUpWindowDiv.style.display = "block";
			this.windowVisible = true;
		}
	}

	this.hideWindow = function() {
		if( this.windowVisible == true ) {
			this.popUpWindowDiv.style.display = "none";
			grayOut(false);
			this.windowVisible = false;
		}
	}

	this.resizeWindow = function(w, h) {

		var scaleAmount = 1.0;
	
		overallWidth = w + windowSidesPadding;
		overallHeight = h + windowTopBottomPadding;
/*	
		if( overallWidth > (w*windowPercentWidth) ) {
			scaleAmount = (w*windowPercentWidth) / overallWidth;
		}
	
		if( overallHeight > (h*windowPercentHeight) ) {
			if( ((h*windowPercentHeight) / overallHeight) < scaleAmount ) {
				scaleAmount = ((h*windowPercentHeight) / overallHeight);
			}
		}
	
		if( scaleAmount != 1.0 ) {
			overallWidth *= scaleAmount;
			overallHeight *= scaleAmount;
	
			overallWidth = Math.round(overallWidth);
			overallHeight = Math.round(overallHeight);
		}	
*/	
		this.popUpWindowDiv.style.width = overallWidth + "px";
		this.popUpWindowDiv.style.height = overallHeight + "px";
	
		getChildElementById(this.popUpWindowDiv, "div", "topMiddleWindow").style.width = (overallWidth - windowTopFixedWidth) + "px";
		getChildElementById(this.popUpWindowDiv, "div", "bottomMiddleWindow").style.width = (overallWidth - windowBottomFixedWidth) + "px";
	
		getChildElementById(this.popUpWindowDiv, "div", "lowerSideLeftWindow").style.height = (overallHeight - windowSidesFixedHeight) + "px";
		getChildElementById(this.popUpWindowDiv, "div", "lowerSideRightWindow").style.height = (overallHeight - windowSidesFixedHeight) + "px";
	
		var contentArea = getChildElementById(this.popUpWindowDiv, "div", "contentArea");

		contentArea.style.width = (overallWidth - windowSidesPadding) + "px";
		contentArea.style.height = (overallHeight - windowTopBottomPadding) + "px";

		this.contentWidth = parseInt(contentArea.style.width);
		this.contentHeight = parseInt(contentArea.style.height);

	}

	this.resizeWindow(w, h);

	this.getContentElement = function() {
		return getChildElementById(this.popUpWindowDiv, "div", "contentArea");
	}
	
	this.center = function(w, h) {
		centerElement(this.popUpWindowDiv.id, parseInt(this.popUpWindowDiv.style.width), parseInt(this.popUpWindowDiv.style.height))
	}

	// default to centered within the document
	this.center(overallWidth, overallHeight);
}

/*
function handleClientWindowResize(e) {
	if( (windowVisible == false) )
		return;

	getWindowSize();
	getScrollXY();
	grayOut(true);

	getWindowSize();
	getScrollXY();

	SetPopUpWindowSize(clientWindowWidth, clientWindowHeight);

	LoadMainImage(popUpWindowMainImage.src, maxScaledMainImageWidth, maxScaledMainImageHeight);
}
*/

function getPopUpWindowHTML() {
	
	var popUpWindowDivInnerHTML = "<div id='leftBorderColumn' style='float: left;'>" +
	"<div id='topLeftWindow'></div>" +
	"<div id='upperSideLeftWindow'></div>" +
	"<div id='lowerSideLeftWindow'></div>" +
	"<div id='bottomLeftWindow'></div>" +
	"</div>" +
	
	"<div id='rightBorderColumn' style='float: right;'>" +
	"<div id='topRightWindow'></div>" +
	"<div id='upperSideRightWindow'></div>" +
	"<div id='lowerSideRightWindow'></div>" +
	"<div id='bottomRightWindow'></div>" +
	"</div>" +
	
	"<div id='middleColumn'>" +
	"<div id='topMiddleWindow'><img id='closePopUp' src='./border/closeButton.png' /></div>" +
	"<div id='contentArea' style='float: right;'></div>" +
	"<div id='bottomMiddleWindow' style='float: left;'></div>" +
	"</div>";
	
	return popUpWindowDivInnerHTML;
}


function getChildElementById(parent, childTagName, childId) {
	
	var allTags = parent.getElementsByTagName(childTagName);
	for (var i in allTags) {
		if( i == "length") continue;

		if( allTags[i].id == childId )
			return allTags[i];
	}
	return null;	
}




/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/
 
AIM = {
 
	createFrame : function(c) {
 
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:block;" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);
 
		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
 
		return n;
	},
 
	setFormTarget : function(formElement, name) {
		formElement.setAttribute('target', name);
	},
 
	submit : function(formElement, c) {
		AIM.setFormTarget(formElement, AIM.createFrame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},
 
	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}
 
		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}
}
