//Used to store the last numeric value of a field
var oldNumericValue;
var currentValue = "";
var tabbedToNewRecordedField = false;
var blockStoreOldDecimalOnce = false;

function clearLastNumericValueCache()
{
	oldNumericValue = "";
	currentValue = "";
}

function storeOldDecimal(theCost)
{
	//alert('storeOldDecimal called');
    if(blockStoreOldDecimalOnce == false)
    {
        //alert('storeOldDecimal theCost.name'+theCost.name+' theCost.value:'+theCost.value+' currentValue:'+currentValue);
        if(currentValue == null || currentValue == 'undefined' || currentValue == "")
        {
        	oldNumericValue = theCost.value;
        }
        else
        {
        	oldNumericValue = currentValue;
        }

        currentValue = theCost.value;
        tabbedToNewRecordedField = true;
    }
    else
    {
        tabbedToNewRecordedField = false;
        //Switch this flag back so next time it allows the number to be stored
        blockStoreOldDecimalOnce = false;
    }
}

function setTabbedToNewRecordedField(bool)
{
	tabbedToNewRecordedField = bool;
}

function getTabbedToNewRecordedField()
{
	return tabbedToNewRecordedField;
}

function getMessageFieldName(name)
{
	//alert('getMessageFieldName name:'+name);
	
	var fieldName;
	
	if(name != null && name != undefined && name != "")
	{
		fieldName = "Field: " + name + " - "
	}
	else
	{
		fieldName = "";
	}
	
	//alert('getMessageFieldName fieldName:'+fieldName);
	return fieldName;
}

function validateNegativeDecimal(theNumber)
{
	return validateNamedNegativeDecimal(theNumber, "");
}

function validateNamedNegativeDecimal(theNumber, name)
{
	return validateNamedNegativeDecimalMaxDecimalPlaces(theNumber, name, "");
}

function validateNegativeDecimalMaxDecimalPlaces(theNumber, maxDecimalPlaces)
{
	return validateNamedNegativeDecimalMaxDecimalPlaces(theNumber, "", maxDecimalPlaces);
}

function validateNamedNegativeDecimalMaxDecimalPlaces(theNumber, name, maxDecimalPlaces)
{
	var fieldName = getMessageFieldName(name);
	
	if(theNumber.value != undefined && theNumber.value != "")
	{
		if(isNaN(theNumber.value) == true )
		{
				alert(fieldName+"The decimal value may only contain a negative number and if required, a single decimal point, e.g. -1.25");
				restoreOldValue(theNumber);
				
				return false;
		}
		else
		{
			if(theNumber.value >= 0)
			{
				alert(fieldName+"The decimal value may only contain a negative number and if required, a single decimal point, e.g. -1.25");
				restoreOldValue(theNumber);
				
				return false;
			}
			else if(isLessThanMaxDecimalPlaces(maxDecimalPlaces, theNumber.value, fieldName) == false)
			{
				restoreOldValue(theNumber);	
				return false;
			}			
		}
	}
	else
	{
		alert(fieldName+"The decimal value may only contain a negative number and if required, a single decimal point, e.g. -1.25");
		restoreOldValue(theNumber);
		
		return false;
	}
	
	//If we move to another recorded field value
	// this ensures we do not lose the old value of the field we are
	// moving away from due to the onfocus event of that object being called.
	tabbedToNewRecordedField = false;
	
	//This is a valid negative decimal
	return true;
}

function validatePositiveDecimalMaxDecimalPlaces(theNumber, maxDecimalPlaces)
{
	return validateNamedPositiveDecimalMaxDecimalPlaces(theNumber, "", maxDecimalPlaces);
}

function validatePositiveDecimal(theNumber)
{
	return validateNamedPositiveDecimal(theNumber, "");
}

function validatePositiveDecimalMaxDecimalPlaces(theNumber, maxDecimalPlaces)
{
	return validateNamedPositiveDecimalMaxDecimalPlaces(theNumber, "", maxDecimalPlaces);
}

function validateNamedPositiveDecimal(theNumber, name)
{
	return validateNamedPositiveDecimalMaxDecimalPlaces(theNumber, name, "");
}

