/**
 * Form field checking functions
 *
 * This file contains form field checking functions
 * This file requires form_library.js to function properly
 */

function checkField(formField, errorMsg) {
  if (!checkFieldValue(formField)) {
    alert(errorMsg);
    formField.focus();
    return false;
  }
  return true;
}

function checkFieldValue(formField) {
  if (trim(formField.value) == "") {
    return false;
  }
  return true;
}

function checkSelectField(formField, errorMsg) {
  if (formField.selectedIndex == 0 || !checkSelectFieldValue(formField)) {
    alert(errorMsg);
    formField.focus();
    return false;
  }
  return true;
}

function checkSelectFieldValue(formField, errorMsg) {
  if (trim(formField.options[formField.selectedIndex].value) == "") {
    if (errorMsg) {
      alert(errorMsg);
      formField.focus();
    }
    return false;
  }
  return true;
}

function checkRadioButton(formField, errorMsg) {
  for (radioIndex=0;radioIndex<formField.length;radioIndex++) {
    if (formField[radioIndex].checked) {
      return true;
    }
  }
  alert (errorMsg);
  return false;
}

function emailCheck(formField, errorMsg) {
  var EmailOk = true
  var Temp = formField;
  var AtSym = Temp.value.indexOf('@');
  var Period = Temp.value.lastIndexOf('.');
  var Space = Temp.value.indexOf(' ');
  var Length = Temp.value.length - 1;
  if ((AtSym < 1) || (Period <= AtSym+1) || (Period == Length ) || (Space  != -1)) {
    EmailOk = false;
    alert(errorMsg);
    formField.focus();
  }
  return EmailOk;
}

function emailCheck2(email1Field, email2Field, errorMsg) {
  var EmailOk = true
  var Email1 = email1Field.value;
  var Email2 = email2Field.value;
  if (Email1 != Email2) {
    alert(errorMsg);
    email1Field.focus();
    return false;
  }
  return EmailOk
}

function echeck(str, message) {
  var at    = "@";
  var dot   = ".";
  var lat   = str.indexOf(at);
  var lstr  = str.length;
  var ldot  = str.indexOf(dot);
  if (str.indexOf(at) == -1) {
	   alert(message);
	   return false;
	}

	if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
    alert(message);
    return false;
	}

	if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
    alert(message);
    return false;
	}

  if (str.indexOf(at,(lat+1)) != -1) {
    alert(message);
    return false;
  }

  if (str.substring(lat-1,lat) == dot || str.substring(lat+1,lat+2) == dot) {
    alert(message);
    return false;
  }

  if (str.indexOf(dot,(lat+2)) == -1) {
    alert(message);
    return false;
  }

  if (str.indexOf(" ") != -1) {
    alert(message);
    return false;
	}

		return true;
}

function validateEmail(formField, message) {
	var emailID = formField;

	if ((emailID.value == null) || (emailID.value == "")) {
		alert(message);
		emailID.focus();
		return false;
	}
	if (echeck(emailID.value, message) == false) {
		emailID.value = "";
		emailID.focus();
		return false;
	}

  return true;
}

function checkCountry(formField, errorMsg) {
  if (formField.selectedIndex == 0) {
    //alert('Select a country please!');
    alert(errorMsg);
    formField.focus();
    return false;
  }
  return true;
}

