var rowOnClass = "rowOn";
var rowOffClass = "rowOff";

var docInsideModal = ((parent.frames.length == 1 && parent.document.getElementById("container")) ||
					   (window.dialogArguments && parent.document.getElementById("container")));

var ie = /MSIE/.test(navigator.userAgent) && !/Opera/.test(navigator.userAgent);
var is_ie = ie;
var moz = navigator.product == "Gecko" && !/Safari/.test(navigator.userAgent);
var is_ie = ie;
var safari = /Safari/.test(navigator.userAgent);

function getEl(name){return document.getElementById(name);}

if (moz)
{
	function extendEventObject()
	{
		Event.prototype.__defineSetter__("returnValue", function (b)
		{
			if (!b) window.event.preventDefault();
			return b;
		});

		Event.prototype.__defineGetter__("srcElement", function () 
		{
			var node = this.target;
			while (node.nodeType != 1) node = node.parentNode;
			return node;
		});

		Event.prototype.__defineGetter__("fromElement", function ()
		{
			var node;
			if (this.type == "mouseover")
				node = this.relatedTarget;
			else if (this.type == "mouseout")
				node = this.target;
			if (!node) return;
			while (node.nodeType != 1) node = node.parentNode;
			return node;
		});

		Event.prototype.__defineGetter__("toElement", function ()
		{
			var node;
			if (this.type == "mouseout")
				node = this.relatedTarget;
			else if (this.type == "mouseover")
				node = this.target;
			if (!node) return;
			while (node.nodeType != 1) node = node.parentNode;
			return node;
		});

		Event.prototype.__defineGetter__("offsetX", function ()
		{
			return this.layerX;
		});
		
		Event.prototype.__defineGetter__("offsetY", function ()
		{
			return this.layerY;
		});
	}
	
	function emulateEventHandlers(eventNames) 
	{
		for (var i = 0; i < eventNames.length; i++) 
		{
			el = document.getElementById("bodyDiv");
			
			if (el)
				el.addEventListener(eventNames[i], function (e) {window.event = e;}, true);
		}
	}

	function extendElementModel() 
	{
		HTMLElement.prototype.__defineGetter__("parentElement", function () {
			if (this.parentNode == this.ownerDocument) return null;
			return this.parentNode;
		});

		HTMLElement.prototype.__defineGetter__("children", function () {
			var tmp = [];
			var j = 0;
			var n;
			for (var i = 0; i < this.childNodes.length; i++) {
				n = this.childNodes[i];
				if (n.nodeType == 1) {
					tmp[j++] = n;
					if (n.name) {
						if (!tmp[n.name])
							tmp[n.name] = [];
						tmp[n.name][tmp[n.name].length] = n;
					}
					if (n.id)
						tmp[n.id] = n
				}
			}
			return tmp;
		});

		HTMLElement.prototype.contains = function (oEl) {
			if (oEl == this) return true;
			if (oEl == null) return false;
			return this.contains(oEl.parentNode);
		};
	}
	
	function emulateAttachEvent()
	{
		HTMLDocument.prototype.attachEvent =
		HTMLElement.prototype.attachEvent = function (sType, fHandler) {
			var shortTypeName = sType.replace(/on/, "");
			fHandler._ieEmuEventHandler = function (e) {
				window.event = e;
				return fHandler();
			};
			this.addEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);
		};

		HTMLDocument.prototype.detachEvent =
		HTMLElement.prototype.detachEvent = function (sType, fHandler) {
			var shortTypeName = sType.replace(/on/, "");
			if (typeof fHandler._ieEmuEventHandler == "function")
				this.removeEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);
			else
				this.removeEventListener(shortTypeName, fHandler, true);
		};
	}
	
	extendEventObject();
	extendElementModel();
}

// attach events
window.onbeforeunload = winOnBeforeUnload;
window.onunload = winOnUnload;
window.onload = winOnLoad;
window.onresize = winOnResize;
document.onclick = docOnClick;
document.ondblclick = docOnClick;

if (ie)
{
	document.ondrag = function () { return false; };
	document.onselectstart = docOnSelectStart;
}