function validateNamedPositiveDecimalMaxDecimalPlaces(theNumber, name, maxDecimalPlaces)
{
	var fieldName = getMessageFieldName(name);
	
	if(theNumber.value != undefined && theNumber.value != "")
	{
		if(isNaN(theNumber.value) == true )
		{
				alert(fieldName+"The decimal value may only contain a positive number and if required, a single decimal point, e.g. 1.25");
				restoreOldValue(theNumber);
				return false;
		}
		else
		{
			if(theNumber.value < 0)
			{
				alert(fieldName+"The decimal value may only contain a positive number and if required, a single decimal point, e.g. 1.25");
				restoreOldValue(theNumber);	
				return false;
			}
			else if(isLessThanMaxDecimalPlaces(maxDecimalPlaces, theNumber.value, fieldName) == false)
			{
				restoreOldValue(theNumber);	
				return false;
			}
		}
	}
	else
	{
		alert(fieldName+"The decimal value may only contain a positive number and if required, a single decimal point, e.g. 1.25");
		restoreOldValue(theNumber);
		
		return false;
	}
	
	//If we move to another recorded field value
	// this ensures we do not lose the old value of the field we are
	// moving away from due to the onfocus event of that object being called.
	tabbedToNewRecordedField = false;
	
	//This is a valid positive decimal
	return true;
}


function validateDecimal(theNumber)
{
	//alert('validateDecimal');

    return validateNamedDecimal(theNumber, "");

    /*
    if(theNumber.value == undefined || theNumber.value == "")
	{
		theNumber.value = 0;
		
		return false;
	}
	else if(isNaN(theNumber.value) )
	{
		alert("The decimal value may only contain numbers and if required, a single decimal point, e.g. 1.25");
		restoreOldValue(theNumber);
		
		return false;
	}

	//If we move to another recorded field value
	// this ensures we do not lose the old value of the field we are
	// moving away from due to the onfocus event of that object being called.
	tabbedToNewRecordedField = false;
	
	//This is a valid decimal
	return true;
	*/
}

function validateNamedDecimal(theNumber, name)
{
	return validateNamedDecimalMaxDecimalPlaces(theNumber, name, "");
}

function validateDecimalMaxDecimalPlaces(theNumber, maxDecimalPlaces)
{
	return validateNamedDecimalMaxDecimalPlaces(theNumber, "", maxDecimalPlaces);
}

function validateNamedDecimalMaxDecimalPlaces(theNumber, name, maxDecimalPlaces)
{
	var fieldName = getMessageFieldName(name);

	if(theNumber.value != undefined && theNumber.value != "")
	{
		if(isNaN(theNumber.value) == true )
		{
				alert(fieldName+"The decimal value may only contain a number and if required, a single decimal point, e.g. 1.25 or -2.87");
				restoreOldValue(theNumber);
				return false;
		}
		else
		{
			if(isLessThanMaxDecimalPlaces(maxDecimalPlaces, theNumber.value, fieldName) == false)
			{
				restoreOldValue(theNumber);
				return false;
			}
		}
	}
	else
	{
		alert(fieldName+"The decimal value may only contain a number and if required, a single decimal point, e.g. 1.25 or -2.87");
		restoreOldValue(theNumber);

		return false;
	}

	//If we move to another recorded field value
	// this ensures we do not lose the old value of the field we are
	// moving away from due to the onfocus event of that object being called.
	tabbedToNewRecordedField = false;

	//This is a valid positive decimal
	return true;
}


function validatePositiveInteger(theNumber)
{
	return validateNamedPositiveInteger(theNumber, "");
}


function validateNamedPositiveInteger(theNumber, name)
{
	//alert('validateNamedPositiveInteger called');
	var fieldName = getMessageFieldName(name);
	
	var intVersion = parseInt(theNumber.value);
	var floatVersion = parseFloat(theNumber.value);
	//alert('validateInteger intVersion:'+intVersion+' floatVersion:'+floatVersion);

	
	if(theNumber.value == undefined || theNumber.value == "" 
		|| isNaN(theNumber.value) || floatVersion != intVersion 
		|| intVersion < 0)
	{
		alert(fieldName + "The value may only contain a positive whole number, e.g. 4");
		restoreOldValue(theNumber);
		
		return false;
	}

	//If we move to another recorded field value
	// this ensures we do not lose the old value of the field we are
	// moving away from due to the onfocus event of that object being called.
	tabbedToNewRecordedField = false;
	
	//This is a valid positive integer
	return true;
}

function validateInteger(theNumber)
{
	var intVersion = parseInt(theNumber.value);
	var floatVersion = parseFloat(theNumber.value);
	//alert('validateInteger intVersion:'+intVersion+' floatVersion:'+floatVersion);

	
	if(theNumber.value == undefined || theNumber.value == "")
	{
		theNumber.value = 0;
		
		return false;
	}
	else if(isNaN(theNumber.value) || floatVersion != intVersion)
	{
		alert("The value may only contain a whole number, e.g. 4");
		restoreOldValue(theNumber);

		return false;
	}

	//If we move to another recorded field value
	// this ensures we do not lose the old value of the field we are
	// moving away from due to the onfocus event of that object being called.
	tabbedToNewRecordedField = false;
	
	//This is a valid integer
	return true;
}

