//For use with RichardNET DataForms 
//Copyright 2005, 2006, 2007 Tad Richard, all rights reserved

//Load Events
if(window.addEventListener != null) {
	window.addEventListener('load', function(){initVerification(); calcTotals();}, false);
	}
else {
	window.attachEvent('onload', function(){initVerification(); calcTotals();});
	}

function initVerification() {
	var thisDataType;
	
	for(var f=0; f < document.forms.length; f++) {
	
		//Trap Form Submits for multiple submit buttons
		document.forms[f].onsubmit = formSubmitHandler;
	
		//Trap Field Events for Field Data Verification
		for(e=0; e < document.forms[f].elements.length; e++) {
		
			var thisElement = document.forms[f].elements[e];
			var thisId = thisElement.getAttribute('id');
			
			//Handle validation events
			if(thisElement.getAttribute('datatype') != null) {
				var thisDataType = thisElement.getAttribute('datatype').toLowerCase();
				
				//Next Screen, Save, & Delete Buttons
				if(thisDataType == 'nextscreen') {
					createEventHandler(thisElement, 'click', 'recordSaveButton(e)')
					}
				
				if(thisDataType == 'save') {
					createEventHandler(thisElement, 'click', 'recordSaveButton(e)')
					}
				
				else if(thisDataType == 'delete') {
					createEventHandler(thisElement, 'click', 'recordDeleteButton(e)')
					}
				
				//Data Fields
				if(thisDataType == 'creditcardnumber') {
					createEventHandler(thisElement, 'blur', 'VerifyCreditCardNumber(e); calcTotals();');
					}
				else if(thisDataType == 'currency') {
					createEventHandler(thisElement, 'blur', 'verifyCurrency(e); calcTotals();');
					}
				else if(thisDataType == 'date') {
					createEventHandler(thisElement, 'blur', 'verifyDate(e)');
					if(typeof Calendar.setup == 'function' && Calendar.setup != null) {
						Calendar.setup({inputField:thisId, ifFormat:"%m/%d/%Y", showsTime:false});
						}
					}
				else if(thisDataType == 'longtext') {
					createEventHandler(thisElement, 'keypress', 'verifyLongText(e)');
					}
				else if(thisDataType == 'number') {
					createEventHandler(thisElement, 'blur', 'verifyNumber(e); calcTotals();');
					}
				else if(thisDataType == 'password') {
					createEventHandler(thisElement, 'blur', 'verifyPassword(e)');
					}
				else if(thisDataType == 'selectother') {
					createEventHandler(thisElement, 'change', 'verifySelectOther(e)');
					createEventHandler(document.getElementById(thisElement.id + '_Other'), 'blur', 'verifyShortText(e)');
					resetSelectOther(thisElement);
					}
				else if(thisDataType == 'shorttext') {
					createEventHandler(thisElement, 'blur', 'verifyShortText(e)');
					}
				else if(thisDataType == 'ssn') {
					createEventHandler(thisElement, 'blur', 'verifySSN(e)');
					}
				else if(thisDataType == 'telephone') {
					createEventHandler(thisElement, 'blur', 'verifyTelephone(e)');
					}
				}
			}
		}
	}

var saveButtonSubmit = false;
function recordSaveButton(e) {
	saveButtonSubmit = true;
	}

var deleteButtonSubmit = false;
function recordDeleteButton(e) {
	deleteButtonSubmit = true;
	}

function formSubmitHandler(e) {
	var thisForm = getEventObject(e);	
	
	if(saveButtonSubmit) {
		saveButtonSubmit = false;
		return verifyRequiredFields(thisForm);
		}
	else if(deleteButtonSubmit) {
		deleteButtonSubmit = false;
		return confirm('Are you sure you wish to delete this record?\nThis can NOT be undone!');
		}
	return true;
	}

function verifyRequiredFields(thisForm) {
	var incomplete = '';
	
	for(var i=0; i < thisForm.elements.length; i++) {
		if(thisForm.elements[i].getAttribute('datatype') != null) {
			if((thisForm.elements[i].getAttribute('required')) && (thisForm.elements[i].getAttribute('required').toLowerCase() == "true") && (thisForm.elements[i].value == '')) {
				incomplete += thisForm.elements[i].getAttribute('label') + '\n';
				}
			}
		}
	
	if(incomplete != '') {
		alert("You have not completed the required information for this form.\nPlease complete the following:\n\n" + incomplete);
		return false;
		}
	else {
		return true;
		}
	}

