﻿/// <reference path="jquery-1.4.2.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;
	var $this = $('#' + g_hash);
	if (g_hash && g_hash != null && g_hash.length > 0 && $this && $this.size() > 0)
	{
		$(window).scrollTop($this.offset().top); 
	}
}

$(document).ready(function()
{
	var $this = $('#' + g_hash);
	if (g_hash && g_hash != null && g_hash.length > 0 && $this && $this.size() > 0)
	{
		window.setTimeout(function() { $(window).scrollTop($this.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());
}

function formatPhone(phone)
{
	phone = phone.toString();
	if (phone.length == 10)
	{
		return '(' + phone.substring(0, 3) + ') ' + phone.substring(3, 6) + '-' + phone.substring(6, 10);
	}
	else
	{
		return phone;
	}
}

// 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;
}

// 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(e)
{
	var code = null;
	if (e == null)
		e = window.event;

	if (e)
	{
		if (e.keyCode)
			code = e.keyCode;
		else if (e.which) 
			code = e.which;
	}
	return code;
}

function checkNumber(e, val)
{
	var keyCode = XBrowserKeyCode(e);
	if (!(keyCode >= 48 && keyCode <= 57)
		&& !(keyCode == 46))
	{
		return false;
	}
}

function checkNumberNoDot(e, val)
{
	var keyCode = XBrowserKeyCode(e);
	if (!(keyCode >= 48 && keyCode <= 57))
	{
		return false;
	}
}

function checkA_Z_0_9(e, val)
{
	var keyCode = XBrowserKeyCode(e);
	if (!(keyCode >= 48 && keyCode <= 57)
	&& !(keyCode >= 65 && keyCode <= 90)
	&& !(keyCode >= 97 && keyCode <= 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("mainContentDiv"));
		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("mainContentDiv"));
		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("mainContentDiv"));
		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 showSecure()
{
	return fnGoToBackPage('../common/secure.aspx');
}

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 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 ConvertJSONDate(dateString)
{
    return eval(dateString.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
}

function FormatDate( date )
{
    return String(date.getMonth() + 1).padLeft(2, '0') + "/" + String(date.getDate()).padLeft(2, '0') + "/" + date.getFullYear();
}

function resetContext()
{
	document.oncontextmenu = null;
}

// 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;
			handleAjaxError(message);
		}
	});
}

function cookieCheck()
{
	// Create a cookie that lasts about a minute
	Cookies.Create("CookieTest", "1", 0.0007)
	if (Cookies.Read("CookieTest") == null)
	{
		var settings = 
		{
			id: 'cookieDialog',
			autoOpen: true,
			title: "Please Enable Cookies",
			text: '<p>To add items to your shopping cart, you must have "cookies" enabled on to your internet browser.  Please fix your internet browser settings and try again.</p><p>If you need help with this, or if you want to place your order over the phone, give us a call at 800-345-6336, 9am to 5pm Eastern Time.  At Road ID, real people answer the phone very quickly.</p><p>Sorry for the inconvenience.</p>',
			width: 420,
			height: null,
			position: "center",
			modal: true,
			resizable: false,
			draggable: false
		};
		showDialog(settings);

		// Log the error
		// 7/8/2010 MAM Removed error logging
		//try { rAjaxJsonPost("../ws.asmx", "Log", { Message: "Cookies not enabled - " + location.href }, function() { }); } catch (e) { };
	}
}