var g_bIsLoaded = false;
var g_bIsDirty = false;

function winOnLoad()
{
	if (document.body.getAttribute('callBeforeOnLoad'))
		eval(document.body.getAttribute('callBeforeOnLoad'));
	
	if (window.moz)
	{
		emulateEventHandlers(["click"]);
		emulateEventHandlers(["mousedown"]);
	
		if (top.opener)
			window.dialogArguments = top.opener;
	}
				
	AdjustSize();
	InitListRows();
	InitMenuButtons();

	window.defaultStatus = "Alt-N WebAdmin";
		
	if (document.body.getAttribute('callOnLoad'))
		eval(document.body.getAttribute('callOnLoad'));
		
	g_bIsLoaded = true;
}

function winOnBeforeUnload()
{
	if (window.docCheckIsDirty)
		window.event.returnValue = docCheckIsDirty();
}

function winOnUnload()
{
	if (document.body.getAttribute('callOnUnLoad'))	
		eval(document.body.getAttribute('callOnUnLoad'));	
}

function winOnResize()
{
	AdjustSize();
}

function docOnClick() 
{
	InitMenuButtons();
}

function docOnSelectStart()
{
	var elem = window.event.srcElement;
	var allowSelect = false;
		
	if (elem.tagName == "INPUT" || elem.tagName == "TEXTAREA")
		return true;
		
	while (elem.tagName != "BODY")
	{
		if (elem.getAttribute("AllowSelect"))
		{
			allowSelect = true;
			break;
		} 
		else 
		{
			elem = elem.parentElement;
		}
	}
	
	return allowSelect;
}
	
function getDocumentName(location)
{
	var curLocation = new String(location);
	var ext = (curLocation.indexOf(".wdm")==-1) ? ".htm" : ".wdm";
	var sEnd = curLocation.indexOf(ext)+4;
	var sBeg = curLocation.lastIndexOf("/",sEnd)+1;
	return curLocation.substring(sBeg,sEnd);
}

function AdjustSize()
{
	var bodyDiv = document.getElementById('bodyDiv');
	
	if (!bodyDiv)
		return;
	
	var Height = window.innerHeight ? window.innerHeight : document.body.clientHeight;

	if (document.getElementById('HeaderTable'))
		Height -= document.getElementById('HeaderTable').offsetHeight;
		
	if (document.getElementById('ListTableTop'))
		Height -= document.getElementById('ListTableTop').offsetHeight;
		
	if (document.getElementById('StatusBar'))
		Height -= document.getElementById('StatusBar').offsetHeight;

	if (Height > 0)
		bodyDiv.style.height = Height;
		
	if (window.ie)
	{	
		var Width = window.innerWidth ? window.innerWidth : document.body.clientWidth;

		if (Width > 0)
			bodyDiv.style.width = Width;
	}
	
	if (window.updateCols)
		updateCols();
}

function SetIsDirty(element)
{
	if (!g_bIsLoaded)
		return;
		
	if (!g_bIsDirty && (!element || !element.readOnly))
	{
		g_bIsDirty = true;
		InitMenuButtons();
	}
}

function SetIsDirtyKey()
{
	if (!window.ie)
		SetIsDirty();
}

function SetIsDirtyChange()
{
	if (!window.ie)
		SetIsDirty();
}

function Cancel()
{
	var temp = document.location;
	document.location = temp;
}

function InitMenuButtons()
{
	var table = document.getElementById("toolbar");
	var bEnabled;
	
	if (!table || !table.rows[0])
		return;
	
	for (var i = 0; i < table.rows[0].cells.length; i++)
	{
		if (table.rows[0].cells[i].getAttribute("require"))
		{	
			bEnabled = eval(table.rows[0].cells[i].getAttribute("require"))
			table.rows[0].cells[i].setEnabled(bEnabled);
		}
	}	
}

