var defaultEmptyOK = true;
var whitespace = " \t\n\r";
var DateSeparators = ".-:/";
var decimalPointDelimiter = "."; // global - set by currency validation
var focusFld;

var daysInMonth = new Array(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

function formValidate(frm,num) {

	var ok = false;
	var flds = frms[num]['flds'];
	var msg = '';
	var nme, tnm;
	var fldOk = false;
	
	for (var i=0;i<flds.length;i++) {
	
		fldOk = true;
		var tnm = flds[i]['n'];
		var nme = flds[i]['d'];
		var typ = flds[i]['t'];
		var req = (flds[i]['r']=='Y');
		if (typ=='RAD') {
			if (req && frm[tnm].value=='') fldOk = false;
		} else if (typ=='CHK') {
			if (req && !frm[tnm].checked) fldOk = false;
		} else if (typ=='EML') {
			if (req && frm[tnm].value=='') fldOk = false;
		} else {
			if (req && frm[tnm].value=='') fldOk = false;
		}
		if (!fldOk) msg+= nme + ', ';
	}
	
	if (msg!='') {
	
		msg = msg.substring(0,msg.length-2);
		msg = frms[num]['mrq'] + "\n" + msg;
		alert (msg);
		
	} else {
		
		ok = true;
	}
	
	return ok;
	
};

function formSubmit(frm) {

	var num = parseInt(frm['fn'].value);
	if (formValidate(frm,num)) {
		frm['f'].value = 'S';
		frm.submit();
	}	
	
};

function formPage(frm,p) {

	//frm['f'].value = 'P';
	frm['f'].value = p;
	frm.submit();

};

function formReset(frm) {

	var num = parseInt(frm['fn'].value);
	var ok = false;
	var msg = frms[num]['mrs'];
	if (confirm(msg)) {
		ok = true;
	}
	return ok;
	
};


function validateDate(num,fld,format) {

	var ok = Fld2Date(fld,format,false);
	if (ok==false) {
		fld.value = '';
		alert (frms[num]['miv']);
		setFocus(fld);
	} else {
		fld.value = ok;
	}
	
};			

function validateDOB(num,fld,format) {

	var ok = Fld2Date(fld,format,true);
	if (ok==false) {
		fld.value = '';
		alert (frms[num]['miv']);
		setFocus(fld);
	} else {
		fld.value = ok;
	}
	
};

function validateCurrency(num,fld,format) {

	decimalPointDelimiter = (format=='1,234.56')?'.':',';
	var ok = Fld2Cur(fld,format);
	if (ok==false) {
		alert (frms[num]['miv']);
		setFocus(fld);
	} else {
		fld.value = ok;
	}
	
};

function Fld2Cur(fld, format) {
	var c = fld.value;
	if (format=='1,234.56') {
		c = Replace(c,',','');
	} else {
		c = Replace(c,'.','');
		c = Replace(c,',','.');
	}	
	if (isCurrency(c)) {
		return formatCur(c,format);
	} else {
		return false;
	}		
};



function setFocusDelayed() {

 	focusFld.focus();
	
};

function setFocus(fld) {

	// delay required otherwise focus does not work
	focusFld = fld;
	setTimeout('setFocusDelayed()',100);
	
};

function validateEmail(num,fld) {

	if (!emailOk(fld.value)) {
		fld.value = '';
		alert (frms[num]['miv']);
		setFocus(fld);
	}
	
};

function validatePostcodeNL(num,fld) {

	var ok = Fld2PostcodeNL(num,fld,true);
	if (ok==false) {
		fld.value = '';
		setFocus(fld);
	} else {
		fld.value = ok;
	}
	
};

function Fld2PostcodeNL(num,fld, warning) {

	var c = fld.value;
	c = c.toUpperCase();
	c = Replace(c,' ','');
	var ok = true;
	if (c.length!=6) {
		ok = false;
	} else {
		var c1;
		for (var i=0;i<c.length;i++) {
			c1 = c.substring(i,i+1);
			if (i<4 && !isDigit(c1)) {
				ok = false;
				break;
			} else if (i>=4 && !isCapitalLetter(c1)) {
				ok = false;
				break;
			}
		}
	}
	if (ok) {
		return (c.substring(0,4) + ' ' + c.substring(4,6));
	} else {
		if (warning) alert(frms[num]['miv']);
		return false;
	}		
};
	

function emailOk (s) {   

	// Email address must be of form a@b.c -- in other words:
	// * there must be at least one character before the @
	// * there must be at least one character before and after the .
	// * the characters @ and . are both required

    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
};

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
};

function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt(parseFloat (s));
    return ((num >= a) && (num <= b));
}

function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
};

