/*
 +-------------------------------------------------------------------+
 |                  J S - C H E C K F O R M   (v1.0)                 |
 |                                                                   |
 | Copyright Gerd Tentler               www.gerd-tentler.de/tools    |
 | Created: Oct. 23, 2001               Last modified: Oct. 21, 2005 |
 +-------------------------------------------------------------------+
 | This program may be used and hosted free of charge by anyone for  |
 | personal purpose as long as this copyright notice remains intact. |
 |                                                                   |
 | Obtain permission before selling the code for this program or     |
 | hosting this software on a commercial website or redistributing   |
 | this software over the Internet or in any other medium. In all    |
 | cases copyright must remain intact.                               |
 +-------------------------------------------------------------------+

  --------  Modified by Soung
 * Extended Date Validation
 * Extended Phone # Validation
 * THIS VALIDATION CODE IS FOR ONLY AMS-DEMO2 WEBSITE (CUSTOM JS THAT OVERRRIDE CURRENT VALIDATION JS FILE)



======================================================================================================

 ARGUMENTS:

  - form-name or -number
  - 'field:title:type:minimum length'[, ...]  (type = number / mail / url / [none])

 Example:

 checkForm('frm1', 'name:::2', 'age::number:1', 'eMail:e-mail:mail:1', 'homepage::url:0');


 *************** modded by Soung ***********************************
 if field is required field then

 age::number:1:1
 or
 age::number:1:0

 ******************************************
------------------------------------------------------------------------------------------------------
 This script was tested with the following systems and browsers:

 - Windows XP: IE 6, NN 7, Opera 7, Firefox 1
 - Mac OS X:   IE 5, Safari 1

 If you use another browser or system, this script may not work for you - sorry.
======================================================================================================
 */
//--------------------------------------------------------------------------------------------------------
// Language settings
//--------------------------------------------------------------------------------------------------------
var msgNumber = "must be a number";
var msgEMail = "must be an e-mail address";
var msgURL = "must be a web address";
var msgFillOut = "Please fill out";
var msgCheckOption = "Please check the box";
var msgNoForm = "Form does not exist";
var msgNoField = "Field does not exist";
var msgWrongDateFormat = "Date format is wrong!! \n\n The format must be mm/dd/yyyy";
var msgWrongPhone = "Phone Number format is incorrect!! \n\n The format must be 10 digit number with no hyphen or 12 digit number with hyphen";

// --------------------------------------------------------------------------------------------------------
// Functions
// --------------------------------------------------------------------------------------------------------

function _trim(str) {
	if (str) {
		str = str.replace(/^\s+/, "");
		str = str.replace(/\s+$/, "");
	}
	return str;
}

