﻿/**************************************

Functions for all web pages.

***************************************/

// Common shortened variable names
var x="undefined",X=undefined;
// Common shortened functions
function I(x){return 0+parseInt(x, 10);}
function F(x){return 0.0+parseFloat(x);}

//cookie functions
function setCookie(c_name,value,expiredays)	{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}	
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
	{ 
	c_start=c_start + c_name.length+1; 
	c_end=document.cookie.indexOf(";",c_start);
	if (c_end==-1) c_end=document.cookie.length;
	return unescape(document.cookie.substring(c_start,c_end));
	} 
  }
return "";
}	

function getScrollBarWidth() {
	var inner = document.createElement('p');
	inner.style.width = '100%';
	inner.style.height = '200px';

	var outer = document.createElement('div');
	outer.style.position = 'absolute';
	outer.style.top = '0px';
	outer.style.left = '0px';
	outer.style.visibility = 'hidden';
	outer.style.width = '200px';
	outer.style.height = '150px';
	outer.style.overflow = 'hidden';
	outer.appendChild(inner);

	document.body.appendChild(outer);
	var w1 = inner.offsetWidth;
	outer.style.overflow = 'scroll';
	var w2 = inner.offsetWidth;
	if (w1 == w2) w2 = outer.clientWidth;

	document.body.removeChild(outer);

	return (w1 - w2);
};

// Default button constant.
var ENTER_CODE = 13;

// Tracks how many times the page has been submitted.
var g_submitCount = 0;

// Peforms default button enter for a text field.
function DoDefaultButton(e, buttonId)
{
	var evt = (!e) ? window.event : e;
	if (evt.keyCode == ENTER_CODE)
	{
		var obj = document.getElementById(buttonId);
		if (obj) {
			obj.click();
		}
		noBubble(evt);
		return false;
	}
	return true;
}

function DoDefaultButtonEx(e, objId, buttonId)
{
	var evt = (!e) ? window.event : e;
	if (evt.keyCode == ENTER_CODE)
	{
		var index = objId.lastIndexOf("_");
		var tempId = objId.substr(0, index + 1) + buttonId;
		var button = document.getElementById(tempId);
		if (button) {
			button.click();
		}
		noBubble(evt);
		return false;
	}
	return true;
}

function showObj(id, displayType)
{
	if (typeof(id) != "undefined") {
		if (!displayType) { displayType = "block"; }
		var obj = document.getElementById(id);
		if (obj) {
			obj.style.display = displayType;
		}
	}
}

function hideObj(id)
{
	if (typeof(id) != "undefined") {
		var obj = document.getElementById(id);
		if (obj) {
			obj.style.display = "none";
		}
	}
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if (typeof (window.pageYOffset) == 'number') {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [scrOfX, scrOfY];
}

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return [myWidth,myHeight];
}

function checkForParentWindow()
{
	var hasParent = false;
	try {
		hasParent = opener.location.href.indexOf('/MyHome') != -1 || opener.location.href.indexOf('/Widgets/') != -1;
	}
	catch(err) {
		if (opener) {
			hasParent = true;
		}
		else {
			hasParent = false;
		}
	}
	if (hasParent) {
		if (opener && opener.focus) {
			opener.focus();
		}
		window.close();
		return false;
	}
	else {
		if (window.location.href.indexOf('/MyHome') == -1) {
			return true;
		}
		else {
			return false;
		}
	}
}

function OpenWindow(location, title, width, height)
{
	var parameters = "location=yes,resizable=yes,menubar=yes,toolbar=yes,scrollbars=yes,status=yes";
	var winName = "";

	if (null != title && "undefined" != typeof(title)) {
		winName = title;
	}
	else {
		winName = document.location.href;
	}

	winName = winName.replace('"', '');
	winName = winName.replace('\'', '');
	winName = winName.replace('/', '');
	winName = winName.replace('\\', '');
	winName = winName.replace('?', '');
	winName = winName.replace('&', '');
	winName = winName.replace(':', '');
	winName = winName.replace(',', '');
	if (20 < winName.length) {
		winName = winName.substr(0, 20);
	}

	if (null != width && "undefined" != typeof(width)) {
		parameters += ",width=" + width;
	}
	if (null != height && "undefined" != typeof(height)) {
		parameters += ",height=" + height;
	}

//alert("\n location = " + location + "\n winName = " + winName + "\n parameters = " + parameters);
	var myWindow = window.open(location, winName, parameters); 
	if (myWindow) {
		if (window.focus) {
			myWindow.focus();
		}
	}
	else {
		window.alert("The window did not open properly. You might have a popup blocker preventing the window from opening.")
	}

	return false;
}

