emptyString = /^\s*$/;
triGood = 0;
triTooLong = 1;
triTooShort = 2;

function focusform(fieldname)
{
	if ((fieldname=='none')||(!document.getElementById))
		return;
	var elem = document.getElementById(fieldname);
	if (elem!=null)
	{
		if (elem.focus) elem.focus();
		if (elem.select) elem.select();
	}
};

function stripspaces(str) 
{
    return str.replace(/ /g,"");
};

function trim(str)
{
	return str.replace(/^\s+|\s+$/g, '');
};

function msg(fld,msgtype,message)
{ 
    var dispmessage;
    if (emptyString.test(message))
        dispmessage = "&nbsp;";
    else
        dispmessage = message;
    var elem = document.getElementById(fld);
    if (elem.firstChild && (elem.firstChild.nodeType == 1))
        elem.firstChild.nodeValue = dispmessage;
    else
        elem.innerHTML = dispmessage;
    elem.className = msgtype;
};

var proceed = 2;  

function commonCheck (vfld,ifld,reqd)
{
    if (!document.getElementById)
        return true;
    var elem = document.getElementById(ifld);
    if (!elem.firstChild && (typeof elem.innerHTML != "string"))
        return true;
    if (emptyString.test(vfld.value)) 
    {
        if (reqd) 
		{
			msg (ifld, "error", "ERROR: Required");  
			vfld.focus();
			if(vfld.select)
				vfld.select();
			return false;
		}
        else 
		{
			msg (ifld, "warn", "");
			return true;
    	}
    }
    return proceed;
};

function valPresent(vfld,ifld)
{
    var stat = commonCheck (vfld,ifld,true);
    if (stat != proceed)
		return stat;
    msg (ifld, "warn", "");  
    return true;
};

function valChecked(vfld,ifld)
{
  if (vfld.checked==true)
    vfld.value="1";
  else
    vfld.value="";
  return (valPresent(vfld,ifld));   
};

function valNumeric(vfld,ifld,reqd)
{
	var str, stat = commonCheck (vfld, ifld, reqd);
	if (stat != proceed)
		return stat;
	str = stripspaces(vfld.value)
	if(isNaN(str))
	{
		msg (ifld, "error", str + " is not a numeric value.");
		return false;
	}
	else
	{
		msg (ifld, "warn", "");		
		return true;
	}  
};

function valQuantity(vfld,ifld,reqd,allowzero)
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed) 
        return stat;
    if (valNumeric(vfld, ifld, reqd))
    {
        var iQuantity, result;
        iQuantity = parseInt(stripspaces(vfld.value));
		result = true;
        if(!allowzero && (iQuantity < 1))
		{
			result = false;
            msg (ifld, "error", "ERROR: Must be > 0.");
		}
        if(iQuantity > 255)
		{
			result = false;
            msg (ifld, "error", "ERROR: Cannot exceed 255.");
		}
        else
        {
            result = true;
			msg (ifld, "validate", "");
        }
		if(!result)
		{
			vfld.focus();
			if (vfld.select)
				vfld.select();
		}
		return result;
    }
    else
        return false;
};

function triCheckLen(str,imin,imax)
{
    var iLength = str.length;
    if (iLength > imax)
        return triTooLong;
    if (iLength < imin)
		return triTooShort;
    return triGood;
};

function valInBounds(vfld,ifld,reqd,imin,imax)
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed)
        return stat;
    var str = vfld.value;
    stat = triCheckLen(str, imin, imax);
    switch(stat)
    {
        case triTooLong:
            msg (ifld, "error", "ERROR: Maximum field length is " + imax + " characters.");
            vfld.focus();
            return false;
            break;
        case triTooShort:
            msg (ifld, "error", "ERROR: Minimum field length is " + imin + " characters.");
            vfld.focus();
            return false;
            break;
        default:
			msg (ifld, "validate", "");
            return true;
            break;
    }
};

function valCompare(vfld,vfld2,ifld,reqd,fldname)
{
    var stat = commonCheck (vfld, ifld, reqd);
    if (stat != proceed)
        return stat;
    if (vfld.value == vfld2.value)
	{
		msg (ifld, "validate", "");
		return true;
	}
    else
    {
        msg (ifld, "error", "ERROR: " + fldname + " values do not match.")
        return false;
    }
};

