function isEmail(fld, name) {
	if (fld.value.length) {
		if (!checkEmail(fld.value)) {
			alert(name+' does not appear to be a valid format, or has illegal characters.  Email addresses must be in xxx@xxx.com format.');
			fld.focus();
			fld.select();
			return false;
		}
	}
	return true;
}

function isEmailMark(fld, name) {
	if (fld.value.length) {
		if (!checkEmail(fld.value)) {
			$('email_format').style.display = '';
			fld.focus();
			fld.select();
			return false;
		}
	}
	$('email_format').style.display = 'none';
	return true;
}


function checkEmail(checkme) {
emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/i
return emailRe.test(checkme);
}

function isNumeric(fld, name) {
	if (fld.value.length) {
		if (isNaN(fld.value)) {
			alert(name+' must be a number.  Please do not include commas or non-numeric characters in your submission.');
			fld.focus();
			fld.select();
			return false;
		}
	}
	return true;
}

function hasNumeric(inpt) {
	er = /[1-9]/;
	return er.test(inpt);
}

function isMoney(fld, name, xmatch) {
	// strip all the currency stuff
	money = _removeCurrency(fld.value);
	if (fld.value.length) {
		if (isNaN(money) || !money.length) {
			alert(name+' appears to be an invalid money format.  Please do not include commas or dollar signs in your submission.');
			fld.focus();
			fld.select();
			return false;
		} else if (money > 99999) {
			alert(name+' is greater than $99,999.  Please enter a lower value.');
			fld.focus();
			fld.select();
			return false;
		} else {
			money -= 0;
			money = (money == Math.floor(money)) ? money + '.00' : ( (money*10 == Math.floor(money*10)) ?  money + '0' : money);
			// money = Math.round(money*100)/100;
			fld.value = money;
		}

	}

	return true;
}

function isRequiredMark(fld, name) { // to mark fields
	var reqtxtid = fld.name + "_required";
	$(fld);
	fld.removeClass('required');
	$(reqtxtid).style.display = 'none';
	if (fld.optional) return true;
	
	if (fld.disabled) return true;
	if (!fld.value.length) {
		fld.addClass('required');
		$(reqtxtid).style.display = '';
		try { // non-visibile element cannot be focused in IE7
			fld.focus();
			if (!fld.options) {
				fld.select();
			}
		} catch(error) {}
		return false;
	}
	
	return true;
}

function isRequiredSelectMark(fld, name) {
	var reqtxtid = fld.name + "_required";
	$(fld);
	fld.removeClass('required');
	$(reqtxtid).style.display = 'none';
	if (!fld.options[fld.selectedIndex].value.length) {
		fld.addClass('required');
		$(reqtxtid).style.display = '';
		fld.focus();
		return false;
	}

	return true;

}	

function isRequired(fld, name) {
	if (fld.disabled) return true;
	if (!fld.value.length) {
		alert(name+' is a required field.');
		fld.focus();
		if (!fld.options) {
			fld.select();
		}
		return false;
	}

	return true;
}

function isMinimum(fld, name, minimum) {
	if (fld.disabled) return true;
	if (fld.value.length < minimum) {
		alert(name+' requires a minimum character count of '+minimum);
		fld.focus();
		fld.select();
		return false;
	}
	return true;
}

function isRequiredSelect(fld, name) {
	if (!fld.options[fld.selectedIndex].value.length) {
		alert(name+ ' is a required field.');
		fld.focus();
		return false;
	}

	return true;

}

function isDate(fld, name) {
	if (fld.value.length) {

		date = _validateUSDate(fld.value);

		if (!date.length) {
			alert(name+' appears to be invalid.  Please use the mm/dd/yyyy format.');
			fld.focus();
			fld.select();
			return false;
		} else {
			fld.value = date;
		}

	}

	return true;
}

function isIdentical(fld1, fld2, label1, label2) {

	if (fld1.value !== fld2.value) {
		alert(label1+' does not match '+label2+'.');
		fld2.focus();
		fld2.select();
		return false;
	} else {
		if (!isRequired(fld1, label1)) return false;
	}

	return true;
}

function isReserved(fld, name, value) {

	if (fld.value.length) {
		reserved = Array('guest','admin');

		val = fld.value.toLowerCase();
		val = escape(val);

		for (i=0;i<reserved.length;i++) {
			if (value != reserved[i]) {
				if (val == reserved[i]) {
					if (val != value) {
						alert(name+' is a reserved word and cannot be used!');
						fld.focus();
						fld.select();
						return false;
					}
				}
			} else {
				fld.value = value;
			}
		}

		if (val.indexOf('%20', 0) >= 0) {
			alert(name+' must not contain spaces.');
			fld.focus();
			fld.select();
			return false;
		}

	}

	// if (!isRequired(fld, name)) return false;

	return true;
}

function hasIllegalChar(fld, name, xchar) {

	if (fld.value.indexOf(xchar) >= 0) {
		alert("'" + xchar + "' is not allowed in " + name);
		fld.focus();
		return true;
	}

	return false;

}