function HelpWindowOpen(location,title,options)
{
	var today = new Date();
	var newTitle = title + today.getTime();
	var myWindow = window.open(location, newTitle, options);
	if (!myWindow) {
		window.alert("The window did not open properly. You might have a popup blocker preventing the window from opening.")
	}
}

function CloseWindow()
{
	try {
		if (window.opener && window.opener.focus) {
			window.opener.focus();
			window.close();
		}
		else {
			window.location = "/MoreAboutOneGreatFamily.aspx"
		}
		//window.opener = "x"; // NOTE: this hack only works for windows that were opened via JavaScript.
	}
	catch (e) { }
}

function closeWindow()
{
	// NOTE: this hack only works for windows that were opened via JavaScript.
	
	//try
	//{

//	window.open("javascript:window.close();", "_self", "");

//	window.opener = null;
//	if ("Firefox" == Browser.Name)
//		window.open('', '_parent', '');
	window.close();
	
	//}
	//catch (e) { }
}

/*
	How to use addOnLoadEvent():

	addOnLoadEvent(function()
	{
		// code to execute
	});

*/

function addOnLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

function addUnLoadEvent(func)
{
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = func;
	}
	else {
		window.onunload = function() {
			if (oldonunload) {
				oldonunload();
			}
			func();
		}
	}
}

function addOnResizeEvent(func)
{
	var oldonresize = window.onresize;
	if (typeof window.onresize != 'function') {
		window.onresize = func;
	}
	else {
		window.onresize = function()
		{
			if (oldonresize) {
				oldonresize();
			}
			func();
		}
	}
}

function addOnScrollEvent(func)
{
	var oldonscroll = window.onscroll;
	if (typeof window.onscroll != 'function') {
		window.onscroll = func;
	}
	else {
		window.onscroll = function() {
			if (oldonscroll) {
				oldonscroll();
			}
			func();
		}
	}
}

function addEventSimple(obj, evt, fn)
{
	if (obj) {
		if (obj.attachEvent) { // IE-only
			obj.attachEvent("on" + evt, fn);
		} else /*if (obj.addEventListener)*/ { // Everyone else
			obj.addEventListener(evt, fn, false);
		}
	}
}

function removeEventSimple(obj, evt, fn)
{
	if (obj.detachEvent) { // IE-only
		obj.detachEvent("on" + evt, fn);
	}
	else /*if (obj.removeEventListener)*/ { // Everyone else
		obj.removeEventListener(evt, fn, false);
	}
}


/// <summary>Returns the value of the checked radio option. If no option(s) are checked it returns an empty string.</summary>
/// <remarks>If calling this against an asp:RadioButtonList use: var selectedValue = getRadioListSelectedValue("<%= serverControl.UniqueID %>");</remarks>
function getRadioListSelectedValue(elemId)
{
	var options = document.getElementsByName(elemId);
	for (var x = 0; x < options.length; ++x)
	{
		if (options[x].type == "radio" && options[x].checked)
		{
			return options[x].value;
		}
	}
	return "";
}

/// <summary>Returns true is the <paramref name="radioId"/> has a non-empty value, otherwise returns false. If <paramref name="errLabelId"/> was passed in it will hide or show the element, also.</summary>
/// <remarks>Here is some example code called from an OnClientClick event:
/// function validateForm()
/// {
/// 	var retVal = validateTextboxValue("<%= signupByNameFirstName.ClientID %>", "firstNameErrorLabel");
///	// notice that we're AND'ing the validate() function with the retVal and that the retVal is always on the right side of the operation..
/// 	retVal = validateRadioValue("<%= signupByNameGender.UniqueID %>", "genderErrorLabel") && retVal; // notice the use of the UniqueID property for RadioButtonList objects..
/// 	retVal = validateEmailTextboxValue("<%= emailAddressTextbox.UniqueID %>", "emailAddressErrorLabel") && retVal;
/// 	return retVal;
/// }
/// </remarks>
function validateRadioValue(radioId, errLabelId, displayType)
{
	var selectedValue = getRadioListSelectedValue(radioId);
	if (!displayType) { displayType = "inline"; }
	hideObj(errLabelId);
	if (selectedValue != "") {
		return true;
	}
	showObj(errLabelId, displayType);
	return false;
}

