﻿/// <reference path="jquery-1.4.1.min.js" />

function $$(controlName)
{
	if (typeof $ControlPrefix == 'undefined') { alert('$$(' + controlName + ') failed: $ControlPrefix is undefined'); }
	return $('#' + $ControlPrefix + controlName);
}

var g_hash;
function jumpToHash(hash)
{
	g_hash = hash;
	if (g_hash && g_hash != null && g_hash.length > 0) { $(window).scrollTop($('#' + hash).offset().top); }
}

$(document).ready(function()
{
	if (g_hash && g_hash != null && g_hash.length > 0)
	{
		window.setTimeout(function() { $(window).scrollTop($('#' + g_hash).offset().top); }, 5);
	}
	var y = $('#ctl00_ctl00_ContentPlaceHolder1_hfY').val();
	if (y && y != null && y > 0) { $(document.body).scrollTop(y); }
});


// Saves the coordinates
function smartScroller_GetCoords()
{
	$('#ctl00_ctl00_ContentPlaceHolder1_hfY').val($(document.body).scrollTop());
}


// Sets the event captures to Save and Restore the scroll position
try
{
	window.onscroll = smartScroller_GetCoords;      /* Saves the position on a scroll event */
	window.onkeypress = smartScroller_GetCoords;    /* Saves the position on a keypress event */
	window.onclick = smartScroller_GetCoords;       /*Saves the position on a click event */
}
catch (e)
{
}

function fnGoToBackPage(pageURL)
{
	try { fnSavePageValues() } catch (e) { }
	__doPostBack('LinkTo_', pageURL);
	return false;
}

/*
Commented out 1/8/2010 by Corey Caldwell
Could not find anything using this function
function linkDisabledPopup()
{
//gModalCloseShowInTitle = true;
//gModalCloseTitle = "Close Dialog";
//showPopWin('../Common/externalLinkIsDisabled.aspx', 300, 135, null)
var URL = "../Common/externalLinkIsDisabled.aspx";
var settings = { id: 'chooseSizeDialog', title: 'What size should I choose?', url: URL, position: "top", width: 300, height: 135 };
$('#fakeInputToNotCausePostback').setDialog(settings);
$('#fakeInputToNotCausePostback').click();
}*/

/*
Commented out 1/8/2010 by Corey Caldwell
Could not find anything using this function
function loadEmailInMainFrame(to)
{
top.frames["mainFrame"].showPopWin('../common/sendemail.aspx?to=' + to, 550, 530, null)
}*/


// Find's the object for nearly any browser.
function objFinder_FindObject(objName)
{
	return document.getElementById ? document.getElementById(objName) : document.all ? document.all[objName] : document.layers ? document.layers[objName] : null;
}

// Get's the object's page-relative X coordinate
function objFinder_FindPosX(obj)
{
	var curleft = 0;

	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	{
		curleft += obj.x;
	}

	return curleft;
}

// Get's the object's page-relative Y coordinate
function objFinder_FindPosY(obj)
{
	var curtop = 0;

	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	{
		curtop += obj.y;
	}

	return curtop;
}




function fnCreateXMLHTTPRequest()
{
	try
	{// instantiate object for Mozilla, Nestcape, etc.
		oHTTPObj = new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{ // instantiate object for Internet Explorer
			oHTTPObj = new ActiveXObject('MSXML2.XMLHTTP.3.0');
		}
		catch (e)
		{ // Ajax is not supported by the browser
			oHTTPObj = null;
		}
	}
	return oHTTPObj;
}

function fnAJAXKeepAlive()
{
	xmlobj = fnCreateXMLHTTPRequest();
	parameters = "";
	//xmlobj.onreadystatechange =  function() { fnCallbackTest(xmlobj); };
	xmlobj.open('POST', "../KeepAlive.aspx/", true);
	xmlobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlobj.setRequestHeader("Content-length", parameters.length);
	xmlobj.setRequestHeader("Connection", "close");
	xmlobj.send(parameters);
	//fnCallback(xmlobj, responseHandler, controlName)
	window.setTimeout("fnAJAXKeepAlive()", keepAliveTimer);
	xmlobj = null;
}

function fnSendSJAXRequest(URL, methodName, parameters, responseHandler, controlName)
{
	window.cursor = "wait";
	xmlobj = fnCreateXMLHTTPRequest();
	//xmlobj.onreadystatechange =  function() { fnCallback(xmlobj,  responseHandler, controlName); };
	xmlobj.open('POST', URL + methodName, false);
	xmlobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlobj.setRequestHeader("Content-length", parameters.length);
	//xmlobj.setRequestHeader("Connection", "close");
	xmlobj.send(parameters);
	fnCallback(xmlobj, responseHandler, controlName);
	xmlobj = null;
}


function fnCallback(http_request1, responseHandler, controlName)
{
	if (http_request1.readyState == 4)
	{
		window.cursor = "auto";
		if (http_request1.status == 200)
		{
			var data = http_request1.responseText;
			if (data.length > 0)
			{
				data = data.replace(/&lt;/g, "<");
				data = data.replace(/&gt;/g, ">");
				var start = data.indexOf("<ReturnData>") + 12;
				var end = data.indexOf("</ReturnData>");
				data = data.substring(start, end);
			}
			responseHandler(data, controlName);
		}
		else
		{
			alert('Failed to get response :' + http_request1.statusText + " status: " + http_request1.status);
			alert(http_request1.responseText);
		}
	}
}


