// Form field initialization
function fnInitParams(fldName, params, f) {
	f = (f == null) ? document.forms['Edit'] : f;
	var e = f[fldName];
	if (e.type == 'select-one')
		//e.options[0].params = 'Value=' + e.options[0].value + '&' + params;
		e.options[0].params = params;
	else
		//e.params = 'Value=' + e.value + '&' + params;
		e.params = params;
}

function fnFormInit1(f) {
	f = (f == null) ? document.forms['Edit'] : f;

	// Fetch field parameters snuck in via the value attribute
	for (var i=0; i<f.elements.length; i++) {
		var e = f.elements[i];
		if ('select-one,text,textarea,password,file'.indexOf(e.type) == -1) continue;
		//if (e.type == 'select-one') e.params = e.options[0].value;
		//else e.params = e.value;
		var fldArgs = fnGetArgs(e.params);
		if (fldArgs == null) continue;
		for (var fldArg in fldArgs) {
			e[fldArg] = fldArgs[fldArg];
		}
		//if (e.type == 'select-one') 
		//	e.options[0].value = (e.Value != null) ? e.Value : '';
		//else
		//	e.value = (e.Value != null) ? e.Value : '';
		if (e.type == 'file' && e.title == null) e.title = 'File Picker';
	}
	f[1].focus();
}

function fnFormInit2(f, args) {
	// Validate parms
	f = (f == null) ? document.forms['Edit'] : f;
	args = (args == null) ? fnGetArgs(location.search.substring(1)) : args;

	// Spin thru form fields
	for (var i=0; i<f.elements.length; i++) {
		var e = f.elements[i];

		//alert(e.name);
		switch (e.type) {
			// Insert "Choose Option" choice for pulldowns if adding
			case 'select-one':
				if (args.fn == 'A' || args.fn == null) {
					if (e.title != null) {
						OptionUnshift(e.options, new Option('-- Choose ' + '"' + e.title + '"' + ' --', ' ', true));
					}else
						OptionUnshift(e.options, new Option('-- Choose One --', ' ', true));
					e.selectedIndex = 0;
				}
				break;

			// Setup check boxes. If adding, use the static default specified in the HTML.
			// If updating, set the checkbox value to the value in the database the corresponds to checked ('Y')
			// A match will cause the checkbox to have a check mark
			case 'checkbox':
				e.checked = (args.fn == 'U') ? e.value == 'Y' : e.checked;
				break;

		}
	}
}

function fnFormInit(f) {
	fnFormInit1(f);
	fnFormInit2(f);
}

// Form processing
function fnFormSave(f) {
	// Validate parms
	var f = (f == null) ? document.forms['Edit'] : f;
	if (fnFormOnSave(f)) f.submit();
	return false;
}

function fnFormOnSave(f) {
	// Validate parms
	var f = (f == null) ? document.forms['Edit'] : f;

	// Spin thru each form field...
	for(var i=0; i<f.elements.length; i++) {
		var e = f.elements[i];
		switch (e.type) {
		case 'text':
		case 'textarea':
		case 'password':
			if (e.value == '') {
				if (e.Required == 'N') continue;
				else return fnOnInvalidFld(e, '% must have a non-blank value. \nPlease correct your entry.');
			}
			switch (e.Type) {
			// Validate numeric fields
			case 'N':
				if (e.MinSize == null) e.MinSize = 1;
				if (isNaN(e.value)) return fnOnInvalidFld(e, '% must be a number. \nPlease correct your entry.');
				if (e.value < e.Min || e.value > Number(e.Max)) {
					return fnOnInvalidFld(e, '% must be between ' + e.Min + ' and ' + e.Max + '. \nPlease correct your entry.');
				}
				// break intentionally omitted!
			// Validate character fields
			case 'C':
				if (e.value.length < e.MinSize) {
					return fnOnInvalidFld(e, '% must have a mininum of ' + e.MinSize + ' characters. \nPlease correct your entry.');
				}
				if (e.value.length > e.MaxSize) {
					return fnOnInvalidFld(e, '% must have a maximum of ' + e.MaxSize + ' characters. \nPlease correct your entry.');
				}
				break;
			case 'Z':
				//alert(!fnValidZipCode(e.value));
				//alert(!isPostCode(e.value));
				if (!(fnValidZipCode(e.value) || isPostCode(e.value)) && e.value != '') {
					return fnOnInvalidFld(e, '% must be a valid US or Canadian Postal Code. \nPlease correct your entry.');
				}
				break;
			// Validate date fields
			case 'D':
				if (!fnValidDate(e.value)) return fnOnInvalidFld(e, '% has an invalid date format.');
				break;
			case 'T':
				if (!fnValidTime(e.value)) return fnOnInvalidFld(e, '% has an invalid time format.');
				break;
			}
			break;
		case 'file':
			if (e.value == '') return fnOnInvalidFld(e, '% must have a non-blank value. \nPlease correct your entry.');
			break;

		// Set correct database value for checkboxes and set checked to true unconditionally
		// Subverts brain-dead Request.Form behavior.
		case 'checkbox':
			e.value = e.checked ? 'Y' : 'N';
			e.checked = true;
			break;
			
		// If adding, field is required and no selection has been made...
		case 'select-one':
			if ((window.location.search.indexOf('fn=A') != -1 || window.location.search.indexOf('fn=') == -1) && 
				e.Required != 'N' && e.selectedIndex == 0) {
				return fnOnInvalidFld(e, 'Please make a selection for %');
			}
		}
		
		//case 'hidden':
		//case 'button':
		//case 'radio':
		//case 'reset':
		//case 'select-multiple':
		//case 'submit':
	}

	// Pass thru HTML query string to next page
	if ((s = window.location.search.substring(1)) != '') {
		f.action += (f.action.indexOf('?') > -1) ? '&' : '?';
		f.action += s;
	}
	//alert(f.action);
	//f.submit();
	return true;
}