function FixPhoneField(phoneField, name) {

	if (phoneField.value.length) {
		var phone = phoneField.value;
		phone = phone.replace(/[^0-9]/g, "");

		if (phone.length != 10) {
			alert(name + " does not appear to be a valid format.  Phone numbers must by in the 111-111-1212 format.");
			phoneField.focus();
			return false;
		}

		phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
		phoneField.value = phone;

		return true;
	}

	return true;
}

function isYear(fld, name) {

	if (fld.value.length) {

		if (isNumeric(fld,name)) {

			if (fld.value < 50) fld.value = parseInt(Math.round(fld.value)) + 2000;
			else if (fld.value < 100 && fld.value > 50) fld.value = parseInt(Math.round(fld.value)) + 1900;

				return true;

		} else {

			alert(name+' appears to be invalid.  Please use the 20xx format.');
			fld.focus();
			fld.select();
			return false;

		}

	}

	return true;

}



function _removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';

  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]|[a-zA-Z]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function _validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/

  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return ''; //doesn't match pattern, bad date
  else{
    var strSeparator = strValue.substring(2,3) //find date separator
		if (!isNaN(strSeparator)) {
			var strSeparator = strValue.substring(1,2) //find date separator
		}
    var arrayDate = strValue.split(strSeparator); //split date into month, day, year
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
    var intDay = arrayDate[1]; // if (intDay < 10) { intDay = '0' + intDay; }
    var intYear = arrayDate[2];
    var intMonth = arrayDate[0]; // if (intMonth < 10) { intMonth = '0' + intMonth; }

    if (intYear == '00') { intYear = '2000'; } else if (intYear < 50) { intYear = parseInt(intYear) + 2000; } else if (intYear > 50 && intYear < 100) { intYear = parseInt(intYear) + 1900; }

    //check if month value and day value agree
    if(arrayLookup[intMonth] != null) {
      if(intDay <= arrayLookup[intMonth] && intDay != 0)
        return intMonth+'/'+intDay+'/'+intYear; //found in lookup table, good date
    }

    //check for February
    if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
      return intMonth+'/'+intDay+'/'+intYear; //Feb. had valid number of days
  }
  return ''; //any other values, bad date
}

	function validateLoadCity(fld,lbl) {

		fld.value = trim_frontandend_whitespace(fld.value);
		str = fld.value;
		str = str.toLowerCase();

		if (str.length <= 5) strTestLength = str.length; else strTestLength = 5;
		intRepCons = 0;

		var ll=""; var lll="";
		arChar = new Array();
		var isOkay = true;

		// Immediately allow a few patterns

			// Allow 29 palms
			// if (str == '29 palms') return true;

			// Allow single character followed by an apostrophe
			re = /^[a-z]'/;
			if (re.test(str)) return true;
//de	alert("made it out");
		// Start rules

		re = /^[a-z]/;
		if (!re.test(str)) isOkay = false; // RULE 1
		re = /^[a-f]/i;
		if (re.test(str)) {  // LIMIT TO A-F

			re = /^[a-d][^a-z]/;  // RULE 2
			if (re.test(str)) isOkay = false;


			if (str.length < 3) isOkay = false; // Not a specified rule
			for (i=0; i < strTestLength; i++) {
				if (i == 1 && ll.toLowerCase() == str.charAt(i) && str.charAt(i) != 'e') isOkay = false; // RULE 6
				if (ll.toLowerCase() == str.charAt(i)) intRepCons++ // Prep - rule 4
				if (ll.toLowerCase() == str.charAt(i) && lll.toLowerCase() == str.charAt(i)) isOkay = false; // RULE 3
				if (str.charAt(i) == "-" && i < 5) isOkay = false; // Dash in first four characters
				lll = ll;
				ll = str.charAt(i);
				if (i < 5) arChar.push(str.charCodeAt(i)); // Check first four characters for consecutive characters
			}

			if (intRepCons > 1) isOkay = false; // RULE 4

			re = /^[a-c][a-z][^a-z]/; // RULE 5
			if (re.test(str)) isOkay = false;


			var isConsec = 0; consecNum = 0; // Check for consecutive characters
			for (i=0; i < arChar.length; i++) {
				if (i==0) {
					sCharCode = arChar[i];
				} else if ( (arChar[i] - sCharCode == i) ) {
					consecNum++;
				}
			}

			if (consecNum > 2) isConsec = 1; // More than two consecutive numbers a-f

			if (isConsec) isOkay = false;
		}

		if (!isOkay) {
			alert('This form was not submitted. The following city name contains an invalid portion:\n' + fld.value + ' \n\nPlease do not attempt to enter non-related words for origination or destination cities.\n\nThank you for your cooperation.');
			fld.focus();
		}
		return isOkay;

	}

	function validateUsername(el,lbl) {
		str = el.value;
		if (!isRequired(el,lbl)) return false;
		if (str.match('[0-9a-zA-Z]{2,8}') != str) {
			alert(lbl + " must be 2-8 characters long, using ONLY letters and digits.");
			return false;
		}
		return true;
	}
	
	function validateUsernameMark(el,lbl) {
		str = el.value;
		if (!isRequiredMark(el,lbl)) return false;
		if (str.match('[0-9a-zA-Z]{2,8}') != str) {
			$('username_info').style.display = '';
			return false;
		}
		$('username_info').style.display = 'none';
		return true;
	}	

	function isFirstLast(el,lbl) {
		str = el.value;
		if (str.indexOf(' ') == -1) {
			alert(lbl + ' must contain a first AND last name.');
			el.focus();
			if (!el.options) { el.select(); }
			return false;
		}
		return true;
	}
	
	function isFirstLastMark(el,lbl) {
		str = el.value;
		if (str.indexOf(' ') == -1) {
			$('owner_mgr_firstlast').style.display = '';
			if (!el.options) { el.select(); }
			return false;
		}		
		$('owner_mgr_firstlast').style.display = 'none';
		return true;
	}	

	// used to protect against inadvertent refresh, navigate away or close -
	// used in conjunction with deactivate_watch_and_submit() in php
	// that function replaces the submit input field entirely, it returns one
	// then for @#$!#$% IE, you need to put one of these in each input field:
	// <?= watch_input() ?>  --- needed in the FORM field as well!! (for Firefox)
	// the php for both is as follows:
	//
	// function deactivate_watch_and_submit($form, $value="Submit") {
	// 		return "<input type='button' onClick=\"form_release(); this.form.submit();\" value='$value'>";
	// }
	//
	// function watch_input() {
	// 		return " onClick=\"form_hold();\" ";
	// }

	function really_close () { return "If you leave this page, all the work you did will be lost."; }
	function form_release() { window.onbeforeunload = null; }
	function form_hold() { window.onbeforeunload = really_close; }