function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
};

function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
};


// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.

    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
};

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
};

function isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
};

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
};

function isDigit (c) {  
	 return ((c >= "0") && (c <= "9"));
};

function isCapitalLetter (c) {  
	 return ((c >= "A") && (c <= "Z"));
};

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
};

function Replace(strSource, charReplaceWhat, charReplaceWith) {

	var S1 = strSource;
	var C1 = charReplaceWhat;
	var C2 = charReplaceWith;
	var C = "";
	var S2 = "";
	for (i=0;i<S1.length;i++) {
		C = S1.substring(i,i+1);
		if (C==C1) {
			C=C2;
		}
		S2 = S2 + C;	
	}
	return S2;
};

function Fld2Date(fld, format, dob) {
	var i;
	var f = fld.value;
	if (isEmpty(f)) return "";
	var a = new Array(2);
	a[0] = "";
	a[1] = "";
	a[2] = "";

	if (isInteger(f) && (f.length==6 || f.length==8)) {

		a[0] = f.substring(0,2);
		a[1] = f.substring(2,4);
		a[2] = f.substring(4,f.length);
				
	} else {
		// convert all separators to /

		for (i=0;i<DateSeparators.length;i++) {
			C = DateSeparators.substring(i,i+1);
			f = Replace(f,C,"/");
		}

		// get day, month, year

		occ = 0;
		p = 0;
		i = 0
		while (p>=0 && i<=2) {
			p = f.indexOf("/", occ)
			if (p >= 0) {
				a[i] = f.substring(occ,p);
				occ = p + 1;
				i=i+1;	
			} else {
				a[i] = f.substring(occ,f.length)	
			}
		}	
	}

	// check date and return valid date or empty string

	if (isDate(a[2],a[1],a[0])) {
		a0 = a[0].toString();
		a1 = a[1].toString();
		if (a0.length < 2) a[0]="0" + a0;
		if (a1.length < 2) a[1]="0" + a1;
		if (a[2].length <= 2) {
			var century = 2000;
			if (dob) {
				if (a[2] > 1) century = 1900;
			}	
			a[2] = century + parseInt(a[2]);
		}
		var d = '';
		switch (format) {
		case 'dd-mm-yyyy':
			d = a[0] + "-" + a[1] + "-" + a[2]; 
			break;
		case 'dd/mm/yyyy':
			d = a[0] + "/" + a[1] + "/" + a[2]; 
			break;
		case 'dd.mm.yyyy':
			d = a[0] + "." + a[1] + "." + a[2]; 
			break;
		}
		return d;	
			
	} else {
		return false;
	}	
};

function Str2Num(s) {
	return (parseFloat(numbersOnly(s)));
};

function formatCur(s,format) {
	return (formatNum(s,format,2));
};

function formatNum(expr,format,decplaces) {
	expr = Replace(expr, ",", ".");
	var str = (Math.round(parseFloat(expr) * Math.pow(10,decplaces))).toString();
	while (str.length <= decplaces) {
		str = "0" + str;
	} 
	var decpoint = str.length - decplaces;
	var n1 = str.substring(0,decpoint);
	var n2 = str.substring(decpoint,str.length);
	var c1000 = (format == '9,999.99')?',':'.';
	var cdec = (format== '9,999.99')?'.':',';
	var n1a = '';
	var j = 0;
	for (var i=n1.length-1;i>=0;i--) {
		j++;
		n1a = n1.substr(i,1) + n1a;
		if (j%3==0 && i>0) {
			n1a = c1000 + n1a;
		}
	}		
	return n1a + cdec + n2;
};

function numbersOnly(strIn) {
	var retVal;
	if (strIn=="") {
		return 0;
	} else {		
		retVal = strIn.replace('.','');
		retVal = retVal.replace('$','');
		retVal = retVal.replace('%','');
		return (parseFloat(retVal));
	}	
};

function isFloat (s) {   
	// returns -1 if not a number
	// returns number of decimals if a number
	var i;
	var seenDecimalPoint = false;
	if (isEmpty(s)) return 0;
    	if (s == decimalPointDelimiter) return -1;
	var numDecimals = 0;
    	for (i = 0; i < s.length; i++) {   
	        var c = s.charAt(i);
	        if ((c == decimalPointDelimiter) && !seenDecimalPoint) {
			seenDecimalPoint = true;
	        } else {
			if (!isDigit(c)) return -1;
			if (seenDecimalPoint) {
				numDecimals = numDecimals + 1;
			}
		}
	}
	return (numDecimals);
}

function isCurrency (s) {
	if (isIntegerInRange(isFloat(s),0,2)) {
		return true;
	} else {
		return false;
	} 
};