function calcTotals() {
	var totalID, sum;
	
	//loop through all div objects
	for(var d=0; d < document.getElementsByTagName('div').length; d++) {
		
		//calc total fields
		if(document.getElementsByTagName('div')[d].getAttribute('totalid')!= null) {
			var totalField = document.getElementsByTagName('div')[d];
			var totalID = totalField.getAttribute('totalid');
			var sum = 0;
			var numberGroupSeparator = ',';
			var decimalCharacter = '.';
			var accuracy = '';
			
			for(var f=0; f < document.forms.length; f++) {
			
				//input fields
				for(var e=0; e < document.forms[f].elements.length; e++) {
					if(document.forms[f].elements[e].getAttribute('addsto') && document.forms[f].elements[e].getAttribute('addsto').indexOf(totalID) >= 0) {
						var thisAccuracy = document.forms[f].elements[e].getAttribute('accuracy')
						if(getNumericValue(thisAccuracy) > getNumericValue(accuracy)) {
							accuracy = thisAccuracy;
							}
						sum += getNumericValue(document.forms[f].elements[e].value);
						}
					}
				
				//read only fields
				for(var e=0; e < document.forms[f].getElementsByTagName('div').length; e++) {
					if(document.forms[f].getElementsByTagName('div')[e].getAttribute('addsto') && document.forms[f].getElementsByTagName('div')[e].getAttribute('addsto').indexOf(totalID) >= 0) {
						var thisAccuracy = document.forms[f].getElementsByTagName('div')[e].getAttribute('accuracy')
						if(getNumericValue(thisAccuracy) > getNumericValue(accuracy)) {
							accuracy = thisAccuracy;
							}
						sum += getNumericValue(document.forms[f].getElementsByTagName('div')[e].innerHTML);
						}
					}
				}
				
			
			if(totalField.getAttribute('currencysymbol')) {
				totalField.innerHTML = totalField.getAttribute('currencysymbol');
				}
			if(totalField.getAttribute('numbergroupseparator')) {
				numberGroupSeparator = totalField.getAttribute('numbergroupseparator');
				}
			if(totalField.getAttribute('decimalcharacter')) {
				decimalCharacter = totalField.getAttribute('decimalcharacter');
				}
			
			if(totalField.getAttribute('decimalplaces')) {
				accuracy = totalField.getAttribute('decimalplaces');
				}
			else if(totalField.getAttribute('currencysymbol') && (totalField.getAttribute('currencysymbol') == '$')) {
				accuracy = '2';
				}
			
			if(accuracy != '') {
				totalField.innerHTML = formatNumber(round(sum, getNumericValue(accuracy)), numberGroupSeparator, decimalCharacter);
				}
			else {
				totalField.innerHTML = formatNumber(sum, numberGroupSeparator, decimalCharacter);
				}
			}
		}
	}