function fnReloadCombo(data, comboName)
{
	// REB - UnEncode &amp; so it doesn't split and displays the desired '&' character in the combo.
	// 1/11/2008
	data = HTMLDecode(data);
	var list = data.split(";");
	if (list.length <= 1)
	{
		fnReloadCombo_SetVisibility(comboName, "none");
	}
	else
	{
		fnReloadCombo_SetVisibility(comboName, "");
		fnReloadCombo_LoadWithArray(comboName, list);
	}
}

function fnReloadText(data, controlName)
{
	$('#' + controlName).html(data);
}

function fnReloadCombo_SetVisibility(comboName, display)
{
	try
	{
		objFinder_FindObject(comboName).parentElement.parentElement.parentElement.parentElement.style.display = display;
	}
	catch (e)
	{
		objFinder_FindObject(comboName).parentNode.parentNode.parentNode.parentNode.style.display = display;
	}
}

function fnReloadCombo_LoadWithArray(comboName, list)
{
	objFinder_FindObject(comboName).options.length = 0;
	for (var i = 0; i < list.length - 1; i++)
	{
		var el = document.createElement("option");
		el.text = list[i];
		var sel = objFinder_FindObject(comboName);
		try
		{
			sel.add(el, null); // standards compliant
		}
		catch (ex)
		{
			sel.add(el); // IE only
		}
	}
}

function fnSelectComboItem_ByText(ComboName, Text)
{
	var e = objFinder_FindObject(ComboName);
	for (var i = 0; i < e.options.length; i++)
	{
		if (trim(HTMLDecode(e.options[i].innerHTML).toUpperCase()) == trim(Text.toUpperCase()))
		{
			e.options[i].selected = true;
			return true;
			break;
		}
	}
	return false;
}

function fnSelectComboItem_ByValue(ComboName, ComboValue)
{
	var e = objFinder_FindObject(ComboName);
	for (var i = 0; i < e.options.length; i++)
	{
		if (trim(e.options[i].value.toUpperCase()) == trim(ComboValue.toUpperCase()))
		{
			e.options[i].selected = true;
			return true;
			break;
		}
	}
	return false;
}

function fnSelectedOption(SelectControlID)
{
	var e = objFinder_FindObject(SelectControlID)
	var i = e.selectedIndex;
	if (i == -1) return ""
	return trim(e.options[i].innerHTML);
}

function AddComboValue(ComboName, ComboValue)
{
	if (fnSelectComboItem_ByText(ComboName, ComboValue))
	{
	}
	else
	{
		var el = document.createElement("option");
		el.text = ComboValue
		el.selected = true;
		var sel = objFinder_FindObject(ComboName);
		try
		{
			sel.add(el, null); // standards compliant
		}
		catch (ex)
		{
			sel.add(el); // IE only
		}
	}
}

function getClassName(o)
{
	if (o.getAttribute('className') != null)
		return o.getAttribute('className');
	else
		return o.getAttribute('class');
}

function ObsoletedFunction(functionName)
{
	alert("A javascript error occured during the page load. \n\nWe would very much appreciate it if you reported this to us.  Just click the 'Report A Bug' link at the bottom of our site. "
    + " \n\nPlease be sure to include the following error description: \n\n" + functionName);
}

function setMaxLength()
{
	ObsoletedFunction("setMaxLength");
}

function setMaxLength2()
{
	ObsoletedFunction("setMaxLength2");
}

function setMaxLength3()
{
	ObsoletedFunction("setMaxLength3");
}

function setMaxLength4()
{
	ObsoletedFunction("setMaxLength4");
}

var sMLLastVal = "";

function addACharacter(e)
{
	if (e.parentNode.previousSibling.getAttribute('maxLength') == 24)
	{
		e.parentNode.previousSibling.setAttribute('maxLength', '25');
		e.parentNode.previousSibling.onchange();
		e.parentNode.previousSibling.style.color = "red";
		e.parentNode.style.backgroundColor = "#ffff99";
	}
	else
	{
		e.parentNode.previousSibling.setAttribute('maxLength', '24');
		e.parentNode.previousSibling.onchange();
		e.parentNode.previousSibling.style.color = "";
		e.parentNode.style.backgroundColor = "";
	}
}


function ResetAddACharacter(e)
{
	e.parentNode.previousSibling.setAttribute('maxLength', '24');
	e.parentNode.previousSibling.onchange();
	e.parentNode.previousSibling.style.color = "";
	e.parentNode.style.backgroundColor = "";
}

function checkMaxLength(e)
{
	ObsoletedFunction("checkMaxLength");
}

function checkMaxLength2(e)
{
	ObsoletedFunction("checkMaxLength2");
}

var xx = 0;

function checkMaxLengthNoCall(e)
{
	ObsoletedFunction("checkMaxLengthNoCall");
}

