// Helper function: determines if a field is blank
function isBlank (field) {
  if ((field.value == null) || (field.value == "")) {
    return true;
  }

// This function does not work... if it is fixed, change this line so it actually runs!
  return false;
  for (var i= 0; i < field.length; i++) {
    var currentChar= charAt (i);

    if ((currentChar != ' ') && (currentChar != '\n') && (currentChar != '')) {
      return false;
    }

    return true;
  }
}

// Verify the form fields for shipments
function verifyShipment (form) {
  var message;
  var emptyFields= "";
  var errors= "";

  if (document.getElementById('hazmat_form')) {
    if (!document.advanced_shipment_lock) {
      document.main_form.hazmat_contents.optional= 1;
      if (document.main_form.hazmat[0].checked) {
        if (isBlank(document.main_form.hazmat_contents)) {
          emptyFields+= "\n-hazmat_contents";
        }
        if (!document.main_form.hazmat_packaged[0].checked && !document.main_form.hazmat_packaged[1].checked && !document.advanced_shipment_lock) {
          emptyFields+= "\n-hazmat_packaged";
        }
        if (!document.main_form.hazmat_labeled[0].checked && !document.main_form.hazmat_labeled[1].checked && !document.advanced_shipment_lock) {
          emptyFields+= "\n-hazmat_labeled";
        }
        if (!document.main_form.hazmat_eligible_to_fly[0].checked && !document.main_form.hazmat_eligible_to_fly[1].checked && !document.advanced_shipment_lock) {
          emptyFields+= "\n-hazmat_eligible_to_fly";
        }
      } else if (!document.main_form.hazmat[1].checked) {
        emptyFields+= "\n-hazardous_materials";
      }
    }
  } else {
    if (!document.main_form.hazmat[1].checked && !document.advanced_shipment_lock) {
      if (document.main_form.hazmat[0].checked) {
        emptyFields+= "\n-hazardous_materials (cannot use online form)";
      } else {
        emptyFields+= "\n-hazardous_materials";
      }
    }
  }

  for (var i= 0; i < form.length; i++) {
    var field= form.elements[i];
    if (((field.type == "text") || (field.type == "textarea")) && !field.optional) {
      if (isBlank (field)) {
        emptyFields+= "\n-" + field.name;
      }
    }
  }

  emptyFields+= checkStates (form);
  emptyFields+= checkChronology (false);

  if (document.main_form.vehicle_required.value == "Select") {
    emptyFields+= "\n-You must specify Vehicle Requirements";
  }

  var contentField= document.main_form.contents.value;
  if (contentField.length < 5) {
    emptyFields+= "\n-contents (must enter at least 5 characters)";
  }

  if (!document.main_form.accept_terms.checked) {
    emptyFields+= "\n-You must accept the terms and conditions";
  }

  if (!checkEmailList(document.main_form.cc_list)) {
      emptyFields+= "\n-Your notification e-mail list must be a set of valid e-mail addresses separated by commas";
  }

  if (!emptyFields) return true;

  message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n\n";
  message+= "The following required fields are empty:" + emptyFields + "\n";

  alert (message);
  return false;
}

