// ************************************************************************************************
// Function to reduce typing.  Use $ instead of document.getElementById
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
//function $(id){
//	var ctrlX;
//	try {
//		ctrlX = document.getElementById(id);
//	} catch (e) {
//
//	} finally {
//		return ctrlX;
//	}
//}


// ************************************************************************************************
// Function to reduce typing when getting the value of a control.
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// Use $V(ctrlName) instead of document.getElementById(ctrlName).value
// ------------------------------------------------------------------------------------------------
function $V(id, encodeIt){
	var ctrlX;
	var value;
	var encodeOutput;
	if (encodeIt) {
		encodeOutput = encodeIt;
	} else {
		encodeOutput = false;
	}
	try {
		ctrlX = document.getElementById(id);
		
		switch(ctrlX.type) { 
			case "hidden": 
		 		value = ctrlX.value; 
		 		break; 
		 	case "text": 
		 		value = ctrlX.value; 
				break; 
		 	case "select-one": 
		 		value = ctrlX.options[ctrlX.selectedIndex].value; 
		 		break; 
		 	case "textarea": 
		 		value = ctrlX.innerHTML; 
		 		break; 
		 	case "checkbox": 
		 		value = (ctrlX.checked==true)?"Y":"N"; 
		 		break; 
		 	case "radio": 
		 		var radios = document.getElementsByName(ctrlX.name);
		 		var radioLength = radios.length;
		 		if(radioLength == undefined ) { 
		 			if ( ctrlX.checked) {
		 				value = radios.value;
		 			}
		 		}
		 		for (var i = 0; i < radioLength; i++) {
		 			if(radios[i].checked) {
		 				value = radios[i].value;
		 			}
		 		}
				break; 
		                
		 	case "select-multiple": 
		 		var selected = new Array();
		 		
		 		for (var x = 0; x < ctrlX.options.length; x++) {
		 		   if (ctrlX.options[x].selected) {
		 		   	selected.push(ctrlX.options[x].value);
		 		   }
		 		}
		 		
		 		value = selected.join();
		 		break; 
				
		 	case "label": 
		 		value = ctrlX.innerHTML; 
		 		break; 
				
		 	case "div": 
		 		value = ctrlX.innerHTML; 
		 		break;
		 		
		} 	// end select		
		
		
	} catch (e) {
		value= '';
	} finally {
		if (encodeOutput == true) {
//			value = simpleEncode(value);
			value = value.replace(/\&/g, "%26amp;");
//			value = value.replace(/\&/g, "%26");
			value = value.replace(/\=/g, "%3d");
			value = value.replace(/\?/g, "%3f");
		}
		
		return value;
	}
}


// ************************************************************************************************
// Function to reduce typing when getting the text of a control.
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// Use $T(ctrlName) instead of document.getElementById(ctrlName).text
// ------------------------------------------------------------------------------------------------
function $T(id){
	var ctrlX;
	var value;
	try {
		ctrlX = document.getElementById(id);
		
		switch(ctrlX.type) { 
			case "hidden": 
		 		value = ctrlX.value; 
		 		break; 
		 	case "text": 
		 		value = ctrlX.value; 
				break; 
		 	case "select-one": 
		 		value = ctrlX.options[ctrlX.selectedIndex].text; 
		 		break; 
		 	case "textarea": 
		 		value = ctrlX.innerHTML; 
		 		break; 
		 	case "checkbox": 
		 		value = (ctrlX.checked==true)?"Y":"N"; 
		 		break; 
		 	case "radio": 
		 		var radios = document.getElementsByName(ctrlX.name);
		 		var radioLength = radios.length;
		 		if(radioLength == undefined ) { 
		 			if ( ctrlX.checked) {
		 				value = radios.value;
		 			}
		 		}
		 		for (var i = 0; i < radioLength; i++) {
		 			if(radios[i].checked) {
		 				value = radios[i].value;
		 			}
		 		}
				break; 
		                
		 	case "select-multiple": 
		 		var selected = new Array();
		 		for (var x = 0; x < ctrlX.options.length; x++) {
		 		   if (ctrlX.options[x].selected) {
		 		   	selected.push(ctrlX.options[x].text);
		 		   }
		 		}
		 		value = selected.join();
		 		break; 
				
		 	case "label": 
		 		value = ctrlX.innerHTML; 
		 		break; 
				
		 	case "div": 
		 		value = ctrlX.innerHTML; 
		 		break;
		 		
		} 	// end select		
		
		
	} catch (e) {
		value= '';
	} finally {
		return value;
	}
}



