// Generic Form Validation
// Jacob Hage (jacob@hage.dk)
var checkObjects	= new Array();
var errors			= "";
var returnVal		= false;
var language		= new Array();
language["header"]	= "The following error(s) occured:"
language["start"]	= "->";
language["field"]	= " Field ";
language["require"]	= " is required";
language["min"]		= " and must consist of at least ";
language["max"]		= " and must not contain more than ";
language["minValue"]= " and must be bigger than ";
language["maxValue"]= " and must be smaller than ";
language["minmax"]	= " and no more than ";
language["chars"]	= " characters";
language["num"]		= " and must contain a number";
language["email"]	= " must contain a valid e-mail address";
language["combo"]	= " must select an option";
// -----------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = name of the input field (Required)
// type= string, num, email (Required)
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// d = (Optional)
// -----------------------------------------------------------------------------
function define(n, type, HTMLname, min, max, minValue, maxValue, d) 
{
 var p;
 var i;
 var x;
	if (!d) 
		d = document;
	if ((p=n.indexOf("?"))>0&&parent.frames.length) 
	{
		d = parent.frames[n.substring(p+1)].document;
		n = n.substring(0,p);
	}
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) 
    {
        x = d.forms[i][n];
    }
for (i = 0; !x && d.layers && i < d.layers.length; i++) {
x = define(n, type, HTMLname, min, max, d.layers[i].document);
return x;       
}
eval("V_"+n+" = new formResult(x, type, HTMLname, min, max, minValue, maxValue);");

    if (eval("V_"+n + ".form"))
    {
        checkObjects[eval(checkObjects.length)] = eval("V_"+n);
    }
    else
    {
    }
}
function formResult(form, type, HTMLname, min, max, minValue, maxValue) {
this.form = form;
this.type = type;
this.HTMLname = HTMLname;
this.min  = min;
this.max  = max;
this.minValue = minValue;
this.maxValue = maxValue;
}
function resetDefines() 
{ 
checkObjects = []; 
}
function validate() 
{
if (checkObjects.length > 0) 
{
errorObject = "";
for (i = 0; i < checkObjects.length; i++) 
{
validateObject = new Object();
validateObject.form = checkObjects[i].form;
validateObject.HTMLname = checkObjects[i].HTMLname;
validateObject.val = trim(checkObjects[i].form.value);
validateObject.len = trim(checkObjects[i].form.value).length;
validateObject.min = checkObjects[i].min;
validateObject.max = checkObjects[i].max;
validateObject.minValue = checkObjects[i].minValue;
validateObject.maxValue = checkObjects[i].maxValue;
validateObject.type = checkObjects[i].type;
    if (validateObject.type == "num" || 
		validateObject.type == "string")
	{
		if ((validateObject.type == "num" && validateObject.len <= 0) || 
		    (validateObject.type == "num" && isNaN(validateObject.val))) 
		{ 
			errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['num'] + "\n";
		} else 
		if (validateObject.min && validateObject.max && (validateObject.len < validateObject.min || validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['minmax'] + validateObject.max+language['chars'] + "\n";
		} else if (validateObject.min && !validateObject.max && (validateObject.len < validateObject.min)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['chars'] + "\n";
		} else if (validateObject.max && !validateObject.min &&(validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['max'] + validateObject.max + language['chars'] + "\n";
		} else if (!validateObject.min && !validateObject.max && validateObject.len <= 0) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + "\n";
	   	}
	   	if (validateObject.type == "num")
	   	{
	   		// validate value range
			if (validateObject.minValue && validateObject.maxValue && (validateObject.val < validateObject.minValue || validateObject.val > validateObject.maxValue)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['minValue'] + validateObject.minValue + language['maxValue'] + validateObject.maxValue + "\n";
			} else if (validateObject.minValue && !validateObject.maxValue && (validateObject.val < validateObject.minValue)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['minValue'] + validateObject.minValue + "\n";
			} else if (validateObject.maxValue && !validateObject.minValue &&(validateObject.val > validateObject.maxValue)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['maxValue'] + validateObject.maxValue + "\n";
			}
	   	}
} else if(validateObject.type == "email") 
   {
	// Checking existense of "@" and ".". 
	// Length of must >= 5 and the "." must 
	// not directly precede or follow the "@"
	if ((validateObject.val.indexOf("@") == -1) || 
		(validateObject.val.charAt(0) == ".") || 
		(validateObject.val.charAt(0) == "@") || 
		(validateObject.len < 6) || 
		(validateObject.val.indexOf(".") == -1) || 
		(validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") || 
		(validateObject.val.charAt(validateObject.val.indexOf("@")-1) == ".")) 
	 { 
		errors += language['start'] + language['field'] + validateObject.HTMLname + language['email'] + "\n"; 
	 }
   }
   else if (validateObject.type == "combo")
   {
		if ((validateObject.val == "DefaultValue") ||
			(validateObject.len < 1))
		{
			errors += language['start'] + language['field'] + validateObject.HTMLname + language['combo'] + "\n";
		}
   }
}

	if (errors) 
	{
		alert(language["header"].concat("\n" + errors));
		errors = "";
		returnVal = false;
        return false;
    } 
	else 
	{
		returnVal = true;
        return true;
    }
}
else return true;
}

// Ionut 2002-12-03
// allow formats nnnn.nn,nnnnn,-nnn, -nn.nn
function isNum(param, allowPoint, allowMinus)
{	
	
    var strNum = param;  
	if (strNum.length == 0)
		return false;

	if (true == allowPoint)
	{
	
        if (strNum.indexOf('.') != strNum.lastIndexOf('.'))
	    {	
		    return false;
	    }
	}
	if ('.' == strNum.charAt(0))
	{
        return false;
    }
    if ('.' == strNum.charAt(strNum.length-1))
	{
        return false;
    }
    
    if (true == allowMinus)
    {
        if ('-' != strNum.charAt(0)) 
            if ((strNum.charAt(0)<'0')||(strNum.charAt(0)>'9'))
	        {
                return false;
            }
    }
    else
    {
        if ((strNum.charAt(0)<'0')||(strNum.charAt(0)>'9'))
	        {
                return false;
            }
    }
    
    for (j=1; j < strNum.length; j++)
	{	
		if (true == allowPoint)
		{
		
            if (strNum.charAt(j) != '.')
		    {
			    if((strNum.charAt(j)<'0')||(strNum.charAt(j)>'9'))
			    {
			    	return false;
			    }
		    }
        }
        else 
        {
             if((strNum.charAt(j)<'0')||(strNum.charAt(j)>'9'))
			    {
			    	return false;
			    }
        }
	}
	return true;
}


//Ionut 2002-12-04
//used to brands and events forms
function checkData(strFieldStringName, strFieldNumberName, strFieldStringHTMLName,  strFieldNumberHTMLName)
{
    if (trim(strFieldStringName).length == 0)
    {
        alert(strFieldStringHTMLName+' is required!');
        return false;
    }
    
    if (!isNum(strFieldNumberName, false, false))
    {
        alert(strFieldNumberHTMLName+' is required and must be a number!');
        return false;
    }
    
    return true;
}

function trim(strText) { 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
} 
// This function replaces all instances of findStr in oldStr with repStr.

function replaceAll(oldStr,findStr,repStr) {
  var srchNdx = 0;  // srchNdx will keep track of where in the whole line
                    // of oldStr are we searching.
  var newStr = "";  // newStr will hold the altered version of oldStr.
  while (oldStr.indexOf(findStr,srchNdx) != -1)  
                    // As long as there are strings to replace, this loop
                    // will run. 
  {
    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
                    // Put it all the unaltered text from one findStr to
                    // the next findStr into newStr.
    newStr += repStr;
                    // Instead of putting the old string, put in the
                    // new string instead. 
    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
                    // Now jump to the next chunk of text till the next findStr.           
  }
  newStr += oldStr.substring(srchNdx,oldStr.length);
                    // Put whatever's left into newStr.             
  return newStr;
}
function toHTML(strVal)
{
	var strRet = strVal;
	if (strVal != null)
    {
        strRet = replaceAll(strRet, '&', '&amp;');
        strRet = replaceAll(strRet, '<', '&lt;');
        strRet = replaceAll(strRet, '>', '&gt;');
        strRet = replaceAll(strRet, '"', '&quot;');
        strRet = replaceAll(strRet, '\r\n', '<br>');
        strRet = replaceAll(strRet, '\n\r', '<br>');
        strRet = replaceAll(strRet, '\r', '<br>');
        strRet = replaceAll(strRet, '\n', '<br>');
        strRet = replaceAll(strRet, '<br>', '<br>\n');
    }
	return strRet;
}
function fromHTML(strVal)
{
	var strRet = strVal;
	if (strVal != null)
    {
        strRet = replaceAll(strRet, '&amp;','&');
        strRet = replaceAll(strRet, '&lt;', '<');
        strRet = replaceAll(strRet, '&gt;', '>');
        strRet = replaceAll(strRet, '&quot;', '"');
        strRet = replaceAll(strRet, '<br>', '\r\n');
        strRet = replaceAll(strRet, '<br>', '\n\r');
        strRet = replaceAll(strRet, '<br>', '\r');
        strRet = replaceAll(strRet, '<br>', '\n');
        strRet = replaceAll(strRet, '<br>\n', '<br>');
    }
	return strRet;
}
 
/*
BogdanB
*/ 

function checkIfContainsNumbers(strNum) 
{
	for (j=1; j < strNum.length; j++)
	{
	    if((strNum.charAt(j)>'0') && (strNum.charAt(j)<'9'))
	    {
	    	return true;
	    }				
	}
}

function IsValidABA(strNumber)
{
	n = 0;
  for (i = 0; i < strNumber.length; i += 3) {
    n += parseInt(strNumber.charAt(i),     10) * 3
      +  parseInt(strNumber.charAt(i + 1), 10) * 7
      +  parseInt(strNumber.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.

  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}


function IsvalidDate(dateStr)
{

if(dateStr=="")
return true;

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

	// To require a 4 digit year entry, use this line instead:
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) 
	{
		//alert("Date is not in a valid format.")
		return false;
	}
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) 
	{ // check month range
		//alert("Month must be between 1 and 12.");
		return false;
	}
	if (day < 1 || day > 31) {
		//alert("Day must be between 1 and 31.");
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) 
	{
		//alert("Day must be smaller than 31 for "+month+".")
		return false
	}
	if (month == 2) 
	{ // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) 
		{
			//alert("The Day for February " + year + " must be less than  " + day + ".");
			return false;
		}
	}

return true;  // date is valid
}


function ValidDate(year, month, day)
{
	var dtDate;
	// javascript months start at 0, not at 1
	dtDate = new Date(year, month-1, day);
	return ((day == dtDate.getDate()) && (month-1 == dtDate.getMonth()) && (year == dtDate.getFullYear()))
}

// returns true if the date given is a saturday or sunday; false otherwise
function Weekend(year, month, day)
{
	var dtDate;
	dtDate = new Date(year, month-1, day);
	return ((0 == dtDate.getDay()) || (6 == dtDate.getDay()));
}

function Is18YearsOld(year, month, day)
{
	var currentDate = new Date();
	mday = currentDate.getDate();
	mmonth = currentDate.getMonth() + 1;
	myear = currentDate.getFullYear();

	iyear = parseInt(year);
	imonth = parseFloat(month);
	iday = parseFloat(day);
	if (iyear > myear-18)
	{
	return false;
	}
	else 
	{
		if (iyear == myear - 18)
		{
			if (imonth > mmonth)
			{
				return false;
			}
			else if (imonth == mmonth)
			{
				if (iday > mday)
				{
					return false;
				}
			}
		}
	}
	return true;
}

function DateIsTodayOrGreater(year, month, day)
{
	var currentDate = new Date();
	mday = currentDate.getDate();
	mmonth = currentDate.getMonth() + 1;
	myear = currentDate.getFullYear();

	iyear = parseInt(year);
	imonth = parseFloat(month);
	iday = parseFloat(day);

	if (iyear >= myear)
	{
		if (imonth >= mmonth)
		{
			if (iday >= mday)
			{
				return true;
			}
		}
	}

	return false;
}

function DateIsTomorowOrGreater(year, month, day)
{
	var currentDate = new Date();
	mday = currentDate.getDate();
	mmonth = currentDate.getMonth();
	myear = currentDate.getFullYear();

	iyear = parseInt(year);
	imonth = parseFloat(month);
	iday = parseFloat(day);

	var futureDate = new Date();
	futureDate.setFullYear(iyear, imonth-1, iday)

	if (futureDate > currentDate)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function takeYear(theDate)
{
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}
//<!-- STEP TWO: Include the .js file in the HEAD of your main document  -->