/// <summary>Returns true is the <paramref name="textboxId"/> has a non-empty value, otherwise returns false. If <paramref name="errLabelId"/> was passed in it will hide or show the element, also.</summary>
/// <remarks>See validateRadioValue() for an example of its usage.</remarks>
function validateTextboxValue(textboxId, errLabelId, displayType)
{
	var obj = document.getElementById(textboxId);
	if (!displayType) { displayType = "inline"; }
	hideObj(errLabelId);
	if (obj && obj.value != "") {
		return true;
	}
	showObj(errLabelId, displayType);
	return false;
}

/// <summary>Returns true is the <paramref name="textboxId"/> has a non-empty value and is a properly formatted email, otherwise returns false. 
/// If <paramref name="emptyLabelId"/> was passed in it will hide or show the element, based on if the textbox is empty or not. 
/// If <paramref name="invalidLabelId"/> was passed in it will hide or show the element, based on if the textbox has an invalid email address or not.
/// Please note that <paramref name="emptyLabelId"/> and <paramref name="invalidLabelId"/> are mutually exclusive of each other.</summary>
/// <remarks>See validateRadioValue() for an example of its usage.</remarks>
function validateEmailTextboxValue(textboxId, emptyLabelId, invalidLabelId, displayType)
{
	var obj = document.getElementById(textboxId);
	var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
//	var filter = /^([\w-]+(?:\.[\w-+]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (!displayType) { displayType = "inline"; }
	hideObj(emptyLabelId);
	hideObj(invalidLabelId);
	if (obj && obj.value != "") {

		if (filter.test(obj.value)) {
			AlertHide("#emailAlert");
			return true;
		}

		else {
			showObj(invalidLabelId, displayType);
			AlertShow("#emailAlert");
		}

	}
	else
	{
		showObj(emptyLabelId, displayType);
		AlertShow("#emailAlert");
	}
	
	return false;
}

//-----------------------------//

function validateEmailConfirmValue(textboxId, emptyLabelId, invalidLabelId, confirmBoxID, displayType)
{
	var obj = document.getElementById(textboxId);
	var obj2 = document.getElementById(confirmBoxID);
//	obj.toLowerCase;
	var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
//	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (!displayType) { displayType = "inline"; }
	hideObj(emptyLabelId);
	hideObj(invalidLabelId);
	if (obj && obj.value.toLowerCase() != "") {
		if (filter.test(obj.value.toLowerCase())) {
			if(obj.value.toLowerCase() != obj2.value.toLowerCase()){
				AlertShow("#emailConfirmationAlert");
				$("#emailConfirmationNoMatch").css("display","block");
		        return false;
		    }
            $("#emailConfirmationNoMatch").css("display","none");
			AlertHide("#emailConfirmationAlert");
			return true;
			
		}
		else {
			showObj(invalidLabelId, displayType);
            $("#emailConfirmationNoMatch").css("display","block");
			AlertShow("#emailConfirmationAlert");
		}
		
	}
	else
	{
		showObj(emptyLabelId, displayType);
		AlertShow("#emailConfirmationAlert");
	}
	return false;
}