// ************************************************************************************************
// Function to reduce typing when getting the value of a control.
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// Use $V(ctrlName) instead of document.getElementById(ctrlName).value
// ------------------------------------------------------------------------------------------------
function setComboValue(id, value){

	ctrlX = $(id);
	for (var x = 0; x < ctrlX.options.length; x++) {
		if (ctrlX.options[x].value == value) {
			ctrlX.options[x].selected = true;
		}
	}
	
}

// ************************************************************************************************
// Function to the get a cookie value.
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The subKey is optional.
// ------------------------------------------------------------------------------------------------
function readCookie(name, subKey) {
	var nameEQ = name + "=";
	var subKeyEQ = subKey + "=";
	
	var sKey = searchArray(document.cookie, ';', name);
	
	if (subKey && subKey != '') {
		var sSubKey = searchArray(sKey, '&', subKey);
		return sSubKey.replace(/\+/g, ' ');
	} else {
		return sKey;
	}
}


// ************************************************************************************************
// Function to the save a cookie value.
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// This function does not allow a subkey
// ------------------------------------------------------------------------------------------------
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=/";
	//if (value.substring(0, 3) == "38|") {
		alert('New Value: [' + name + ']\r\nCookie Value: [' + readCookie(name, "") + ']')
	//}
}


// ************************************************************************************************
// Function to the save a cookie value.
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The subKey is optional.
// ------------------------------------------------------------------------------------------------
function saveCookie(name, subKey, value, days) {

	// replace all the spaces with a plus sign
	value = value.replace(/\ /g, '+');
	
	var nameEQ = name + "=";
	var subKeyEQ = subKey + "=";
	
	var sKey = "&" + searchArray(document.cookie, ';', name);
	var sKeyOld = sKey;
	
	if (subKey && subKey != '') {
		// Get the old value if it exists
		var sSubKey = searchArray(sKey, '&', subKey);
		
		if (sSubKey == '') {
			// Append the value to the key
			if (sKey == '') {
				sKey = subKeyEQ + value;
			} else {
				// append the new value
				sKey += "&" + subKeyEQ + value;
			}
		} else {
			// Replace the old value with the new value
			//if (value.substring(0, 3) == "38|") {
			//	alert('Cookie: ' + sKey + '\r\nOld Value: ' + sSubKey + '\r\nNew Value: ' + value + '\r\nReplace [' + "&" + subKeyEQ + sSubKey + '] with [' + "&" + subKeyEQ + value + ']');
			//}
			sKey = sKey.replace('&' + subKeyEQ + sSubKey, '&' + subKeyEQ + value)
		}
	} else {
		sKey = value;
	}

	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else {
		var expires = "";
	}
	
	// trim off the first "&"
	while (sKey.charAt(0)=='&')  { sKey = sKey.substring(1, sKey.length); }
	
	document.cookie = name + "=" + sKey + expires + "; path=/";
	//if (value.substring(0, 3) == "38|") {
	//	alert('Old Value: [' + sKeyOld + ']\r\nNew Value: [' + sKey + ']\r\nCookie Value: [' + readCookie(name, subKey) + ']')
	//}
}


// ************************************************************************************************
// Function to parse an string by a delimiter and return the value located.  Used to parse cookies.
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
function searchArray(sText, sDelimiter, name, debug) {
	var ca = sText.split(sDelimiter);
	var nameEQ = name + "=";
	for(var i=0;i < ca.length;i++) {
		var c = ca[i].trim();
		// if (debug == true ) { alert('ca[' + i + '] = ' + c); }
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length,c.length);
		}
	}
	return '';
	
}