function InitListRows()
{	
	if (document.waForm && document.waForm.SelectId && 
		 document.waForm.SelectId.value && document.getElementById("ListTableBot"))
	{
		var listRow = document.getElementById("ListTableBot").rows;
		var selectIdArr = document.waForm.SelectId.value.split(",");
		
		for (var g = 0; g < selectIdArr.length; g++)
		{
			for (var i = 0; i < listRow.length; i++)
			{
				if (listRow[i].getAttribute("glc_form_waForm_SelectId") == selectIdArr[g])
				{
					listRow[i].className = rowOnClass;
					ListControl.ActiveRows[ListControl.ActiveRows.length] = i;
					ListControl.startRowId = i;
				}
			}
		}
		
		var b = document.getElementById("bodyDiv");
		if (b) bDiv.focus();
	}
}

function InitToolbar()
{
	var table = document.getElementById("toolbar");
	var filter_button = document.getElementById("filter_button");
	
	if (!table) return;
		
	for (var i = 0; i < table.rows[0].cells.length; i++)
	{
		createButton(table.rows[0].cells[i]);
		if (table.rows[0].cells[i].getAttribute("require"))
			table.rows[0].cells[i].setEnabled(false);
	}
	
	if (filter_button)
		filter_button.setToggle(true);
	
	if (document.waForm && document.waForm.Filter && 
		 document.waForm.Filter.value.length > 0 && 
		 (document.waForm.FilterMatch.value != '1' || document.waForm.Filter.value != '*'))
	{
		if (filter_button)
			filter_button.setValue(true);
	}
}

function AddListItem(ListName)
{
	var input = eval('document.waForm.New'+ListName);
	var list  = eval('document.waForm.'+ListName);
	var value = input.value;
	
	if (value.length < 1)
		return;
		
	var bFound = false;
	
	for (var i = 0; i < list.length; i++)
	{
		if(list[i].text == value)
		{
			bFound = true;
			break;
		}
	}
	
	if (!bFound)
	{
		newOption = new Option();
		newOption.text = value;
		
		list.options[list.length] = newOption;

		SetIsDirty();
	}
	
	input.value = "";
}

function DeleteListItem(ListName)
{
	var list  = eval('document.waForm.'+ListName);
	var i = list.length;
	
	while(i--)
	{
		if(list.options[i].selected)
		{
			list.options[i] = null;
			SetIsDirty();
		}
	}
}

function ClearList(ListName)
{
	var list  = eval('document.waForm.'+ListName);
	var length = list.length;
	
	for (var i = 0; i < length; i++)
	{
		list.options[0] = null;
	}
	
	if (length > 0)
		SetIsDirty();
}

function EnableFormFields(bEn, ar)
{
	var i = ar.length, ff;

while(i--){
		if (!ar[i]){break;}
		ff = ar[i];
		if (ff.tagName == "FIELDSET"){ continue;}
		if (ff.tagName != "TEXTAREA" && ff.type != "text"){ff.disabled = (bEn ? false : true);}
		ff.readOnly = (bEn ? false : true);
		ff.disabled = (bEn ? false : true);
	}
}

function RequestHTTP(url)
{
	var xmlhttp = CreateXMLHTTPObject();
	xmlhttp.open('GET', url, true);
}

