var userErrorRoutine
var ns4 = (document.layers)? true:false
var ie4 = (document.all)? true:false

// Verify that the passed value is numeric
function isNumeric ( inputValue ) {
	oneDecimal = false
	inputStr = inputValue.toString()
	for ( var i = 0 ; i < inputStr.length ; i++ ) {
		var oneChar = inputStr.charAt(i)
		if ( i == 0 && oneChar == '-' )
		{
			continue
		}
		if ( oneChar < '0' || oneChar > '9' ) {
			return false
		}
	}
	return true
}

function isDigits (inputValue){
    inputStr = inputValue.toString();
    if (isEmpty(inputValue)){
        return false;
    }
    for ( var i = 0; i < inputStr.length; i++){
        var oneChar = inputStr.charAt(i);
        if (oneChar == ' ') continue;
        if (oneChar < '0' || oneChar > '9'){
            return false;
        }
    }
    return true;
}

// Verify that the passed field contains data
function isEmpty ( inputValue ) {

	if ( inputValue == null || inputValue == '' )  {
		return true
	}
		return false
}
// Verify that the value in the passed input field is numeric.  Issue an error if the data is not numeric
function vaValidateNumeric ( inputField ) {

	if ( !(isEmpty ( inputField.value ))) {
		if ( isNumeric ( inputField.value )) {
			return true } }
	if ( !(isEmpty ( inputField.value ))) {
		vaReportError ( 'Please enter a numeric into this field' )
		// clear the field coz of netscape bugs
		if (ns4) inputField.value = ""
		inputField.focus()
		inputField.select()
		return false}
	}
// Display the error using the 'alert' method or execute a userErrorRoutine if
// available
function vaReportError ( errorString ) {
	if ( userErrorRoutine != null ) {
		eval ( userErrorRoutine )
	}
	else {
		alert ( errorString ) }
	}
// Verify that the user input is a value between min and max
function vaValidateNumericRange ( inputField, min, max ) {
	var lowNum , highNum
	if ( vaValidateNumeric ( inputField ) ) {
		lowNum = parseFloat ( min )
		highNum = parseFloat ( max )
		if ( vaValidateRange ( inputField , lowNum, highNum )) {
			return true }
		// clear the field coz of netscape bugs
		if (ns4) inputField.value = ""
		inputField.focus()
		inputField.select()
		return false
	} }

// Verify that the user input is a value between min and max and not null
function vaValidateNumericRangeRequired ( inputField, min, max)
{
	var lowNum , highNum
	if (isEmpty ( inputField.value ))
	{
		vaReportError ( 'Field CANNOT be blank. Please Enter a number into the field' )
		inputField.focus()
		inputField.select()
		return false

	}
	if ( vaValidateNumeric ( inputField ) )
	{
		lowNum = parseFloat ( min )
		highNum = parseFloat ( max )
		if ( vaValidateRange ( inputField , lowNum, highNum ))
		{
			return true
		}
		// clear the field coz of netscape bugs
		if (ns4) inputField.value = ""
		inputField.focus()
		inputField.select()
		return false
	}
}
// Return true if value falls between min and max
function vaValidateRange ( inputField , min , max )
{
	if ( vaValidateMin ( inputField , min ))
	{
		if ( vaValidateMax ( inputField , max ))
		{
			return true
		}
	}
	if (ns4) inputField.value = ""
	inputField.focus()
	inputField.select()
	return false
}

// Verify that the passed value is greater than min
function vaValidateMin ( inputField , min ) {
	if ( inputField.value >= min ) {
		return true }
	vaReportError ( 'Enter a value greater than or equal to ' + min )
	inputField.focus()
	inputField.select()
	return false }

// Verify that the passed value is less than max
function vaValidateMax ( inputField , max ) {
	if ( inputField.value <= max ) {
		return true }
	vaReportError ( 'Enter a value less than or equal to ' + max )
	inputField.focus()
	inputField.select()
	return false }

// Convert the text in the passed field to upper case and replace its 'value'
// with the upper cased string
function vaConvertToUpperCase ( inputField ) {
	if ( !(isEmpty (inputField.value ))) {
		inputField.value = inputField.value.toUpperCase() } }