/// <summary>Returns true is the <paramref name="textboxId"/> if properly formatted email, otherwise returns false. 
/// If <paramref name="invalidLabelId"/> was passed in it will hide or show the element, based on if the textbox has an invalid email address or not.
/// Please note that <paramref name="emptyLabelId"/> and <paramref name="invalidLabelId"/> are mutually exclusive of each other.</summary>
/// <remarks>See validateRadioValue() for an example of its usage.</remarks>
/// obj.value == obj2.value compares the primary and secondary email address's and checks to make sure they aren't the same
function validateEmailOtherTextboxValue(textboxId, invalidLabelId, primaryEmailId, secondEmailConfirm, displayType)
{
	var obj = document.getElementById(textboxId);
	var obj2 = document.getElementById(primaryEmailId);
	
	var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
//	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (!displayType) { displayType = "inline"; }
	hideObj(invalidLabelId);
	
	if (obj && obj.value != "") {
		if (filter.test(obj.value)) {
		     if(obj.value.toLowerCase() == obj2.value.toLowerCase()){
				AlertShow("#secondaryEmail");
				$("#secondEmailMatch").css("display","block");
				
		        return false;
		    }
		    else {
			AlertHide("#secondaryEmail");
			$("#secondEmailMatch").css("display","none");
			return true;
		    }
		}
		else {
			showObj(invalidLabelId, displayType);
			AlertShow("#secondaryEmail");
			$("#secondEmailMatch").css("display","none");
		}
	}
	else
	{
		AlertHide("#secondaryEmail");
		$("#secondEmailMatch").css("display","none");
		return true;
	}
	return false;
}

/// <summary></summary>
/// <returns>The size [x,y] that was passed to the JSForm.ApplySettings() function.</returns>
function ApplyJSFormSize(popupId, popupTitle)
{
	var size = [ 0, 0 ];
	if (parent && parent.JSForm)
	{
		var obj = document.getElementById('autoResizeContainer');
		if (obj) {
			//obj.style.display = "block";
			obj.style.position = "relative";
			obj.style.top = "0px";
			obj.style.left = "0px";
			width = size[0];
			if (obj.style.width) { // i always use the width provided, whether it differs from the current or not (unlike the height)
				width = I(obj.style.width);
			}
			height = size[1];
			if (obj.style.height && I(obj.style.height) > height) {
				height = I(obj.style.height) + 1;
			}
//alert([ size, obj.style.width, obj.style.height, width, height ]);
			size = [ width, height ];
		}
		else {
			size = getSize(200, 100);
		}
		if (popupTitle) {
			parent.JSForm.ApplySettings({ id:popupId, title:popupTitle, 'width':size[0], 'height':size[1] });
		}
		else {
			parent.JSForm.ApplySettings({ id:popupId, 'width':size[0], 'height':size[1] });
		}
	}
	return size;
}

var MINWIDTH = 40;
var MINHEIGHT = 10;

function getSize(MinWidth, MinHeight)
{
	//alert(document.readyState);
	if (document.all) {
		while (document.readyState != "complete") { };
	}

	if (!MinWidth || MinWidth < MINWIDTH) {
		MinWidth = MINWIDTH;
	}
	if (!MinHeight || MinHeight < MINHEIGHT) {
		MinHeight = MINHEIGHT;
	}

	// always scroll widget content to the top, 
	// just in case it is moved down by the user by accident.
	//alert('scroll');
	if (window.scrollTo) {
		window.scrollTo(0,0);
	}
	if (window.scroll) {
		window.scroll(-1000,-1000);
	}
	
	var width = 0;
	var height = 0;
	
	if (document.all) {
		width = document.body.scrollWidth;
		width += I(document.body.style.marginLeft) + I(document.body.style.marginRight);
		width += I(document.body.style.paddingLeft) + I(document.body.style.paddingRight);
		width += 0; // IE adjustment
		
		height = document.body.scrollHeight + 2;
		height += I(document.body.style.marginTop) + I(document.body.style.marginBottom);
		height += I(document.body.style.paddingTop) + I(document.body.style.paddingBottom);
		height += 0; // IE adjustment
	}
	else {
		width = I(document.documentElement.scrollWidth);
		width += I(document.body.style.marginLeft) + I(document.body.style.marginRight);
		width += I(document.body.style.paddingLeft) + I(document.body.style.paddingRight);
		width += 0; // Firefox adjustment

		height = document.height;
		height += I(document.body.style.marginTop) + I(document.body.style.marginBottom);
		height += I(document.body.style.paddingTop) + I(document.body.style.paddingBottom);
		height += 0; // Firefox adjustment
	}

	if (MinWidth > width) {
		width = MinWidth;
	}
	if (MinHeight > height) {
		height = MinHeight;
	}

//console.info([ width, height ]);
	return [ width, height ];
}

var ELLIPSIS = '\u2026';
//var ELLIPSIS = "...";

