//Description:    Client-side code library for .asp templates
//Author:         Steve Eidemiller
//Created:        02/22/2002

/**************************************************************************
Revision History:
07/25/2003 - SteveE - Added strtrim() and validateSearchForm() to support Hype search blocks
07/25/2003 - SteveE - Added validateRadioGroup() and validatePoll() to support polls
08/22/2003 - SteveE - Added SteveM's form validation function for the Provider Directory search block: validateProviderSearchForm()
09/09/2003 - SteveE - Added support for HTTPS/SSL connections to webresources.childrenshc.org (added "WebResourceServer" variable and adjusted URL's to reference it)
05/10/2007 - SteveE - Added support for the new Alert! box style in Hyper
08/23/2007 - SteveE - Added support for IE5/IE6 printing of transparent PNG's. Specifically, the chcBeforePrint() and chcAfterPrint() functions.
10/07/2008 - Steph	- Added functions for Form Template validation
10/16/2009 - SteveE - Added Google Analytics function
**************************************************************************/

//Determine the location of the resource server
var WebResourceServer = "http://webresources.childrensmn.org/";
var url = String(window.location.href).toLowerCase();
if (url.indexOf("dagobah") > -1 || url.indexOf("tatooine") > -1 || url.indexOf("endor") > -1 || url.indexOf("echo") > -1) WebResourceServer = "http://" + "naboo" + ".childrensmn.org/"; //Trying to avoid the Hall of Shame robot
if (String(window.location).indexOf("https://") == 0) WebResourceServer = "https://webresources.childrenshc.org/";

//Roll-over code for the left/right navigation "buttons" (or "dots") to the left of each link
var navLevels = 6;
var navImages = new Array();
for(var i = 1; i <= navLevels; i++)
{
	navImages[i] = new Array(); //Array of two image objects for on and off button states
	navImages[i][0] = new Image();
	navImages[i][0].src  = WebResourceServer + "Images/Navigation/nav" + i + "_button_off.gif"; //0=off
	navImages[i][1] = new Image();
	navImages[i][1].src  = WebResourceServer + "Images/Navigation/nav" + i + "_button_on.gif";  //1=on
}
function navChangeImages(navLevel, imageNumber, onOff)
{
	document.getElementById("navImage" + imageNumber).src = navImages[navLevel][onOff].src;
}

//Generic support functions
function strtrim(str)
{
	return str.replace(/^\s+/, "").replace(/\s+$/, "");
}

//Validate generic 'Search' forms
function validateSearchForm(txt)
{
	if (strtrim(txt.value).length == 0) txt.focus();
	return strtrim(txt.value).length != 0;
}

//Validate the Provider Directory search form (which = the <form> instance)
function validateProviderSearchForm(which)
{
	//If (no fields have values)...
	if (which.drname.value == "" && which.city.value == "" && which.clinic.value == "" && which.specialty.selectedIndex == 0)
	{
		alert("You must enter a name, city, clinic or select a specialty field.  Please complete them, then submit again.");
		which.drname.focus();
		return false;
	}
	else
	{
		return true;
	}
}

//Validation function to see if ANY radio button is selected in a given group
function validateRadioGroup(frm, groupName)
{
	var checked = false;
	for (var i = 0; i < frm.elements.length; i++)
	{
		if (frm.elements[i].type == "radio")
		{
			if (frm.elements[i].name == groupName) checked |= frm.elements[i].checked;
		}
	}
	return checked;
}

//Validation function to ensure that something was selected for each radio button group
function validatePoll(frm)
{
	//For (each form element)...
	for (var i = 0; i < frm.elements.length; i++)
	{
		//If (this element is a radio button)...
		if (frm.elements[i].type == "radio")
		{
			//If (a radio button is NOT selected in this group)...
			if (!validateRadioGroup(frm, frm.elements[i].name))
			{
				//Tell the user why the vote can't be accepted yet
				alert("Please select an option for each question before voting.");
				return false; //Vote denied until the form is properly filled out
			}
		}
	}

	//All fields are filled out properly, so go ahead and submit the form
	return true;
}

