//*****************************************************************************
// Common JavaScript code for www.srpnet.com pages.
//*****************************************************************************

// Set the default window status message.
window.defaultStatus = "SRP\u2122."

//*****************************************************************************
// Window onload code.
//
// Note: Do not set window.onload directly, use WindowAddOnloadHandler()
// instead.
//*****************************************************************************

// Set the master onload handler.
window.onload = WindowOnload;

// Create an array for the event handlers.
WindowOnloadHandlers = new Array();

//-----------------------------------------------------------------------------
// Adds a function to the array of window.onload handlers.
//-----------------------------------------------------------------------------
function WindowAddOnloadHandler(h)
{
	WindowOnloadHandlers[WindowOnloadHandlers.length] = h
}

//-----------------------------------------------------------------------------
// The master window.onload handler, calls each function in the array.
//-----------------------------------------------------------------------------
function WindowOnload(e)
{
	for (var i = 0; i < WindowOnloadHandlers.length; i++)
		try
		{
			WindowOnloadHandlers[i](e);
		}
		catch (ex)
		{}
}

//*****************************************************************************
// SRP Banner control code.
//*****************************************************************************

// Build a list of all tab names.
var SrpBannerTabNames = new Array("None", "MyAccount", "ElectricServices", "WaterServices");

//-----------------------------------------------------------------------------
// Deactivates all tabs.
//-----------------------------------------------------------------------------
function SrpBannerClearAllTabs(prefix)
{
	try
	{
		// For each tab, show its "off" image and hide its menu bar.
		for (var i = 1; i < SrpBannerTabNames.length; i++)
		{
			document.getElementById(prefix + SrpBannerTabNames[i] + "TabOnImg").style.display  = "none";
			document.getElementById(prefix + SrpBannerTabNames[i] + "TabOffImg").style.display = "";
			document.getElementById(prefix + SrpBannerTabNames[i] + "MenuBar").style.display   = "none";
		}

		// Show the "None" menu.
		document.getElementById(prefix + SrpBannerTabNames[0] + "MenuBar").style.display = "";

		return false;
	}
	catch (ex)
	{
		return true;
	}
}

//-----------------------------------------------------------------------------
// Activates a specific tab.
//-----------------------------------------------------------------------------
function SrpBannerActivateTab(prefix, name)
{
	// Deactivate all tabs.
	SrpBannerClearAllTabs(prefix);

	try
	{
		// For the designated tab, show its "on" image and menu bar.
		document.getElementById(prefix + name + "TabOffImg").style.display = "none";
		document.getElementById(prefix + name + "TabOnImg").style.display  = "";
		document.getElementById(prefix + name + "MenuBar").style.display   = "";

		// Hide the "None" menu.
		document.getElementById(prefix + SrpBannerTabNames[0] + "MenuBar").style.display  = "none";

		// Save the selected tab name in the hidden form field.
		document.getElementById(prefix + "ClientActivatedTabHidden").value = name;

		return false;
	}
	catch (ex)
	{
		return true;
	}
}

//*****************************************************************************
// Keypress event handling code.
//
// Note: This code prevents the common browser behaviour of submitting a form
// when the ENTER key is pressed as this is usually undesireable when multiple
// submit buttons are present.
//
// You can optionally specify a default button that will be clicked instead. To
// do so, assign the button's ID to the global DefaultButton variable. You can
// use the global OldDefaultButton variable to save and restore any existing
// default button.
//*****************************************************************************

// Set the page keypress event handler.
document.onkeypress = DocumentOnkeypress;

// Define the default button for the ENTER key (set to null here for no
// default). Also define a variable for saving and restoring the current
// default button.
var DefaultButton    = null;
var OldDefaultButton = null;