//Verification Functions
function verifyShortText(e) {
	var field = getEventObject(e),
	minLength = 'none',
	maxLength = 'none';
	
	if (field.getAttribute('minlength'))
		minLength = field.getAttribute('minlength');
	if (field.getAttribute('maxlength'))
		maxLength = field.getAttribute('maxlength');
	
	if(field.value == '') { 
		return true;
		}

	if(!isNaN(minLength) && (minLength > 0) && (field.value.length < minLength)) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' has a minimum length of ' + minLength + ' characters.');
			}
		else {
			alert('This field has a minimum length of ' + minLength + ' characters.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	
	if(!isNaN(maxLength) && (maxLength > 0) && (field.value.length > maxLength)) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' has a maximum length of ' + maxLength + ' characters.');
			}
		else {
			alert('This field has a maximum length of ' + maxLength + ' characters.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	
	if((field.value.length > 0) && field.getAttribute('regexvalidator') && (field.getAttribute('regexvalidator').length > 0)) {
		var regx = new RegExp(field.getAttribute('regexvalidator'));
		if(regx.test(field.value)) {
			if(field.getAttribute('regexerror') && (field.getAttribute('regexerror'))) {
				alert(field.getAttribute('regexerror'));
				}
			else {
				alert('This field is formatted improperly.');
				}
			field.value = '';
			field.focus();
			return false;
			}
		}
	return true;
	}

function verifyLongText(e) {
	var field = getEventObject(e),
	minLength = 'none',
	maxLength = 'none';
	
	if (field.getAttribute('minlength'))
		minLength = field.getAttribute('minlength');
	if (field.getAttribute('maxlength'))
		maxLength = field.getAttribute('maxlength');
	
	if(field.value == '') { 
		return true;
		}

	if(!isNaN(minLength) && (minLength > 0) && (field.value.length < minLength)) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' has a minimum length of ' + minLength + ' characters.');
			}
		else {
			alert('This field has a minimum length of ' + minLength + ' characters.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	
	if(!isNaN(maxLength) && (maxLength > 0) && (field.value.length > maxLength)) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' has a maximum length of ' + maxLength + ' characters.');
			}
		else {
			alert('This field has a maximum length of ' + maxLength + ' characters.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	return true;
	}

function verifyNumber(e) {
	var field = getEventObject(e),
	minValue = 'none',
	maxValue = 'none',
	decimalPlaces = '',
	newVal = '' + field.value,
	numberGroupSeparator = ',',
	decimalCharacter = '.';
	
	if (field.getAttribute('minvalue'))
		minValue = field.getAttribute('minvalue');
	if (field.getAttribute('maxvalue'))
		maxValue = field.getAttribute('maxvalue');
	if (field.getAttribute('decimalplaces'))
		decimalPlaces = field.getAttribute('decimalplaces');

	if(field.value == '') { 
		return true;
		}
	
	//adjust string
	if((field.getAttribute('numbergroupseparator')) && (field.getAttribute('numbergroupseparator') != '')) {
		numberGroupSeparator = field.getAttribute('numbergroupseparator');
		}
	var regx = new RegExp('\\' + numberGroupSeparator, 'g');
	newVal = newVal.replace(regx, '');
	
	if((field.getAttribute('decimalcharacter')) && (field.getAttribute('decimalcharacter') != '')) {
		decimalCharacter = field.getAttribute('decimalcharacter');
		}
	newVal = newVal.replace(decimalCharacter, '.');
	
	//check numeric
	if(isNaN(parseFloat(newVal))) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' must be a numeric value.');
			}
		else {
			alert('Please enter a numeric value.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	
	//check bounds
	if(!isNaN(minValue) && (minValue != '') && (parseFloat(newVal) < getNumericValue(minValue, numberGroupSeparator, decimalCharacter))) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' may be no less than ' + minValue + '.');
			}
		else {
			alert('This value may be no less than ' + minValue + '.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	
	if(!isNaN(maxValue) && (maxValue != '') && (parseFloat(newVal) > getNumericValue(maxValue, numberGroupSeparator, decimalCharacter))) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' may be no greater than ' + maxValue + '.');
			}
		else {
			alert('This value may be no greater than ' + maxValue + '.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	
	//round off based upon accuracy
	if((decimalPlaces != null) && (decimalPlaces != '')) {
		newVal = round(newVal, decimalPlaces);
		}
	
	//format number string
	field.value = formatNumber(newVal, numberGroupSeparator, decimalCharacter);
	
	return true;
	}

function verifyCurrency(e) {
	var field = getEventObject(e),
	currencySymbol ='$';
	
	if((field.getAttribute('currencysymbol')) && (field.getAttribute('currencysymbol') != '')) {
		currencySymbol = field.getAttribute('currencysymbol');
		}
	
	field.value = field.value.replace(currencySymbol, '');
	
	if(verifyNumber(e)) {
		field.value = field.currencysymbol + field.value;
		return true
		}
	else {
		return false;
		}
	}

function verifyDate(e) {
	var field = getEventObject(e),
	minValue = 'none',
	maxValue = 'none';
	
	if (field.getAttribute('minvalue'))
		minValue = field.getAttribute('minvalue');
	if (field.getAttribute('maxvalue'))
		maxValue = field.getAttribute('maxvalue');
	
	if(field.value == '') {
		return true;
		}
	
	var thisDate = new Date(field.value);
	
	if(isNaN(thisDate)) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' must contain a valid date in the form of MM/DD/YYYY.');
			}
		else {
			alert('This field must contain a valid date in the form of MM/DD/YYYY.');
			}
		field.value = '';
		field.focus();
		return false;
		}
	
	if((minValue != null) && (minValue != '')) {
		minDate = new Date(minValue);
		if(thisDate < minDate) {
			if(field.getAttribute('label')) {
				alert('\'' + field.getAttribute('label') + '\' must be on or after ' + minValue + '.');
				}
			else {
				alert('This field must be on or after ' + minValue + '.');
				}
			field.value = '';
			field.focus();
			return false;
			}
		}
	
	if((maxValue != null) && (maxValue != '')) {
		maxDate = new Date(maxValue);
		if(thisDate > maxDate) {
			if(field.getAttribute('label')) {
				alert('\'' + field.getAttribute('label') + '\' must be on or before ' + maxValue + '.');
				}
			else {
				alert('This field must be before ' + maxValue + '.');
				}
			alert('\'' + field.getAttribute('label') + '\' must be on or before ' + maxValue + '.');
			field.value = '';
			field.focus();
			return false;
			}
		}
	
	return true;
	}