function shortenString(message, className, lineCount, lineHeight)
{
	var tempDiv = document.createElement("DIV"); 
	if (!tempDiv)
	{
		return;
	}
	tempDiv.style.position = "absolute";
	tempDiv.style.left = "0px";
	tempDiv.style.top = "0px";
	tempDiv.style.display = "block";
	//tempDiv.style.visibility = "hidden";
	tempDiv.className = className;
	tempDiv.innerHTML = message;
	document.body.appendChild(tempDiv);
//debugger;
//	try {
//		tempDiv.style.width = I(tempDiv.clientWidth) + "px!important";
//	} catch (e) { }

	var totalHeight = lineCount * lineHeight;
	var ellipsis = "";
	
//alert('pixelWidth='+pixelWidth);
	while (tempDiv.clientHeight > (totalHeight + 5))
	{
		ellipsis = ELLIPSIS;
		var index = message.lastIndexOf(" ");
		if (index == -1)
		{
			tempDiv.innerHTML = message;
			break;
		}
		message = trim(message.substr(0, index));
		if (message.substr(message.length - 1, 1) == "-")
		{
			message = trim(message.substr(0, message.length - 1));
		}
		tempDiv.innerHTML = message + ELLIPSIS;
	}

	document.body.removeChild(tempDiv);
	return message + ellipsis;
}

var elemTraceContent = null;

function trapTraceContent(linkId)
{
	var style = document.createElement("STYLE");
	if (style) {
		style.outerText = "<STYLE>span.tracecontent { display:none; } span.tracecontent td { background-color:#fff !important; }</STYLE>";
	}
	var objList = document.getElementsByTagName("SPAN");
	if (objList && objList.length > 0) {
		for (var i = 0; i < objList.length; i++) {
			if (objList[i].className == "tracecontent") {
				elemTraceContent = objList[i];
				break;
			}
		}
	}
	if (elemTraceContent) {
		elemTraceContent.style.display = "none";
		var link = document.getElementById(linkId);
		if (link) {
			addEventSimple(link, "click", showHideTraceContent);
		}
	}
}

function showHideTraceContent()
{
	if (elemTraceContent) {
		if (null == elemTraceContent.style.display || "undefined" == typeof(elemTraceContent.style.display) || "" == elemTraceContent.style.display || "none" == elemTraceContent.style.display) {
			elemTraceContent.style.display = "block";
		}
		else {
			elemTraceContent.style.display = "none";
		}
	}
}

function addSelectOption(element, index, option)
{
	var cN;
	var o;
	if('string' == typeof element) {
		element = document.getElementById(element);
	}
	if('string' == typeof option) {
		o = document.createElement('option');
		o.text = option;
	} else {
		o = option;
	}
	if ((cN = element.childNodes)) {
		if(2 == element.add.length) {
			element.add(o, ((0 > index) || (cN.length == index)) ? null : cN[index]);
		} else {
			element.add(o, index);
		}
	}
	return o;
}

// 
// DOM utility methods
// 

function getElementsByAttribute(attr, value, tag)
{
	//alert("getElementsByAttribute(" + attr + ", " + value + ", " + tagName + ")");
	
	var ar = new Array();
	var attribute;
	var tagName = "";
	var tags;
	var attrs;
	
	if (tag != undefined) {
		tagName = tag;
	}

	if ("" != tagName) {
		tags = document.getElementsByTagName(tagName);
	}
	else {
		tags = document.all;
	}
	
	for (var i=0; i<tags.length; i++) {
		attrs = tags[i].attributes;
		if (null != attrs) {
			for (var j=0; j<attrs.length; j++) {
				attribute = new ajxAttribute(attrs[j]);
				if (attribute.getName() == attr && attribute.getValue() == value) {
					ar[ar.length] = new ajxNode(tags[i]);
					break;
				}
			}
		}
	}
	//alert(ar.length);
	return ar;
}


// 
// String utility methods
// 

function trim(value)
{
	if (undefined != value && "" != value) {
		return value.replace(/^\s*|\s*$/g,"");
	}
	else {
		return "";
	}
}