//-----------------------------------------------------------------------------
// The keypress event handler, prevents form submission when the ENTER key is
// pressed. If a default button is set, it will click that button instead.
//-----------------------------------------------------------------------------
function DocumentOnkeypress(e)
{
	try
	{
		// Determine if the ENTER key was pressed.
		if ((window.event != null && window.event.keyCode == 13) || (e != null && e.keyCode == 13))
		{
			// Determine what element is in focus.
			var el;
			if (window.event != null)
				el = window.event.srcElement;
			if (e != null)
				el = e.target;

			if (el != null)
			{
				// Determine if that element is a link or button.
				var isLink   = false;
				var isButton = false;
				if (el.tagName == "A")
					isLink = true;
				if ((el.tagName == "BUTTON" || el.tagName == "INPUT") &&
				    (el.type == "button" || el.type == "image" || el.type == "reset" || el.type == "submit"))
					isButton = true;

				// If the element is not a link or button, supress the default
				// event behaviour (submitting the form).
				if (!isLink && !isButton)
				{
					if (window.event != null)
						window.event.returnValue = false;
					if (e != null)
						e.preventDefault();

					// If a default button is set, click it.
					if (DefaultButton != null)
					{
						var btn = document.getElementById(DefaultButton);
						if (btn != null && btn.click != null)
							btn.click();
					}
				}
			}
		}
	}
	catch (ex)
	{}
}

//*****************************************************************************
// Web utility code.
//*****************************************************************************

//-----------------------------------------------------------------------------
// Scrolls the page, if necessary, to place the given element into view.
//
// Note: This function should be called via a window.onload event handler.
//-----------------------------------------------------------------------------
function ScrollIntoView(id)
{
	try
	{
		// Get the element, initialize scroll values.
		var el = document.getElementById(id);
		var scrollX = 0;
		var scrollY = 0;

		// Check the horizontal positon.
		var x = GetElementPageOffsetLeft(el);
		var w = GetViewportWidth();
		if (x + el.offsetWidth > w)
			scrollX = x;

		// Check the vertical position.
		var y = GetElementPageOffsetTop(el);
		var h = GetViewportHeight();
		if (y + el.offsetHeight > h)
			scrollY = y;

		// Scroll as needed.
		if (scrollX > 0 || scrollY > 0)
			window.scrollTo(scrollX, scrollY);
	}
	catch (ex)
	{}
}

//*****************************************************************************
// IE style fixes code.
//*****************************************************************************

WindowAddOnloadHandler(IeStyleFix);

function IeStyleFix()
{
	if (document.all == null || window.opera == true)
		return false;

	// Check the IE version.
	try
	{
		var ver = "";
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			ver = parseFloat(RegExp.$1);
		if (ver >= 7.0)
			return false;
	}
	catch (ex)
	{}

	try
	{
		// Simulates the following style selector:
		//
		//   h1 + p, h1 + ol, h1 + ul, h1 + ol p, h1 + ul p,
		//   h2 + p, h2 + ol, h2 + ul, h2 + ol p, h2 + ul p,
		//   h3 + p, h3 + ol, h3 + ul, h3 + ol p, h3 + ul p
		//
		// by adding a style class ("adjacentToHeader") to the latter element.
		var headerTags = new Array("H1", "H2", "H3");
		var elList, el;
		var i, j;

		var mainColumnEl = document.getElementById("maincolumn");
		for (i = 0; i < headerTags.length; i++)
		{
			elList = mainColumnEl.getElementsByTagName(headerTags[i]);
			for (j = 0; j < elList.length; j++)
			{
				el = elList[j].nextSibling;
				// If the tag that follows is a paragraph or list element, add the
				// style class.
				if (el != null &&
				    (el.tagName == "P" || el.tagName == "OL" || el.tagName == "UL"))
					el.className += " adjacentToHeader";
			}
		}
	}
	catch (ex)
	{}
}

//*****************************************************************************
// Utility functions.
//*****************************************************************************

//-----------------------------------------------------------------------------
// Opens a new browser window.
//-----------------------------------------------------------------------------
function NewWindow(url, name, features)
{
	if (name == null)
		window.open(url);
	else
	{
		if (features == null)
			window.open(url, name);
		else
			window.open(url, name, features);
	}
	return false;
}

//-----------------------------------------------------------------------------
// Clears all form input fields, for use by classic ASP forms.
//-----------------------------------------------------------------------------
function ClearForm(f)
{

	// Clear all form elements, this will also blank out fields set with a
	// default value.
	var fld;
  for (var i = 0; i < f.length; i++)
	{
		fld = f.elements[i];
		if ((fld.type == "checkbox" || fld.type == "radio") && fld.checked)
			fld.checked = false;
		if (fld.type == "select-one" || fld.type == "select-multiple")
			fld.selectedIndex = 0;
		if (fld.type == "hidden" || fld.type == "password" || fld.type == "text" || fld.type == "textarea")
			fld.value = "";
	}
	return false;
}

