var inDebugMode = false;

function debugAlert(message)
{
	if (inDebugMode)
		alert(message);
}

//easy window closing function, attemts to refocus on parent
function closeWindow()
{
	try {window.opener.focus();}
	catch(ex) {}
	window.close();
}

//generic event bubble cancel function
function cancelEvent(e)
{
	if (e.cancelBubble)
		e.cancelBubble = true;
	if (e.stopPropogation)
		e.stopPropogation();
}

//generic confirm action function
function confirmAction(text)
{
	return confirm("Are you sure you would like to perform this " + text + "?");
}

//generic confirm delete function
function confirmDelete()
{
	return confirm("Are you sure you would like to delete the selected items?");
}

//easy retrieval of event target
function getEventTarget(e)
{
	var targ;

	if (e.target)
		targ = e.target;
	else if (e.srcElement)
		targ = e.srcElement;

	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

	return targ;
}

function getScrollTop()
{
	if (document.documentElement.scrollTop)
		return document.documentElement.scrollTop;
	if (document.body.scrollTop)
		return document.body.scrollTop;
	if (window.pageYOffset)
		return window.pageYOffset;
	return 0;
}

function getWindowHeight()
{
	if (window.innerHeight)
		return window.innerHeight;
	if (document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	if (document.body.clientHeight)
		return document.body.clientHeight;
	return 0;
}


///////////////////////////////////////////
// Common Page / Popup Opening Functions
///////////////////////////////////////////

//easy function to open page in parent window, if available.  if parent is not available, then open new window
function openInParent(url)
{
	try
	{
		window.opener.document.location = url;
		window.opener.focus();
	}
	catch(ex)
	{
		openWindowDefault(url,"NewWindow");
	}
}

//easy window opening functionality
function openWindow(url,windowName,args)
{
	window.open(url,windowName,args);
}

//easy window opening with default sizing and setup
function openWindowDefault(url,windowName)
{
	openWindow(url,windowName,"height=600,width=700,scrollbars=1,resizable=1");
}

function openDialogWindow(url,windowName)
{
	openWindow(url,windowName,"height=700,width=775,scrollbars=1,resizable=1");
}

function openDialogWindow2(url,windowName,finishAction,cancelAction,callback,callbackPrefix)
{
	//append params to url
	if (url.indexOf("?") >= 0)
		url += "&Master=Dialog";
	else
		url += "?Master=Dialog";
	if (finishAction) url += "&FinishAction=" + finishAction;
	if (cancelAction) url += "&CancelAction=" + cancelAction;
	if (callback) url += "&Callback=" + callback;
	if (callbackPrefix) url += "&CallbackPrefix=" + callbackPrefix;
	
	openWindow(url,windowName,"height=620,width=700,scrollbars=1,resizable=1");
}

function openPrintWindow(url,windowName,isLandscape)
{
	var width = isLandscape ? "1000" : "770";
	openWindow(url,windowName,"height=600,width=" + width + ",scrollbars=1,resizable=1,menubar=1");
}

function openWindowLandscape(url,windowName)
{
	openWindow(url,windowName,"height=612,width=800,scrollbars=1,resizable=1");
}

//execute command in opener window, with built in fail options
function execOpenerCommand(cmd,closeOnComplete)
{
	try
	{
		eval(cmd);
		if (closeOnComplete)
			closeWindow();
	}
	catch(ex)
	{
		alert("The original window is no longer open or available.  The command cannot be completed.");
	}
}

///////////////////////////////////////////
// Common Field Functions
///////////////////////////////////////////
function field_addClassName(el, className)
{
	field_removeClassName(el, className);
	el.className = (el.className + " " + className).trim();
}

function field_removeClassName(el, className) {
    el.className = el.className.replace(className, "").trim();
}

function field_onFocus(id)
{
	var field = document.getElementById(id);
	try
	{
		if (field)
		{
			if (field.value.length > 0)
				field.select();
			else
				field.focus();
		}			
	}
	catch (ex) {/*do nothing*/}		
}

//function will check all checkboxes in provided element
//if postfix provided, function will only check checkboxes with an id that ends with the postfix
function table_selectAllCheckboxes(id,check,postfix)
{
	var el = document.getElementById(id)
	if (el)
	{
		var fields = el.getElementsByTagName("input");
		for (var i=0; i<fields.length; i++)
		{
			var field = fields[i];
			if (field.type.toLowerCase() == "checkbox")
				if (!postfix || (field.id.match(postfix + "$") == postfix))
					field.checked = check;
		}
	}
}

///////////////////////////////////////////
// Common Textarea Functions
///////////////////////////////////////////
function textarea_onInsert(field, value) 
{
	//IE
	if (document.selection)
	{
		field.focus();
		sel = document.selection.createRange();
		sel.text = value;
	}
	//MOZILLA/NETSCAPE
	else if (field.selectionStart || field.selectionStart == '0')
	{
		var startPos = field.selectionStart;
		var endPos = field.selectionEnd;
		field.value = field.value.substring(0, startPos) + value + field.value.substring(endPos, field.value.length);
	}
	else
	{
		field.value += value;
	}
	field.focus();
}

///////////////////////////////////////////
// Common Select Box Functions
///////////////////////////////////////////
function select_addOption(field,text,value)
{
	if (field)
		field.options[field.options.length] = new Option(text,value);
}

function select_removeSelectedOptions(field)
{
	if (field)
	{
		for (var i=field.options.length-1; i>=0; i--)
		{
			if (field.options[i].selected)
				field.removeChild(field.options[i]);
		}
	}
}

///////////////////////////////////////////
// Trim Functions
///////////////////////////////////////////
function ltrim(str) 
{ 
    return str.replace(/^[ ]+/, ''); 
} 
 
function rtrim(str) 
{ 
    return str.replace(/[ ]+$/, ''); 
} 
 
function trim(str) 
{ 
    return ltrim(rtrim(str)); 
} 

///////////////////////////////////////////
// Repositioning Functions
///////////////////////////////////////////
function item_reposition(field,item,itemOutsideFixedArea)
{
	//wrap in try as sometimes the offsetLeft and offsetTop fail in IE
	try
	{
		var lft = field.offsetLeft;
		var tp = field.offsetTop;

		//determine position of field
		var o = field.offsetParent;
		while (o)
		{
			if (o.style.position != "fixed" && o.style.position != "absolute")
			{
				lft += o.offsetLeft;
				tp += o.offsetTop;
				o = o.offsetParent;
			}
			else
			{
				if (itemOutsideFixedArea)
				{
					lft += o.offsetLeft;
					tp += getScrollTop() + o.offsetTop;
				}
				o = null;
			}
		}

		//adjust top position for field height
		var fieldHeight = field.offsetHeight;
		var itemHeight = parseInt(item.style.height);
		var scrollAmt = getScrollTop();

		if (tp - itemHeight >= scrollAmt && tp + fieldHeight + itemHeight > getWindowHeight() + scrollAmt)
			tp -= itemHeight;
		else
			tp += fieldHeight;

		if (item.style.left != lft + "px")
			item.style.left = lft + "px";
		if (item.style.top != tp + "px") 
			item.style.top = tp + "px";
	}
	catch(ex)
	{;/* do nothing*/}
}


///////////////////////////////////////////
// Custom Validator Functions
///////////////////////////////////////////
function isDateFieldValid(value)
{
	return ((value.length > 0) && (!(isNaN(Date.parse(value)))));
}

function isDateValid(sender, args)
{
	args.IsValid = ((args.Value.length > 0) && (!(isNaN(Date.parse(args.Value)))));
}

function isEmailValid(sender, args)
{
	var reEmail = /^([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*@((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$/g;
	args.IsValid = (args.Value.search(reEmail) == 0);
}

function warnIfDateInPast(value)
{
	var dt = Date.parse(value);
	var today = new Date();
	if (dt < new Date(today.getFullYear(),today.getMonth(),today.getDate()))
		alert("You have selected a date in the past.");
}


///////////////////////////////////////////
// Rollover Functionality
///////////////////////////////////////////
//create global variables to hold info
var oImages = new Array()

//called from pages to preload rollover images
function preloadImages(directory,prefix,extension)
{
	//preload images for each image name passed
	for (var i=3;i<arguments.length;i++)
	{
		oImages[arguments[i] + "Off"] = new Image();
		oImages[arguments[i] + "Off"].src = directory + prefix + arguments[i] + "Off." + extension;
		oImages[arguments[i] + "On"] = new Image();
		oImages[arguments[i] + "On"].src = directory + prefix + arguments[i] + "On." + extension;
	}
}

function preloadTristateImages(directory,prefix,extension)
{
	//preload images for each image name passed
	for (var i=3;i<arguments.length;i++)
	{
		oImages[arguments[i] + "Off"] = new Image();
		oImages[arguments[i] + "Off"].src = directory + prefix + arguments[i] + "Off." + extension;
		oImages[arguments[i] + "On"] = new Image();
		oImages[arguments[i] + "On"].src = directory + prefix + arguments[i] + "On." + extension;
		oImages[arguments[i] + "Hover"] = new Image();
		oImages[arguments[i] + "Hover"].src = directory + prefix + arguments[i] + "Hover." + extension;
	}
}

function toggleImage(id)
{
	var img = document.getElementById(id + "Image");
	var alwaysOn = (img ? img.getAttribute("alwayson") : "");

	if (img && (alwaysOn != "1"))
	{
		try
		{
			if (img.src == oImages[id + "On"].src)
				img.src = oImages[id + "Off"].src;
			else
				img.src = oImages[id + "On"].src;
		}
		catch(ex) {;}
	}
}

function toggleTristateImage(id)
{
	var img = document.getElementById(id + "Image");
	var alwaysOn = img.getAttribute("alwayson");

	if (img && (alwaysOn != "1"))
	{
		try
		{
			if (img.src == oImages[id + "Off"].src)
				img.src = oImages[id + "Hover"].src;
			else if (img.src == oImages[id + "Hover"].src)
				img.src = oImages[id + "Off"].src;
		}
		catch(ex) {;}
	}
}

//set attribute on image preventing it from being changed
function setImageAlwaysOn(id)
{
	var img = document.getElementById(id + "Image");

	if (img)
	{
		toggleImage(id);
		img.setAttribute("alwayson","1");
	}

	//make sure valid reference was given
	//if (oImages[id + "Off"])
	//{
	//	oImages[id + "Off"].src = oImages[id + "On"].src;
	//	toggleImage(id);
	//}
}

///////////////////////////////////////////
// Unique Object
///////////////////////////////////////////
function UniqueObjectDescriptor(id,name)
{
	this.id = id;
	this.name = name;
}

///////////////////////////////////////////
// Activate Objects (workaround for IE change to <object> tag
///////////////////////////////////////////
function activateObjects()
{
	var o = document.getElementsByTagName("object");
	for (var i = 0; i < o.length; i++)
		o[i].outerHTML = o[i].outerHTML;
}