function trimAll(value)
{
	if (undefined != value && "" != value) {
		while (value.substr(0, 1) == " " || value.substr(0, 1) == "\t" || value.substr(0, 1) == "\r" || value.substr(0, 1) == "\n") {
			value = value.substr(1);
		}
		while (value.substr(value.length - 1, 1) == " " || value.substr(value.length - 1, 1) == "\t" || value.substr(value.length - 1, 1) == "\r" || value.substr(value.length - 1, 1) == "\n") {
			value = value.substr(0, value.length - 1);
		}
		return value;
	}
	else {
		return "";
	}
}

function urlencode(str)
{
	//.split("<").join("%3C").split(">").join("%3E").split("\"").join("%22").split(" ").join("%20");
	str = str.replace(/\//g, "%2F");
	str = str.replace(/\?/g, "%3F");
	str = str.replace(/=/g, "%3D");
	str = str.replace(/&/g, "%26");
	str = str.replace(/</g, "%3C");
	str = str.replace(/>/g, "%3E");
	str = str.replace(/\"/g, "%22");
	str = str.replace(/ /g, "%20");
	return str;
}

function removebreaks(str)
{
	//.split("<br>").join("").split("<br/>").join("").split("<br />").join("").split("\r\n").join("").split("\r").join("").split("\n").join(""));
	str = str.replace(/\\n/g, "");
	str = str.replace(/\\r/g, "");
	str = str.replace(/<br*\/>/g, "");
	str = str.replace(/<br>/g, "");
	return str;
}

function showHideDiv(id, callerId, closeId1, closeId2, closeId3, closeId4, closeId4)
{
	var obj = document.getElementById(id);
	if (obj) {
		if (null == obj.style.display || "undefined" == typeof(obj.style.display) || "" == obj.style.display || "none" == obj.style.display) {
			obj.style.display = "block";
		}
		else {
			obj.style.display = "none";
		}
	}
	if (callerId && null != callerId && "undefined" != typeof(callerId)) {
		obj = document.getElementById(callerId);
		if (obj) {
			//showProperties(obj);
			obj.blur();
		}
	}
	for (var i = 1; i < 5; i++) {
		if ("undefined" != typeof(eval("closeId" + i))) {
			obj = document.getElementById(eval("closeId" + i));
			//showProperties(obj)
			if (obj) {
				obj.style.display = "none";
			}
		}
	}
}

/// <summary>This method takes an unlimited number of arguments. The first argument specifies the ID of the element you want to show. The remaining arguments specify elements to hide.</summary>
/// <remarks></remarks>
function showElementFromList()
{
	var elemToShowId = arguments[0];
	for (var i = 1; i < arguments.length; i++) {
		if (arguments[i]) {
			var obj = document.getElementById(arguments[i]);
			if (obj) {
				obj.style.display = (elemToShowId == arguments[i]) ? "block" : "none";
			}
		}
	}
	return false;
}


// 
// Debug utils
// 

function showProperties(obj)
{
	var str = "Properties that have values for :" + obj + "\n";
	var namestr = '';
	for (name in obj) {
		if (obj[name]) {
			//typeof returns "number" "string" "boolean" "function" "undefined" "object"
			var type = typeof(obj[name]);
			if (type != "object" && type != "function") {
				str += "[" + name + "]["+type+"] = " + obj[name] + "\n";
			}
		}
		namestr += name + ", ";
	}
	str += "\n\n Click OK to show all possible values\n\n";
	var y = confirm(str);
	if (y) {
		alert(namestr);
	}
}

// on-page debugging stuff
/*var m_textDebug = document.getElementById('textDebug');
var m_showDebug = true;
function debugValue(msg)
{
	if (m_showDebug && m_textDebug) {
		m_textDebug.value = msg + "\n" + m_textDebug.value;
		var ar = m_textDebug.value.split('\n');
		if (ar.length > 200) {
			var stringTemp = "";
			for (var i = 0; i < 80; i++) {
				stringTemp += ar[i] + "\n";
			}
			m_textDebug.value = stringTemp;
		}
	}
}

function debugInnerHTML(objId)
{
	if (m_textDebug) {
		var obj = document.getElementById(objId);
		var msg = "objId was not found";
		if (obj) {
			if (obj.innerHTML) {
				msg = obj.innerHTML;
			}
			else {
				msg = "obj.innerHTML was not found";
			}
			//msg = msg.split("><div").join(">\n<div").split("><table").join(">\n<table").split("><tr").join(">\n<tr").split("><td").join(">\n<td");
		}
		m_textDebug.value = msg;
	}
}*/

//function getObject(objId)
//{
//	var obj = document.getElementById(objId);
//	if (test(obj))
//		return obj;
//	else
//		return null;
//}

function test(obj)
{
	if (null != obj && "undefined" != typeof(obj) && undefined != obj) {
		return true;
	}
	else {
		return false;
	}
}

function getElementsByClassName(className, tag, elm)
{
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for (var i=0; i<length; i++) {
		current = elements[i];
		if (testClass.test(current.className)) {
			returnElements.push(current);
		}
	}
	return returnElements;
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj && obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

// Event propagation cancelling function
function noBubble(e)
{
	try {
		var evt = (e) ? e : window.event;
		if (typeof(evt.cancelBubble) != "undefined") { evt.cancelBubble = true; }
		if (typeof(evt.returnValue) != "undefined") { evt.returnValue = false; } // firefox
		if (evt.stopPropagation) { evt.stopPropagation(); } // firefox
		if (evt.preventDefault) { evt.preventDefault(); } // firefox
	}
	catch (ex) {
		alert(ex.message);
	}
}

function preventKeyPressBubble(e)
{
	try {
		var evt = (e) ? e : window.event;
		if (document.all && typeof(evt.keyCode) != "undefined") { evt.keyCode = 0; }
		if (document.all && typeof(evt.returnValue) != "undefined") { evt.returnValue = 0; } // IE
		noBubble(e);
	}
	catch (ex) {
		alert(ex.message);
	}
}


function addRowHighlighting(id, title, url)
{
	var obj = document.getElementById(id);
	if (obj) {
		var parentRow = obj.parentNode.parentNode;
		var children = parentRow.childNodes;
		var numChildren = children.length;
		parentRow.setAttribute("title", title);
		for (var count = 0; count < numChildren; count++) {
			parentRow.childNodes[count].onclick = function() { window.location = url; };
			parentRow.childNodes[count].onmouseover = function() { this.style.cursor = "pointer"; };
		}
	}
}


// Date validation functions
function dateCheck(strDateInput)
{
	var strDatestyle = "US"; //United States date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intDay;
	var intMonth;
	var intYear;
	var booFound = false;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = strDateInput;
	
	if (strDate.length < 6) {
		return false;
	}
		
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				err = 1;
				return false;
			}
			else {
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
		}
	}
	
	if (booFound == false) {
		if (strDate.length > 5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
		else {
			err = 1;
			return false;
		}
	}
	
	if (strYear.length == 2) {
		if (strYear[0] == '0') {
			strYear = '20' + strYear;
		}
		else {
			strYear = '19' + strYear;
		}
	}
	
	// US style
	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}
	
	intDay = I(strDay);
	
	if (isNaN(intDay)) {
		// check for other format before ending
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
		
		intDay = I(strDay);
		
		// TODO: THIS IS AN ERROR
		if (isNaN(intday)) {
			err = 2;
			return false;
		}
	}
	
	intMonth = I(strMonth);
	
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) {
			err = 3;
			return false;
		}
	}
	
	intYear = I(strYear);
	
	if (isNaN(intYear)) {
		err = 4;
		return false;
	}
	
	if (intMonth > 12 || intMonth < 1) {
		err = 5;
		return false;
	}
	
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) {
		err = 6;
		return false;
	}
	
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) {
		err = 7;
		return false;
	}
	
	if (intMonth == 2) {
		if (intDay < 1) {
			err = 8;
			return false;
		}
		
		if (LeapYear(intYear) == true) {
			if (intDay > 29) {
				err = 9;
				return false;
			}
		}
		else {
			if (intDay > 28) {
				err = 10;
				return false;
			}
		}
	}
	
	return true;
}