// Verify the form fields for srq shipments
function verifySRQShipment (form) {
  var message;
  var emptyFields= "";
  var errors= "";

  if (document.getElementById('hazmat_form')) {
    document.main_form.hazmat_contents.optional= 1;
    if (document.main_form.hazmat[0].checked) {
      if (isBlank(document.main_form.hazmat_contents)) {
        emptyFields+= "\n-hazmat_contents";
      }
      if (!document.main_form.hazmat_packaged[0].checked && !document.main_form.hazmat_packaged[1].checked && !document.advanced_shipment_lock) {
        emptyFields+= "\n-hazmat_packaged";
      }
      if (!document.main_form.hazmat_labeled[0].checked && !document.main_form.hazmat_labeled[1].checked && !document.advanced_shipment_lock) {
        emptyFields+= "\n-hazmat_labeled";
      }
      if (!document.main_form.hazmat_eligible_to_fly[0].checked && !document.main_form.hazmat_eligible_to_fly[1].checked && !document.advanced_shipment_lock) {
        emptyFields+= "\n-hazmat_eligible_to_fly";
      }
    } else if (!document.main_form.hazmat[1].checked) {
      emptyFields+= "\n-hazardous_materials";
    }
  }

  for (var i= 0; i < form.length; i++) {
    var field= form.elements[i];
    if (field.required) {
      if (isBlank (field)) {
        emptyFields+= "\n-" + field.name;
      }
    }
  }

  emptyFields+= checkChronology (true);

  if (!document.main_form.accept_terms.checked) {
    emptyFields+= "\n-You must accept the terms and conditions";
  }

  if (!emptyFields) return true;

  message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n\n";
  message+= "The following required fields are empty:" + emptyFields + "\n";

  alert (message);
  return false;
}

// Verify the form fields for quotes
function verifyFreeQuote (form, emptyFields) {
  var error= false;

  if (!emptyFields) {
    emptyFields= "";
  }

  if (isBlank (form.name)) {
    emptyFields+= "\n-name";
  }

  if (isBlank (form.email)) {
    emptyFields+= "\n-email";
  }

  if (isBlank (form.phone)) {
    emptyFields+= "\n-phone";
  }

  if (!emptyFields) return true;

  var message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n\n";
  message+= "The following required fields are empty:" + emptyFields + "\n";

  alert (message);
  return false;
}

function verifyQuote (form) {
  var emptyFields= "";

  for (var i= 0; i < form.length; i++) {
    var field= form.elements[i];
    if (field.required) {
      if (isBlank (field)) {
        emptyFields+= "\n-" + field.name;
      }
    }
  }

  emptyFields+= checkStates (form);

  return verifyFreeQuote (form, emptyFields);
}

function checkYear (field) {
  var year= new Date().getFullYear ();

  if (isNaN(field.value) || field.value < year) {
    field.value= year;
  }
}

function checkInt (field) {
  if (isNaN (field.value) || isBlank (field) || field.value <= 0) {
    field.value= "";
  } else {
    field.value= Math.ceil (field.value);
  }
}

function checkFloat (field, max) {
  if (isNaN (field.value) || isBlank (field)) {
    field.value= "";
  } else {
    field.value= (Math.floor (field.value * 100)) / 100;
    if (field.value > max) {
      field.value= max;
    }
  }
}

function checkText (field, maxLength) {
  if (field.value.length >= maxLength) {
    field.value= field.value.substring (0, maxLength);
  }
}

function checkSpecialInstructions (field, maxLength, blockId) {
  checkText (field, maxLength);
  document.getElementById (blockId).innerHTML= field.value.length;
}

function setDates () {
  var day= new Date ();
  if (document.pickupDate) {
    day= new Date (document.pickupDate);
  }

  document.main_form.pickup_date_month.value= day.getMonth () + 1;
  document.main_form.pickup_date_year.value= day.getFullYear ();

  updateMonth ("pickup_date");
  document.main_form.pickup_date_day.value= day.getDate ();

  if (document.deliveryDate) {
    day= new Date (document.deliveryDate);
  } else {
    day.setDate(day.getDate() + 1);
  }

  document.main_form.delivery_date_month.value= day.getMonth () + 1;
  document.main_form.delivery_date_year.value= day.getFullYear ();

  updateMonth ("delivery_date");

  document.main_form.delivery_date_day.value= day.getDate ();
}

function setPickupTimes () {
  document.main_form.pickup_ready_time.value= document.pickupReadyTime ? document.pickupReadyTime : "08:00:00";
  document.main_form.close_time.value= document.closeTime ? document.closeTime : "17:00:00";
  if (document.deliveryTime) document.main_form.delivery_time.value= document.deliveryTime;
}