//function getUnloadPromptMsg() { return "If you leave this page, all the work you did will be lost."; }
//function enableUnloadPrompt(enabled) { window.onbeforeunload = enabled ? getUnloadPromptMsg : null; }

function trim_frontandend_whitespace (value) {
	var start=-1;
	var end=-1;
	for(x=0; start==-1; ++x) if (value.charAt(x) != ' ') start = x;
	for(x=value.length-1; end==-1; --x) if (value.charAt(x) != ' ') end = x;

	value = value.substr(start,end+1);
	return value;
}

function confirmSubmitNoZips( multiple ) {
	if (multiple) {
		return confirm('Warning: You are about to submit one or more loads without valid zip codes.\nThose loads will not qualify for the "Zips Validated" icon on the Search Vehicles page.\n\n\nClick OK to accept these loads without zip codes or Cancel to add the zips.');
	} else {
		return confirm('Warning: You are about to submit this load without valid zip codes.\nYour load will not qualify for the "Zips Validated" icon on the Search Vehicles page.\n\n\nClick OK to accept this load without zip codes or Cancel to add the zips.');
	}
}

/* ****** rc 01/23/08 adapted from Intranet for checking form before leaving page ********** */

// must document.body.onBeforeUnload="return leavePage()";
var __unsubmitted = false; // <form> page must "setUnsubmitted(true, form, ['excluded','inputs'])" to enable
var __form;				   //   AND include "&& setUnsubmitted(false)" in onsubmit
var __exclude;
var __holdUnsubmitted = false; // for <a> focus/blur to put back to prior setting
function setUnsubmitted( unsub, form, exclude ) {
	__unsubmitted = unsub;
	__form = form;
	__exclude = exclude;
	return true;
}
// exclude links where HREF="JAVASCRIPT"..."
// must ensure no other links have 'javascript' // use '#' and onclick instead
// also had to hard code focus/blur in dynCalendar popup links since links are not in the DOM when this runs
function setExcludedLinks( ) {
	var links = document.getElementsByTagName('a');
	for (var i = 0; i < links.length; ++i) {
		var el = links[i];
		if (el.href.search(/javascript:/) == 0) {
			el.onfocus = function() {__unsubmitted = false};
			el.onblur = function() {__unsubmitted = true};
		}
	}
}
function leavePage( ) {
	if (!__unsubmitted || !__form) {
		return '';
	}
	var warn = false;
	for (var i = 0; i < __form.elements.length; ++i) {
		var el = __form.elements[i];
		if (__exclude && __exclude.indexOf(el.name) > -1) {
			continue;
		}
		if (el.disabled) {
			continue;
		}
//console.log(el.name);
		switch (el.type) {
			case 'button':
				continue;
			case 'select-one':
			case 'select-multiple':
				var opts = el.options;
				for (var q = 0; q < opts.length; ++q) {
					if (opts[q].selected != opts[q].defaultSelected) {
//console.log('1: ' + el.name, opts[q].selected + ' != ' + opts[q].defaultSelected, opts[q].value + ' != ' + opts[q].defaultValue);
						warn = true;
						break;
					}
				}
				break;
			case 'checkbox':
			case 'radio':
				if (el.checked != el.defaultChecked) {
//console.log('2: ', el.name);
					warn = true;
				}
				break;
			default:
				if (el.value != el.defaultValue) {
//console.log('3: ', el.name, el.value + ' != ' + el.defaultValue);
					warn = true;
				}
		}
		if (warn) {
			return 'Unsaved changes have been made on this page.';
		}
	}
//return 'x';
	return '';
}