function fnFormDelete(f, fld) {
	// Validate parms
	var f = (f == null) ? document.forms['Edit'] : f;
	var fld = (fld == null) ? f.elements[0] : fld; // Default to first field as id if not specified
	if (fnFormOnDelete(f, fld)) f.submit();
	return false;
}

function fnFormOnDelete(f, title, fld) {
	// Validate parms
	var f = (f == null) ? document.forms['Edit'] : f;
	var title = f.elements[0].value;
	var fld = (fld == null) ? f.elements[1] : fld; // Default to first field as id if not specified

	// Fetch field value
	var val = (fld.type == 'select-one') ? fld.options[fld.selectedIndex].innerText : val = fld.value;

	if (confirm('Are you sure you want to delete this ' + title + ': ' + val + '?')) {
		// Switch from update to delete function
		if ((s = window.location.search.substring(1)) != '') {
			f.action += (f.action.indexOf('?') > -1) ? '&' : '?';
			f.action += s.replace(/fn=U/, 'fn=D');
		}
		return true;
	}
	return false;
}

// Field validation
function fnOnInvalidFld(fld, msg) {
	if ('text,textarea,password,file'.indexOf(fld.type) != -1) fld.select();
	alert(msg.replace(/%/,"''" + fld.name + "''"));
	fld.focus();
	return false;
}

function fnValidZipCode(s) {
	return (s.search(/^\d{5}$/) != -1);
}

// Date validation
function fnValidDate(s) {
	var p = new RegExp('^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4}|\\d{2})$');
	if (s.search(p) == -1) return false;
	var m = s.match(p);
	var intMonth = parseInt(m[1], 10);
	var intDay = parseInt(m[2], 10);
	var intYear = parseInt(m[3], 10);

	// Validate month
	if (intMonth < 1 || intMonth > 12) return false;

	// Validate day
	if(intDay < 1) return false;
	switch (intMonth) {
		case 1:
		case 3:
		case 4:
		case 7:
		case 8:
		case 10:
		case 12:
			if(intDay > 31) return false;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			if(intDay > 30) return false;
			break;
		case 2:
			if(intDay > (fnLeapYear(intYear) ? 29 : 28)) return false;
			break;
	}
	return true;
}

function fnLeapYear(y) {
	return (y%4==0 && (y%100!=0 || y%400==0));
}

function fnValidTime(s) {
	var p = new RegExp('^(\\d{1,2}):(\\d{1,2}):(\\d{2})\\s[A|P]M$');
	if (s.search(p) == -1) return false;
	var m = s.match(p);
	var intHour = parseInt(m[1], 10);
	var intMinute = parseInt(m[2], 10);
	var intSecond = parseInt(m[3], 10);

	if (intHour < 1 || intHour > 12) return false;
	if (intMinute < 1 || intMinute > 60) return false;
	if (intSecond < 1 || intSecond > 60) return false;

	return true;
}

   //Canada's postal code rules:
	   
	   //Postal code must be exactly six characters. 
	   //Letters and numbers alternate. 
	   //Certain letters never occur (I AND O) 
	   //The first character is even more restricted 
	   
	   function isPostCode(entry){ // CANADIAN CODES ONLY
	   strlen = entry.length; if (strlen != 6) {return false;}
	   entry=entry.toUpperCase();        // in case of lowercase characters
	   // Check for legal characters in string - note index starts at zero
	   if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(0)) < 0) {return false;}
	   if ('0123456789'.indexOf(entry.charAt(1)) < 0) {return false;}
	   if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(2)) < 0) {return false;}
	   if ('0123456789'.indexOf(entry.charAt(3)) < 0) {return false;}
	   if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(4)) < 0) {return false;}
	   if ('0123456789'.indexOf(entry.charAt(5)) < 0) {return false;}
	   return true; }