function checkStates (form) {
  var emptyFields= "";

  if (form.to_state.value == "Other") {
    if (isBlank (form.to_state_other)) {
      emptyFields+= "\n-to_state_other";
    }
  }
  if (form.from_state.value == "Other") {
    if (isBlank (form.from_state_other)) {
      emptyFields+= "\n-from_state_other";
    }
  }

  return emptyFields;
}

function updateState (block) {
  document.main_form[block + "state_other"].disabled= (document.main_form[block + "state"].value != "Other");
}

function verifyUser (form, password) {
  var error= "";

  if (isBlank (form.username)) {
    error+= "\n-You must enter a user name";
  }
  if (isBlank (form.user_password) && password) {
    error+= "\n-You must enter a password";
  } else {
    if (form.user_password.value != form.user_password2.value) {
      error+= "\n-Submitted passwords do not match";
    }
  }

  error+= verifyRoles ();

  if (!error) return true;

  var message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n" + error;

  alert (message);
  return false;
}

function verifyUserRequest (form, password) {
  var error= "";

  if (isBlank (form.fullname)) {
    error+= "\n-You must enter a full name";
  }
  if (isBlank (form.email)) {
    error+= "\n-You must enter an email address";
  }
  if (isBlank (form.phone_area) && isBlank (form.phone_exchange) && isBlank (form.phone_number)) {
    error+= "\n-You must enter a contact number";
  }
  if (isBlank (form.client)) {
    error+= "\n-You must enter a client name";
  }

  error+= verifyRoles ();

  if (!error) return true;

  var message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n" + error;

  alert (message);
  return false;
}

function deleteUser (user_id, username) {
  var message= "Are you sure you want to delete user " + username + " from the system?";
  if (confirm (message)) {
    document.location= "user_admin.php?rm=delete_user&id=" + user_id;
    return true;
  }
}

function copyUser (user_id, username) {
  var message= "Enter a new username for the copy of user '" + username + "'";
  if (response= prompt (message, "New User")) {
    document.location= "user_admin.php?rm=copy_user&id=" + user_id + "&name=" + response;
    return true;
  }
}

function resetUserPassword (user_id, username, password, email) {
  var message= "User " + username + "'s password will be changed to '" + password + "', and this new password will be sent to the following e-mail address.";
  response= prompt (message, email);
  if (response) {
    document.location= "user_admin.php?rm=reset_password&id=" + user_id +"&pw=" + password + "&email=" + response;
    return true;
  }
}

function getDate (block) {
  var day= document.main_form[block+"_day"].value;
  var month= document.main_form[block+"_month"].value - 1;
  var year= document.main_form[block+"_year"].value;

  if (!year) {
    day= document[block+"_day"];
    month= document[block+"_month"] - 1;
    year= document[block+"_year"];
  }

  var date= new Date (year, month, day);

  return date;
}

function checkDate (block, srq) {
  var emptyFields= "";

  scriptDate= getDate (block);

  var today= new Date ();
  today.setHours (0, 0, 0, 0);

  if (srq) {
    today.setTime (today.getTime() - (30 * (1000 * 60 * 60 * 24)));

    if (scriptDate < today) {
      emptyFields+= "\n-" + block + " must not be more than 30 days in the past";
    }

  } else {
    if (scriptDate < today) {
      emptyFields+= "\n-" + block + " must not be in the past";
    }
  }

  if (document.main_form[block+"_day"].disabled == false) {
    var formDate= document.main_form[block+"_day"].value;

    if (formDate != scriptDate.getDate ()) {
      emptyFields+= "\n-" + block + " (invalid date)";
    }
  }

  return emptyFields;
}