function isLessThanMaxDecimalPlaces(maxDecimalPlaces, theNumberValue, fieldName)
{
	//alert('isLessThanMaxDecimalPlaces called maxDecimalPlaces:'+maxDecimalPlaces+' theNumberValue:'+theNumberValue+' fieldName:'+fieldName);
    if(maxDecimalPlaces != "")
	{
		//Check that the number is not greater than the max number of decimal places required
        var numberDecimals = countNumberDecimals(theNumberValue,'.');

        if(numberDecimals > maxDecimalPlaces)
		{
			alert(fieldName+"The value may only have a maximum of " + maxDecimalPlaces + " decimal places");
			return false;
		}
	}
	
	return true;
}

// use dec_sep for internationalization
function countNumberDecimals(x, dec_sep)
{
	var tmp=new String();
	tmp=x;

    if(tmp.indexOf(dec_sep)>-1)
	{
	    return tmp.length-tmp.indexOf(dec_sep)-1;
	}
	else
	{
	    return 0;
	}
}

function isInteger(numberToTest)
{
	var intVersion = parseInt(numberToTest);
	var floatVersion = parseFloat(numberToTest);

	//alert('isInteger intVersion:'+intVersion+' floatVersion:'+floatVersion);
	
	if(floatVersion == intVersion)
	{
		//alert('isInteger is an integer');
		return true;
	}
	else
	{
		//alert('isInteger is not an integer');
		return false;
	}
}

function restoreOldValue(theNumber)
{
	//alert('restoreOldValue called');
	//alert('restoreOldValue tabbedToNewRecordedField:'+tabbedToNewRecordedField+' oldNumericValue:'+oldNumericValue+' theNumber.value:'+theNumber.value+' currentValue:'+currentValue);
	
	if(tabbedToNewRecordedField == true)
	{
		if(oldNumericValue == undefined || oldNumericValue == null || oldNumericValue == "")
		{
            theNumber.value = "";
		}
		else
		{
            theNumber.value = oldNumericValue;
		}
	}
	else if(currentValue != undefined || currentValue != null || currentValue != "")
	{
		theNumber.value = currentValue;
	}
	else
	{
		theNumber.value = "";
	}

    //This will fire off the onfocus event for the input again which means that the storeOldDecimal
    // will fire again and store the bogus number that we just overwrote. So we want to block the storeOldDecimal
    // function in this case.
    blockStoreOldDecimalOnce = true;
	theNumber.focus();
}

function validatePositivePercentageMaxDecimalPlaces(theNumber, maxDecimalPlaces, minValue, maxValue)
{
    return validateNamedPositivePercentageMaxDecimalPlaces(theNumber, "", maxDecimalPlaces, minValue, maxValue);
}

function validateNamedPositivePercentageMaxDecimalPlaces(theNumber, name, maxDecimalPlaces, minValue, maxValue)
{
    var fieldName = getMessageFieldName(name);

    var valid = validatePositiveDecimalMaxDecimalPlaces(theNumber, maxDecimalPlaces);

    if(valid == true)
    {
        var theNumberValue = theNumber.value;
        if(theNumberValue > maxValue)
        {
            restoreOldValue(theNumber);
            alert(fieldName+"The percentage value may not be greater than "+maxValue+" percent.");
            return false;
        }
        else if(theNumberValue < minValue)
        {
            restoreOldValue(theNumber);
            alert(fieldName+"The percentage value may not be less than "+minValue+" percent.");
            return false;
        }

    }

    return valid;
}

function validateNegativePercentageMaxDecimalPlaces(theNumber, maxDecimalPlaces, minValue, maxValue)
{
    return validateNamedNegativePercentageMaxDecimalPlaces(theNumber, "", maxDecimalPlaces, minValue, maxValue);
}

function validateNamedNegativePercentageMaxDecimalPlaces(theNumber, name, maxDecimalPlaces, minValue, maxValue)
{
    var fieldName = getMessageFieldName(name);

    var valid = validateNegativeDecimalMaxDecimalPlaces(theNumber, maxDecimalPlaces);

    if(valid == true)
    {
        var theNumberValue = theNumber.value;
        if(theNumberValue < maxValue)
        {
            restoreOldValue(theNumber);
            alert(fieldName+"The negative percentage value may not be greater than "+maxValue+" percent.");
            return false;
        }
        else if(theNumberValue > minValue)
        {
            restoreOldValue(theNumber);
            alert(fieldName+"The negative percentage value may not be less than "+minValue+" percent.");
            return false;
        }
    }

    return valid;
}