// ************************************************************************************************
// Function to clear a cookie
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
function clearCookie(key, subkey) {
	saveCookie(key, subkey, "", 1);
}


// ************************************************************************************************
// Function to fix the Progress Bar.  When changing the class of an element to a class that 
// utilizes a htc file for behavior, the htc file downloads but does not fire download complete 
// to IE.  Setting the window status forces IE to peek at active downloads and perform a clean
// up of the progress bar of there are no active downloads.
// ------------------------------------------------------------------------------------------------
function fixProgressBar() {
	setTimeout("runProgressBarFix()", 100);
}


// ************************************************************************************************
// Function to fix the Progress Bar.  When changing the class of an element to a class that 
// utilizes a htc file for behavior, the htc file downloads but does not fire download complete 
// to IE.  Setting the window status forces IE to peek at active downloads and perform a clean
// up of the progress bar of there are no active downloads.
// ------------------------------------------------------------------------------------------------
function runProgressBarFix() {
	// try { document.close(); } catch (e) {}
	window.status = 'Finished';
	window.status = '';
	return
}

	
// ************************************************************************************************
// Function to Enable/Disable controls
// ------------------------------------------------------------------------------------------------
function EnableDisable(id, status){
	if(status || status==false){
		$(id).disabled = status;
	}else{
		if($(id).disabled==true){
			$(id).disabled = false;
		}else{
			$(id).disabled = true;
		}
	}
}

// ************************************************************************************************
// Function to display loading from javascript
// ------------------------------------------------------------------------------------------------
function Loading(sType){

	try {
		$('Splash').style.display = (sType == "D")?"inline":"none";
	} catch (e) {
		
	}
	
}