//Standard colors (NOTE: this is a copy from Styles.inc)
var chcColors = new Array(
		//Dark versions
		new Array(10, "303030", "Olson Black"),
		new Array(11, "00A9E0", "Olson Blue"),
		new Array(12, "BD8A5E", "Olson Brown"),
		new Array(13, "80379B", "Olson Dark Red"),
		new Array(14, "9A9B9C", "Olson Gray"),
		new Array(15, "BED600", "Olson Green"),
		new Array(16, "FFA02F", "Olson Orange"),
		new Array(17, "4C5CC5", "Olson Purple"),
		new Array(18, "CA005D", "Olson Red (Rubine)"),
		new Array(19, "009AA6", "Olson Teal"),
		new Array(20, "FCD900", "Olson Yellow"),

		//Light versions
		//new Array(60, "808080", "Olson Black (light)"), //Not defined in any of our style guides
		new Array(61, "72B5CC", "Olson Blue (light)"),
		new Array(62, "D3BF96", "Olson Brown (light)"),
		new Array(63, "B382C7", "Olson Dark Red (light)"),
		//new Array(64, "9FA0A4", "Olson Gray (light)"),  //Not defined in any of our style guides
		new Array(65, "BAC696", "Olson Green (light)"),
		new Array(66, "FBAF73", "Olson Orange (light)"),
		new Array(67, "8193DB", "Olson Purple (light)"),
		new Array(68, "E28A9E", "Olson Red (light)"),
		new Array(69, "5BBBB7", "Olson Teal (light)"),
		new Array(70, "E8CE79", "Olson Yellow (light)")
);

//Convert a chcColors[] index to its hex value
function chcColorHexFromIndex(index)
{
	var hex = "000000";
	for (var i = 0; i < chcColors.length; i++)
	{
		if (chcColors[i][0] == index)
		{
			hex = chcColors[i][1];
			break;
		}
	}
	return hex;
}

//Convert a hex value to its corresponding chcColors[] index (or -1 if the hex value is not a standard color)
function chcColorIndexFromHex(hex)
{
	var index = -1;
	for (var i = 0; i < chcColors.length; i++)
	{
		if (chcColors[i][1].toLowerCase() == hex.toLowerCase())
		{
			index = chcColors[i][0];
			break;
		}
	}
	return index;
}

//Background gradient support
var hypeBgGradientObjects = new Array(); //Vertical gradients
function hypeBgGradientAddObject(container)
{
	hypeBgGradientObjects.push(container);
}
var hypeBgGradientObjects2 = new Array(); //Gradient bubbles
function hypeBgGradientAddObject2(container)
{
	hypeBgGradientObjects2.push(container);
}
var hypeBgGradientObjects3 = new Array(); //Alert Gradients
function hypeBgGradientAddObject3(container)
{
	hypeBgGradientObjects3.push(container);
}

//Determine if an element is a descendant of a link tag
function chcElementIsLinkChild(cssElement)
{
	while (cssElement.parentElement)
	{
		if (cssElement.tagName == "A") return true;
		cssElement = cssElement.parentElement;
	}
	return false;
}

//Determine the absolute x,y position of a CSS element
function chcElementAbsolutePosition(cssElement)
{
	var x = 0;
	var y = 0;
	while (cssElement.offsetParent)
	{
		x += cssElement.offsetLeft;
		y += cssElement.offsetTop;
		if (typeof(cssElement.clientLeft) != "undefined") x += cssElement.clientLeft; //IE padding
		if (typeof(cssElement.clientTop)  != "undefined") y += cssElement.clientTop;  //IE padding
		cssElement = cssElement.offsetParent;
	}
	var point = {x: x, y: y};
	return point;
}

