﻿var clientID_Dictionary = new Object();

//	convertToURL - encodes a string in the URL format
//	args:
//		strInput - string to encode
//
//	return value: URL encoded output
//
function convertToURL(strInput) {
	var result = "";
	var strCopyInput = new String(strInput);
	
	/*for (i = 0; i < strInput.length; i++)
	{
		if (strInput.charAt(i) == " ")
		{
			result += "+";
		} else {
			result += strInput.charAt(i);
		}
	}*/
	result = strCopyInput.replace(" ", "+");
	return(escape(result));
}

//	convertFromURL - decodes a URL string
//	args:
//		strInput - string to decode
//
//	return value: URL decoded output
//
function convertFromURL(strInput)
{
	var result = strInput.replace(/\+/g, " ");
	
	return(unescape(result));
}

//	convertToHTML - inserts HTML formatting into plain text
//	args:
//		strInput - string to convert
//
//	return value: HTML output
//
function convertToHTML(strInput)
{
	var result = strInput.replace(/\n/g, "<br />\n");
	
	return("<div>" + result + "</div>");
}

//	getOptionString - string manipulation on an option string pseudo-dictionary
//	args:
//		searchOptionString - string to search within
//		desiredKey - string to search for
//
//	return value: matching value
//
function getOptionString(searchOptionString, desiredKey)
{
	var startPosition = 0;
	var endPosition = 0;
	if(searchOptionString.indexOf("[" + desiredKey + "=")==-1)
	{
		return("");
	} else {
		//string found, find the beginning of it
		startPosition = searchOptionString.indexOf("[" + desiredKey + "=") + desiredKey.length + 2;
		endPosition = searchOptionString.indexOf("]", startPosition);
		//alert("option string: " + searchOptionString + " search " + desiredKey + " return " + convertFromURL(searchOptionString.substring(startPosition, endPosition)));
		return(convertFromURL(searchOptionString.substring(startPosition, endPosition)));
	}
}

//	setOptionString - string manipulation on an option string pseudo-dictionary
//	args:
//		searchOptionString - string to search within
//		desiredKey - string to search for
//		newValue - string to set as new value
//
//	return value: new pseudo-dictionary string
//
function setOptionString(searchOptionString, desiredKey, newValue)
{
	var startPosition = 0;
	var endPosition = 0;
	var modifiedOptionString = searchOptionString;
	var currentValue = getOptionString(searchOptionString, desiredKey);
	//alert(convertToURL(newValue));
	if(searchOptionString.indexOf("[" + desiredKey + "=")==-1)
	{
		//insert as new
		modifiedOptionString += " [" + desiredKey + "=" + convertToURL(newValue) + "]";
		
		return(modifiedOptionString);
	} else {
		//replace operation
		modifiedOptionString = modifiedOptionString.replace("[" + desiredKey + "=" + convertToURL(currentValue) + "]", "[" + desiredKey + "=" + convertToURL(newValue) + "]");
		return(modifiedOptionString);
	}
}

//	getRegisteredElement - finds objects in the clientID_Dictionary mapping
//	args:
//		elementID - server ID
//
//	return value: element if it exists
//
function getRegisteredElement(elementID)
{
	if(clientID_Dictionary[elementID] != null)
	{
		return document.getElementById(clientID_Dictionary[elementID]);
	} else {
		return null;
	}
}

//	pressNameSearchKey - checks for enter key behavior on missionary name fields
//	args: none
//
//	return value: false, to prevent postback
//
function pressNameSearchKey(evtKey)
{
	if(isEventEnterKey(evtKey) == true)
	{
		//simulate button click
		getRegisteredElement("btnMasterSearchGo").click();
		return false;
	}	else {
		return true;
	}
}

//	isEventEnterKey - checks to see whether an event is an enter key
//	args:
//		evtKey - event raised from some element
//		
//	return value: true for any button pressed besides enter, false otherwise to stop regular submit
//
function isEventEnterKey(evtKey)
{
	if(getEventCharacterCode(evtKey) == 13)
	{
		return true;
	}	else {
		return false;
	}
}

//	getEventCharacterCode - checks to see whether an event is an enter key
//	args:
//		evtKey - event raised from some element
//		
//	return value: whatever the character code entered is
//
function getEventCharacterCode(evtKey)
{
	if(evtKey && evtKey.which)
	{
		evtKey = evtKey;
		//character code is contained in NN4's which property
		return evtKey.which;
	}	else {
		if(event)
		{
			evtKey = event;
			//character code is contained in IE's keyCode property
			return evtKey.keyCode;
		} else {
			return -1;
		}
	}
}

//	forceDefaultEnterButtonClick - forces a certain button to be clicked on an enter from a textbox or other form input
//	args:
//		evtKey - event raised from some element
//		idDesiredButton - id of button to raise click() event for
//		
//	return value: true for any button pressed besides enter, false otherwise to stop regular submit
//
function forceDefaultEnterButtonClick(evtKey, idDesiredButton)
{
	if(isEventEnterKey(evtKey) == true)
	{
		document.getElementById(idDesiredButton).click();
		return false;
	}
	else
	{
		return true;
	}
}