// Convert the text in the passed field to lower case and replace its 'value'
// with the lower cased string
function vaConvertToLowerCase ( inputField ) {
	if ( !(isEmpty (inputField.value ))) {
		inputField.value = inputField.value.toLowerCase() } }

// Verify that the user has entered at least minChars
function vaValidateMinChars ( inputField , minChars ) {
	if ( inputField.value.length >= minChars ) {
		return true }
	vaReportError ( 'Field requires at least ' + minChars + ' characters' )
	inputField.focus()
	inputField.select()
	return false
}
function isDecimalField ( inputValue )
{
	oneDecimal = false;
	inputStr = inputValue.toString()
	for ( var i = 0 ; i < inputStr.length ; i++ )
	{
		var oneChar = inputStr.charAt(i)
		if ( i == 0 && oneChar == '-' ) continue
		if ( oneChar == '.' && !oneDecimal )
		{
			oneDecimal = true;
			continue
		}
		if ( oneChar < '0' || oneChar > '9' ) return false
	}
	return true;
}
function isCurrencyField ( inputValue )
{
	oneDollar = false;
	oneDecimal = false;

	inputStr = inputValue.toString()
	for ( var i = 0 ; i < inputStr.length ; i++ )
	{
		var oneChar = inputStr.charAt(i)
		if (oneChar == ',' ) continue
		if ( i == 0 && oneChar == '-' ) continue
		if ( oneChar == '.' && !oneDecimal )
		{
			oneDecimal = true;
			continue
		}
		else if ( oneChar == '$' && !oneDollar )
		{
			oneDollar = true
			continue
		}
		if ( oneChar < '0' || oneChar > '9' ) return false
	}
	return true;
}
function _formatCurrencyField ( inputFld )
{
	negative=false;
	// carry on
	num = inputFld.value;
	if (num.charAt(0) == "-")  negative = true;			// check it negative number
	num = num.toString().replace(/\$|\,/g,'');			//
	if(isNaN(num)) num = "0";
	abs_num = Math.abs(num);						// use absolute value to cater for negatives
	cents = Math.floor((abs_num* 100 + 0.5) % 100);			// retrieve the cents
	num = Math.floor((abs_num * 100+ 0.5) / 100).toString();	// retrieve dollars

	if(cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4 * i + 3)) +','+ num.substring(num.length-(4 * i + 3));
	if (negative)inputFld.value = "-$" + num + '.' + cents;	// neg
	if (!negative)inputFld.value = "$" + num + '.' + cents;	// pos
	return true;
}
function validateFormatCurrency(inputFld)
{
	if ( !(isEmpty ( inputFld.value )))
	{
		// check if currency first
		if (!isCurrencyField(inputFld.value))
		{
			vaReportError ( 'Please enter a VALID currency value into this field \n eg $###.## or ### or ###.##' )
			// clear the field coz of netscape bugs
			if (ns4) inputFld.value = "";
			inputFld.focus();
			inputFld.select();
			return false;
		}
		_formatCurrencyField ( inputFld ) // format the field

	}
	return true;
}
function validateCurrencyRange(inputFld, min, max)
{
	negative = false;
	if ( !(isEmpty ( inputFld.value )))
	{
		// check if currency first
		if (!isCurrencyField(inputFld.value))
		{
			vaReportError ( 'Please enter a VALID currency value into this field \n eg $###.## or ### or ###.##' )
			// clear the field coz of netscape bugs
			if (ns4) inputFld.value = "";
			inputFld.focus();
			inputFld.select();
			return false;
		}
		// now check the ranges
		var num = 0.00;
		var lowNum = 0.00;
		var highNum = 0.00;
		input_num = inputFld.value;
		input_num = input_num.toString().replace(/\$|\,/g,'');			// remove all formatting
		num = parseFloat ( input_num )		// input
		lowNum = parseFloat ( min )		// low range
		highNum = parseFloat ( max )		// higher range
		if (num < lowNum )
		{
			vaReportError ( 'Please enter a VALID currency value greater than or equal to ' + min )
			// clear the field coz of netscape bugs
			if (ns4) inputFld.value = "";
			inputFld.focus();
			inputFld.select();
			return false;
		}
		if (num > highNum )
		{
			vaReportError ( 'Please enter a VALID currency value less than or equal to ' + max )
			// clear the field coz of netscape bugs
			if (ns4) inputFld.value = "";
			inputFld.focus();
			inputFld.select();
			return false;
		}
		// all is cool, carry on
		_formatCurrencyField ( inputFld ) // format the field

	}
	return true;
}