function PostXMLHTTP(formName, formUrl, displayXML, useThisForm)
{
	var bSaved = false;
	var resultingXML = null;
	var xmlhttp = CreateXMLHTTPObject();
	
	if (!xmlhttp) return;

	var form = useThisForm ? useThisForm : eval('document.'+formName+'.elements');
	var docName = getDocumentName(document.location);
	var urls = document.location.search.replace('?','');
	var postUrl = (formUrl)? formUrl : docName + '?postXML=1&' + urls;

	if (form.ItemList)
	{
		var length = form.ItemList.options ? 1 : form.ItemList.length;
		
		for (var i = 0; i < length; i++)
		{
			var TempList = "";
			var list = "";
			var formfield = "";
			
			if (form.ItemList.options)
			{
				list = eval('document.' + formName + '.' + form.ItemList.name);
				formfield = eval('document.' + formName + '.' + form.ItemList.name + 'List');
			}
			else
			{
				list = eval('document.' + formName + '.' + form.ItemList[i].name);
				formfield = eval('document.' + formName + '.' + form.ItemList[i].name + 'List');
			}

			for (n = 0; n < list.length; n++)
			{
				if (n == 0)
				{
					TempList = list[n].text;
					continue;
				}
				
				TempList += "|";
				TempList += list[n].text;	
			}
			
			formfield.value = TempList;
		}
	}
	
	var xmlString = '<root>\n<Form Name="'+formName+'" Document="'+docName+'" UrlVars="'+urls+'">\n';
	var i = form.length;
	
	while(i--) with (form[i])
	{
		try
		{
			if (name != "" && (type != "radio" || checked))
				xmlString+= ('<'+name+' Type="' +type+'"><![CDATA['+((type=="checkbox")?((checked)?1:0):value)+']]></'+name+'>\n');
		}
		catch(e) {}
	}
	
	xmlString += '</Form>\n</root>';

	if (displayXML) 
		alert("Sending XML:\n\n"+xmlString);

	xmlhttp.open('POST', postUrl, false);
	
	try
	{
		xmlhttp.send(xmlString);
	}
	catch(e)
	{
		alert("Unable to save data, error contacting server!");
	}
		
	if (xmlhttp.responseXML)
	{
		if (displayXML)
			alert("Returning XML:\n\n" + xmlhttp.responseText);
		
		var bSaved = false;
		var node = xmlhttp.responseXML.getElementsByTagName("PostResults");
		
		if (node[0])
		{
			if (node[0].getAttribute("Complete") == "true")
				bSaved = true;
			
			if (!bSaved)
			{
				if (node[0].getAttribute("Error"))
					eval("alert('" + node[0].getAttribute("Error") + "');");
					
				if (node[0].getAttribute("FormField"))
				{
					try 
					{
						eval('document.'+formName+'.'+node[0].getAttribute("FormField")).focus();
						eval('document.'+formName+'.'+node[0].getAttribute("FormField")).select();
					} 
					catch(e) {}
				}
			}
			else
			{
				node = xmlhttp.responseXML.getElementsByTagName("Message");
				
				if (node.length == 1)
					alert(node[0].childNodes[0].nodeValue);
			}
		}
	}
	else
	{
		alert("Unable to save data, the server returned an invalid response.");
	}
		
	if (bSaved)
	{
		g_bIsDirty = false;
		InitMenuButtons();
	}
	
	var finalResult = new Array();
	finalResult[0] = bSaved;
	finalResult[1] = xmlhttp.responseXML;
	return finalResult;
}

function CreateXMLHTTPObject()
{
	var xObject = null;

	try 
	{
		xObject = new ActiveXObject("Msxml2.xmlhttp.4.0");
	}
	catch (e)
	{
		try
		{
			xObject = new XMLHttpRequest(); 
		}
		catch (e)
		{
			try 
			{
				xObject = new ActiveXObject("Msxml2.xmlhttp");
			} 
			catch (e) 
			{
				try 
				{
					xObject = new ActiveXObject("Microsoft.xmlhttp");
				} 
				catch (e) 
				{
					alert("Error: Unable to create XML HTTP object!");
				}
			}
		}
	}

	return xObject;
}

function CreateModalWindow(url, width, height, sizeable, status, scroll, data)
{
	if (window.ie)
	{
		if (!data) data = window;
		if (!status) status = 'no';
		if (!scroll) scroll = 'no';
		if (!sizeable) sizeable = 'yes';
		
		winprops = 	"dialogHeight:" + height + "px;dialogWidth:" + width + "px;"+
					"edge:Raised;center:Yes;help:No;resizable:" + sizeable + 
					";status:" + status + ";scroll:" + scroll +";";
					
		var result = window.showModalDialog(url, data, winprops);
		return result;
	}
	else
	{
		var newWindowWidth   = (width) ? width : (screen.availWidth * .75);
		var newWindowHeight  = (height) ? height - 30 : (screen.availHeight * .75);
		var newWindowAttribs = "modal,width=" + newWindowWidth + ",height=" + newWindowHeight +
							   ",status=no,resizable=yes,menubar=no,toolbar=no";
	
		window.open(url, "", newWindowAttribs);
	}
}