// ===================================================================================================
// Created by Tim McAteer
// Created on 2009-03-07
// ---------------------------------------------------------------------------------------------------
// Used to log visits on the main pages of the agent web sites
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Sample Usage
// ---------------------------------------------------------------------------------------------------
// /includes/logVisit.asp?AW=5&DT=2009/3/7&PD=About Page&NV=0&RV=0
// ===================================================================================================
function logVisit(AgentNumber, AgentWebId, IPAddress, PageDesc) {
	
	//alert('Your IP Address is ' + IPAddress);
	
	var entryPage = 'N';
	var LastVisit = '';
	var NewVisit = '0';
	var RepeatVisit = '0';
	var today = new Date();
	
	LastVisit = readCookie(AgentNumber, 'LastVisit');
	
	if (LastVisit == '') {
		NewVisit = '1';
	} else {
		// if it's been more than an hour since the last visit...
		var oldDate = new Date(LastVisit);
		var minsDiff = Math.ceil((today.getTime()-oldDate.getTime())/(1000 * 60));
		if (minsDiff >= 60) {
			RepeatVisit = '1';
		}
	}
	
	// is this the entry page?
	// get the current domain
	var domain = location.href;
	// parse off the http:// or https:// or whatever
	var lRet = domain.indexOf('://');
	if (lRet > 0) {
		domain = domain.substr(lRet + 3, domain.length - lRet - 3);
	}
	// find the next "/"
	var lRet = domain.indexOf('/');
	if (lRet > 0) {
		domain = domain.substr(1, lRet - 1);
	}
	// Now domain is trimmed down
	// [http://www.bestinsuranceweb.com/tim/default.asp] is trimmed down to [www.bestinsuranceweb.com]
	// check for the domain in the referrer.
	if(document.referrer.length > 0 && document.referrer.indexOf(domain) != -1){
	    entryPage = 'N';
	} else {
	    entryPage = 'Y';
	}
	//if (document.referrer == '') { entryPage = 'Y'; }
	
	// What just happened?  Show me...
	//alert('Last Visit: ' + LastVisit + '\r\nNew Visit: ' + NewVisit + '\r\nRepeat Visit: ' + RepeatVisit);
	
	// save the cookie for the next visit
	saveCookie(AgentNumber, 'LastVisit', Date(), 999)
	
	var dispDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate()
	
	//alert('dispDate: ' + dispDate);
	
	// send a request via AJAX to save the info to SQL Server
	var sURL = '/includes/logVisit.asp?AW=' + AgentWebId;
	sURL += '&DT=' + dispDate;
	sURL += '&PD=' + PageDesc;
	sURL += '&NV=' + NewVisit;
	sURL += '&RV=' + RepeatVisit;
	sURL += '&IP=' + IPAddress;
	sURL += '&XP=N';
	sURL += '&EP=' + entryPage;
	sURL += '&RF=' + document.referrer;
	sURL += '&SW=' + screen.width;
	sURL += '&SH=' + screen.height;
	sURL += '&BR=' + BrowserDetect.browser;
	sURL += '&BV=' + BrowserDetect.version;
	sURL += '&OS=' + BrowserDetect.OS;
	sURL += '&LG=' + BrowserDetect.language;
	sURL += '&AV=' + navigator.userAgent;
	
	//alert(sURL);
	
	simpleAJAX(sURL);
	
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
		this.language = navigator.userLanguage || navigator.language || "an unknown language";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();



// ************************************************************************************************
// Send Email
// ------------------------------------------------------------------------------------------------
function Email(sFromName, sFromAddress, sReplyToAddress, sToAddress, sCCAddress, sBCCAddress, sPriority, sSubject, sBodyFormat, sBody, sURL, sAttachments, sDeleteAttachments, sApplication, sModule, sOtherParameters, sDateToSend){
	url = "/webservices/Email.asp"
	
	params = "FN=" + sFromName + 
		"&FA=" + sFromAddress +
		"&RA=" + sReplyToAddress +
		"&TA=" + sToAddress +
		"&CA=" + sCCAddress +
		"&BA=" + sBCCAddress +
		"&P=" + sPriority +
		"&S=" + sSubject +
		"&BF=" + sBodyFormat +
		"&B=" + sBody +
		"&U=" + sURL +
		"&A=" + sAttachments +
		"&DA=" + sDeleteAttachments +
		"&AP=" + sApplication +
		"&M=" + sModule +
		"&OP=" + sOtherParameters +
		"&DS=" + sDateToSend

	url = simpleEncode(url);
	params = simpleEncode(params);

	AJAXRequest("null", url, false, "POST", params);
}

                
// ************************************************************************************************
// Function to build form values into string for passing into AJAX "post" call
// ------------------------------------------------------------------------------------------------
function getFormValues(fobj) 
{ 
   var str = ""; 
   var valueArr = null; 
   var val = ""; 
   var cmd = ""; 
	var ctrlID = '';
	   
   for(var i = 0;i < fobj.elements.length;i++) 
   { 
			ctrlID = fobj.elements[i].id;
			if (ctrlID == '' || ctrlID == 'undefined') {
			ctrlID = fobj.elements[i].name;
		}
		try {
			str += ctrlID + "=" + simpleEncode($V(ctrlID)) + "&";
		} catch (e) {}
   }	// end for 
   
   str = str.substr(0,(str.length - 1));	
   return str; 
}

// ************************************************************************************************
// Function to perform an Simple AJAX call
// ------------------------------------------------------------------------------------------------
function simpleAJAX(URL){
	// mozilla
	// if (window.XMLHttpRequest) {
	if(window.XMLHttpRequest && !(window.ActiveXObject)) {
	    xmlObj = new XMLHttpRequest();
	// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject){
		// Try the new MSXML2 object first.  It is in IE 6 and faster than the old version
		try {
			xmlObj=new ActiveXObject("Msxml2.XMLHTTP")
		} catch(e) {
			xmlObj=new ActiveXObject("Microsoft.XMLHTTP")
		}
	}
	// Append a random number
	if(URL.search(/\?/i) > 0){
		URL = URL + "&rndId=" + Math.random();
	}else{
		URL = URL + "?rndId=" + Math.random();
    }
    // if we have an object
    if (xmlObj) {
		xmlObj.open("GET", URL);
	    xmlObj.send(null);
    }
}


// ************************************************************************************************
// Function to perform an AJAX call
// ------------------------------------------------------------------------------------------------
function AJAXRequest(callback, datapage, async, method, str){
	// mozilla
	// if (window.XMLHttpRequest) {
	if(window.XMLHttpRequest && !(window.ActiveXObject)) {
	    xmlObj = new XMLHttpRequest();
	// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject){
		// Try the new MSXML2 object first.  It is in IE 6 and faster than the old version
		try {
			xmlObj=new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch(e) {
			xmlObj=new ActiveXObject("Microsoft.XMLHTTP")
		}
	}
	if(datapage.search(/\?/i) > 0){
		datapage = datapage + "&rndId=" + Math.random();
	}else{
		datapage = datapage + "?rndId=" + Math.random();
    }
    if (xmlObj) {
		if (async)
		    xmlObj.onreadystatechange = eval(callback);
		// xmlObj.onstatusmessage = debugPrint('Test');
		if (method!=''){
			method = method;
		}else{
			method = "GET";
		}
	    xmlObj.open(method, datapage, async);
	    if (method=='POST'){
			xmlObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			if (str.left(1) == "?") { str = str.substr(1) }
			if (str.left(1) == "&") { str = str.substr(1) }
			xmlObj.send(str);
		}else{
			xmlObj.send(null);
		}
    }
}


// ************************************************************************
// Run a SQL Statement from javascript
// ************************************************************************
function executeSQL(sSQL, ReturnField) {
		
	// Encode the string for webserver to SQL Server happiness
	sSQL = simpleEncode(sSQL);
				
	// window.clipboardData.setData("Text", sSQL);
	// alert(sSQL);
				
	// Execute the SQL Statement
	if (ReturnField && ReturnField != '') {
		AJAXRequest("null", "/WebServices/genericSQL.asp", false, "POST", "RT=V&RF=" + ReturnField + "&SQL=" + sSQL );
	} else {
		AJAXRequest("null", "/WebServices/genericSQL.asp", false, "POST", "RT=ERR&SQL=" + sSQL );
	}
	return xmlObj.responseText;
}


// ************************************************************************
// Show/Hide Code For DIV's
// ************************************************************************
function showHide(ctrlX, divName) {
	// alert('Show/Hide Search DIV');
	try {
		var divX = $(divName);
	} catch (e) {}
	if ( divX && divX != undefined) {
		if (divX.style.display == 'none') {
			divX.style.display = 'inline';
			ctrlX.style.background = 'url(/images/collapse.gif) no-repeat';
			type = "inline";
		} else {
			divX.style.display = 'none';
			ctrlX.style.background = 'url(/images/expand.gif) no-repeat';
			type = "none";
		}
	}
	try{
		setDimensions();
	} catch (e) {}
	try{
		Cookie("STARS", divName, "", "", type, "AE")
	} catch (e) {}
}

// ************************************************************************
// Count characters and display message/error
// ************************************************************************
function CharCount(obj, text, div, maxlength){
	i = obj.value.length;
	if(maxlength != '' && i > maxlength){
		obj.value = left(obj.value, maxlength)
		alert("This field only allows " + maxlength + " character(s), the field has been truncated to meet this length requirement!");
	}
	text = text.replace(/%%val%%/gi, i);
	$(div).innerHTML = text;
}

// ************************************************************************************************
// Function to redirect the page from Javascript
// ------------------------------------------------------------------------------------------------
function RedirectPage(target, parent, frame){
	if(parent != ''){
		if(frame != ''){
			if(navigator.userAgent.indexOf("Firefox")!=-1){
				top.frames[frame].location.href=target;
			} else {
				window.parent.frames(frame).location.href=target;
			}
		}else{
			window.parent.location.href=target
		}
	}else{
		window.location.href=target
	}
}


// ************************************************************************************************
// Function to update a DIV with an AJAX call
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
function updateDIV(divName, urlGet) {
	// alert('updateDIV function called');
	try {
		// Look for Keys to replace
		urlGet = replaceKeys(urlGet);
		
		// window.clipboardData.setData("Text", urlGet);
		// alert("Call this webservice: " + urlGet);
		
		AJAXRequest("null", urlGet, false, "GET", "");
		var sReturn = xmlObj.responseText;
		// alert("Value Returned.");
		document.getElementById(divName).innerHTML = sReturn;
	} catch (e) { 
		
	}
}

// ************************************************************************************************
// Function to update a DIV with an AJAX call
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
function updateDIVDebug(divName, urlGet) {
	// alert('updateDIV function called');
	try {
		// Look for Keys to replace
		urlGet = replaceKeys(urlGet);
		
		window.clipboardData.setData("Text", urlGet);
		alert("Call this webservice: " + urlGet);
		
		AJAXRequest("null", urlGet, false, "GET", "");
		var sReturn = xmlObj.responseText;
		// alert("Value Returned: " + sReturn);
		document.getElementById(divName).innerHTML = sReturn;
	} catch (e) { 
		
	}
}

// ************************************************************************************************
// Function to catch an enter in a text box and treat it as a tab
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
function enterTab() {
	if ((window.event.which && window.event.which == 13) || (window.event.keyCode && window.event.keyCode == 13)) { 
		window.event.keyCode=9; 
	}
}


// ************************************************************************************************
// Function to only allow numbers in a text box
// ------------------------------------------------------------------------------------------------
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}


// ************************************************************************************************
// Function used to replace any keywords in the input string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The function will search for any keywords (in the format %%keyword%%) and then look in the 
// document for any form elements with the id specified in the keyword.  For example, the string
// "EXEC spGetCCDetail %%CallCenterID%%" will look in the document for an element named 
// CallCenterID and replace its value in the string.  If the control is not located, a blank 
// is returned and replaced with the keyword.
// ************************************************************************************************
function replaceKeys(strX, doubleQuotes) {

	strX = strX.replace('~', '');
	
	// alert('function replaceKeys\r\n================================================================================\r\nString to search: ' + strX);
	
	var lRet = strX.indexOf("%%");
	while (lRet >= 0) {
		var lRetEnd = strX.indexOf("%%", lRet + 2);
		var sReplace = strX.substring(lRet, lRetEnd + 2);
		var sControl = sReplace.replace(/%/g, "");
		var sValue = $V(sControl);
		
		// alert('function replaceKeys\r\n================================================================================\r\nString to replace: ' + sReplace + '\r\nControl Name: ' + sControl + '\r\nControl Value: ' + sValue);
		if (doubleQuotes && doubleQuotes == "Y") { sValue = sValue.replace(/'/g, "''"); }
		strX = strX.replace(sReplace, sValue);
		lRet = strX.indexOf("%%");
	}
	return strX;
}


// ************************************************************************************************
// Function to return a SQL compliant URLEncoded string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
function simpleEncode(plaintext){
	plaintext = plaintext.replace(/\%/g, "%25");
	plaintext = plaintext.replace(/ /g, "%20");
	plaintext = plaintext.replace(/\(/g, "%28");
	plaintext = plaintext.replace(/\)/g, "%29");
	plaintext = plaintext.replace(/\+/g, "%2B");
	
	plaintext = plaintext.replace(/\&lt;/g, "<");
	plaintext = plaintext.replace(/\&gt;/g, ">");
	
	plaintext = plaintext.replace(/\&amp;/g, "%26amp;");
//	plaintext = plaintext.replace(/\&/g, "&amp;");
	
	return plaintext;
}

// ************************************************************************************************
// Function to return a browser compliant URLEncoded string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The Javascript escape and unescape functions do not correspond with what browsers actually do.
// ************************************************************************************************
function URLEncode(plaintext)
{
	var safeChars = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var hex = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (safeChars.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    // UNicode character...
				encoded += "+";
			} else {
				encoded += "%";
				encoded += hex.charAt((charCode >> 4) & 0xF);
				encoded += hex.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}


// ************************************************************************************************
// Function to return a browser compliant URLEncoded string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The Javascript escape and unescape functions do not correspond with what browsers actually do.
// ************************************************************************************************
function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var hexChars = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& hexChars.indexOf(encoded.charAt(i+1)) != -1 
					&& hexChars.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
		}else{
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
		}
	}else{
		   plaintext += ch;
		   i++;
		}
	} // while
   
   return plaintext;
	}