// Cookie utilities from http://www.quirksmode.org/js/cookies.html
var Cookies = 
{
	Create: function(name, value, days) 
	{
		if (days) 
		{
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},
	Read: function(name) 
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i = 0; i < ca.length; i++) 
		{
			var c = ca[i];

			while (c.charAt(0) == ' ')
				c = c.substring(1, c.length);

			if (c.indexOf(nameEQ) == 0) 
				return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	Delete: function(name) 
	{
		createCookie(name,"",-1);
	}
};

// 90 minutes, 5 seconds by default.  Can be changed by the base page emitting JS to change this number.
// A number < 300000 (5 min) will cause this function not to fire (i.e. for ERP or the timeout being too low)
var pageTimeoutMS = 5405000; // in ms
var minPageTimeoutMS = 300000; // minimum time to timeout and when the warning will show
var idleStart;
var pageTimeoutURL = "../MyAccount/MyAccountLogin.aspx";
var pageTimeout = null;
$(document).ready(function()
{
	startTimeout();
});
function startTimeout()
{
	idleStart = new Date();
	clearTimeout(pageTimeout);

	if (pageTimeoutMS >= minPageTimeoutMS)
	{
		// Show warning page 5 min (300000 ms) before the session will time out
		pageTimeout = setTimeout(function()
		{
			warnTimeout(minPageTimeoutMS);
		}, pageTimeoutMS - minPageTimeoutMS);
	}
}
function warnTimeout(ms)
{
	var settings = 
	{
		id: 'warnDialog',
		autoOpen: true,
		title: "Your Login is About to Expire",
		text: '<p>You have been inactive for <span id="timeoutTimeInactive">?</span>.</p><p>If you are finished, click the "Log Out" button.<br/>If you need more time, click the "Continue" button.</p><p>Unless you choose an option below, you will automatically be logged out in <span id="timeoutTimeRemaining" style="color: #FB7134;">?</span>.</p>',
		width: 400,
		height: null,
		position: "center",
		modal: true,
		resizable: false,
		draggable: false,
		leftButtonTitle: "Log Out",
		leftButtonFn: function()
		{
			SetWaitPage();
			$(this).dialog("close");
			logOut(pageTimeoutURL);
		},
		rightButtonTitle: "Continue",
		rightButtonFn: function()
		{
			SetWaitPage();
			refreshSession();
			$(this).dialog("close");
			ClearWaitPage();
		}
	};
	var $dialog = showDialog(settings);

	updateWarningTimes(ms);

	// remove the close button
	$('.ui-dialog-titlebar-close .ui-icon-closethick', $dialog.parent());
}
function updateWarningTimes(ms)
{
	if (ms > 0)
	{
		var now = new Date();
		var idleMS = now.getTime() - idleStart.getTime();
		$("#timeoutTimeInactive").text(formatTime(idleMS));

		$("#timeoutTimeRemaining").text(formatTime(ms));

		var updateInterval = 1000;
		pageTimeout = setTimeout(function()
		{
			updateWarningTimes(ms - updateInterval);
		}, updateInterval);
	}
	else
		location.href = pageTimeoutURL;
}
function formatTime(ms)
{
	var min, sec, retVal;

	min = Math.floor(ms / 60000);
	ms -= min * 60000;

	sec = Math.floor(ms / 1000);
	ms -= sec * 1000;

	retVal = "";
	
	if (min > 0)
	{
		retVal += min + " minute";
		if (min > 1)
			retVal += "s";
		if (sec > 0)
				retVal += " and ";
	}

	if (sec > 0)
	{
		retVal += sec + " second";
		if (sec > 1)
			retVal += "s";
	}

	return retVal;
}
function rAjaxJsonPost(sURL, method, postData, sFunction, async)
{
	if (pageTimeoutMS >= minPageTimeoutMS)
	{
		// Reset the timeout since this will usually refresh their session
		startTimeout();
	}
	
	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;
			handleAjaxError(message);
		}
	});
}
function rAjaxJsonPostNoError(sURL, method, postData, sFunction, async)
{
	if (pageTimeoutMS >= minPageTimeoutMS)
	{
		// Reset the timeout since this will usually refresh their session
		startTimeout();
	}
	
	if (arguments.length == 4) { async = true; }
	SetWaitPage();
	$.jmsajax({
		type: "POST",
		url: sURL,
		method: method,
		dataType: "msjson",
		data: postData,
		async: async,
		success: sFunction,
		error: null
	});
}
function handleAjaxError(message)
{
	if (message.indexOf('Access To Service Denied') > -1)
	{
		if (window.location.toString().toLowerCase().indexOf('dealer') > -1 || window.location.toString().toLowerCase().indexOf('mp=d') > -1)
		{
			window.location = "../Dealer/Login.aspx?error=expired";
			return;
		}
		if (window.location.toString().toLowerCase().indexOf('sponsorship') > -1)
		{
			window.location = "../Sponsorship/Login.aspx?error=expired";
			return;
		}
		else
		{
			window.location = "../MyAccount/MyAccountLogin.aspx?error=expired";
			return;
		}
	}
	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(), cursor: "wait" });
		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 = 100;
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.css({ cursor: "default" });
			setTimeout(function() { newLoadingDiv.hide(); }, 10);
		}
		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 setupDefaultDialogSettings(settings)
{
	return $.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);
}