//
function onBodyLoad()
{
	//Determine the current style
	if (typeof(StyleIndex) == "undefined") var StyleIndex = 1; //Default style

	//Determine gradient colors
	var gradientBackground = "F1F6CD";
	var gradientTop        = "BED600"; //For Vertical Gradients
	var gradientBottom     = "F1F6CD";
	var gradientTop2       = "C2D82C"; //For Bubble Gradients
	var gradientBottom2    = "DFEE9A";
	var gradientTop3       = "ECAEBD"; //For Alert Gradients
	var gradientBottom3    = "FBE9ED";
	switch (StyleIndex)
	{
		case 0:
			gradientBackground = "FFFFFF";
			gradientTop        = "F1F5F8"; //For Vertical Gradients
			gradientBottom     = "FFFFFF";
			gradientTop2       = "F1F5F8"; //For Bubble Gradients
			gradientBottom2    = "FFFFFF";
			gradientTop3       = "ECAEBD"; //For Alert Gradients
			gradientBottom3    = "FBE9ED";
			break;
		case 1:
			gradientBackground = "F1F6CD";
			gradientTop        = "BED600"; //For Vertical Gradients
			gradientBottom     = "F1F6CD";
			gradientTop2       = "C2D82C"; //For Bubble Gradients
			gradientBottom2    = "DFEE9A";
			gradientTop3       = "ECAEBD"; //For Alert Gradients
			gradientBottom3    = "FBE9ED";
			break;
		case 2:
			gradientBackground = "F1F6CD";
			gradientTop        = "BED600"; //For Vertical Gradients
			gradientBottom     = "F1F6CD";
			gradientTop2       = "C2D82C"; //For Bubble Gradients
			gradientBottom2    = "DFEE9A";
			gradientTop3       = "ECAEBD"; //For Alert Gradients
			gradientBottom3    = "FBE9ED";
			break;
	}

	//Implement background gradients for Hype blocks
	for (var i = 0; i < hypeBgGradientObjects.length; i++)
	{
		var htmlElement = document.getElementById(hypeBgGradientObjects[i]);
		var gradientURL = WebResourceServer + "DynamicImages/VerticalGradient.ashx?height=" + htmlElement.clientHeight + "&rgb1=" + gradientTop + "&rgb2=" + gradientBottom;
		htmlElement.style.backgroundRepeat = "repeat-x";                //NOTE: We have to do these things separately because of Checkpoint
		htmlElement.style.backgroundImage = "url(" + gradientURL + ")"; //NOTE: We have to do these things separately because of Checkpoint
	}
	for (var i = 0; i < hypeBgGradientObjects2.length; i++)
	{
		var htmlElement = document.getElementById(hypeBgGradientObjects2[i]);
		var gradientURL = WebResourceServer + "DynamicImages/VerticalGradient2.ashx?height=" + htmlElement.clientHeight + "&width=" + htmlElement.clientWidth + "&rgb1=" + gradientTop2 + "&rgb2=" + gradientBottom2 + "&bgcolor=" + gradientBackground;
		htmlElement.style.backgroundRepeat = "repeat-x";                //NOTE: We have to do these things separately because of Checkpoint
		htmlElement.style.backgroundImage = "url(" + gradientURL + ")"; //NOTE: We have to do these things separately because of Checkpoint
	}
	for (var i = 0; i < hypeBgGradientObjects3.length; i++)
	{
		var htmlElement = document.getElementById(hypeBgGradientObjects3[i]);
		var gradientURL = WebResourceServer + "DynamicImages/AlertGradient.ashx?height=" + htmlElement.clientHeight + "&width=" + htmlElement.clientWidth + "&rgb1=" + gradientTop3 + "&rgb2=" + gradientBottom3 + "&bgcolor=FFFFFF";
		htmlElement.style.backgroundRepeat = "repeat-x";                //NOTE: We have to do these things separately because of Checkpoint
		htmlElement.style.backgroundImage = "url(" + gradientURL + ")"; //NOTE: We have to do these things separately because of Checkpoint
	}

	//Determine the size of the gradient under the left-nav, and install it
	var leftNavTD = document.getElementById("chcLeftNav");               //Contains the left-nav <table>
	var leftNavTable = document.getElementById("chcLeftNavTable");       //Contains all the left-nav content
	var leftNavGradient = document.getElementById("chcLeftNavGradient"); //This is the <div> just below the left-nav <table>
	if (leftNavTD != null && leftNavTable != null && leftNavGradient != null)
	{
		var gradientHeight = Math.max(36, leftNavTD.clientHeight - leftNavTable.clientHeight); //NOTE: The '36' is also in LeftNavigation.inc
		var gradientURL = WebResourceServer + "DynamicImages/VerticalGradient.ashx?height=" + gradientHeight + "&rgb1=" + gradientTop + "&rgb2=" + gradientBottom;
		leftNavGradient.style.height = gradientHeight;
		leftNavGradient.style.backgroundRepeat = "repeat-x";                //NOTE: We have to do these things separately because of Checkpoint
		leftNavGradient.style.backgroundImage = "url(" + gradientURL + ")"; //NOTE: We have to do these things separately because of Checkpoint
	}

	//Determine the size of the gradient under the right-nav, and install it
	var rightNavTD = document.getElementById("chcRightNav");               //Contains the right-nav <table>
	var rightNavTable = document.getElementById("chcRightNavTable");       //Contains all the right-nav content
	var rightNavGradient = document.getElementById("chcRightNavGradient"); //This is the <div> just below the right-nav <table>
	if (rightNavTD != null && rightNavTable != null && rightNavGradient != null)
	{
		var gradientHeight =  Math.max(36, rightNavTD.clientHeight - rightNavTable.clientHeight); //NOTE: The '36' is also in RightNavigation.inc
		var gradientURL = WebResourceServer + "DynamicImages/VerticalGradient.ashx?height=" + gradientHeight + "&rgb1=" + gradientTop + "&rgb2=" + gradientBottom;
		rightNavGradient.style.height = gradientHeight;
		rightNavGradient.style.backgroundRepeat = "repeat-x";                //NOTE: We have to do these things separately because of Checkpoint
		rightNavGradient.style.backgroundImage = "url(" + gradientURL + ")"; //NOTE: We have to do these things separately because of Checkpoint
	}

	//Stretch the Hype table's bottom row of spacers to fill all available vertical space
	var headerTD = document.getElementById("chcHeader");
	var containerTD = document.getElementById("chcHeaderAndContent");
	var hypeTable = document.getElementById("chcHypeContent");
	var hypeBottomSpacer0 = document.getElementById("chcHypeColumnBottomSpacer0");
	if (hypeBottomSpacer0 != null && containerTD != null && headerTD != null && hypeTable != null)
	{
		//We only need to edit one spacer to adjust the height of the entire table/tr
		hypeBottomSpacer0.style.height = containerTD.clientHeight - headerTD.clientHeight - hypeTable.clientHeight + 1;
	}

	//Position the search form over the header graphic for StarNet tab pages. It is 'relative' positioned so that it stays in place as the browser window is resized.
	var searchForm = document.getElementById("chcStarNetSearchForm");
	var starNetBannerImage = document.getElementById("chcStarNetBannerImage");
	if (searchForm != null && starNetBannerImage != null)
	{
		var p  = chcElementAbsolutePosition(starNetBannerImage);
		var p2 = chcElementAbsolutePosition(searchForm);
		searchForm.style.top = p.y - p2.y + (starNetBannerImage.clientHeight - searchForm.clientHeight) / 2; //Set the 'top' relative to the default location at the bottom of the page
		searchForm.style.visibility = "visible";
	}

	//Position the style flipper
	var styleFlipper = document.getElementById("chcStyleFlipper");
	if (styleFlipper != null)
	{
		var p2 = chcElementAbsolutePosition(styleFlipper);
		styleFlipper.style.top = -p2.y + 14;
		styleFlipper.style.left = styleFlipper.clientWidth + 10;
		styleFlipper.style.visibility = "visible";
	}

	//This is a patch to address a bug in IE6 SP1 that causes certain images to not be loaded.
	if (navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf("MSIE 6.0") > -1 && navigator.appMinorVersion.indexOf("SP1") > -1) //Verify that we're running IE6 SP1 (browser detection is intentionally sparse here and designed to detect only IE6 SP1)
	{
		//For (each image on this page)...
		for (var i = 0; i < document.images.length; i++)
		{
			//If (the image has not loaded) Then try and force a re-load by reassigning the URL to .src
			if (!document.images[i].complete) document.images[i].src = document.images[i].src;
		}
	}	
}