function showArea(id)
{
	//var areaToShow = document.getElementById(id);
	//areaToShow.style.display = "block";
    //Use JQuery slide to show area
    $('#'+id).slideDown('slow');

	//Hide the hide button
	var showButton = document.getElementById('show'+id);
    //The function may be called directly from something else without a button
    if(showButton != null && showButton != 'undefined')
    {
	    showButton.style.display = "none";
    }

	//Show the show button
	var hideButton = document.getElementById('hide'+id);
    //The function may be called directly from something else without a button
    if(hideButton != null && hideButton != 'undefined')
    {
	    hideButton.style.display = "block";
	}
}

function hideArea(id)
{
	//var areaToHide = document.getElementById(id);
	//areaToHide.style.display = "none";
    //Use JQuery slide to hide area
    $('#'+id).slideUp('slow');

	//Clear out the content from this element
	//weightArea.innerHTML = "";

	//Show the add button
	var showButton = document.getElementById('show'+id);
    //The function may be called directly from something else without a button
    if(showButton != undefined)
    {
	    showButton.style.display = "block";
	}

	//Hide the remove button
	var hideButton = document.getElementById('hide'+id);
    //The function may be called directly from something else without a button
    if(hideButton != undefined)
    {
	    hideButton.style.display = "none";
    }
}


function showAreas(name)
{
	var counter = 0;
	var areaToShow;
	var buttonHidden = false;

	while (true)
	{
		//Hide the show areas button, show the hide areas button
		if(buttonHidden == false)
		{
			buttonHidden = true;

			//Hide the hide button
			var showButton = document.getElementById('show'+name);
            //The function may be called directly from something else without a button
			if(showButton != undefined)
			{
			    showButton.style.display = "none";
			}

			//Show the show button
			var hideButton = document.getElementById('hide'+name);
            //The function may be called directly from something else without a button
			if(hideButton != undefined)
			{
    			hideButton.style.display = "block";
    		}
		}

		//Lets show each area
		areaToShow = document.getElementById(name+counter);
		if(areaToShow != undefined)
		{
			areaToShow.style.display = "block";
		}
		else
		{
			//No more areas to show
			break;
		}

		counter = counter + 1;
	}
}


function hideAreas(name)
{
	var counter = 0;
	var areaToHide;
	var buttonHidden = false;

	while (true)
	{
		//Hide the show areas button, show the hide areas button
		if(buttonHidden == false)
		{
			buttonHidden = true;

			//Show the add button
			var showButton = document.getElementById('show'+name);
            //The function may be called directly from something else without a button
			if(showButton != undefined)
			{
			    showButton.style.display = "block";
			}

			//Hide the remove button
			var hideButton = document.getElementById('hide'+name);
            //The function may be called directly from something else without a button
			if(hideButton != undefined)
			{
    			hideButton.style.display = "none";
    		}
		}

		//Lets hide each area
		areaToHide = document.getElementById(name+counter);

		if(areaToHide != undefined)
		{
			areaToHide.style.display = "none";
		}
		else
		{
			//No more areas to hide
			break;
		}

		counter = counter + 1;
	}
}

function convertHTMLToVisibleWebPageTags(codeText)
{
    //alert("convertHTMLToVisibleWebPageTags codeText before conversion:"+codeText);

    //make the HTML into visible example HTML on the web page
    //Replace should replace all occurrences in one go, however, on IE it was only replacing the first occurance?
    // The following overcomes that issue.
    //Use m.replace(/"/g, ""); for global replace
    var safetyCounter = 0;
    if(codeText != undefined || codeText != "")
    {
        while(codeText.indexOf('<') != -1)
        {
            codeText = codeText.replace('<','&lt;');

            if(safetyCounter++ > 100)
            {
                break;
            }
        }

        //Reset safetyCounter
        safetyCounter = 0;

        while(codeText.indexOf('>') != -1)
        {
            codeText = codeText.replace('>','&gt;');
            if(safetyCounter++ > 100)
            {
                break;
            }
        }
    }

    //alert("convertHTMLToVisibleWebPageTags codeText after conversion:"+codeText);

    return codeText;
}

function checkIdentifierForValidCharacters(textToCheck)
{
    return checkForValidCharacters(textToCheck, 'IDENTIFIER');
}

function checkTextForValidCharacters(textToCheck)
{
    return checkForValidCharacters(textToCheck, 'TEXT');
}

function checkForValidCharacters(textToCheck, checkType)
{
    //alert('checkForValidCharacters called for textToCheck:'+textToCheck);
    var correct = true;

    if(textToCheck != undefined || textToCheck != '')
    {
        var textToCheckLength = textToCheck.length;
        textToCheck = textToCheck.toUpperCase();

        for(var j=0; j < textToCheckLength; j++)
        {
            if(checkType == 'IDENTIFIER' && checkIdentifierCharacterIsValid(textToCheck.substring(j, j+1) ) == false)
            {
                //All the characters must check out as valid characters, once we find one that doesn't it is considered incorrect.
                correct = false;
                break;
            }
            else if(checkType == 'TEXT' && checkTextCharacterIsValid(textToCheck.substring(j, j+1) ) == false)
            {
                //All the characters must check out as valid characters, once we find one that doesn't it is considered incorrect.
                correct = false;
                break;
            }
        }
    }
    else
    {
        correct = false;
    }

    //alert('checkForValidCharacters is textToCheck correct? '+correct);
    return correct;
}