function setupDialogWindow(settings)
{
	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);

	if (settings.url)
		$dialog.load(settings.url, settings.onloadfn)

	$dialog.dialog(dialogSettings);

	$(':button:contains("' + settings.leftButtonTitle + '")', $dialog.parent()).css(settings.leftButtonCSS);
	$(':button:contains("' + settings.rightButtonTitle + '")', $dialog.parent()).css(settings.rightButtonCSS);
	
	// Make the close button click the left button
	$('.ui-dialog-titlebar-close .ui-icon-closethick', $dialog.parent()).click(function()
	{
		$(':button:contains("' + settings.leftButtonTitle + '")', $dialog.parent()).click();
	});

	return $dialog;
}

function showDialog(settings)
{
	settings = setupDefaultDialogSettings(settings);
	return setupDialogWindow(settings);
}

(function($)
{
	//Based on article from http://blog.nemikor.com/category/jquery-ui/jquery-ui-dialog/
	$.fn.setDialog = function(settings)
	{
		settings = setupDefaultDialogSettings(settings);

		return this.each(function()
		{
			$(this).unbind('click.setDialog');

			$(this).one('click.setDialog', function()
			{
				var $dialog = setupDialogWindow(settings);

				$(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 showPrivacy()
{
	return showPopup(this, 'Privacy Policy', '../common/privacy.aspx?MP=0', 500, 500, true, null, null);
}
function showContactUs()
{
	return showPopup(this, 'Contact Us', '../common/contact_us.aspx?MP=0', 500, 500, true, null, null);
}

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);
}

function setupInputOnEnter()
{
	/// <summary>
	///		Will cause any inputs with a css class of inputOnEnter containing an attribute
	///		of buttonid to click the button specified by the id in buttonid when the user
	///		types enter
	///	</summary>
	$("input.inputOnEnter[buttonid]").unbind("keypress.clickOnEnter").bind("keypress.clickOnEnter", function(event)
	{
		if (isEnterKey(event))
		{
			var buttonID = "#" + $(this).attr("buttonid");

			// Add a little delay to the button click so that any other functions (like a 
			//  dropdown browser suggestion) have time to complete before we click
			setTimeout("$('" + buttonID + "').click();", 100);
			
			return false;
		}
	});
}

function triggerLoginResult(isLoggedIn)
{
	if (isLoggedIn)
		$(document).trigger($.Event("loginSuccessful"));
	else
		$(document).trigger($.Event("loginUnsuccessful"));
}



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.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;
}

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);
}
String.prototype.padLeft = function(len, padChar)
{
	var temp = this;
	while (temp.length < len) { temp = padChar + temp; }
	return temp;
}
String.prototype.padRight = function(len, padChar)
{
	var temp = this;
	while (temp.length < len) { temp += padChar; }
	return temp;
}

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 = {};
function parseTemplate(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 + " # >";
}




(function($)
{
	$.fn.valNN = function(arg)
	{
		this.each(function()
		{
			if (!arg)
				$(this).val('');
			else
				$(this).val(arg);
		});
	}
	$.fn.capitalizeFirstName = function()
	{
		/// <summary>
		///		Makes a call to a webservice to correctly capitalize a first name
		///	</summary>
		///	<returns type="jQuery"></returns>
		this.each(function()
		{
			var $this = $(this);
			var postData = { WSToken: WSToken, input: $this.val() };

			rAjaxJsonPost
			(
				"../ws.asmx",
				"CapitalizeFirstName",
				postData,
				function(retVal)
				{
					$this.val(retVal);
					ClearWaitPage();
				}
			);
		});

		return this;
	}
	$.fn.capitalizeLastName = function()
	{
		/// <summary>
		///		Makes a call to a webservice to correctly capitalize a last name
		///	</summary>
		///	<returns type="jQuery"></returns>

		this.each(function()
		{
			var $this = $(this);
			var postData = { WSToken: WSToken, input: $this.val() };

			rAjaxJsonPost
			(
				"../ws.asmx",
				"CapitalizeLastName",
				postData,
				function(retVal)
				{
					$this.val(retVal);
					ClearWaitPage();
				}
			);
		});

		return this;
	}
	$.fn.basicDialogSetup = function(autoOpen, title, width, height, modal, closeFunction, leftBtnTitle, leftBtnFunction, rightBtnTitle, rightBtnFunction)
	{
		/// <summary>
		/// Basic setup for a roadid styled popup on a container with the desired text.  Does not auto open
		/// </summary>
		/// <param name="autoOpen" type="bool"></param>
		/// <param name="title" type="string"></param>
		/// <param name="width" type="int"></param>
		/// <param name="height" type="int"></param>
		/// <param name="modal" type="bool"></param>
		/// <param name="closeFunction" type="function"></param>
		/// <param name="leftBtnTitle" type="string"></param>
		/// <param name="leftBtnFunction" type="function"></param>
		/// <param name="rightBtnTitle" type="string"></param>
		/// <param name="rightBtnFunction" type="function"></param>
		/// <returns type="jQuery" />  
		this.each(function()
		{
			var $this = $(this);

			var settings =
			{
				autoOpen: false,
				title: title,
				modal: modal,
				close: closeFunction,
				buttons: {}
			};

			if (width)
				settings["width"] = width;
			if (height)
				settings["height"] = height;
			if (leftBtnTitle)
				settings["buttons"][leftBtnTitle] = leftBtnFunction;
			else
			{
				leftBtnTitle = "Close";
				settings["buttons"][leftBtnTitle] = function() { $this.dialog("close"); };
			}
			if (rightBtnTitle)
				settings["buttons"][rightBtnTitle] = rightBtnFunction;

			$this.dialog(settings);

			$(':button:contains("' + leftBtnTitle + '")', $this.parent()).css({ "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", "padding": "0" });
			$(':button:contains("' + rightBtnTitle + '")', $this.parent()).css({ "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" });

			if (autoOpen)
				$this.dialog("open");
		});
	}
})(jQuery);

function Redirect(url)
{
	SetWaitPage();
	window.location = url;
}

/* 
 * jQuery URL Encode/Decode plugin
 * From: http://0061276.netsolhost.com/tony/testurl.html
*/
$.extend({ URLEncode: function(c)
{
	var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
	while (x < c.length)
	{
		var m = r.exec(c.substr(x));
		if (m != null && m.length > 1 && m[1] != '')
		{
			o += m[1]; x += m[1].length;
		} else
		{
			if (c[x] == ' ') o += '+'; else
			{
				var d = c.charCodeAt(x); var h = d.toString(16);
				o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
			} x++;
		} 
	} return o;
},
	URLDecode: function(s)
	{
		var o = s; var binVal, t; var r = /(%[^%]{2})/;
		while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '')
		{
			b = parseInt(m[1].substr(1), 16);
			t = String.fromCharCode(b); o = o.replace(m[1], t);
		} return o;
	}
});

function refreshSession()
{
	var postData = { WSToken: WSToken };

	rAjaxJsonPost
	(
		"../ws.asmx",
		"RefreshSession",
		postData,
		function(result)
		{
			startTimeout();
		}
	);
}

function logOut(url)
{
	var postData = { WSToken: WSToken };

	rAjaxJsonPost
	(
		"../ws.asmx",
		"LogOutCustomer",
		postData,
		function(result)
		{
			if (url && url.length > 0)
			{
				window.location = url;
			}
			else if (window.location.href.toLowerCase().indexOf("/dealer/") > -1 || window.location.href.toLowerCase().indexOf("/mp=d/"))
			{
				window.location = "../Dealer/Default.aspx";
			}
			else
			{
				window.location = "../Common/Default.aspx";
			}
		}
	);
}

function logOutERP()
{
	var postData = { WSToken: WSToken };

	rAjaxJsonPost
	(
		"../ws.asmx",
		"LogOutERP",
		postData,
		function(result)
		{
			window.location = "../ERP/ERPLogin.aspx";
		}
	);
}

function ChangeSession(url)
{
	if (confirm("You are (or have) logged as an Admin user on a different instance of this browser.\n\n" +
						"Click \"OK\" if you've lost the original window/tab that you logged into ERP with.\n" +
						"Otherwise, click \"Cancel\" and go back to the original window/tab.\n\n" +
						"Would you like to completely log out of ERP?"))
	{
		// logout and be redirected to erplogin.aspx
		logOutERP();
	}
	else
	{
		// Close this tab/window
		window.open('', '_self', '');
		window.opener = top;
		window.close();
	}
}

function createCookie(name, value, days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name, "", -1);
}

function autoTab(input, len, e)
{
	var keyCode = XBrowserKeyCode(e);
	var filter = [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];
	if (input.value.length >= len && !containsElement(filter, keyCode))
	{
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input) + 1) % input.form.length].focus();
	}
}

function containsElement(arr, ele)
{
	var found = false, index = 0;
	while (!found && index < arr.length)
	{
		if (arr[index] == ele)
			found = true;
		else
			index++;
	}
	return found;
}

function getIndex(input)
{
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
	{
		if (input.form[i] == input) 
			index = i;
		else i++;
	}
	return index;
}