//Special handling of transparent PNG's for IE5 and IE6. Method adapted from http://homepage.ntlworld.com/bobosola/index.htm, which uses DirectX filters to render a background image in a <span>.
var pngTransparencyCompatibilityFlag = true;
var chcRoundedImageID = 0;
var pngImages = new Array(); //IE can't print images loaded with DirectX filters, so we need to keep track of those images and swap them out with regular images when printing
function hypeRenderRoundedImage(imgURL, imgWidth, imgHeight)
{
	//Firefox and IE7
	if (pngTransparencyCompatibilityFlag)
	{
		document.write("<img src=\"" + imgURL + "\" width=\"" + imgWidth + "\" height=\"" + imgHeight + "\"/>");
	}

	//IE5 and IE6
	else
	{
		var imgID = "chcRoundedImage" + chcRoundedImageID;
		document.write("<span id=\"" + imgID + "\" style=\"width: " + imgWidth + "; height: " + imgHeight + "; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader();\"></span>");
		var span = document.getElementById(imgID);
		span.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgURL; //NOTE: We have to do this separately because of Checkpoint
		if (chcElementIsLinkChild(span)) span.style.cursor = "pointer"; //Fix the mouse pointer for rounded images that are linked, since the inserted <span> doesn't inherit the default <a> mouse pointer in IE6
		chcRoundedImageID++;
		pngImages[pngImages.length] = imgID; //Track this image for printing purposes
	}
}
function hypeRenderHeadingArrowButton(imgURL, imgID, headingLevel)
{
	//Determine if we need to specify a class="" attribute, which will determine the vertical alignment of the button relative to any heading text
	var cssClass = "";
	if (headingLevel != null) cssClass = " class=\"h" + headingLevel + "Button\"";

	//Firefox and IE7
	if (pngTransparencyCompatibilityFlag)
	{
		document.write("<img src=\"" + imgURL + "\" width=\"15\" height=\"15\" id=\"" + imgID + "\"" + cssClass + " language=\"JavaScript\" onmouseover=\"swapImage_Heading('" + imgID + "',1);\" onmouseout=\"swapImage_Heading('" + imgID + "',0);\"/>");
	}

	//IE5 and IE6
	else
	{
		//Note that we are using two <span>'s nested together. IE6 demonstrates severe flickering when mouse events are tied to the inner <span>, possibly due to the image transparency.
		document.write("<span style=\"width: 15; height: 15; cursor: pointer;\" language=\"JavaScript\" onmouseover=\"swapImage_Heading('" + imgID + "',1);\" onmouseout=\"swapImage_Heading('" + imgID + "',0);\">" +
		                   "<span id=\"" + imgID + "\"" + cssClass + " style=\"width: 15; height: 15; cursor: pointer; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader();\">" +
		                   "</span>" +
		               "</span>");
		document.getElementById(imgID).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgURL; //NOTE: We have to do this separately because of Checkpoint, and because of a browser bug in IE6SP1 where h3 tags had issues with rollovers
		pngImages[pngImages.length] = imgID; //Track this image for printing purposes
	}
}