function verifyPassword(e) {
	var field = getEventObject(e),
	entryField = document.getElementById(field.id + "_Entry");
	
	if(entryField.value != field.value) {
		if(field.getAttribute('label')) {
			alert('The \'' + entryField.getAttribute('label') + '\' and \'' + field.getAttribute('label') + '\' values do not match.\n\nPlease re-enter.');
			}
		else {
			alert('The values do not match.\n\nPlease re-enter.');
			}
		field.value = '';
		entryField.value = '';
		entryField.focus();
		}
	}

function verifySelectOther(e) {
	var field = getEventObject(e);
	
	resetSelectOther(field, true);
	return true;
	}

function resetSelectOther(field) {
	var otherField = document.getElementById(field.id + '_Other'),
	baseName,
	userInitiated = false;
	
	if(arguments.length > 1) {
		userInitiated = arguments[1];
		}
	
	if(field.name.length < otherField.name.length) {
		baseName = field.name;
		}
	else {
		baseName = otherField.name;
		}
	
	if(field.value.substring(0,5).toLowerCase() == 'other') {
		otherField.name = baseName;
		field.name = baseName + "_Select";
		otherField.disabled = false;
		if(userInitiated) otherField.focus();
		}
	else {
		field.name = baseName;
		otherField.name = baseName + "_Other";
		otherField.value = '';
		otherField.disabled = true;
		}
	
	return true;
	}

function verifySSN(e) {
	var field = getEventObject(e);

	if(field.value == '') {
		return true;
		}
	
	var regx = new RegExp('[^0-9]', 'g');
	var newVal = field.value.replace(regx, '');
	
	if(newVal.length != 9) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' must be in the form of 000-00-0000');
			}
		else {
			alert('This field must be in the form of 000-00-0000');
			}
		
		field.focus();
		field.value = '';
		return false;
		}
	else {
		field.value = newVal.substring(0,3) + '-' + newVal.substring(3,5) + '-' + newVal.substring(5,9);
		return true;
		}
	}

function verifyTelephone(e) {
	var field = getEventObject(e);
	
	if(field.value == '') {
		return true;
		}
	
	var regx = new RegExp('[^0-9]', 'g');
	var newVal = field.value.replace(regx, '');
	
	if(newVal.length != 10) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' must be a ten digit telephone number in the format of (123) 456-7890.');
			}
		else {
			alert('Please enter a ten digit telephone number in the format of (123) 456-7890.');
			}
		field.focus();
		field.value = '';
		return false;
		}
	else {
		field.value = '(' + newVal.substring(0,3) + ') ' + newVal.substring(3,6) + '-' + newVal.substring(6,10);
		return true;
		}
	}

function VerifyCreditCardNumber(e) {
	var field = getEventObject(e);
	
	if((field.value == '') || (field.value.indexOf('X') >= 0)) {
		return true;
		}
	
	var regx = new RegExp('[^0-9]', 'g');
	var newVal = field.value.replace(regx, '');
	
	if((newVal.length < 13) || (newVal.length > 16) || (newVal.substring(0,1) < '3') || (newVal.substring(0,1) > '6') || (!LuhnCheckNumber(newVal))) {
		if(field.getAttribute('label')) {
			alert('\'' + field.getAttribute('label') + '\' is not an acceptable credit card number.');
			}
		else {
			alert('This field is not an acceptable credit card number.');
			}
		field.focus();
		field.value = '';
		return false;
		}
	else {
		field.value = newVal;
		return true;
		}
	}


//Browser Specific Event Handling Functions
function createEventHandler(object, eventString, functionString) {
	if(window.addEventListener != null) {
		if(object.id != '')
			eval('document.getElementById(\'' + object.id + '\').addEventListener(\'' + eventString +'\', function(e){' + functionString + '}, true);');
		else if((document.getElementByName != null) && (object.name != ''))
			eval('document.getElementByName(\'' + object.name + '\').item(0).addEventListener(\'' + eventString +'\', function(e){' + functionString + '}, true);');
		}
	else if(window.attachEvent != null) {
		if(object.id != '')
			eval('document.getElementById(\'' + object.id + '\').attachEvent(\'on' + eventString + '\', function(){' + functionString + '});');
		else if((document.getElementByName != null) && (object.name != ''))
			eval('document.getElementsByName(\'' + object.name + '\').item(0).attachEvent(\'on' + eventString + '\', function(){' + functionString + '});');
		}
	return true;
	}