function checkForm() {

	var args = checkForm.arguments;

	var f = args[0];
	var form1;
	if ((typeof (f) == 'string')) {
		form1 = document.forms[f];
	} else {
		if (!f.form) {
			return false;
		}
		form1 = f.form;
	}

	var msg = "";
	var arr, field, title, type, minLength, elem, val, cnt, i, j, fieldRq;

	var valid_url = /^(https?|ftp):\/\/([a-zA-Z0-9._-]+:[a-zA-Z0-9._-]+@)?[a-zA-Z0-9äöüÄÖÜ#._\/~% -]+(\?([a-zA-Z0-9_-]+(=[a-zA-Z0-99äöüÄÖÜß+%?_-]+&?)?)*)?$/;
	var valid_mail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9äöüÄÖÜ.-]+\.[a-zA-Z]{2,4}$/;
	var valid_phone2 = /^[2-9]\d{2}\-\d{3}\-\d{4}$/;
	// var valid_phone = /^[0-9]\d{1}\[0-9]\d{9}$/;
	var valid_phone = /^[2-9]\d{9}$/;

	if (form1) {
		for (i = 1; i < args.length; i++) {
			arr = args[i].split(":");
			field = _trim(arr[0]);
			title = _trim(arr[1]);
			if (!title)
				title = field;
			type = _trim(arr[2]);
			minLength = _trim(arr[3]);
			fieldRq = _trim(arr[4]);
			elem = form1.elements[field];

			if (form1.elements && form1.elements[field]) {
				elem = form1.elements[field];
				val = _trim(elem.value);

				if (val != "") {
					if (type == "number") {
						val = val.replace(",", ".");
						if (isNaN(val))
							msg += '"' + title + '" ' + msgNumber + "\n";
					} else if (type == "mail" && val.search(valid_mail) == -1)
						msg += '"' + title + '" ' + msgEMail + "\n";
					else if (type == "url" && val.search(valid_url) == -1)
						msg += '"' + title + '" ' + msgURL + "\n";
					/* Added by Soung */

					else if (type == "datetype") {
						if (isDate(val, title) == false) {
							return false;
						}
					} else if (type == "phone") {
						if (val.search(valid_phone) > -1
								|| val.search(valid_phone2) > -1) {
						} else {
							msg += '"' + title + '" ' + msgWrongPhone + "\n";
						}
					}
				}

				if (minLength) {
					if (elem.length) {
						if (elem.options) {
							for (j = cnt = 0; j < elem.options.length; j++) {
								if (elem.options[j].selected
										&& elem.options[j].value != "")
									cnt++;
							}
						} else
							for (j = cnt = 0; j < elem.length; j++) {
								if (elem[j].checked)
									cnt++;
							}
					} else if (elem.type == "checkbox")
						cnt = elem.checked ? 1 : 0;
					else
						cnt = val.length;
					if (fieldRq == "1" && !cnt) {
						msg += msgFillOut + ' "' + title + '"\n';
					}
				}
			} else
				msg += msgNoField + ': "' + field + '"\n';
		}

		if (msg)
			alert(msg);
		else {

			if (form1.action.match('/includes/formSubmit/')) {
				form1.action = '/includes/formSubmit/confirmed/';
			}
			form1.submit();

			if (f == "amsForm_2") {
				document.ReDirectTo_mtips.action = document.ReDirectTo_mtips.URLREDIRECT.value;
				document.ReDirectTo_mtips.submit();
			} else if (f == "amsForm_3") {
				document.ReDirectTo_ptour.action = document.ReDirectTo_ptour.URLREDIRECT.value;
				document.ReDirectTo_ptour.submit();
			} else {
				document.ReDirectTo.action = document.ReDirectTo.URLREDIRECT.value;
				document.ReDirectTo.submit();
			}

		}
	} else
		alert(msgNoForm + ': "' + f + '"');
}

/*
 * 
 * 
 * DATE VALIDATION
 * 
 * 
 * 
 */

var dtCh = "/";
var minYear = 1900;
var maxYear = 2100;

function isInteger(s) {
	var i;
	for (i = 0; i < s.length; i++) {
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9")))
			return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag) {
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1)
			returnString += c;
	}
	return returnString;
}

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);
}
function DaysArray(n) {
	for ( var i = 1; i <= n; i++) {
		this[i] = 31
		if (i == 4 || i == 6 || i == 9 || i == 11) {
			this[i] = 30
		}
		if (i == 2) {
			this[i] = 29
		}
	}
	return this
}

function isDate(dtStr, title) {

	var daysInMonth = DaysArray(12)
	var pos1 = dtStr.indexOf(dtCh)
	var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
	var strMonth = dtStr.substring(0, pos1)
	var strDay = dtStr.substring(pos1 + 1, pos2)
	var strYear = dtStr.substring(pos2 + 1)
	strYr = strYear
	if (strDay.charAt(0) == "0" && strDay.length > 1)
		strDay = strDay.substring(1)
	if (strMonth.charAt(0) == "0" && strMonth.length > 1)
		strMonth = strMonth.substring(1)
	for ( var i = 1; i <= 3; i++) {
		if (strYr.charAt(0) == "0" && strYr.length > 1)
			strYr = strYr.substring(1)
	}
	month = parseInt(strMonth)
	day = parseInt(strDay)
	year = parseInt(strYr)
	if (pos1 == -1 || pos2 == -1) {
		alert(title + " : The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length < 1 || month < 1 || month > 12) {
		alert(title + "Please enter a valid month")
		return false
	}
	if (strDay.length < 1 || day < 1 || day > 31
			|| (month == 2 && day > daysInFebruary(year))
			|| day > daysInMonth[month]) {
		alert(title + "Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
		alert(title + "Please enter a valid 4 digit year between " + minYear
				+ " and " + maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh, pos2 + 1) != -1
			|| isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
		alert(title + "Please enter a valid date")
		return false
	}
	return true
}