function checkCountryState(countryField, stateField, errorMsg1, errorMsg2) {
  stateUSarray = new Array ("AA","AE","AL","AK","AP","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","VI","WA","WV","WI","WY");
  stateCanadaArray = new Array ("AB","BC","MB","NB","NF","NT","NS","ON","PE","QC","SK","YT");
  indexUS = 1;
  indexCanada = 2;
  countryValue = countryField.value;
  stateValue = countryField.value;
  if (countryValue == indexUS) {
    for (x=0;x<stateUSarray.length;x++) {
      if (stateValue == stateUSarray[x]) return true;
    }
    //alert('Please enter the two character state code.');
    alert(errorMsg1);
    stateField.focus();
    return false;
  } else if (countryValue == indexCanada) {
    for (x=0;x<stateCanadaArray.length;x++) {
      if (stateValue == stateCanadaArray[x]) return true;
    }
    //alert('Please enter the two character province code.');
    alert(errorMsg2);
    stateField.focus();
    return false;
  }
  return true;
}
function checkCountryStateSelect(countryField, stateField, errorMsg1, errorMsg2) {
  stateUSarray = new Array ("AA","AE","AL","AK","AP","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","VI","WA","WV","WI","WY");
  stateCanadaArray = new Array ("AB","BC","MB","NB","NF","NT","NS","ON","PE","QC","SK","YT");
  countryValue = countryField.options[countryField.selectedIndex].value;
  stateValue = stateField.options[stateField.selectedIndex].value;
  if (countryValue == 'US') {
    for (x=0;x<stateUSarray.length;x++) {
      if (stateValue == stateUSarray[x]) return true;
    }
    alert(errorMsg1);
    stateField.focus();
    return false;
  } else if (countryValue == 'CA') {
    for (x=0;x<stateCanadaArray.length;x++) {
      if (stateValue == stateCanadaArray[x]) return true;
    }
    alert(errorMsg2);
    stateField.focus();
    return false;
  }
  return true;
}

function passwordCheck (pass1Field, pass2Field, errorMsg1, errorMsg2) {
  password1 = pass1Field.value;
  password2 = pass2Field.value
  if (password1.length < 4) {
    //alert ('Password must be at least 4 characters long');
    alert(errorMsg1);
    pass1Field.focus();
    return false;
  } else if (password1 != password2) {
    //alert ('Passwords must match');
    alert(errorMsg2);
    pass1Field.focus();
    return false;
  }
  return true;
}

function checkCardExpiration (cardExpMonthField, cardExpYearField, errorMsg)
{
  // perform validation
  currentDate = new Date();
  currentYear = currentDate.getYear();
  if (currentYear < 1990) currentYear+= 1900;

  if (cardExpYearField.value < 2000) {
    cardExpYearField.value='20'+cardExpYearField.value;
  }

  input_month = cardExpMonthField.value;
  input_year  = cardExpYearField.value;

  // determine exit condition
  if ((input_month < 1 || input_month > 12) ||
      (input_year < currentYear || input_year > currentYear + 10) ||
      (input_year == currentYear && input_month < currentDate.getMonth() + 1)
      )  {
    alert (errorMsg);
    cardExpMonthField.focus();
    return false;
  }

  return true;
}

function checkPhoneNumber(formField, errorMsg) {
  var allowedchars = "0123456789()-+ ";
  var i = 0;
  for (i = 0; i <= formField.value.length -1; i++) {
    if (allowedchars.indexOf(formField.value.charAt(i)) == -1) {
      alert(errorMsg);
      return false;
    } // End if statement
  } // End for loop
  return true;
}