//-----------------------------------------------------------------------------
// Returns an element's left offset relative to the page.
//-----------------------------------------------------------------------------
function GetElementPageOffsetLeft(el)
{
	var x = el.offsetLeft;

	if (el.offsetParent != null)
		x += GetElementPageOffsetLeft(el.offsetParent);

	return x;
}

//-----------------------------------------------------------------------------
// Returns an element's top offset relative to the page.
//-----------------------------------------------------------------------------
function GetElementPageOffsetTop(el)
{
	var y = el.offsetTop;

	if (el.offsetParent != null)
		y += GetElementPageOffsetTop(el.offsetParent);

	return y;
}
		
//-----------------------------------------------------------------------------
// Returns the width of the browser viewport.
//-----------------------------------------------------------------------------
function GetViewportWidth()
{
	if (window.innerWidth != null)
		return window.innerWidth;

	if (document.documentElement.clientWidth != null)
		return (document.documentElement.clientWidth != 0 ? document.documentElement.clientWidth : document.body.clientWidth);
}
		
//-----------------------------------------------------------------------------
// Returns the height of the browser viewport.
//-----------------------------------------------------------------------------
function GetViewportHeight()
{
	if (window.innerHeight != null)
		return window.innerHeight;

	if (document.documentElement.clientHeight != null)
		return (document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.clientHeight);
}
//*****************************************************************************
// Page validation functions, for use during development only.
//*****************************************************************************

// Add a link for HTML validation to the page (for specific domains only).
try
{
	if (document.domain == "dev.srpnet.com" || document.domain == "srpapp158")
		WindowAddOnloadHandler(AddHtmlValidationLink);
}
catch (ex)
{}

function AddHtmlValidationLink(e)
{
	var div = document.createElement("DIV");
	div.style.backgroundColor = "#ffffd0";
	div.style.borderBottomColor = "#a0a060";
	div.style.borderBottomStyle = "solid";
	div.style.borderBottomWidth = "1px;"
	div.style.display = "block";
	div.style.left = "0px";
	div.style.padding = "1px 1em";
	div.style.position = "absolute";
	div.style.textAlign = "left";
	div.style.top = "0px";
	div.style.width = "100%";
	div.style.visibility = "visible";
	div.style.zIndex = "9999";
	try
	{
		div.style.MozOpacity = "0.75";
		div.style.filter = "alpha(opacity = 75)";
	}
	catch (ex)
	{}
	var link = document.createElement("A");
	link.appendChild(document.createTextNode("Validate HTML"));
	link.href = "#";
	link.onclick = ValidatePage;
	link.style.color = "#008000";
	link.style.fontWeight = "bold";
	link.style.textDecoration = "none";
	link.title = "Click to validate this page's HTML.";
	div.appendChild(link);
	document.body.appendChild(div);
}

//-----------------------------------------------------------------------------
// Fetches the current page and submits the source to an online HTML validator.
//-----------------------------------------------------------------------------
function ValidatePage(e)
{
	/* HTML Help validator.
	try
	{
		// Create a form element.
		var formEl = document.createElement("FORM");
		formEl.action = "http://www.htmlhelp.com/cgi-bin/validate.cgi";
		formEl.enctype = "application/x-www-form-urlencoded";
		formEl.method = "POST";

		// Create a container for the form contents.
		var divEl = formEl.appendChild(document.createElement("DIV"));

		// Add the form fields.
		var elementEl = document.createElement("INPUT");
		elementEl.type = "hidden";
		elementEl.name = "charset";
		elementEl.value = "UTF8";
		divEl.appendChild(elementEl);	

		elementEl = document.createElement("INPUT");
		elementEl.type = "hidden";
		elementEl.name = "input";
		elementEl.value = "yes";
		divEl.appendChild(elementEl);	

		elementEl = document.createElement("INPUT");
		elementEl.type = "hidden";
		elementEl.name = "area";
		elementEl.value = HttpGet(document.location);
		divEl.appendChild(elementEl);

		// Add the form to the page and submit it.
		formEl = document.body.appendChild(formEl);
		formEl.submit();
	}
	catch (ex)
	{}
	*/

	/* W3C validator. */
	try
	{
		// Create a form element.
		var formEl = document.createElement("FORM");
		formEl.action = "http://validator.w3.org/check";
		formEl.enctype = "multipart/form-data";
		formEl.method = "POST";

		// Create a container for the form contents.
		var divEl = formEl.appendChild(document.createElement("DIV"));

		// Add the form fields.
		var elementEl = document.createElement("INPUT");
		elementEl.type = "hidden";
		elementEl.name = "doctype";
		elementEl.value = "Inline";
		divEl.appendChild(elementEl);	

		elementEl = document.createElement("INPUT");
		elementEl.type = "hidden";
		elementEl.name = "ss";
		elementEl.value = "1";
		divEl.appendChild(elementEl);	

		elementEl = document.createElement("INPUT");
		elementEl.type = "hidden";
		elementEl.name = "vebose";
		elementEl.value = "1";
		divEl.appendChild(elementEl);	

		elementEl = document.createElement("INPUT");
		elementEl.type = "hidden";
		elementEl.name = "fragment";
		elementEl.value = HttpGet(document.location);
		divEl.appendChild(elementEl);

		// Add the form to the page and submit it.
		formEl = document.body.appendChild(formEl);
		formEl.submit();
	}
	catch (ex)
	{}

	return false;
}