function verifyRoles () {
  if (!(document.main_form.phone_area.value.length == 3 &&
      document.main_form.phone_exchange.value.length == 3 &&
      document.main_form.phone_number.value.length == 4)) {
    if (!(document.main_form.phone_area.value.length == 0 &&
        document.main_form.phone_exchange.value.length == 0 &&
        document.main_form.phone_number.value.length == 0)) {
      return "\n-contact_number (incomplete).";
    } else {
      if (document.main_form.role_11.checked) {
        return "\n-contact_number";
      }
    }
  }

  return "";
}

// Makes sure pickup is before delivery
function checkChronology (srq) {
  var emptyFields= "";

  emptyFields+= checkDate ("pickup_date", srq);
  emptyFields+= checkDate ("delivery_date", srq);

  pickupDate= getDate ("pickup_date");
  deliveryDate= getDate ("delivery_date");
  var deliveryMessage;

  var lastDay= new Date (); // The latest the pickup date can be - 60/180 days after creation/now
  var daysAllowed1= srq ? 180 : 60;
  if (document.createdDate) {
    deliveryMessage= "\n-delivery_date must not be more than "+daysAllowed1+" days after creation";

    lastDay.setTime (document.createdDate.getTime() + (daysAllowed1 * (1000 * 60 * 60 * 24)));

    if (pickupDate > lastDay) {
      emptyFields+= "\n-pickup_date must not be more than "+daysAllowed1+" days after creation";
    }
  } else {
    deliveryMessage= "\n-delivery_date must not be more than "+daysAllowed1+" days in the future";

    lastDay.setTime (lastDay.getTime() + (daysAllowed1 * (1000 * 60 * 60 * 24)));

    if (pickupDate > lastDay) {
      emptyFields+= "\n-pickup_date must not be more than "+daysAllowed1+" days in the future";
    }
  }

  // Delivery date cannot be more than 30 days after pickup date or 60 days in the future
  var lastDay2= new Date ();
  var daysAllowed= srq ? 90 : 30;
  lastDay2.setTime (pickupDate.getTime() + (daysAllowed * (1000 * 60 * 60 * 24)));
  if (lastDay > lastDay2) {
    lastDay= lastDay2;
    deliveryMessage= "\n-delivery_date must not be more than "+daysAllowed+" days after pickup_date";
  }

  if (deliveryDate > lastDay) {
    emptyFields+= deliveryMessage;
  }

  if (emptyFields == "") {
    pickupDate= getDate ("pickup_date");
    deliveryDate= getDate ("delivery_date");

    if (srq) {
      if (pickupDate > deliveryDate) {
        emptyFields= "\n-delivery_date (must not be before pickup_date)";
      }
    } else {
      if (pickupDate >= deliveryDate) {
        emptyFields= "\n-delivery_date (must be after pickup_date)";
      }
    }
  }

  if (!srq) {
    var pickup= document.main_form.pickup_ready_time.value;
    var close= document.main_form.close_time.value;

    if (!(pickup == "" || pickup == "AM:WND" || pickup == "PM:WND" || close == "") && pickup > close) {
      emptyFields+= "\n-close time (must not be before pickup ready time)";
    }
  }

  return emptyFields;
}

// Adds dimensions fields to shipment forms
function addDimensions () {
  var dimension= document.getElementById ("dim1");

  if (dimension.style.display == "none") {
    dimension.style.display= "block";
  } else {
    dimension= document.getElementById ("dim2");
    if (dimension.style.display == "none") {
      dimension.style.display= "block";
    } else {
      dimension= document.getElementById ("dim3");
      dimension.style.display= "block";
      button= document.getElementById ("dims_button");
      button.style.display= "none";
      dimNotes= document.getElementById ("dim_notes");
      dimNotes.style.display= "block";
    }
  }
}

// Verify the form fields for addresses
function verifyAddress (form) {
  var message;
  var emptyFields= "";
  var errors= "";

  for (var i= 0; i < form.length; i++) {
    var field= form.elements[i];
    if (((field.type == "text") || (field.type == "textarea")) && !field.optional) {
      if (isBlank (field)) {
        emptyFields+= "\n-" + field.name;
      }
    }
  }

  if (form.state.value == "Other") {
    if (isBlank (form.state_other)) {
      emptyFields+= "\n-state_other";
    }
  }
  if (!emptyFields) return true;

  message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n\n";
  message+= "The following required fields are empty:" + emptyFields + "\n";

  alert (message);
  return false;
}