function checkName(nameField, errorMsg) {
  if (nameField.value.search(/^[\sa-zA-Z\'\-]+$/) != -1) {
    return true;
  }
  else {
    nameField.focus();
    alert(errorMsg);

    return false;
  }
}

function checkTextBoxAgainstSelectBox(objSelectBox, objTextBox, errorMsg, objLabel) {
  var flag        = false;
  var hCode       = objTextBox.value;
  var selectValue = null;

  hCode = hCode.replace(/^\s*|\s*$/g,"");
  hCode = hCode.toUpperCase();

  if (hCode != null && hCode != '') {
    for (var i = 0; i < objSelectBox.length; i++) {
      if (objSelectBox[i].value.toUpperCase() == hCode) {
        objSelectBox[i].selected = true;
        flag = i;
        break;
      }
    }

    if (flag == false) {
      alert(hCode + ' ' + errorMsg);
      objTextBox.value = null;
      return false;
    }
    else {
      if (objLabel) {
        objLabel.innerHTML = objSelectBox.options[flag].text;
      }
    }
  }
  objTextBox.value = hCode;
}


function checkBirthdate(yearObj, monthObj, dayObj, errorMsg)
{
  today = new Date();

  year   = new Number(yearObj.options[yearObj.selectedIndex].value);
  month  = new Number(monthObj.options[monthObj.selectedIndex].value);
  day    = new Number(dayObj.options[dayObj.selectedIndex].value);

  bdate_timestamp = (fixYear(year)*10000) + (month*100) + day;
  tdate_timestamp = (fixYear(today.getYear())*10000) + ((today.getMonth() + 1)*100) + today.getDate();  // getMonth() returns 0..11

  if (bdate_timestamp > tdate_timestamp) {
    alert(errorMsg)
    return false;
  }

  return true;
}

function alertError(formObj,errorMsg)
{
  if (errorMsg && errorMsg.length) {
    alert(errorMsg);
  }

  formObj.focus();
  return false;
}

function integerCheck(inputObj, errorMsg, updateValue)
{
  num = new Number(inputObj.value);

  if (isNaN(num)) {
    return alertError(inputObj, errorMsg);
  }

  intVal = parseInt(inputObj.value);

  if (intVal.toString().length != inputObj.value.length) {
    return alertError(inputObj, errorMsg);
  }

  if (updateValue) {
    inputObj.value = intVal;
  }

  return true;
}

function floatCheck(inputObj, errorMsg, allowInt, updateValue)
{
  num = new Number(inputObj.value);

  if (isNaN(num)) {
    return alertError(inputObj, errorMsg);
  }

  if (!allowInt && inputObj.value.search(/\./) == -1) {
    // Did not find a "." so not a valid float.
    return alertError(inputObj, errorMsg);
  }

  if (updateValue) {
    inputObj.value = num;
  }

  return true;
}

function urlCheck(inputObj, errorMsg)
{
  if (inputObj.value.search(/^(ht|f)tp(s)*\:\/\/([a-z0-9]+[a-z0-9_-]*[\.]{1,1})+[a-z]{2,6}[\/]*$/) == -1 &&
      inputObj.value.search(/^([a-z0-9]+[a-z0-9_-]*[\.]{1,1})+[a-z]{2,6}$/) == -1) {
    return alertError(inputObj, errorMsg);
  }

  return true;
}

function colorCheck(inputObj, errorMsg)
{
  if (inputObj.value.toUpperCase().search(/^\#([A-H0-9]){6,6}$/) == -1) {
    return alertError(inputObj, errorMsg);
  }

  return true;
}

/**
 * Check to see if card expires before final payment due date.
 *
 * @param (Form Object) formName
 * @return bool
 */
function checkFinalDueDateWithCreditCardExpiryDate(form_object, final_payment_date)
{
  // Disregard check if no expiry year select
  if (!form_object.ccValidTilYear || form_object.ccValidTilYear.selectedIndex == 0) {
    return true;
  }

  // Disregard check if no expiry month select
  if (!form_object.ccValidTilMonth || form_object.ccValidTilMonth.selectedIndex == 0) {
    return true;
  }

  // Disregard check if no final payment date.
  if (!final_payment_date || !final_payment_date.length) {
    return true;
  }

  expiry_year  = form_object.ccValidTilYear.options[form_object.ccValidTilYear.selectedIndex].value;
  expiry_month = form_object.ccValidTilMonth.options[form_object.ccValidTilMonth.selectedIndex].value;
  expiry       = new Date(expiry_year, expiry_month - 1);

  // We expect final due date in the format 'yyyy-mm-dd hh:mm:ss' or 'yyyy-mm-dd'.
  try {
    final_payment_date = final_payment_date.split(' ');
    final_payment_date = final_payment_date[0];
    final_payment_date = final_payment_date.split('-');

    final_date = new Date(final_payment_date[0], final_payment_date[1] - 1);
  }
  catch(ex)
  {
    // There was an error with the date conversion.
    // Not the customers fault, we must have sent a bad final_payment_date to the template.
    return true;
  }

  if (final_date.getTime() > expiry.getTime()) {
    return false;
  }


  return true;
}

/**
 * Determines if form_object contains a valid phone number.
 *
 * @param (Form Object) form_object
 * @return bool
 */
function isValidPhone(form_object)
{
  var phone = form_object.value;

  // Removing non-digit characters for validation check
  phone = phone.replace(/[^0-9]/g, '');

  // Phone numbers shorter 10 digits or longer than 15 digits are not valid
  if (phone.length < 10 || phone.length > 15) {
    return false;
  }

  // All 0's phone numbers are not valid
  phone = phone.replace(/0/g, '');
  if (!phone) {
    return false;
  }

  return true;
}