function dateParse(strDateInput)
{	
	var strDatestyle = "US"; //United States date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intDay;
	var intMonth;
	var intYear;
	var booFound = false;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = strDateInput;
	
	if (strDate.length < 6) {
		return null;
	}
		
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				err = 1;
				return null;
			}
			else {
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
		}
	}
	
	if (booFound == false) {
		if (strDate.length > 5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
		else {
			err = 1;
			return null;
		}
	}
	
	// US style
	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}
	
	intDay = I(strDay);
	
	if (isNaN(intDay)) {
		// check for other format before ending
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
		
		intDay = I(strDay);
		
		if (isNaN(intDay)) {
			err = 2;
			return null;
		}
	}
	
	intMonth = I(strMonth);
	
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) {
			err = 3;
			return null;
		}
	}
	
	intYear = I(strYear);
	
	if (isNaN(intYear)) {
		err = 4;
		return null;
	}
	
	if (intMonth > 12 || intMonth < 1) {
		err = 5;
		return null;
	}
	
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) {
		err = 6;
		return null;
	}
	
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) {
		err = 7;
		return null;
	}
	
	if (intMonth == 2) {
		if (intDay < 1) {
			err = 8;
			return null;
		}
		
		if (LeapYear(intYear) == true) {
			if (intDay > 29) {
				err = 9;
				return null;
			}
		}
		else {
			if (intDay > 28) {
				err = 10;
				return null;
			}
		}
	}
	
	return intDay.toString() + "/" + intMonth.toString() + "/" + intYear.toString();
}