// Verify the form fields for contacts
function verifyContact (form) {
  var message;
  var emptyFields= "";
  var errors= "";

  for (var i= 0; i < form.length; i++) {
    var field= form.elements[i];
    if (((field.type == "text") || (field.type == "textarea")) && !field.optional) {
      if (isBlank (field)) {
        emptyFields+= "\n-" + field.name;
      }
    }
  }

  if (!emptyFields) return true;

  message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n\n";
  message+= "The following required fields are empty:" + emptyFields + "\n";

  alert (message);
  return false;
}

function getMonthLength (month, year) {
  var monthLengths= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  if (month == 1) {
    var date= new Date (year, 1, 29);
    if (date.getDate () == 29) {
      return 29;
    }
  }

  return monthLengths[month];
}

function updateMonth (block) {
  var month= document.main_form[block+"_month"].value - 1;
  var year= document.main_form[block+"_year"].value;
  var oldDay= document.main_form[block+"_day"].value;

  if (document.abbreviate) {
    var dayNames= ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  } else {
    var dayNames= ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  }

  var date= new Date (year, month, 1);
  weekday= date.getDay ();

  options= document.main_form[block+"_day"].options;
  while (options.length > 0) {
    options[0]= null;
  }

  var monthLength= getMonthLength (month, year);
  for (var i= 0; i < monthLength; i++) {
    options[i]= new Option (""+(i+1)+" "+dayNames[(i+weekday)%7], i+1);
  }

  if (oldDay > monthLength) {
    oldDay= monthLength;
  }
  document.main_form[block+"_day"].value= oldDay;
}

function updateCountry (state, country) {
  var value= state.options[state.selectedIndex].value;

  if (value == "Other") {
    return;
  }

  if (value == "AB" || value == "BC" || value == "MB" || value == "NB" || value == "NL" || value == "NS" || value == "NT" || value == "NU" || value == "ON" || value == "PE" || value == "QC" || value == "SK" || value == "YT") {
    document.main_form[country].value= "CA";
  } else {
    document.main_form[country].value= "US";
  }

  return;

// THIS CODE IS NO LONGER USED
//  var countryValue= state.options[state.selectedIndex].getAttribute ("country");
//  if (countryValue) {
//    document.main_form[country].value= countryValue;
//  }
}

function verifyOpsContact (form) {
  var error= "";

  if (isBlank (form.last_name)) {
    error+= "\n-You must enter a last name for this contact";
  }
  if (form.category_id.value == 0) {
    error+= "\n-You must select a category";
  }

  if (!error) return true;

  var message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n" + error;

  alert (message);
  return false;
}

function verifyContactCategory (form) {
  var error= "";

  if (isBlank (form.name)) {
    error+= "\n-You must enter a category name";
  }

  if (!error) return true;

  var message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n" + error;

  alert (message);
  return false;
}

function checkHawb (field) {
  for (var i= 0; i < field.value.length; i++) {
    var charCheck= field.value.charAt (i);
    if ((charCheck >= 'a' && charCheck <= 'z') || (charCheck >= 'A' && charCheck <= 'Z') || (charCheck >= '0' && charCheck <= '9')) {
      continue;
    } else {
      alert ("Pre-Assigned HAWB Numbers may contain only letters and numbers");
      field.value= "";
    }
  }

  var pattern= /^WP\d{6}$/i;
  if (pattern.test (field.value)) {
    alert ("The pre-assigned HAWB number you have entered is reserved for internal use.  Please specify a different HAWB or leave the field blank.");
    field.value= "";
  }
}

