/*
 +-------------------------------------------------------------------+
 |                  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




======================================================================================================

 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 = "Please enter a valid phone number including an area code.";

//--------------------------------------------------------------------------------------------------------
// 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 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_phone  = /^[2-9]\d{9}$/;
	// var valid_phone  = /^[0-9]\d{1}\[0-9]\d{9}$/;
	// var valid_phone2  = /^[2-9]\d{2}\-\d{3}\-\d{4}$/;
	// var valid_phone2 = /^[2-9]\d{2}-\d{3}-\d{4}$/;

	if(document.forms[f])
	{
		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]);

			if(type == 'datetypedropdown') {

				var check_date_result = check_date_dp(field,title);


				//if the field is required
				if(fieldRq > 0 && check_date_result[0] > 0 ) {

					msg += check_date_result[1];
				}
				// not required but field is filled with at leat one element (either month,day,year)
				else {
				//	if (check_date_result[0] < 3 ) {
					//	msg += check_date_result[1];
					//}
				}
			}


			elem = document.forms[f].elements[field];
			if(elem)
			{
				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")
					{
						// TREAT DATE DROPDOWN AS NORMAL FORM OBJECT ( WHEN DATE Select dropdown is unavailable )//
						if (isDate(val,title)==false)
						{
							return false ;
						}


					}

					else if(type == "phone")
					{
	//					else if(type == "phone"&& val.search(valid_phone) == -1)
						var stripped = val.replace(/[\(\)\.\-\ ]/g, '');
						//strip out acceptable non-numeric characters
						if (stripped.search(valid_phone) == -1) {
							msg += msgWrongPhone + "\n\n";
						}
					}
					/* End */
				}
				if(minLength && type != 'datetypedropdown')
				{
					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(cnt < minLength) msg += msgFillOut + ' "' + title + '"\n';
					if(fieldRq == "1" && !cnt)
					{
						msg += msgFillOut + ' "' + title + '"\n';
					}
				}
			}
			else {


						msg += msgNoField + ': "' + field + '"\n';


			}
		}

		if(msg) alert(msg);
		else
		{
			if(document.forms[f].action.match('/includes/formSubmit/'))
			{
				document.forms[f].action='/includes/formSubmit/confirmed/';
			}
			document.forms[f].submit();
			if (document.ReDirectTo)
			{
				document.ReDirectTo.action = document.ReDirectTo.URLREDIRECT.value;
				document.ReDirectTo.submit();
			}
		}
	}
	else alert(msgNoForm + ': "' + f + '"');
}


function check_date_dp (fd_name,title) {

				var msg = "";
				var error_counter = 0;
				var date_field_month = document.getElementsByName(fd_name+"_month")[0].value;
				var date_field_day = document.getElementsByName(fd_name+"_day")[0].value;
				var date_field_year = document.getElementsByName(fd_name+"_year")[0].value;


				if (date_field_month == "") {
					msg += msgFillOut + ' "Month of ' + title +'"\n';
					error_counter++;
				}
				if (date_field_day == "") {
					msg += msgFillOut + ' "Day of ' + title +'"\n';
					error_counter++;
				}
				if (date_field_year == "") {
					msg += msgFillOut + ' "Year of ' + title +'"\n';
					error_counter++;
				}

				var return_r  = new Array(error_counter,msg);

					// if there is no empty field (to generate complete date string otherwise complete date string becomes null)
					var insertDate = "";
					if (error_counter < 1)  {
						insertDate = number_padding(date_field_month.toString())+"/";
						insertDate += number_padding(date_field_day.toString())+"/";
						insertDate += date_field_year.toString();
					}
					document.getElementsByName(fd_name)[0].value = insertDate;

return return_r;
}

function number_padding (date_num) {

		if (date_num < 10) {
			date_num = '0'+date_num.toString();
		}

	 return date_num;

}

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;
}