function setField ( inputField, data )
{
	inputField.value = data
	return true
}


// opens the attachment window

var remote=null;
function openWindow(n,u,w,h,x)
{
  var winl = (screen.width - w) / 2;
  var wint = (screen.height - h) / 2;
  args="width="+w+",height="+h+",top="+wint+",left="+winl+",resizable=yes,scrollbars=yes,status=0";
  remote=window.open(u,n,args);
  if (remote != null)
  {
    if (remote.opener == null)
      remote.opener = self;
  }
  if (x == 1) { return remote; }
}

// help window
var hwnd=null;
function openNewWindow(url, title, width, height)
{
  hwnd=openWindow(title,url,width, height, 1);
  hwnd.focus();
}
// for hiding and showing elements
function hide(id)
{
	if (ns4) document.layers[id].visibility = "hide"
	else if (ie4) document.all[id].style.visibility = "hidden"
}
function show(id)
{
	if (ns4) document.layers[id].visibility = "show"
	else if (ie4) document.all[id].style.visibility = "visible"
}
//
function checkCharCount(field, maxlimit)
{
  if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit);
}

function updateSpinNumber(fld, action, max, min)
{
	var maxValue = parseInt(max);
	var minValue = parseInt(min);
	var intValue = 0;
	fld.value=eval(fld.value+action);
	intValue = parseInt(fld.value);
	if (intValue > max) fld.value=minValue ;
	if (intValue < min) fld.value=maxValue;
	intValue = parseInt(fld.value);
	if (intValue < 10 ) fld.value = "0" + fld.value;

}
// Verify that the value in the passed input field does not have a space in it other Issue an error
function isSpaceEmbedded ( inputValue )
{
	oneDecimal = false
	inputStr = inputValue.toString()
	for ( var i = 0 ; i < inputStr.length ; i++ )
	{
		var oneChar = inputStr.charAt(i)
		// if in the middle of the string
		if ( oneChar == ' ' && i < inputStr.length - 1) return false
	}
	return true
}


function vaNoSpacesEmbedded ( inputField )
{
	if (isSpaceEmbedded ( inputField.value )) return true;

	vaReportError ( 'Field CANNOT have space(s) embedded. Please remove the space(s)' )
	// clear the field coz of netscape bugs
	if (ns4) inputField.value = ""
	inputField.focus()
	inputField.select()
	return false}



function makeBlankArray(numberElements)
{
	this.length=numberElements;
	for (var i=0;i< numberElements; i++)
	{
		this[i] = null;
	}
}

function createRequiredField(fldname, message)
{
	this.fieldname	= fldname;
	this.message	= message;
	return this;
}

function validateRequired(which, oRequired)
{
	var pass=true;
	var radio_check_pass=true; // used for radiobuttons
	var focusField = null;
	var z = 0;
	var fields = new Array();
    // for each field
    for (i=0;i<which.length;i++)
    {
        var tempobj=which.elements[i];
        var objectname = tempobj.name;
        var success = true;
        // check if they are on the required list
        for ( var x = 0 ; x < oRequired.length ; x++ )
        {
            var requiredfld  = oRequired[x].fieldname ;
            if (objectname == requiredfld )
            {	// test field, textarea, file
                if ((tempobj.type=="text"||tempobj.type=="textarea"||tempobj.type=="file"||tempobj.type=="password" )&&tempobj.value=='')
                {
                    success=false;
                }
                if ( tempobj.type.toString().charAt(0)=="s"&& tempobj.selectedIndex < 0) // select box
                {
                    success=false;
                }
                if (tempobj.type=="radio")
                {
                    var obj_length = eval("document." + formname + "." + objectname + ".length");
                    radio_check_pass = false;
                    for (x=0;x< obj_length;x++)
                    {
                        var obj_checked = eval("document." + formname + "." + objectname + "[" + x + "].checked");
                        if (obj_checked)
                        {
                            radio_check_pass=true;
                            break;
                        }
                    }
                    if (!radio_check_pass)
                    {
                        success=false;
                    }
                }
                if (!success)
                {
                    if (z == 0) focusField = tempobj;
                    fields[z++] = oRequired[x].message;
                }
                success = true
            }
        }
    }
    if (fields.length > 0)
    {
        focusField.focus();
        alert(fields.join('\n'));
        pass=false;
    }
    return pass;
}