// ************************************************************************************************
// Function to return a Month Name
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
function monthName(monthID, abbrev) {
	sMonth='Invalid Month';
	switch(monthID) {
	case 0: sMonth = 'January'; break;
	case 1: sMonth = 'February'; break;
	case 2: sMonth = 'March'; break;
	case 3: sMonth = 'April'; break;
	case 4: sMonth = 'May'; break;
	case 5: sMonth = 'June'; break;
	case 6: sMonth = 'July'; break;
	case 7: sMonth = 'August'; break;
	case 8: sMonth = 'September'; break;
	case 9: sMonth = 'October'; break;
	case 10: sMonth = 'November'; break;
	case 11: sMonth = 'December'; break;
	}
	if (abbrev && abbrev != 'N' && sMonth != 'Invalid Month') { 
		sMonth = sMonth.left(3);
	}
	return sMonth;
}


// ************************************************************************************************
// Function to return a trimmed string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The function trim can be used or the trim function can be called from a string
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// var sText = '  This is a test string.  '
// return "trim: [" + sText.trim() + "]"  >> returns "trim: [This is a test string.]"
// return "trim: [" + trim(sText) + "]"  >> returns "trim: [This is a test string.]"
// ************************************************************************************************
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
function trim(stringToTrim) {
	return String(str).trim();
}