//Image swapping functions
function swapImageNavButton(imgID, hover)
{
	var img = document.getElementById(imgID);
	var url = img.src;

	url = url.replace(/&textrgb\=[\dABCDEF]{6}/gi, "");
	var hoverRGB   = "";
	var noHoverRGB = "";
	switch (StyleIndex)
	{
		case 0:  hoverRGB = "202020"; noHoverRGB = "202020"; break;
		case 1:  hoverRGB = "CA005D"; noHoverRGB = "202020"; break;
		case 2:  hoverRGB = "202020"; noHoverRGB = "202020"; break;
	}
	url += "&textrgb=" + (hover == 1 ? hoverRGB : noHoverRGB);

	url = url.replace(/&hover\=1/gi, "");
	if (hover == 1) url += "&hover=1";
	img.src = url;
}
function swapImage_LeftNavButton(imgID, hover)
{
	swapImageNavButton(imgID, hover);
}
function swapImage_RightNavButton(imgID, hover)
{
	swapImageNavButton(imgID, hover)
}
function swapImage_StarNetButton(imgID, hover)
{
	var img = document.getElementById(imgID);
	var url = img.src;

	url = url.replace(/&textrgb\=[\dABCDEF]{6}/gi, "");
	var selectedRGB = "";
	var hoverRGB    = "";
	var noHoverRGB  = "";
	if (url.indexOf("&selected=1") > -1)
	{
		switch (StyleIndex) //Selected
		{
			case 0:  hoverRGB = "202020"; noHoverRGB = "202020"; break;
			case 1:  hoverRGB = "CA005D"; noHoverRGB = "202020"; break;
			case 2:  hoverRGB = "202020"; noHoverRGB = "202020"; break;
		}
	}
	else
	{
		switch (StyleIndex) //Not selected
		{
			case 0:  hoverRGB = "FFFFFF"; noHoverRGB = "FFFFFF"; break;
			case 1:  hoverRGB = "CA005D"; noHoverRGB = "FFFFFF"; break;
			case 2:  hoverRGB = "FFFFFF"; noHoverRGB = "FFFFFF"; break;
		}
	}
	url += "&textrgb=" + (hover == 1 ? hoverRGB : noHoverRGB);

	url = url.replace(/&hover\=1/gi, "");
	if (hover == 1) url += "&hover=1";
	img.src = url;
}
function swapImage_Arch(imgID, hover)
{
	var img = document.getElementById(imgID);
	var url = img.src.replace(/_hover/i, "");
	if (hover == 1) url = url.replace(/\.gif/i, "_Hover.gif");
	img.src = url;
}
function swapImage_Heading(imgID, hover)
{
	if (pngTransparencyCompatibilityFlag)
	{
		var img = document.getElementById(imgID);
		var url = img.src.replace(/_hover/i, "");
		if (hover == 1) url = url.replace(/\.png/i, "_Hover.png");
		img.src = url;
	}
	else
	{
		var span = document.getElementById(imgID);
		var url = span.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src.replace(/_hover/i, "");
		if (hover == 1) url = url.replace(/\.png/i, "_Hover.png");
		span.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = url;
	}
}