//http://www.cjboco.com/brew-house/Html2Ascii/
function html2Ascii(str) {
   var htmlCode = new Array('&aacute;', '&acirc;', '&acirc;', '&acute;', '&aelig;', '&agrave;', '&amp;', '&aring;', '&atilde;', '&auml;', '&brvbar;', '&ccedil;', '&cedil;', '&cent;', '&copy;', '&curren;', '&deg;', '&divide;', '&eacute;', '&ecirc;', '&egrave;', '&eth;', '&euml;', '&frac12;', '&frac14;', '&frac34;', '&iacute;', '&icirc;', '&iexcl;', '&igrave;', '&iquest;', '&iuml;', '&laquo;', '&ldquo;', '&lsquo;', '&macr;', '&mdash;', '&micro;', '&middot;', '&nbsp;', '&ndash;', '&not;', '&ntilde;', '&oacute;', '&ocirc;', '&ograve;', '&ordf;', '&ordm;', '&oslash;', '&otilde;', '&ouml;', '&para;', '&plusmn;', '&pound;', '&quot;', '&raquo;', '&rdquo;', '&reg;', '&rsquo;', '&sect;', '&shy;', '&sup1;', '&sup2;', '&sup3;', '&szlig;', '&thorn;', '&times;', '&uacute;', '&ucirc;', '&ugrave;', '&uml;', '&uuml;', '&yacute;', '&yen;');
   var charCode = new Array(225, 226, 226, 180, 230, 224, 38, 229, 227, 228, 124, 231, 184, 162, 169, 63, 176, 247, 233, 234, 232, 60, 235, 49, 49, 51, 237, 238, 161, 236, 191, 239, 171, 32, 32, 175, 32, 181, 183, 160, 32, 172, 241, 243, 244, 242, 170, 186, 248, 245, 246, 182, 177, 163, 34, 187, 32, 174, 32, 167, 45, 49, 50, 51, 223, 60, 42, 250, 251, 249, 168, 252, 121, 165);
   var stripped = str.replace(/(<([^>]+)>)/ig,"");
   stripped = stripped.replace(/\t/g," ");
   stripped = stripped.replace(/(  )*/g,"");
   for(x=0;x<htmlCode.length;x++) {
	  var reg = new RegExp(htmlCode[x], "ig");
	  stripped = stripped.replace(reg,String.fromCharCode(charCode[x]));
   }
   return(stripped);
}