// ************************************************************************************************
// Function to return a left trimmed string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The function trim can be used or the trim function can be called from a string
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// var sText = '  This is a test string.  '
// return "ltrim: [" + sText.ltrim() + "]"  >> returns "ltrim: [This is a test string.  ]"
// return "ltrim: [" + ltrim(sText) + "]"  >> returns "ltrim: [This is a test string.  ]"
// ************************************************************************************************
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
function ltrim(stringToTrim) {
	return String(str).ltrim();
}

// ************************************************************************************************
// Function to return a right trimmed string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The function trim can be used or the trim function can be called from a string
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// var sText = '  This is a test string.  '
// return "rtrim: [" + sText.rtrim() + "]"  >> returns "rtrim: [  This is a test string.]"
// return "rtrim: [" + rtrim(sText) + "]"  >> returns "rtrim: [  This is a test string.]"
// ************************************************************************************************
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
function rtrim(stringToTrim) {
	return String(str).rtrim();
}

// ************************************************************************************************
// Function to return the left part of a string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The function trim can be used or the trim function can be called from a string
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// var sText='This is a test string.'
// return "left: [" + sText.left(10) + "]"  >> returns "left: [This is a ]"
// return "left: [" + left(sText, 10) + "]"  >> returns "left: [This is a ]"
// ************************************************************************************************
String.prototype.left = function(n) {
	if (n <= 0)
	    return "";
	else if (n > this.length)
	    return this;
	else
	    return this.substring(0,n);
}
function left(str, n){
	return String(str).left(n);
}