function verifyUserSimple (form) {
  var error= "";

  if (isBlank (form.username)) {
    error+= "\n-You must enter a user name";
  }

  if (!(form.phone_area.value.length == 3 &&
      form.phone_exchange.value.length == 3 &&
      form.phone_number.value.length == 4)) {
    if (!(form.phone_area.value.length == 0 &&
        form.phone_exchange.value.length == 0 &&
        form.phone_number.value.length == 0)) {
      error+= "\n-Contact number is incomplete";
    } else {
      error+= "\n-You must enter a contact number";
    }
  }

  if (form.account_id.value == "") {
    error+= "\n-You must choose an account";
  }

  if (isBlank (form.send_to)) {
    error+= "\n-You must enter an address to send this user information to";
  }


  if (!error) return true;

  var message= "The form was not submitted because of the following errors.\n";
  message+= "Please correct any errors and submit the form again.\n" + error;

  alert (message);
  return false;
}

// Adds dimensions fields to shipment forms
function addDimsNew (weight, max) {
  var totalDims= document.main_form.num_dims.value;
  var iterations= 1; // The number of new rows to create
  var pieces= parseInt (document.main_form.pieces.value);
  var maxDims= max ? max : 99;

  if (totalDims < pieces) {
    iterations= pieces - totalDims;
  } else if (totalDims >= 3 && max > 5) {
    iterations= 3;
  }

  for (var i= 0; i < iterations; i++) {
    var hideButton= addDimRow (weight, max);

    if (hideButton) {
      document.getElementById ("new_dims_button").style.display= "none";
    }
  }
}

// Adds an actual dimension row to the form, returns true if dims are full
function addDimRow (weight, max) {
  var totalDims= document.main_form.num_dims.value;
  var maxDims= max ? max : 99;

  if (document.dimMax) {
    maxDims= document.dimMax;
  }

  if (totalDims >= maxDims) {
    return true;
  }

  totalDims++;
  document.main_form.num_dims.value= totalDims;

  var container= document.getElementById ("dim_container");

  var mainDiv= document.createElement ("div");
  mainDiv.appendChild (createDimInput (totalDims, "x"));
  mainDiv.appendChild (document.createTextNode (" in. x "));
  mainDiv.appendChild (createDimInput (totalDims, "y"));
  mainDiv.appendChild (document.createTextNode (" in. x "));
  mainDiv.appendChild (createDimInput (totalDims, "z"));
  mainDiv.appendChild (document.createTextNode (" in."));

  if (weight) {
    mainDiv.appendChild (document.createTextNode (", "));
    mainDiv.appendChild (createDimInput (totalDims, "wt"));
    mainDiv.appendChild (document.createTextNode (" lbs."));
  }

  container.appendChild (mainDiv);

  return (totalDims == maxDims);
}

// Creates an input tag for a dim
function createDimInput (number, letter) {
  var tag= document.createElement ("input");

  tag.type= "text";
  tag.id= tag.name= "dim"+number+letter;
  tag.size= letter == "wt" ? 2 : 1;
  tag.value= "";
  tag.maxLength= letter == "wt" ? 5 : 3;
  if (document.customerQuotes) {
    tag.onblur= function () { checkInt (this); updateEffectiveWeight (); };
    tag.onkeypress= function () { return disableEnterKey (event); };
  } else {
    tag.onblur= function () { checkInt (this); };
  }
  tag.optional= true;

  return tag;
}

function checkGenerated(select) {
  var checked= select.options[select.selectedIndex].getAttribute ('generated');
  var checkbox= document.getElementById ('generate_hawb');
  checkbox.checked= (checked == 'generated');
}

function checkEmailList(input) {
    var addresses= input.value.split(',');
    for (i= 0; i < addresses.length; i++) {
        addresses[i]= addresses[i].replace(/^\s+|\s+$/g, "");
        if (addresses[i] == '') {
            continue;
        }
        if (!addresses[i].match(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)) {
            return false;
        }
    }

    return true;
}