//-----------------------------------------------------------------------------
// Loads a web page via HTTP GET and returns the source as a string.
//-----------------------------------------------------------------------------

// Constant defining possible Microsoft XML HTTP ProgIDs.
var XML_MSXML_HTTP_PROGIDS = new Array(
	"MSXML2.XMLHTTP.4.0",
	"MSXML2.XMLHTTP.3.0",
	"MSXML2.XMLHTTP",
	"Microsoft.XMLHTTP"
);

function HttpGet(url)
{
	var xmlHttp;

	// Check the URL.
	if (url == null)
	{
		alert("Error in HttpGet():\n\nNo URL given.");
		return null;
	}

	// Create the appropriate XMLHTTP object for the browser.
	if (window.XMLHttpRequest != null)
	{
		// The Mozilla way.
		xmlHttp = new XMLHttpRequest();
	}
	else if (window.ActiveXObject != null)
	{
		// The IE way.
		var i;
		var success = false;
		// Try each ProgID till one works.
		for (i = 0; i < XML_MSXML_HTTP_PROGIDS.length && !success; i++)
		{
			try
			{
				xmlHttp = new ActiveXObject(XML_MSXML_HTTP_PROGIDS[i]);
				success = true;
			}
			catch (e) {}
		}
	}
	else
	{
		alert("Error in HttpGet():\n\nCannot create an XMLHTTP object.");
		return null;
	}

	// Get the document and return it as a text string.
//	try
//	{
		xmlHttp.open("GET", url, false);
		xmlHttp.send(null);
		// Check the HTTP response status code. If it was bad, display an error
		// message.
		if (xmlHttp.status != "200")
		{
			alert("Error in HttpGet():\n\nHTTP request for '" + url
				+ "' failed with status '" + xmlHttp.status + " "
				+ xmlHttp.statusText + "'.");
			return null;
		}
		else
		{
			var text = xmlHttp.responseText;
			
			// Get the document type.
			var doctype = "";
			if (document.doctype != null && document.doctype.publicId != null)
				doctype = document.doctype.publicId;
			else if (document.childNodes.length > 1 && document.childNodes[0].nodeValue !== null)
				doctype = document.childNodes[0].nodeValue;
				
			// Is the document XHTML?
			if (doctype.indexOf("XHTML") < 0)
			{
				// No, need to fix ID attribute names (these are pre-ASP.Net 2.0 pages).
				var re = new RegExp("id=\"__", "g");
				text = text.replace(re, "id=\"x__");
			}

			return text;
		}
//	}
//	catch (e)
//	{
		// For IE, extract error information.
//		if (e.number != null)
//			alert("Error in HttpGet():\n\n"
//				+ e.name + ": " + e.description + "\n"
//				+ "Facility Code: " + (e.number >> 16 & 0x1FFF) + "\n"
//				+ "Error Code: " + (e.number & 0xFFFF) + ".");
		// For all others, display the exception.
//		else
//			alert("Error in HttpGet():\n\n" + e.toString());
//		return null;
//	}
}

//*****************************************************************************
// End of page validation code.
//*****************************************************************************