// ************************************************************************************************
// Function to return the right portion of a string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The function trim can be used or the trim function can be called from a string
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// var sText='This is a test string.'
// return "right: [" + sText.right(10) + "]"  >> returns "right: [st string.]"
// return "right: [" + right(sText, 10) + "]"  >> returns "right: [st string.]"
// ************************************************************************************************
String.prototype.right = function(n) {
	if (n <= 0)
	    return "";
	else if (n > this.length)
	    return this;
	else
		var iLen = this.length;
		return this.substring(iLen, iLen - n);
}
function right(str, n){
	return String(str).right(n);
}

// ************************************************************************************************
// Function to remove all HTML Tags from a string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// The function stripTags can be used or the stripTags function can be called from a string
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// var sText='This is a <i><b>test</b> string</i>.'
// return "stripTags: [" + sText.stripTags() + "]"  >> returns "stripTags: [This is a test string.]"
// return "stripTags: [" + stripTags(sText) + "]"  >> returns "stripTags: [This is a test string.]"
// ************************************************************************************************
String.prototype.stripTags = function() {
	return this.replace(/<\/?[^>]+>/gi, '');
}
function stripTags(str){
	return String(str).stripTags();
}


// ************************************************************************************************
// Function to "camelize" a string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
// var sText='TIM MCATEER'
// return "camelize: [" + sText.camelize() + "]"  >> returns "camelize: [Tim McAteer]"
// var sText='STEPHEN BENTLEY'
// return "camelize: [" + sText.camelize() + "]"  >> returns "camelize: [Stephen Bentley]"
// ************************************************************************************************
String.prototype.toCamelCase = function() {

var x = 0;
var sTemp = '';
var upChar = true;

	for (x=0; x < this.length; x++) {
		if (sTemp.length >= 2 ) {
			if (sTemp.right(2) == "Mc") {
				upChar = true;
			}
			if (sTemp.right(1) == " ") {
				upChar = true;
			}
		}
		if (sTemp.length >= 3 ) {
			if (sTemp.right(3) == "Mac") {
				upChar = true;
			}
		}
		if (upChar == true) {
			sTemp += this.substr(x, 1).toUpperCase();
		} else {
			sTemp += this.substr(x, 1).toLowerCase();
		}
		upChar = false;
	}
    
	return sTemp;
}