function getEventObject(e) {
	if((window.addEventListener != null) && (e != null)) {
		return e.target;
		}
	else if((window.attachEvent != null) && (event != null)) {
		return event.srcElement;
		}
	else {
		return null;
		}
	}

// Auxillary Functions //
function getNumericValue(numericString) {
	var separator = ',';
	var decimalChar = '.';
	
	if(arguments.length > 1) {
		separator = arguments[1];
		}
	if(arguments.length > 2) {
		decimalChar = arguments[2];
		}
	
	if(numericString == null) {
		return 0;
		}
	
	var regx = new RegExp('\\' + separator, 'g');
	numericString = numericString.replace(regx, '');
	numericString = numericString.replace(decimalChar, '.');
	
	if((numericString == '') || (isNaN(numericString))) { 
		return 0;
		}
	else {
		return parseFloat(numericString);
		}
	}

function round(value, places) {
	var plusPoint5 = new String('.');
	
	for(j=0; j < places; j++) {
		plusPoint5 += '0';
		}
	plusPoint5 += '5';
	
	if(value < 0) {
		valueString = new String(parseFloat(value) - parseFloat(plusPoint5));
		}
	else {
		valueString = new String(parseFloat(value) + parseFloat(plusPoint5));
		}
	
	decimal = valueString.indexOf('.');
	if(decimal > 0) {
		valueString = valueString.substring(0, parseInt(decimal) + parseInt(places) + 1);
		}
	
	if(valueString.indexOf('.') == valueString.length - 1) {
		valueString = valueString.substring(0, valueString.length - 1);
		}
	
	return valueString;
	}

function formatNumber(number) {
	var separator = ',',
	decimalChar = '.';
	
	if(arguments.length > 1) {
		separator = arguments[1];
		}
	if(arguments.length > 2) {
		decimalChar = arguments[2];
		}
	
	var numberString = '' + number;
	var parts = numberString.split('.');
	var wholePart = parts[0];
	var decimalPart = parts.length > 1 ? decimalChar + parts[1] : '';
	
	var regx = /(\d+)(\d{3})/;
	while (regx.test(wholePart)) {
		wholePart = wholePart.replace(regx, '$1' + separator + '$2');
		}
	
	return wholePart + decimalPart;
	}
	
function LuhnCheckNumber(numberString) {
	var sum = 0;
	var alt = false;
	for (var i = numberString.length - 1; i >= 0; i--) {
		var digit = parseInt(numberString.charAt(i));
		if (alt) {
			digit *= 2;
			if (digit > 9)
			    digit -= 9;
			}
		sum += digit;
		alt = !alt;
		}
	return ((sum % 10) == 0);
	}

//postElsewhere reformats ASP.NET control names and posts the data to another page
function postElsewhere(URL) {
	var windowName = '_self';
	
	if(arguments.length > 1) {
		windowName = arguments[1];
		}
	
	var theForm;
	if(window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
		theForm = document.Form1;
	}
	else {
		theForm = document.forms["Form1"];
	}
	
	//Duplicate fields for .NET controls
	newDiv = document.createElement('div');
	for(var e=0; e < theForm.elements.length; e++) {
		if(theForm.elements[e].name.indexOf('$') >= 0) {
			if(theForm.elements[e].value) {
				var newField = theForm.elements[e].cloneNode(false);
				var oldNameParts = theForm.elements[e].name.split('$');
				newField.name = oldNameParts[oldNameParts.length - 1];
				newField.value = theForm.elements[e].value;
				newDiv.appendChild(newField);
				}
			}
		}
	theForm.appendChild(newDiv);
	
	//Store existing values
	var viewStateValue = theForm.__VIEWSTATE.value;
	var formAction = theForm.action;
	var formTarget = theForm.target;
	
	//Set new values
	theForm.__VIEWSTATE.value = '';
	theForm.__VIEWSTATE.name = 'NOVIEWSTATE';
	theForm.action = URL;
	theForm.target = windowName;
	
	theForm.submit();
	
	//Reset stored values
	theForm.__VIEWSTATE.name = '__VIEWSTATE';
	theForm.__VIEWSTATE.value = viewStateValue;
	theForm.action = formAction;
	theForm.target = formTarget;
	theForm.removeChild(newDiv);
	}