function convertQuotesToUnicode(text)
{
    var convertedText = text;
    if(convertedText != undefined && convertedText != null)
    {
        convertedText = convertedText.replace(/"/g,"&quot;");
        convertedText = convertedText.replace(/'/g,"&#39;");
    }

    return convertedText;
}

function escapeJavaScriptDoubleQuote(text)
{
    var convertedText = text;
    if(convertedText != undefined && convertedText != null)
    {
        convertedText = convertedText.replace(/"/g,"\\\"");
    }

    return convertedText;
}

function escapeJavaScriptSingleQuote(text)
{
    var convertedText = text;
    if(convertedText != undefined && convertedText != null)
    {
        convertedText = convertedText.replace(/'/g,"\\'");
    }

    return convertedText;
}

function checkIdentifierCharacterIsValid(characterValue)
{
	//alert('checkIdentifierCharacterIsValid characterValue:'+characterValue);
    if(characterValue == null || characterValue == "" || characterValue == undefined || characterValue == " ")
	{
		//alert('checkIdentifierCharacterIsValid characterValue is null');
        return false;
	}
	else
	{
		if(characterValue == 'A'
                || characterValue == 'B'
                || characterValue == 'C'
                || characterValue == 'D'
                || characterValue == 'E'
                || characterValue == 'F'
                || characterValue == 'G'
                || characterValue == 'H'
                || characterValue == 'I'
                || characterValue == 'J'
                || characterValue == 'K'
                || characterValue == 'L'
                || characterValue == 'M'
                || characterValue == 'N'
                || characterValue == 'O'
                || characterValue == 'P'
                || characterValue == 'Q'
                || characterValue == 'R'
                || characterValue == 'S'
                || characterValue == 'T'
                || characterValue == 'U'
                || characterValue == 'V'
                || characterValue == 'W'
                || characterValue == 'X'
                || characterValue == 'Y'
                || characterValue == 'Z'
                || characterValue == '_'
                || isNaN(characterValue) == false
                )
		{
            //alert('checkIdentifierCharacterIsValid characterValue is a valid character');
            return true;
		}
    }

	return false;
}

function checkTextCharacterIsValid(characterValue)
{
	//alert('checkTextCharacterIsValid characterValue:'+characterValue);
    if(characterValue == null || characterValue == "" || characterValue == undefined)
	{
		//alert('checkTextCharacterIsValid characterValue is null');
        return false;
	}
	else
	{
		if(characterValue == 'A' || characterValue == 'a'
                || characterValue == 'B' || characterValue == 'b'
                || characterValue == 'C' || characterValue == 'c'
                || characterValue == 'D' || characterValue == 'd'
                || characterValue == 'E' || characterValue == 'e'
                || characterValue == 'F' || characterValue == 'f'
                || characterValue == 'G' || characterValue == 'g'
                || characterValue == 'H' || characterValue == 'h'
                || characterValue == 'I' || characterValue == 'i'
                || characterValue == 'J' || characterValue == 'j'
                || characterValue == 'K' || characterValue == 'k'
                || characterValue == 'L' || characterValue == 'l'
                || characterValue == 'M' || characterValue == 'm'
                || characterValue == 'N' || characterValue == 'n'
                || characterValue == 'O' || characterValue == 'o'
                || characterValue == 'P' || characterValue == 'p'
                || characterValue == 'Q' || characterValue == 'q'
                || characterValue == 'R' || characterValue == 'r'
                || characterValue == 'S' || characterValue == 's'
                || characterValue == 'T' || characterValue == 't'
                || characterValue == 'U' || characterValue == 'u'
                || characterValue == 'V' || characterValue == 'v'
                || characterValue == 'W' || characterValue == 'w'
                || characterValue == 'X' || characterValue == 'x'
                || characterValue == 'Y' || characterValue == 'y'
                || characterValue == 'Z' || characterValue == 'z'
                || characterValue == '_'
                || characterValue == '-'
                || isNaN(characterValue) == false
                )
		{
            //alert('checkTextCharacterIsValid characterValue is a valid character');
            return true;
		}
    }

	return false;
}

//Generic function to set a dom oject value by its ID
function setValueByID(id, valueToSet)
{
	var objToSet = document.getElementById(id);
	if(objToSet != undefined && objToSet != null)
	{
		//alert('setValueByID for:'+id+' with value of:'+valueToSet);
		objToSet.value=valueToSet;
	}
	else
	{
		alert('setValueByID ERROR Could not find object by ID:'+id);
	}
	
}

function decodeUnicodeText(textToDecode)
{
    var result = '';

    for (i=0; i<textToDecode.length; i++)
    {
        result += '&#' + textToDecode.charCodeAt(i) + ';';
    }

    return result;
}


//Recursively searches down and entire DOM tree to find all named elements
// Use for extracting all the data INPUT tags from a form.
function findAllNamedElementTags(objectToSearch)
{
	//alert('findAllNamedElementTags called');
	var tagList = new Array();
	findNamedElements(objectToSearch, tagList);

	return tagList;
}


function findNamedElements(nodeListToSearch, masterListOfElementObjs)
{
	//alert('findNamedElements called for nodeListToSearch:'+nodeListToSearch);
	var foundElementObj;

	if(nodeListToSearch != null || nodeListToSearch != 'undefined')
	{
		//alert('findNamedElements nodeListToSearch length:'+nodeListToSearch.length);

		for(var i=0; i < nodeListToSearch.length; i++)
		{
			foundElementObj = nodeListToSearch[i];
			//alert('findNamedElements foundElementObj element id:'+foundElementObj.id+' name:'+foundElementObj.name+' value:'+foundElementObj.value+' foundElementObj.nodeType:'+foundElementObj.nodeType+' class:'+foundElementObj.className);

			if(foundElementObj != null && foundElementObj != 'undefined')
			{
				if(foundElementObj.nodeType==1)
				{
					//This node may be a named tag, in which case, we also want to store it!
					if(foundElementObj.name != undefined && foundElementObj.name != 'undefined' && foundElementObj.name != '')
					{
						//alert('findNamedElements NAMED ELEMENT FOUND foundElementObj element id:'+foundElementObj.id+' name:'+foundElementObj.name+' value:'+foundElementObj.value);
						masterListOfElementObjs[masterListOfElementObjs.length] = foundElementObj;
					}					

					//This node MAY HAVE child nodes, lets dig down deeper.
					//Recursively find if there are any frames in this frame.
					masterListOfElementObjs = findNamedElements(foundElementObj.childNodes, masterListOfElementObjs);										
				}
			}

		}
	}

	return masterListOfElementObjs;
}


//Only will need to use this is the String.replace method is not available on all browsers!
function replaceString(oldS,newS,fullS)
{
	// Replaces oldS with newS in the string fullS
	for (var i=0; i<fullS.length; i++)
	{
		if (fullS.substring(i,i+oldS.length) == oldS)
		{
			fullS = fullS.substring(0,i)+newS+fullS.substring(i+oldS.length,fullS.length)
		}
	}

	return fullS;
}


function obtainCheckedRadioButton(radioButton)
{
    var checkedRadioButton = null;

    if(radioButton.length == undefined)
    {
        //There must be only 1 option in the list of radio buttons as it has no array
        //alert('obtainCheckedRadioButton radio button array length:'+radioButton.value)
        if(radioButton.checked == true)
        {
            checkedRadioButton = radioButton;
        }
    }
    else
    {
        //alert('obtainCheckedRadioButton radio button array length:'+radioButton.length)
        for(var i=0; i < radioButton.length; i++)
        {
            if(radioButton[i].checked == true)
            {
                checkedRadioButton = radioButton[i];
                break;
            }
        }
    }

    return checkedRadioButton;
}

function checkRadioButton(radioButton, valueToCheck)
{
    //alert('checkRadioButton called radioButton:'+radioButton+' valueToCheck:'+valueToCheck);

    if(radioButton.length == undefined)
    {
        //There must be only 1 option in the list of radio buttons as it has no array
        //alert('checkRadioButton radio button array length:'+radioButton.value)
        if(radioButton.checked == valueToCheck)
        {
            radioButton.checked == true;
        }
        else
        {
            radioButton.checked == false;
		}
    }
    else
    {
        //alert('checkRadioButton radio button array length:'+radioButton.length)
        for(var i=0; i < radioButton.length; i++)
        {
            if(radioButton[i].value == valueToCheck)
            {
                radioButton[i].checked = true;
                break;
            }
        }
    }
}

//http://www.quirksmode.org/dom/maxlength.html
function setTextAreaMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'textAreaCounter';
    //Use JQuery to remove any existing counters
    $('.textAreaCounter').remove();

	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
            var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength');
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = checkTextAreaMaxLength;
            //Trigger the event to set the counter with the actual number of characters already used and enforce
            // any changes in the max length.
			x[i].onkeyup();
		}
	}
}
//http://www.quirksmode.org/dom/maxlength.html
function checkTextAreaMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength)
    {
        this.relatedElement.className = 'alertRed';
        //this.value.length = maxLength;
        //Force the text back to the max length
        this.value = this.value.substring(0,maxLength);

        currentLength = this.value.length;
        if (currentLength <= maxLength)
        {
            this.relatedElement.className = '';    
        }
    }
    else
    {
        this.relatedElement.className = '';
    }

    this.relatedElement.firstChild.nodeValue = currentLength;
	// not innerHTML
}