//	initiateMissionarySearch - sends request for matching sites to the search service
//	args:
//
//	return value: false
//
function initiateMissionarySearch()
{
	try
	{
		if(getRegisteredElement("txtMasterSearchFirstName").value == "" && getRegisteredElement("txtMasterSearchLastName").value == "")
		{
			document.getElementById("divMasterSearchOutput").innerHTML = "You must provide either a first or last name to search."
		} else {
			document.getElementById("divMasterSearchOutput").innerHTML = "Searching...";
			var nameString = "[FirstName=" + convertToURL(getRegisteredElement("txtMasterSearchFirstName").value) + "] [LastName=" + convertToURL(getRegisteredElement("txtMasterSearchLastName").value) + "]";
			//alert("searching with input " + nameString);
			var retValue = TI.M411.Services.MissionarySearch.FindSitesByMissionaryName(nameString, missionarySearchComplete, missionarySearchError, "search");
		}
	}
	catch(err)
	{
		alert("Error was found in function initiateMissionarySearch()\n\nError message:\n\n" + err.message);
		outputValue = false;
	}
	return false;
}


//	missionarySearchComplete - process successful completion of search service
//	args:
//		result - HTML to insert into results
//		userContext - string passed from initiation function
//
//	return value: none
//
function missionarySearchComplete(result, userContext)
{
	document.getElementById("divMasterSearchOutput").innerHTML = result;
}

//	missionarySearchError - process error from search service
//	args:
//		result - HTML to insert into results
//		userContext - string passed from initiation function
//
//	return value: none
//
function missionarySearchError(result, userContext)
{
	document.getElementById("divMasterSearchOutput").innerHTML = "Error:" + convertToHTML(result.get_message());
}

//	formatClean - takes commas and other junk out of a string and returns it
//	args:
//		stringInput - string value containing number, zero or more commas
//
//	return value: stripped string
//
function formatClean(num)
{
	var sVal='';
	var nVal = num.length;
	var sChar='';
	var minus='-';
	
	//iterate through each character in the string, allowing only numbers and the period character into the result
	for(i=0;i<nVal;i++)
	{
		sChar = num.charAt(i);
		nChar = sChar.charCodeAt(0);
		//if((nChar==48){}
		if ((nChar >=48) && (nChar <=57))  { sVal += num.charAt(i);   }
		if (sChar=='.') {sVal += sChar;	}
	}
	var newsVal=sVal;
	if(Number(sVal)!=0)
	{
		for(i=0;i<sVal.length;i++)
		{
			sChar = sVal.charAt(i);
			nChar = sChar.charCodeAt(0);
			if(nChar!=48)
			{
				break;
			}
			else{
				newsVal=sVal.substring(i+1,sVal.length);
			}
		}
		sVal=newsVal;
	}
	
	//deal with empty string (bad input)
	if(sVal==''){sVal='0';}
	//add leading zero
	if(sVal.indexOf('.')==0) {sVal = '0' + sVal;}
	//deal with minus character
	if(num.indexOf(minus)==0) {sVal = minus + sVal;}
	//alert("result of formatClean function: " + sVal);
	return sVal;
}

//	cleanNumber - uses formatClean, then returns as a number instead of a string
//	args:
//		stringInput - string value containing number
//
//	return value: numeric representation for use in calculations
//
function cleanNumber(stringInput)
{
	return(Number(formatClean(stringInput)));
}

//	formatNumber - puts proper commas into numeric data
//	args:
//		num - guess
//		numFixedPrecision - how many digits to also display
//
//	return value: formatted string representation of number
//
function formatNumber(num, numFixedPrecision)
{
	var sVal='';
	var minus='-';
	var CommaDelimiter=',';
	var intVersion = 0;
	var numVersion = 0;
	var stringNum;
	
	intVersion = Math.abs(parseInt(num));
	if (numFixedPrecision == null) {
		numVersion = Math.abs(Number(num));
	} else {
		numVersion = Math.abs(Number(num)).toFixed(numFixedPrecision);
	}
	stringNum = new String(numVersion);
	
	var samount = new String(intVersion);
	for (var i = 0; i < Math.floor((samount.length-(1+i))/3); i++)
	{
		samount = samount.substring(0,samount.length-(4*i+3)) + CommaDelimiter + samount.substring(samount.length-(4*i+3));
	}
	if(stringNum.indexOf('.') > 0)
	{
		samount = samount + stringNum.substring(stringNum.indexOf('.'));
	}
	if(Number(num) < 0)
	{
		samount = minus + samount;
	}
	return(samount);
}

//	autoCleanInput - uses formatNumber and cleanNumber to prettify input in a text box
//	args:
//		inputElement - element with a value that can be cleaned
//		numFixedPrecision - optional number of digits after decimal point to show
//
//	return value: none
//
function autoCleanInput(inputElement, numFixedPrecision)
{
	if(numFixedPrecision==null) numFixedPrecision=0;
	var intermediateValue = inputElement.value;
	inputElement.value = formatNumber(cleanNumber(intermediateValue), numFixedPrecision);
	return;
}

//	toggleVisibilityLink - toggles visibility of an element, and flips the contents of a link
//	args:
//		idToggleElement - what to switch on or off
//		linkElement - a link passed as 'this'
//		textOff - text of On position
//		textOn - text of Off position
//		forceOption - "show" or "hide" or null
//
//	return value: false
//
function toggleVisibilityLink(idToggleElement, linkElement, textOff, textOn, forceOption)
{
	var useOption;
	
	if(linkElement.innerHTML==textOn)
	{
		useOption = "hide";
	} else {
		useOption = "show";
	}
	
	//override
	if(forceOption != null)
	{
		useOption = forceOption;
	}
	
	if(document.getElementById(idToggleElement))
	{
		if(useOption == "hide")
		{
			//switch to Off position
			document.getElementById(idToggleElement).style["display"]="none";
			//change text to Off value
			linkElement.innerHTML=textOff;
		} else {
			//switch to On position
			document.getElementById(idToggleElement).style["display"]="block";
			//change text to On value
			linkElement.innerHTML=textOn;
		}
	}
	
	return false;
}