function validateEmail(fld)
{
	var bValid = true;
	var i = 0;
	if (!checkEmail(fld.value))
	{
		fld.focus();
		alert("The email address you have entered is invalid. Please enter a legitimate email address and resubmit your form");
		bValid = false;
	}
	return bValid;
}


function checkEmail(emailStr) {
    while (true){
        if (emailStr.charAt(emailStr.length - 1) == ' '){
            emailStr = emailStr.substring(0, emailStr.length -2);
        }else{
            break;
        }
    }
	if (emailStr.length == 0) {
	   return true;
	}
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray == null) {
	   return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	if (user.match(userPat) == null) {
	   return false;
	}
	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null) {
	   for (var i = 1; i <= 4; i++) {
		  if (IPArray[i] > 255) {
			 return false;
		  }
	   }
	   return true;
	}
	var domainArray=domain.match(domainPat);
	if (domainArray == null) {
	   return false;
	}
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if ((domArr[domArr.length-1].length < 2) ||
	   (domArr[domArr.length-1].length > 3)) {
	   return false;
	}
	if (len < 2) {
	   return false;
	}
	return true;
}

	function confirmDialog(message)
	{
   		if (confirm(message))
		   return true;
		else
    		return false;
	}

    // Returns true if character c is a char
    // (A .. Z, a .. z).
    function isChar (c) {
        return ((c >= "A" && c <= "Z") || ((c >= "a") && (c <= "z")))
    }

    function validChar(fieldValue) {
        // return true if it's a full letter value

        var i;
        var s = fieldValue;
        if (isEmpty(fieldValue)) {
            return false;
        }
        for (i = 0; i < s.length; i++)
        {
            // Check that current character is number.
            var c = s.charAt(i);

            if (!isChar(c)) return false;
        }

        // All characters are letters.
        return true;
    }

    // return true if the value contains only space
    function isAllSpace ( inputValue )
    {
        if (isEmpty(inputValue)) {
            return true;
        }

        inputStr = inputValue.toString()
        for ( var i = 0 ; i < inputStr.length ; i++ )
        {
            var oneChar = inputStr.charAt(i)
            if ( oneChar != ' ') {
                return false
            }
        }
        return true
    }

    function common_char_convert(checkField, checkLimit) {
        var checkValue = checkField.value;
        var chars_converted = '';
        var qstr = '';
        var cstr = '';
        var bstr = '';
        var expanded_max = 0;

        for ( j=0; j<checkValue.length; j++ ) {
            var oneChar = checkValue.charAt(j);
            var oneCode = checkValue.charCodeAt(j);
            if ( oneCode > 127 ) {
                qstr += oneChar;
                if ( search(chars_converted, oneChar) == false ) {
                    chars_converted += oneChar + '    ';
                }
                oneChar = '&#' + oneCode +';';
                expanded_max += oneChar.length-1;
            }

            if ( oneChar == '<' | oneChar == '>' | oneChar == '&'  ) {
                bstr += oneChar;
                oneChar = '&#' + oneCode +';';
                expanded_max += oneChar.length-1;
            }
            cstr += oneChar;
        }
        if ( qstr != '' | bstr != '' ) {
            var database_limit = checkLimit;
            var fl = checkValue.length + expanded_max;
            if ( fl > database_limit ) {
                alert('We have identified that some of the characters you have entered need special attention to print correctly.\n\n' +
                      'This has reduced the number of characters you can enter in at least one of the larger text boxes. \n\n' +
                      'Please review it again and check that you have not lost vital text at the end of the larger text boxes.' +
                      ' If you continue to have problems, please advise the vam helpdesk using the \'contact\' link at the top right corner of the main VAM page.');
            }
            checkField.value = cstr;
        }
    }

    function search ( str, ch ) {
        for ( n=0; n<str.length; n++ ) {
            if ( str.charAt(n) == ch ) {
                return true;
            }
        }
        return false;
    }
//  -->