function valLuhnsFormula(vfld,ifld,reqd,imin,imax)
{
	var strInput = vfld.value;
	vfld.value = stripspaces(vfld.value);
	var str = vfld.value, digit, sum = 0, mul = 1, iLength = str.length, stat = commonCheck (vfld, ifld, reqd);
	if (stat != proceed)
		return stat;
	if (valInBounds(vfld, ifld, reqd, imin, imax))
	{
		vfld.value = strInput;
		for (i = 0; i < iLength; i++)
		{
			digit = str.substring(iLength - i - 1, iLength - i);
			tproduct = parseInt(digit, 10) * mul;
			if (tproduct >= 10)
				sum += (tproduct % 10) + 1;
			else
				sum += tproduct;
			if (mul == 1)
				mul++;
			else
				mul--;
		}
		if ((sum % 10) == 0)
		{
			msg (ifld, "validate", "");
            return true;
		}
		else
		{
			msg (ifld, "error", "ERROR: Check card number. Does not validate under Luhn's Formula.");
			return false;
		}
	}
	else
	{
		vfld.value = strInput;
		return false;
	}
};

function parseEmail(str)
{
	var filter1 = /^.{1,64}@.{5,255}$/
	var filter2 = /^([&'\=\?\+\^\-\{\}\~\w]+(\.?[&'\=\?\+\^\-\{\}\~\w]+)*)@(\[?)([A-Z0-9\-]+[-]?)+([A-Z0-9\-]+\.)+([A-Z]{2,4}|[0-9]{1,3})(\]?)$/i
	return (filter1.test(str) && filter2.test(str))
};

function valCardDate(vfld, ifld, reqd)
{
	var input, a_values, i, result = true;
	input = vfld.value;
	if (input.length == 0) 
		result = !reqd;
	else
	{
		if (input.length != 5)
			result = false;
		else
		{
			a_values = input.split("/", 2);
			for (i=0; i < a_values.length; i++)
				if (isNaN(a_values[i]) || (a_values[i].length != 2))
				{	result = false;	break;	}
			if (result) result = !((a_values[0] < 1) || (a_values[0] > 12)); 
		}
	}
	if (!result) msg (ifld,'error','ERROR: Use format mm/yy');
	else msg (ifld, 'validate', '');
	return result;
};

function bValidDate (str)
{
	var dateformat = /^\d{2}\/\d{2}\/\d{4}$/
	if (!dateformat.test(str))
		return false;
	else
	{
		var DateArray = str.split('/')
		var dayfield=DateArray[0];
		var monthfield=DateArray[1];
		var yearfield=DateArray[2];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		
		return (!((dayobj.getMonth()+1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)))
	}
}

function valDate(vfld, ifld, reqd)
{
    var stat = commonCheck (vfld, ifld, reqd);
	var result;
	
    if (stat != proceed)
        return stat;
	else
		result = bValidDate(vfld.value);
		
	if (result) msg(ifld,'validate','');
	else msg(ifld,'error','ERROR: Invalid date value. Use format dd/mm/yyyy');
	
	return result;
}

function valCardDate(vfld, ifld, reqd)
{
	var input, a_values, i, result = true;
	input = vfld.value;
	if (input.length == 0) 
		result = !reqd;
	else
	{
		if (input.length != 5)
			result = false;
		else
		{
			a_values = input.split("/", 2);
			for (i=0; i < a_values.length; i++)
				if (isNaN(a_values[i]) || (a_values[i].length != 2))
				{	result = false;	break;	}
			if (result) result = !((a_values[0] < 1) || (a_values[0] > 12)); 
		}
	}
	if (!result) msg (ifld,'error','ERROR: Use format mm/yy');
	else msg (ifld, "validate", "");
	return result;
};

function valEmailAddress(vfld,ifld,reqd)
{
	var stat = commonCheck (vfld, ifld, reqd);
	if (stat != proceed)
		return stat;
	if (valInBounds(vfld, ifld, reqd, 7, 128))
	{
		var str = vfld.value;
		if (!parseEmail(str))
		{
			msg (ifld,'error','ERROR: ' + str + ' is not recognised as a valid email address.');
			return false;
		}
		else
		{
			msg (ifld, "validate", "");
            return true;
		}
	}
	else
		return false;
};

function FormatCurrency(value)
{
	var i = parseFloat(value);
	var minus = '';
	if (isNaN(i))
		i = 0.00;
	if (i < 0)
		minus = '-';
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	var s = new String(i);
	if (s.indexOf('.') < 0)
		s += '.00';
	if (s.indexOf('.') == (s.length - 2))
		s += '0';
	s = minus + s;
	return s;
};

function showPopup(url, w, h)
{
	/* WARNING: window.open cannot have spaces in 2nd argument. IE cannot understand those spaces.  */
	var newwindow = window.open(url,'image','height=' + h + ',width=' + w + ',top=100,left=200,status=0,toolbar=0,resizable=0,scrollbars=1,location=0,menubar=0'); 
	if (window.focus) 
	{
		newwindow.focus();
	}
	return false;
}