function LeapYear(intYear)
{
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) {
			return true;
		}
	}
	else {
		if (intYear % 4 == 0) {
			return true;
		}
	}
	return false;
}

// 
// This adds the insertAdjacentElement, insertAdjacentHTML, and insertAdjacentText methods to the 
// default HTMLElement object of the browser.
// 
// This will only be created for those browsers which do not already support those methods.
// 

if (typeof HTMLElement != "undefined" && !HTMLElement.prototype.insertAdjacentElement)
{
	HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode)
	{
		switch (where) {
			case 'beforeBegin': {
				this.parentNode.insertBefore(parsedNode, this)
				break;
			}
			case 'afterBegin': {
				this.insertBefore(parsedNode, this.firstChild);
				break;
			}
			case 'beforeEnd': {
				this.appendChild(parsedNode);
				break;
			}
			case 'afterEnd': {
				if (this.nextSibling) {
					this.parentNode.insertBefore(parsedNode, this.nextSibling);
				}
				else {
					this.parentNode.appendChild(parsedNode);
				}
				break;
			}
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function(where, htmlStr)
	{
		//alert(this);
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where, parsedHTML)
	}

	HTMLElement.prototype.insertAdjacentText = function(where, txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where, parsedText)
	}
}


function GetOffset(obj)
{
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft, curtop];
}


if ("undefined" != typeof(String))
{
	if (!String.prototype.endsWith)
	{
		String.prototype.endsWith = function(pattern)
		{
			var d = this.length - pattern.length;
			return d >= 0 && this.lastIndexOf(pattern) === d;
		}
	}

	if (!String.prototype.format)
	{
		// var firstName = 'Kody';
		// var lastName = 'Brown';
		// var hello = "Hello, my name is {0} {1}.".format(firstName, lastName);
		String.prototype.format = function()
		{
			var str = this;
			for (var i = 0; i < arguments.length; i++)
			{
				var re = new RegExp('\\{' + (i) + '\\}', 'gm');
				str = str.replace(re, arguments[i]);
			}
			return str;
		}
	}

	if (!String.format)
	{
		// TODO: You can NOT escape { and } characters with this code..
		// var firstName = 'Kody';
		// var lastName = 'Brown';
		// var hello = String.format("Hello, my name is {0} {1}.", firstName, lastName);
		String.format = function()
		{
			if (0 == arguments.length) {
				return null;
			}
			var str = arguments[0];
			for (var i = 1; i < arguments.length; i++)
			{
				var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
				str = str.replace(re, arguments[i]);
			}
			return str;
		}
	}
}

function isValidPassword(strPassword)
{
	var filter = /^[^|#\$%@/\\'\&]{6,20}$/i;
	if (filter.test(strPassword))
	{
		return true;
	}
	else
	{
		return false;
	}
}

//Focus on First Text Input Field
if (typeof $ == 'function')
	$(function() {
		//$("input:text:visible:first").focus();

		var str = document.URL;
		if (!str.indexOf("/Account/Login.aspx")) {
			$("input:text:visible:first").focus();
		}


	});