function CreateWindow(newUrl, newWidth, newHeight)
{
	var newWindowWidth   = (newWidth) ? newWidth : (screen.availWidth * .75);
	var newWindowHeight  = (newHeight) ? newHeight : (screen.availHeight * .75);
	var newWindowAttribs = "modal,width="+newWindowWidth+",height="+newWindowHeight+",status=no,resizable=yes,menubar=no,toolbar=no";
	
	newUrl += (newUrl.indexOf("?") == -1) ? "?" : "&";

	window.open(newUrl,"",newWindowAttribs);
}

function cookie(name, val, expires, path)
{
	this.name = name;
	this.val = val;
	this.expires = expires;
	this.path = path;

	this.read = function()
	{
		var ckie = document.cookie;
		var ckName = this.name + "=", i = 0, x, end;

		while (i < ckie.length)
		{
			x = (i + ckName.length);
			if (ckie.substring(i, x) == ckName)
			{
				if ((end = ckie.indexOf(";", x)) == -1) { end = ckie.length; }
				return unescape(ckie.substring(x, end));
			}
			i = ckie.indexOf(" ", i);
			if (++i === 0) { break; }
		}
		return null;
	};

	this.set = function()
	{
		var tempExp = this.expires;
		var exp = new Date();
		var start = new Date(0);

		if (start.getTime() > 0)
		{
			exp.setTime(exp.getTime() - start.getTime());
		}

		exp.setTime(exp.getTime() + (this.expires * 86400000));
		this.expires = exp;

		document.cookie = this.name + "=" + escape(this.val) +
						  ((this.expires) ? "; expires=" + this.expires.toGMTString() : "") +
						  ((this.path) ? "; path=" + this.path : "");

		this.expires = tempExp;
	};

	this.kill = function()
	{
		document.cookie = this.name + "=" +
						  ((this.path) ? "; path=" + this.path : "") +
						  "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	};
}

function ReplaceURLVar(sQuery, sVar, sNewValue)
{
	if (!sQuery || !sVar) { return new String(); }
	sQuery = new String(sQuery);

	var question = sQuery.indexOf('?'), buffer = '', pairs = [], pair = [], i = 0, bMatch = false, poundMe = sQuery.indexOf('#'), sPounds = '';

	if (poundMe != -1)
	{
		sPounds = sQuery.substr(poundMe);
		sQuery = sQuery.substr(0, poundMe);
	}

	if (question == -1)
	{
		return sQuery + '?' + sVar + '=' + encodeURIComponent(sNewValue) + sPounds;
	}

	buffer = sQuery.substr(0, question + 1);
	sQuery = sQuery.substr(question + 1);
	pairs = sQuery.split('&');

	for (i = 0; i < pairs.length; i++)
	{
		pair = pairs[i].split('=');
		if (pair[0] == '') { continue; }
		buffer += (i == 0 ? '' : '&') + pair[0] + '=' + (pair[0] == sVar ? encodeURIComponent(sNewValue) : pair[1]);
		if (pair[0] == sVar) { bMatch = true; }
	}

	if (!bMatch && sNewValue != null)
	{
		buffer += (i == 0 ? '' : '&') + sVar + '=' + encodeURIComponent(sNewValue);
	}

	return buffer + sPounds;
}

function ValidateEmailAddress(emailAddress, bWildCard) 
{
	if (bWildCard)
	{
		if (emailAddress.length < 3)
			return false;
			
		if (emailAddress.indexOf("@") == -1)
			return false;
			
		return true;
	}
	
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\"[^\"\\]+\"))@((\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return re.test(emailAddress);
}

function ValidateIPAddress(IPAddress, bWildCard) 
{
	if (bWildCard)
	{
		if (IPAddress.length < 7)
			return false;
			
		var nIndex;
		
		if ((nIndex = IPAddress.indexOf(".")) == -1)
			return false;
			
		if ((nIndex = IPAddress.indexOf(".",nIndex)) == -1)
			return false;
			
		if ((nIndex = IPAddress.indexOf(".",nIndex)) == -1)
			return false;
			
		return true;
	}
	
	var re = /^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/;
	return re.test(IPAddress);
}

function ValidateInt(value) 
{
	if (value.length < 1)
		return false;
		
	var re = /^\d*$/;
	return re.test(value);
}