// ************************************************************************************************
// Create an array from a string
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ------------------------------------------------------------------------------------------------
String.prototype.toArray = function() {
   return this.split('');
 }
  

// ************************************************************************************************
// Function to return a string containing the current date time stamp
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
Date.prototype.formatDateTime = function() {
	return (this.getFullYear() + '/' + right('0' + (this.getMonth() + 1), 2) + '/' + right('0' + this.getDate(), 2) + ' ' + this.getHours() + ':' + right('0' + this.getMinutes(), 2) + ':' + right('0' + this.getSeconds(), 2) + '.' + right('000' + this.getMilliseconds(), 3));
}


// ************************************************************************************************
// Function to return a string containing the current date time stamp
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
Date.prototype.formatDate = function() {
	return (this.getFullYear() + '/' + right('0' + (this.getMonth() + 1), 2) + '/' + right('0' + this.getDate(), 2));
}
  

// ************************************************************************************************
// Function to return a string containing the current date time stamp
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
Date.prototype.displayDateTime = function() {
	return ((this.getMonth() + 1) + '/' + this.getDate() + '/' + this.getFullYear() + ' ' + this.getHours() + ':' + right('0' + this.getMinutes(), 2) + ':' + right('0' + this.getSeconds(), 2) + '.' + right('000' + this.getMilliseconds(), 3));
}


// ************************************************************************************************
// Function to return a string containing the current date time stamp
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
Date.prototype.displayDate = function() {
	return ((this.getMonth() + 1) + '/' + this.getDate() + '/' + this.getFullYear());
}
  

// ************************************************************************************************
// Function to return a string containing the current date time stamp
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
Date.prototype.formatTime = function() {
	return (this.getHours() + ':' + right('0' + this.getMinutes(), 2) + ':' + right('0' + this.getSeconds(), 2) + '.' + right('000' + this.getMilliseconds(), 3));
}
  

// ************************************************************************************************
// Function to return a string containing the current date time stamp
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
function getDateTimeStamp() {
	var d = new Date();
	return (d.getYear() + '/' + right('0' + d.getMonth(), 2) + '/' + right('0' + d.getDay(), 2) + ' ' + d.getHours() + ':' + right('0' + d.getMinutes(), 2) + ':' + right('0' + d.getSeconds(), 2) + '.' + right('000' + d.getMilliseconds(), 3));
}

// ************************************************************************************************
// Function to return a string containing the current time stamp
// ------------------------------------------------------------------------------------------------
// Created By Tim McAteer
// ************************************************************************************************
function getTimeStamp() {
	var d = new Date();
	return (d.getHours() + ':' + right('0' + d.getMinutes(), 2) + ':' + right('0' + d.getSeconds(), 2) + '.' + right('000' + d.getMilliseconds(), 3));
}