//Printing support specifically for IE5 and IE6. The DirectX filters used to display transparent PNG's don't print, so we have to temporarily insert actual <img> tags into the <span> tags using the filters.
function chcBeforePrint()
{
	//For each transparent PNG on the page...
	for (var i = 0; i < pngImages.length; i++)
	{
		var element = document.getElementById(pngImages[i]);
		if (element != null)
		{
			//Determine an appropriate CSS class to use for printing. Rounded images don't need a class, and right-aligned round arrow buttons use a different class than non-aligned round arrow buttons.
			var cssClass = "";
			if (element.className != "") //If (this PNG is not a rounded image)...
			{
				//Is this button in a <table>? (true)  Or is it just following inline with some header text? (false)
				var isRightAlignedButton = (pngImages[i].indexOf("_AlignRight") > -1);
				if (isRightAlignedButton)
				{
					cssClass = " class=\"" + element.className + "PrintR\""; //Most likely a right-aligned round arrow button
				}
				else
				{
					cssClass = " class=\"" + element.className + "Print\""; //Most likely a non-aligned round arrow button
				}
			}

			//Insert a real <img> inside the <span> tag hosting the transparent PNG. Since the DirectX filters won't print, the <span> tag will be empty on the printout, and thus replaced by this image.
			element.innerHTML = "<img src=\"" + element.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src + "\"" + cssClass + " width=\"" + element.style.width + "\" height=\"" + element.style.height + "\"/>";
		}
	}
}
function chcAfterPrint()
{
	//For each transparent PNG on the page...
	for (var i = 0; i < pngImages.length; i++)
	{
		var element = document.getElementById(pngImages[i]);
		if (element != null)
		{
			//Remove the temporary <img> used for printing
			element.innerHTML = "";
		}
	}
}

// Check whether string s is empty.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// Function validateEmail implemented using regular expressions, checking for a valid format:
function validateEmail(sField)
{
	var addressPattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;   
		
	if (isEmpty(sField.value)) return true;
    if (!addressPattern.test(sField.value))  return false;
			
	return true;
}

//Validate SSN
function SSNValidation(ssn) 
{
	var matchArr = ssn.value.match(/^(\d{3})-?\d{2}-?\d{4}$/);
	var numDashes = ssn.value.split('-').length - 1;
	
	if (ssn.value.length == 0) return true;
	if (matchArr == null || numDashes == 1) return false;
	
	return true;
}

// Function validateZipCode implemented using regular expressions, checking for a valid format:
// Looking for the either five digits: xxxxx OR five digits - four digits:  xxxxx-xxxx
function validateZipCode(sField)
{
	var zipCodePattern = /(^\d{5}$)|(^\d{5}\-\d{4}$)/;  
	
	if (isEmpty(sField.value))					return true;	
   	if (!zipCodePattern.test(sField.value))  	return false;
		
	return true;
}  // end validateZipCode

//Validates that a phone number is 10 digits and contains only numbers
function validatePhone(fld) 
{
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

	if (stripped.length == 0) return 0;    	
    if (isNaN(parseInt(stripped))) return 1; //Illegal Characters 
    if (!(stripped.length == 10)) return 2;	 // Not enough digits
    
   	return 0;
}		

//This function will check the character length on the passed in a <textarea> field and, if it exceeds the max passed in length,
//will send back how many extra characters were entered.
function maxlength(field, maxvalue)
{
	//If (the field has no text in it) Then, that's within the maxvalue limit, so that's OK
	if (field.value == null) return 0;
	
	//Determine how many characters have been entered, and how many need to be trimmed off for the user
	var q = field.value.length;
	var r = q - maxvalue;
	
	//If (the field has too much text in it)...
	if (q > maxvalue) return r;
		
	//Field is OK
	return 0;
}