function checkMaxLengthNoCall2(e)
{
	ObsoletedFunction("checkMaxLengthNoCall2");
}



function CalcKeyCode(aChar)
{
	var character = aChar.substring(0, 1);
	var code = aChar.charCodeAt(0);
	return code;
}

function XBrowserKeyCode()
{
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	return code;
}

function checkNumber(val)
{
	if (!(XBrowserKeyCode() >= 48 && XBrowserKeyCode() <= 57)
        && !(XBrowserKeyCode() == 46))
	{
		try
		{
			window.event.keyCode = 0;
			window.event.preventDefault();
			return false;
		}
		catch (e)
		{
			return false;
		}
	}
}

function checkNumberNoDot(val)
{
	if (!(XBrowserKeyCode() >= 48 && XBrowserKeyCode() <= 57))
	{
		try
		{
			window.event.keyCode = 0;
			window.event.preventDefault();
			return false;
		}
		catch (e)
		{
			return false;
		}
	}
}

function checkA_Z_0_9(val)
{
	if (!(XBrowserKeyCode() >= 48 && XBrowserKeyCode() <= 57)
    && !(XBrowserKeyCode() >= 65 && XBrowserKeyCode() <= 90)
    && !(XBrowserKeyCode() >= 97 && XBrowserKeyCode() <= 122))
	{
		try
		{
			window.event.keyCode = 0;
			window.event.preventDefault();
			return false;
		}
		catch (e)
		{
			return false;
		}
	}
}

function showHelp(subject, width, height, position, scrolling, borderColor)
{

	var ifHlp = objFinder_FindObject('ifHelp');
	if (!ifHlp) { return false; }
	ifHlp.src = "../imagesV3/shim.gif";

	var ifDoc = ifHlp.contentDocument ? ifHlp.contentDocument : ifHlp.contentWindow ? ifHlp.contentWindow.document : ifHlp.document ? ifHlp.document : null;
	if (!ifDoc) { return false; }

	var leftpad = 5;
	var toppad = 0;

	ifHlp.style.width = width;
	if (navigator.userAgent.indexOf("Apple") >= 0 && navigator.userAgent.indexOf("Safari") >= 0)
	{
		leftpad = 15;
		toppad = 7;
	} else
	{
		if (navigator.appName == "Microsoft Internet Explorer")
		{
			leftpad = 0;
			toppad = 0;
			ifHlp.style.width = "275px";
		}
	}

	if (subject.indexOf(".") > -1)
		imageID = 'img' + subject.substring(0, subject.indexOf("."));
	else
		imageID = 'img' + subject;

	var imgBtn = objFinder_FindObject(imageID);
	//if (!imgBtn) {return false;}

	if (subject.indexOf(".") > -1)
		ifHlp.src = subject;
	else
		ifHlp.src = '../Help/' + subject + '.htm';
	//  ifDoc.location.replace('../Help/'+subject+'.htm');

	ifHlp.style.borderColor = borderColor;

	ifDoc.scrolling = scrolling;

	ifHlp.style.height = height;
	ifHlp.style.width = width;


	if (position.toLowerCase() == 'left')
	{
		if (imgBtn.height != null) imageHeight = imgBtn.height;
		else imageHeight = 20;
		ifHlp.style.top = (objFinder_FindPosY(imgBtn) + imageHeight + toppad) + "px";

		widthNum = width.replace("px", "");
		if (imgBtn.width != null) imageWidth = imgBtn.width;
		else imageWidth = 20;
		ifHlp.style.left = (objFinder_FindPosX(imgBtn) - widthNum + imageWidth + leftpad) + "px";
	}
	else if (position.toLowerCase() == 'right')
	{
		ifHlp.style.top = (objFinder_FindPosY(imgBtn) + toppad) + "px";
		if (imgBtn.width != null) imageWidth = imgBtn.width;
		else imageWidth = 20;
		ifHlp.style.left = (objFinder_FindPosX(imgBtn) + imageWidth + leftpad) + "px";
	}
	else if (position.toLowerCase() == 'center')
	{
		windowH = getViewportHeight2();
		calcedCenter = (windowH - height.replace("px", "")) / 2;
		if (calcedCenter < objFinder_FindObject('ctl00_ctl00_ContentPlaceHolder1_hfY').value)
			calcedCenter = objFinder_FindObject('ctl00_ctl00_ContentPlaceHolder1_hfY').value;
		ifHlp.style.top = calcedCenter + "px";
		leftedge = objFinder_FindPosX(objFinder_FindObject("RoadIDMasterTDContent_TD"));
		offset = (575 - width.replace("px", "")) / 2;
		ifHlp.style.left = (leftedge + offset) + "px";
	}
	else if (position.toLowerCase() == 'centerabove')
	{
		ifHlp.style.top = (objFinder_FindPosY(imgBtn) + toppad - height.replace("px", "")) + "px";
		leftedge = objFinder_FindPosX(objFinder_FindObject("RoadIDMasterTDContent_TD"));
		offset = (575 - width.replace("px", "")) / 2;
		ifHlp.style.left = (leftedge + offset) + "px";
	}
	else if (position.toLowerCase() == 'centerscreen')
	{
		ifHlp.style.top = parseInt(getScrollTop(), 10) + "px";
		leftedge = objFinder_FindPosX(objFinder_FindObject("RoadIDMasterTDContent_TD"));
		offset = (575 - width.replace("px", "")) / 2;
		ifHlp.style.left = (leftedge + offset) + "px";
	}
}