function selectTextInputById(id)
{
    var inputText = document.getElementById(id);
    if(inputText != null)
    {
        inputText.focus();
        inputText.select();
    }
}

function selectThisTextInput(thisObj)
{
    if(thisObj != null)
    {
        thisObj.focus();
        thisObj.select();
    }
}


function setElementDisplayByIDOnOff(onOff, elementID, displayValueOn, displayValueOff)
{
	var elementObj = document.getElementById(elementID);

	if(elementObj != undefined)
	{
		if(onOff == "true")
		{
				elementObj.style.display = displayValueOn;
		}
		else
		{
				elementObj.style.display = displayValueOff;
		}
	}
}


function setElementByIDOnOff(onOff, elementID)
{
	var elementObj = document.getElementById(elementID);

	if(elementObj != undefined)
	{
		if(onOff == "true")
		{
				elementObj.style.display = "block";
		}
		else
		{
				elementObj.style.display = "none";
		}
	}
}

function trim(str) {
    return str.replace(/(^\s+|\s+$)/g,'');
}

function strip(str) {
  return str.replace(/\s+/, "");
}

function extractFileNameFromPath(fileWithPathDelimiters)
{
    //If it is a mac the file path delimiter will be /
    // If it is a PC the file delimiter will be \
    //So we look at both and work out which it is.

    var extractedFileName = fileWithPathDelimiters;
    var pcDelimiterSplitArray = fileWithPathDelimiters.split("\\");
    var macDelimiterSplitArray = fileWithPathDelimiters.split("/");

    if(macDelimiterSplitArray.length > pcDelimiterSplitArray.length)
    {
        extractedFileName = macDelimiterSplitArray[macDelimiterSplitArray.length - 1];
    }
    else if(macDelimiterSplitArray.length < pcDelimiterSplitArray.length)
    {
        extractedFileName = pcDelimiterSplitArray[pcDelimiterSplitArray.length - 1];
    }
    
    return extractedFileName;
}