// Function validateStateCode, checking for a valid format:
function validateStateCode(sField)
{
	// Valid U.S. Postal Codes for states, territories, armed forces, etc.
	// See http://www.usps.gov/ncsc/lookups/abbr_state.txt.

	var USStateCodeDelimiter = "|";
	var USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP"

	if (isEmpty(sField.value)) return true;
		
	return ( (USStateCodes.indexOf(sField.value.toUpperCase()) != -1) && (sField.value.indexOf(USStateCodeDelimiter) == -1) )
			
}  // end validateStateCode

//////////////  Start of Date Validation functions //////////////////////////////////////////////////////

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
//var minYear=1900;
//var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this
}

function isDate(dtStr, minDate, maxDate){
	
	var thisMinDate = "01/01/2000";
	var thisMaxDate = "01/01/2020";
	
	if (minDate != "") thisMinDate = minDate;
	if (maxDate != "") thisMaxDate = maxDate;
	
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	
	strYr=strYear;
	
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
		
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	
	//turn passed in date into a date instead of string so we can compare
	var thisDate = new Date();
	thisDate.setYear(year);
	thisDate.setMonth(month - 1);
	thisDate.setDate(day);
	
	//maxDate - turn it into date so you can compare date to date
	var maxDatePos1=thisMaxDate.indexOf(dtCh);
	var maxDatePos2=thisMaxDate.indexOf(dtCh,maxDatePos1+1);
	var strmaxDateMonth=thisMaxDate.substring(0,maxDatePos1);
	var strmaxDateDay=thisMaxDate.substring(maxDatePos1+1,maxDatePos2);
	var strmaxDateYear=thisMaxDate.substring(maxDatePos2+1);
	maxDateMonth=parseInt(strmaxDateMonth);
	maxDateDay=parseInt(strmaxDateDay);
	maxDateYear=parseInt(strmaxDateYear);
	
	thisMaxDate = new Date();
	thisMaxDate.setYear(maxDateYear);
	thisMaxDate.setMonth(maxDateMonth - 1);
	thisMaxDate.setDate(maxDateDay);

	//minDate - turn it into date so you can compare date to date
	var minDatePos1=thisMinDate.indexOf(dtCh);
	var minDatePos2=thisMinDate.indexOf(dtCh,minDatePos1 + 1);
	var strMinDateMonth=thisMinDate.substring(0,minDatePos1);
	var strMinDateDay=thisMinDate.substring(minDatePos1+1,minDatePos2);
	var strMinDateYear=thisMinDate.substring(minDatePos2+1);
	minDateMonth=parseInt(strMinDateMonth);
	minDateDay=parseInt(strMinDateDay);
	minDateYear=parseInt(strMinDateYear);
	
	thisMinDate = new Date();
	thisMinDate.setYear(minDateYear);
	thisMinDate.setMonth(minDateMonth - 1);
	thisMinDate.setDate(minDateDay);
	
	if (pos1==-1 || pos2==-1){		
		return "The date format should be : mm/dd/yyyy";
	}
	if (strMonth.length < 1 || month < 1 || month > 12){
		return "Please enter a valid month";
	}
	if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]){
		return "Please enter a valid day";
	}
	if (strYear.length != 4 ){
		return "Please enter a valid 4 digit year";
	}
	
	if (thisDate < thisMinDate || thisDate > thisMaxDate){
		return "Please enter a valid date between " + minDateMonth + "/" + minDateDay + "/" + minDateYear  + " and " + maxDateMonth + "/" + maxDateDay + "/" + maxDateYear;
	}
	
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return "Please enter a valid date";
	}
return "";
}
////////  End of Date Validation functions /////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Google Analytics
///////////////////////////////////////////////////////////////////////////



function chcGoogleAnalytics_TrackThisPage()
{
	var gaJsHost = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.');
	document.write(unescape('%3Cscript src="' + gaJsHost + 'google-analytics.com/ga.js" type="text/javascript"%3E%3C/script%3E'));
	try
	{
		var pageTracker = _gat._getTracker('UA-11218847-1'); //Unique Google Analytics profile ID for "www.chidrensmn.org"
		pageTracker._setDomainName('.childrensmn.org');  //Force our domain name
		pageTracker._trackPageview();
	} catch(e) {}
}