function getViewportHeight2()
{
	if (window.innerHeight != window.undefined) return window.innerHeight;
	if (document.compatMode == 'CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight;

	return window.undefined;
}

function hideHelp()
{
	var ifHlp = objFinder_FindObject('ifHelp');
	ifHlp.style.top = '-2000px';
	ifHlp.style.left = '-2000px';
	ifHlp.src = "../imagesV3/shim.gif";
}

function HTMLEncode(strHTML)
{
	var html = "" + strHTML;
	var arrE = [["&", "&amp;"], ["\"", "&quot;"], ["<", "&lt;"], [">", "&gt;"]];
	var arrO = [];

	for (var i = 0, j = html.length, k = arrE.length; i < j; ++i)
	{
		var c = arrO[i] = html.charAt(i);
		for (var l = 0; l < k; ++l)
		{
			if (c == arrE[l][0])
			{
				arrO[i] = arrE[l][1];
				break;
			}
		}
	}
	return arrO.join("");
}

function HTMLDecode(strHTML)
{
	var html = strHTML

	html = html.replace(/&AMP;/gi, "&");
	html = html.replace(/&QUOT;/gi, "\"");
	html = html.replace(/&LT;/gi, "<");
	html = html.replace(/&GT;/gi, ">");
	return html;
}
// Removes leading whitespaces
function LTrim(value)
{

	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim(value)
{

	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trim(value)
{

	return LTrim(RTrim(value));

}

function IsNonZeroNonBlank(value)
{
	try
	{
		if (isNaN(value)) return false;
		if (value == 0) return false;
	}
	catch (e)
	{
		return false;
	}
	return true
}


function fnWordCountOfOptions(elementName)
{
	var i = 0;
	try
	{
		e = objFinder_FindObject(elementName);
		i = e.options.length;
		for (var j = 0; j < e.options.length - 1; j++)
		{
			if (e.options[j].innerHTML.indexOf("Add") > -1) i--;
			if (e.options[j].innerHTML.indexOf("None") > -1) i--;
		}
	}
	catch (e)
	{
	}
	if (i == 1) return "one";
	else if (i == 2) return "two";
	else if (i == 3) return "three";
	else if (i == 4) return "four";
	else if (i == 5) return "five";
	else if (i == 6) return "six";
	else if (i == 7) return "seven";
	else if (i == 8) return "eight";
	else if (i == 9) return "nine";
	else if (i == 10) return "ten";
	else if (i == 11) return "eleven";
	else if (i == 12) return "twelve";
	else return "numerous";
}


function upperFirst(s)
{
	return s.charAt(0).toUpperCase() + s.substring(1, s.length);
}




//********************  Click And Disable *******************
var wasClicked = false;
var _sCmd;
var _sArgs;
var wasPosted = false;

function ClickAndDisable(sButton, sCmd, sArgs)
{
	showTransMask();
	if (wasClicked == true) return false;
	wasClicked = true;
	var btn1 = objFinder_FindObject(sButton);
	_sCmd = sCmd;
	_sArgs = sArgs;
	addRIDEvent(btn1, 'load', PostIt);
	btn1.src = "../imagesV3/loading.gif";
	return false;
}

function PostIt()
{
	if (wasPosted == true) return;
	wasPosted = true;
	__doPostBack(_sCmd, _sArgs);
}


function addRIDEvent(obj, evType, fn)
{
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent)
	{
		var r = obj.attachEvent("on" + evType, fn);
		return r;
	} else
	{
		return false;
	}
}
//********************  END Click And Disable *******************


function showDemo()
{
	$.getScript('../Scripts/flashsniffer.js', function()
	{
		if (jimAuld.utils.flashsniffer.installed)
		{
			var settings = { id: 'InteractiveDemo', title: 'Road ID Interactive Demo', url: '../demo/InteractiveDemoSWF.htm', height: 600, width: 600, modal: true };
		}
		else
		{
			var settings = { id: 'InteractiveDemo', title: 'Road ID Interactive Demo', url: '../demo/demo1.aspx', height: 680, width: 620, leftButtonTitle: null, modal: true };
		}
		$('#fakeInputToNotCausePostback').setDialog(settings);
		$('#fakeInputToNotCausePostback').click();
	});
}


function demoEmail()
{
	hidePopWin(true);
	location = "../Checkout/KioskReceipt.aspx?mode=direct";
}

function showSecure()
{
	if (typeof (KioskID) == "undefined")
	{
		return fnGoToBackPage('../common/secure.aspx');
	}
	else
	{
		gModalCloseShowInTitle = true;
		gModalCloseTitle = "Close Dialog";
		showPopWin('../common/secureKiosk.aspx', 620, 600, null)
		return false;
	}
}

function showKioskSecure()
{
	gModalCloseShowInTitle = true;
	gModalCloseTitle = "Close Dialog";
	showPopWin('../common/secureKiosk.aspx', 620, 620, null)
}

function showClearMyDataHelp()
{
	gModalCloseShowInTitle = true;
	gModalCloseTitle = "Close Help";
	showPopWin('../help/ClearMyData.aspx', 300, 210, null)
}

function copyClipChar(e)
{
	holdtext = objFinder_FindObject("holdtext");
	//holdtext.innerText = e.innerText;
	if (document.all)
	{
		holdtext.innerText = e.innerText;
	}
	else
	{
		holdtext.textContent = e.textContent;
	}
	Copied = holdtext.createTextRange();
	Copied.execCommand("Copy");
	return false;
}

function kioskShowDemo()
{
	showPopWin('../demo/demo1.aspx', 600, 600, null)
}

function disableRightClick(e)
{
	if (e && e.event)
	{
		if (e.event.button == 2 || e.event.button == 3)
			return disableContextMenu(e);
	}
}
function disableContextMenu(e)
{
	alert('Right Clicking on our logo has been disabled.  Friends of Road ID can download our logo by going to www.RoadID.com/logos');
	return cancel(e);
}

function cancel(e)
{
	if (e && e.event)
		e.cancelBubble = true;
	document.oncontextmenu = function() { return false; }
	window.setTimeout("resetContext()", 20);

	return false;
}

function resetContext()
{
	document.oncontextmenu = null;
}

function kioskTimeOut()
{
	showPopWin('../Kiosk/KioskTimeout.aspx', 400, 200, kioskResetTimeout)
}

function kioskResetTimeout()
{
	window.clearTimeout(kioskTimer);
	kioskTimer = window.setTimeout('kioskTimeOut()', 3 * 60000);
}
function kioskResetTimeoutMouseMove()
{
	if (xpos == null)
	{
		xpos = event.clientX;
		ypos = event.clientY;
	}
	else if (Math.abs(xpos - event.clientX) > 5 || Math.abs(ypos - event.clientY) > 5)
	{
		window.clearTimeout(kioskTimer);
		kioskTimer = window.setTimeout('kioskTimeOut()', 3 * 60000);
	}
}

function kioskClearAndGoHome()
{
	hidePopWin(true);
	location = "../Checkout/KioskReceipt.aspx?mode=direct";
}

function kioskScreenSaverTimeOut()
{
	parent.location = "../testimonial/KioskTestimonial.aspx" + "?ReturnURL=" + ReturnURL;
}

function KioskScreenSaverKeyPress()
{
	window.clearTimeout(kioskScreenSaverTimer);
	kioskScreenSaverTimer = window.setTimeout('kioskScreenSaverTimeOut()', 5 * 60000);
}

var xpos = null;
var ypos = null;

function KioskScreenSaverMouseMove()
{
	if (xpos == null)
	{
		xpos = event.clientX;
		ypos = event.clientY;
	}
	else if (Math.abs(xpos - event.clientX) > 5 || Math.abs(ypos - event.clientY) > 5)
	{
		window.clearTimeout(kioskScreenSaverTimer);
		kioskScreenSaverTimer = window.setTimeout('kioskScreenSaverTimeOut()', 5 * 60000);
	}
}




// getAnchorPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the page.
function getAnchorPosition(anchorname)
{
	// This function will return an Object with x and y properties
	var useWindow = false;
	var coordinates = new Object();
	var x = 0, y = 0;
	// Browser capability sniffing
	var use_gebi = false, use_css = false, use_layers = false;
	if (document.getElementById) { use_gebi = true; }
	else if (document.all) { use_css = true; }
	else if (document.layers) { use_layers = true; }
	// Logic to find position
	if (use_gebi && document.all)
	{
		x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y = AnchorPosition_getPageOffsetTop(document.all[anchorname]);
	}
	else if (use_gebi)
	{
		var o = document.getElementById(anchorname);
		x = AnchorPosition_getPageOffsetLeft(o);
		y = AnchorPosition_getPageOffsetTop(o);
	}
	else if (use_css)
	{
		x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y = AnchorPosition_getPageOffsetTop(document.all[anchorname]);
	}
	else if (use_layers)
	{
		var found = 0;
		for (var i = 0; i < document.anchors.length; i++)
		{
			if (document.anchors[i].name == anchorname) { found = 1; break; }
		}
		if (found == 0)
		{
			coordinates.x = 0; coordinates.y = 0; return coordinates;
		}
		x = document.anchors[i].x;
		y = document.anchors[i].y;
	}
	else
	{
		coordinates.x = 0; coordinates.y = 0; return coordinates;
	}
	coordinates.x = x;
	coordinates.y = y;
	return coordinates;
}

// getAnchorWindowPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the window
function getAnchorWindowPosition(anchorname)
{
	var coordinates = getAnchorPosition(anchorname);
	var x = 0;
	var y = 0;
	if (document.getElementById)
	{
		if (isNaN(window.screenX))
		{
			x = coordinates.x - document.body.scrollLeft + window.screenLeft;
			y = coordinates.y - document.body.scrollTop + window.screenTop;
		}
		else
		{
			x = coordinates.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset;
			y = coordinates.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset;
		}
	}
	else if (document.all)
	{
		x = coordinates.x - document.body.scrollLeft + window.screenLeft;
		y = coordinates.y - document.body.scrollTop + window.screenTop;
	}
	else if (document.layers)
	{
		x = coordinates.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset;
		y = coordinates.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset;
	}
	coordinates.x = x;
	coordinates.y = y;
	return coordinates;
}

// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft(el)
{
	var ol = el.offsetLeft;
	while ((el = el.offsetParent) != null) { ol += el.offsetLeft; }
	return ol;
}
function AnchorPosition_getWindowOffsetLeft(el)
{
	return AnchorPosition_getPageOffsetLeft(el) - document.body.scrollLeft;
}
function AnchorPosition_getPageOffsetTop(el)
{
	var ot = el.offsetTop;
	while ((el = el.offsetParent) != null) { ot += el.offsetTop; }
	return ot;
}
function AnchorPosition_getWindowOffsetTop(el)
{
	return AnchorPosition_getPageOffsetTop(el) - document.body.scrollTop;
}


function rAjax(sURL, sData, sFunction)
{
	SetWaitPage();
	$.ajax({
		type: "GET",
		url: sURL,
		data: sData,
		contentType: "application/text; charset=utf-8",
		dataType: "xml",
		success: sFunction,

		error: function(xhr, ajaxOptions, thrownError)
		{
			var message = sURL + '\n' + xhr.status + '\n' + xhr.statusText + '\n' + xhr.responseText + '\n' + thrownError + '\n' + ' sData: ' + sData;
			try { rAjaxJsonPost("../ws.asmx", "Log", { Message: message }, function() { }); } catch (e) { };
			ClearWaitPage();
			alert(message);
		}
	});
}

function rAjaxJsonPost(sURL, method, postData, sFunction, async)
{
	if (arguments.length == 4) { async = true; }
	SetWaitPage();
	$.jmsajax({
		type: "POST",
		url: sURL,
		method: method,
		dataType: "msjson",
		data: postData,
		async: async,
		success: sFunction,
		error: function(xhr, ajaxOptions, thrownError)
		{
			var message = method + '\n' + xhr.status + '\n' + xhr.statusText + '\n' + xhr.responseText + '\n' + thrownError + ' postData: ' + postData.toString() + '\n' + sURL;
			try { rAjaxJsonPost("../ws.asmx", "Log", { Message: message }, function() { }); } catch (e) { };
			ClearWaitPage();
			alert(message);
		}
	});
}

var waitPageLastSet = new Date();
var clearWaitPageTimeout;
function SetWaitPage()
{
	var newLoadingDiv = $("#modalOverlay");

	if (newLoadingDiv)
	{
		clearTimeout(clearWaitPageTimeout);
		//$('body').css({ 'overflow': 'hidden' });
		$(document).bind("resize.modal", function()
		{
			newLoadingDiv.css({ width: $(document).width(), height: $(document).height() });
		});
		newLoadingDiv.css({ width: $(document).width(), height: $(document).height() });
		waitPageLastSet = new Date();
		newLoadingDiv.show();
	}
	else
	{
		if (!$.browser.msie)
		{
			$('#ctl00_ctl00_divMainMain').css({ opacity: ".3" });
		}
		else
		{
			$('#ctl00_ctl00_divMainMain').css({ filter: "alpha(opacity = 30);" });
		}
		$('#ctl00_ctl00_divMainMain').css({ cursor: "wait" });
	}
}

var minWaitPageTime = 500;
function ClearWaitPage()
{
	var newLoadingDiv = $("#modalOverlay");

	if (newLoadingDiv)
	{
		var now = new Date();
		var timeElapsed = now.getTime() - waitPageLastSet.getTime();
		if (timeElapsed >= minWaitPageTime)
		{
			$(document).unbind("resize.modal");
			//$('body').css({ 'overflow': '' });
			newLoadingDiv.hide();
		}
		else
		{
			// Add 1 ms to make sure we clear it after the valid time and don't have
			// to make another call due to timing strangeness
			clearWaitPageTimeout = setTimeout("ClearWaitPage();", minWaitPageTime + 1 - timeElapsed);
		}
	}
	else
	{
		if (!$.browser.msie)
		{
			$('#ctl00_ctl00_divMainMain').css({ opacity: "1" });
		}
		else
		{
			$('#ctl00_ctl00_divMainMain').css({ filter: "" });
		}
		$('#ctl00_ctl00_divMainMain').css({ cursor: "default" });
	}
}

function SetColorRollOverSection(Product_abv, ColorNameArray, ImagePath)
{
	var n = 1;
	var MaxOnLine = 6;
	for (var i = 0; i < ColorNameArray.length; i++)
	{
		var ColorName = ColorNameArray[i];
		var startNewLine = false;
		if (n == MaxOnLine)
		{
			startNewLine = true;
			n = 1;
		}
		SetColorRollOver(Product_abv, ColorName, startNewLine, ImagePath);
		n++;
	}
}

function SetColorRollOver(Product_abv, ColorName, AddBRTag, ImagePath)
{
	var ending = "&nbsp;";
	if (AddBRTag) ending = "<br />";
	var tag = String.format('<img id="{0}_{1}_hover" src="../../imagesV3/ColorBlock/{1}_block.gif" border="0" alt="" />{2}', Product_abv, ColorName, ending);
	$('#' + Product_abv + '_COLORS').append(tag);
	$('#' + Product_abv + '_' + ColorName + '_hover').mouseover(function()
	{
		RollOverColor(Product_abv, ColorName, ImagePath)
	});
}

function RollOverColor(Product_abv, ColorName, ImagePath)
{
	$('#' + Product_abv + '_ProductImage').attr('src', ImagePath + Product_abv + '_' + ColorName + '.jpg');
}

(function($)
{
    //Based on article from http://blog.nemikor.com/category/jquery-ui/jquery-ui-dialog/
    $.fn.setDialog = function(settings)
    {
        settings = $.extend({
            //id: 'thisID',
            autoOpen: true,
            title: "title",
            url: null,
            text: '',
            width: null,
            height: null,
            position: "top",
            modal: false,
            resizable: true,
            onloadfn: null,
            draggable: true,
            leftButtonTitle: "CLOSE",
            leftButtonFn: function() { $(this).dialog("close"); },
            leftButtonCSS: { "background-image": "url(../imagesV3/Buttons/button_blue.gif)", "color": "white", "height": "30px", "border": "0", "font-size": "12px", "float": "left", "text-shadow": "black 0 0 1px", "min-width": "100px", "line-height": "30px" },
            rightButtonTitle: null,
            rightButtonFn: null,
            rightButtonCSS: { "background-image": "url(../imagesV3/Buttons/button_orange.gif)", "color": "white", "height": "30px", "border": "0", "font-size": "12px", "float": "right", "text-shadow": "black 0 0 1px", "min-width": "100px", "line-height": "30px", "padding": "0" }
        }, settings);

        //        $.extend($.ui.dialog.prototype, {
        //            'addbutton': function(buttonName, func) {
        //                var buttons = this.element.dialog('option', 'buttons');
        //                buttons[buttonName] = func;
        //                this.element.dialog('option', 'buttons', buttons);
        //            }
        //        });

        return this.each(function()
        {
            $(this).unbind('click.setDialog');

            $(this).one('click.setDialog', function()
            {
                var fullTitle
                if (settings.draggable)
                {
                    fullTitle = '<div id="' + settings.id + '" title=" ' + settings.title + ' <span style=\'font-size:xx-small; font-style:italic;\'>Click here to drag panel</span>">' + settings.text + '</div>';
                }
                else
                {
                    fullTitle = '<div id="' + settings.id + '" title=" ' + settings.title + ' ">' + settings.text + '</div>';
                }


                var bottomButtons = new Object();

                if (settings.leftButtonTitle != null)
                {
                    bottomButtons[settings.leftButtonTitle] = settings.leftButtonFn;
                }
                if (settings.rightButtonTitle != null)
                {
                    bottomButtons[settings.rightButtonTitle] = settings.rightButtonFn;
                }

                var dialogSettings =
				{
				    autoOpen: settings.autoOpen,
				    closeOnEscape: true,
				    position: settings.position,
				    modal: settings.modal,
				    resizable: settings.resizable,
				    draggable: settings.draggable,
				    buttons: bottomButtons
				};
                if (settings.width)
                    dialogSettings["width"] = settings.width;
                if (settings.height)
                    dialogSettings["height"] = settings.height;

                var $dialog = $(fullTitle);
                $dialog
                    .load(settings.url, settings.onloadfn)
                    .dialog(dialogSettings);



                $(':button:contains("' + settings.leftButtonTitle + '")', $dialog.parent()).css(settings.leftButtonCSS);
                $(':button:contains("' + settings.rightButtonTitle + '")', $dialog.parent()).css(settings.rightButtonCSS);
                $('.ui-dialog-titlebar-close .ui-icon-closethick').bind('click.setDialog', settings.leftButtonFn);

                $(this).bind('click.setDialog', function()
                {
                    $dialog.dialog('open');

                    return false;
                });

            });
        });
    };
})(jQuery);

function showPopup(button, title, url, width, height, modal, rightButtonTitle, rightButtonFn)
{
	var id = button.id + "_popup";
	var settings =
	{
		"id": button.id + "_popup",
		"title": title
	};

	if (url.match(/^.*(gif|jpg|jpeg|png)$/i))
		settings["text"] = "<div style=\"text-align: center;\"><img src=\"" + url + "\" /></div>";
	else
		settings["url"] = url;

	if (width)
		settings["width"] = width;

	if (height)
		settings["height"] = height;

	if (modal)
		settings["modal"] = modal;

	if (rightButtonTitle)
		settings["rightButtonTitle"] = rightButtonTitle;

	if (rightButtonFn)
		settings["rightButtonFn"] = rightButtonFn;

	// Add an element so we can click it and show the popup
	var ele = $("<span id=\"" + id + "\"></span>");
	ele.setDialog(settings);
	ele.click();
	return false;
}

function showWristMeasure()
{
	showPopup($("#fakeInputToNotCausePostback")[0], "What size should I choose?", "../common/measure.aspx?MP=0", 650, 500, true);
}

function isEnterKey(event)
{
	return (event.which && event.which == 13) || (event.keyCode && event.keyCode == 13);
}

/*
* Sets up all inputs with a "inputOnEnter" class and that have a "buttonID" 
* attribute so that when a user hits enter, the specified id in the 
* "buttonID" attribute is clicked
*/
function setupInputOnEnter()
{
	$("input.inputOnEnter[buttonid]").bind("keypress.clickOnEnter", function(event)
	{
		if (isEnterKey(event))
		{
			var buttonID = "#" + $(this).attr("buttonid");
			$(buttonID).click();
			return false;
		}
	});
}

function triggerLoginResult(isLoggedIn)
{
	if (isLoggedIn)
		$(document).trigger($.Event("loginSuccessful"));
	else
		$(document).trigger($.Event("loginUnsuccessful"));
}

String.format = function()
{
	var s = arguments[0];
	for (var i = 0; i < arguments.length - 1; i++)
	{
		var reg = new RegExp("\\{" + i + "\\}", "gm");
		s = s.replace(reg, arguments[i + 1]);
	}

	return s;
}

function stripOutAspElements(element)
{
	/// <summary>
	///		Removes the form and viewstate from the specified element.  
	///		Used for cleaning up dynamically loaded pages so that IE will post back correctly
	///	</summary>
	/// <param name="element" optional="true">The element in the dom to clean.  Defaults to body if not specified.</param>
	
	if (!element)
		element = "body";

	var $this = $(element);
	var $content = $("form", $this).children("div:last");
	$this.append($content);
	$("form", $this).remove();
}

function getQueryStringParamater(name)
{
	/// <summary>
	///		Returns the paramater from the query string matching the supplied name.
	///	</summary>
	/// <param name="name">Name of field to get.</param>
	///	<returns type="string">Empty string if not found, the value of the specified paramater otherwise.</returns>
	
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null)
		return "";
	else
		return results[1];
}

String.prototype.trim = function()
{
	/// <summary>
	///		Removes leading and trailing spaces from the string
	///	</summary>
	///	<returns type="string"></returns>
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
String.prototype.capitalize = function(eachWord)
{
	/// <summary>
	///		Returns the supplied string with the first letter capitalized
	///	</summary>
	/// <param name="eachWord" optional="true">If true, capitalize each word in the string</param>
	///	<returns type="string"></returns>

	if (eachWord)
		return this.replace(/(^|\s)([a-z])/g, function(m, p1, p2) { return p1 + p2.toUpperCase(); });
	else
		return this.substring(0, 1).toUpperCase() + this.substring(1);
}


function isCapslock(e)
{
	/// <summary>
	///		Detects whether capslock is on by checking for upper/lower case combined with the shift key
	///	</summary>
	/// <param name="e">Keypress event</param>
	///	<returns type="bool">True if capslock is on</returns>
	
	e = (e) ? e : window.event;

	var charCode = false;
	if (e.which)
	{
		charCode = e.which;
	} 
	else if (e.keyCode)
	{
		charCode = e.keyCode;
	}

	var shifton = false;
	if (e.shiftKey)
	{
		shifton = e.shiftKey;
	} 
	else if (e.modifiers)
	{
		shifton = !!(e.modifiers & 4);
	}

	if ((charCode >= 97 && charCode <= 122 && shifton) || (charCode >= 65 && charCode <= 90 && !shifton))
		return true;
	else
		return false;

}

function stripToInt(str)
{
	return str.replace(/[^\d]/g, "");
}


var _tmplCache = {}
this.parseTemplate = function(str, data)
{
    /// <summary>
    /// FOUND AT http://www.west-wind.com/weblog/posts/509108.aspx
    /// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
    /// and # # code blocks for template expansion.
    /// NOTE: chokes on single quotes in the document in some situations
    ///       use &amp;rsquo; for literals in text and avoid any single quote
    ///       attribute delimiters.
    /// </summary>    
    /// <param name="str" type="string">The text of the template to expand</param>    
    /// <param name="data" type="var">
    /// Any data that is to be merged. Pass an object and
    /// that object's properties are visible as variables.
    /// </param>    
    /// <returns type="string" />  
    var err = "";
    try
    {
        var func = _tmplCache[str];
        if (!func)
        {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            //                        str
            //                  .replace(/[\r\t\n]/g, " ")
            //                  .split("<#").join("\t")
            //                  .replace(/((^|#>)[^\t]*)'/g, "$1\r")
            //                  .replace(/\t=(.*?)#>/g, "',$1,'")
            //                  .split("\t").join("');")
            //                  .split("#>").join("p.push('")
            //                  .split("\r").join("\\'") + "');}return p.join('');";

            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err + " # >";
}