//May not be used for cross domain content but works fine from the same domain
function extractIFrameBody(iFrameEl) {

  var doc = null;
  if (iFrameEl.contentDocument) { // For NS6
    doc = iFrameEl.contentDocument;
  } else if (iFrameEl.contentWindow) { // For IE5.5 and IE6
    doc = iFrameEl.contentWindow.document;
  } else if (iFrameEl.document) { // For IE5
    doc = iFrameEl.document;
  } else {
    alert("Error: could not find sumiFrame document");
    return null;
  }
  return doc.body;

}

//The escape function does not properly encode the '+' and '/' character
// (I've no idea why it's programmed in that way), these characters need to be converted manually.
// This is done using String.replace function.
function properlyEscapeURI(uri)
{
    var incorrectEncodedURI = escape(uri);
    var encodedURI = incorrectEncodedURI.replace("+", "%2B");
    encodedURI=incorrectEncodedURI.replace("/", "%2F");

    return encodedURI;
}

function convertToUpperCase(ctrl)
{
	try
	{
		var currentCaretPosition = doGetCaretPosition(ctrl);
		ctrl.value = ctrl.value.toUpperCase();
		setCaretPos(ctrl, currentCaretPosition);
	} catch (err) {
		//Unable to change the input to upper case, not the end of the world
	}
}

/*
* doGetCaretPosition and setCaretPos from:
* http://www.webdeveloper.com/forum/archive/index.php/t-74982.html
*/
function doGetCaretPosition(ctrl){
	var CaretPos = 0;
	// IE Support
	if (document.selection) {

	ctrl.focus ();
	var Sel = document.selection.createRange();
	var SelLength = document.selection.createRange().text.length;
	Sel.moveStart ('character', -ctrl.value.length);
	CaretPos = Sel.text.length - SelLength;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
	CaretPos = ctrl.selectionStart;

	return (CaretPos);
}


function setCaretPos(obj, position) {
	if (obj.setSelectionRange) {
		obj.focus();
		obj.setSelectionRange(position, position);
	} else if (obj.createTextRange) {
		var range = obj.createTextRange();
		range.move("character", position);
		range.select();
	} else if(window.getSelection){

	s = window.getSelection();
	var r1 = document.createRange();


	var walker=document.createTreeWalker(obj, NodeFilter.SHOW_ELEMENT, null, false);
	var p = position;
	var n = obj;

	while(walker.nextNode()) {
		n = walker.currentNode;
		if(p > n.value.length) {
		p -= n.value.length;
		}
		else break;
	}
	n = n.firstChild;
	r1.setStart(n, p);
	r1.setEnd(n, p);

	s.removeAllRanges();
	s.addRange(r1);

	} else if (document.selection) {
		var r1 = document.body.createTextRange();
		r1.moveToElementText(obj);
		r1.setEndPoint("EndToEnd", r1);
		r1.moveStart('character', position);
		r1.moveEnd('character', position-obj.innerText.length);
		r1.select();
	}
}

function changeTextAreaRowHeightById(textAreaID, newRowHeight)
{
    var textAreaObj = document.getElementById(textAreaID);
    textAreaObj.rows = newRowHeight;
}

//Controls the maximum number of characters a user is allowed to input
function changeTextAreaMaxLengthById(textAreaID, newMaxSize, maxColumnWidth)
{
    //Use JQuery to lookup the text area
    var textAreaObj = $('#'+textAreaID);
    if(textAreaObj != null)
    {
        //Use JQuery to change the maxlength attribute
        textAreaObj.attr('maxlength',newMaxSize);

        //Use JQuery to change the column width of the text area, but to a width no greater than the max allowed column width
        if(newMaxSize < maxColumnWidth)
        {
            textAreaObj.attr('cols',newMaxSize);
        }
        else
        {
            textAreaObj.attr('cols',maxColumnWidth);                        
        }

        //Apply the new max length attribute on the text area
        setTextAreaMaxLength();
    }
}

//
//POPUP Functions START
//
function parentCallBack(originatorID, data)
{
    if(parent != self)
    {
        //If the parent window has a callback function then we will call it
        if(parent.callBack)
        {
            parent.callBack(originatorID, data);
        }            
    }
}

//When a popup is triggered the current popup trigger name is stored here.
// e.g. For the Product Manager, this would want to store the product stock code which was in context
// when the popup was triggered.
var g_popupTriggerName = "";

function setPopupTriggerName(popupTriggerName)
{
    g_popupTriggerName = popupTriggerName;
}

function getPopupTriggerName()
{
    return g_popupTriggerName;
}
//
//POPUP Functions END
//


