function chooseType (value) {
  if (value == "") return;
  if (value != "Form" && document.getElementById ("quote_type").options[0].value == "") document.getElementById ("quote_type").options[0]= null;

  var code= value.substring (0, 2);
  // console.log(code);
  document.getElementById ("submit_form").style.display= "block";
  document.getElementById ("details_form").style.display= (code == "Ge" || code == "Oc") ? "none" : "block";
  document.getElementById ("generic_details_form").style.display= code == "Ge" ? "block" : "none";
  document.getElementById ("ocean_details_form").style.display= code == "Oc" ? "block" : "none";
  if (value != "Form") {
    document.getElementById ("shipping_method_block").style.display= code == "Fr" ? "none" : "";
    document.getElementById ("special_charges_block").style.display= code == "US" ? "none" : "";
    document.getElementById ("handling_block").style.display= code == "US" ? "" : "none";
    document.getElementById ("documents_required_block").style.display= code == "US" ? "" : "none";
    document.getElementById ("known_shipper_block").style.display= code == "US" ? "" : "none";
    document.getElementById ("form_template_block").style.display= code == "US" ? "" : "none";
    document.getElementById ("add_return_block").style.display= code == "US" ? "" : "none";

    document.getElementById ("us_exp_com_block").style.display= value == "US Exp. Com." ? "" : "none";
    document.getElementById ("us_exp_ata_block").style.display= value == "US Exp. ATA" ? "" : "none";
    document.getElementById ("us_import_block").style.display= value == "US Import" ? "" : "none";
  }
}

function setPickupType (type) {
  document.getElementById ("normal_pickup_block").style.display= type == "normal" ? "" : "none";
  document.getElementById ("normal_delivery_block").style.display= type == "normal" ? "" : "none";
  document.getElementById ("weekday_pickup_block").style.display= type == "weekday" ? "" : "none";
}

// This function passes all relevant parameters to an AJAX function to get quote text and subject
function getQuoteText () {
  if (typeof(document.main_form.known_shipper) != 'undefined' && document.getElementById('known_shipper_block').style.display != 'none') {
    if (!document.main_form.known_shipper[0].checked && !document.main_form.known_shipper[1].checked) {
        alert ("You must choose whether this quote has a known shipper");
        return void(0);
    }
  }

  updateEffectiveWeight ();

  var parameterList= [
    "to_name_first",
    "to_name_last",
    "account_name",
    "shipping_method",
    "pickup_date_month",
    "pickup_date_day",
    "pickup_date_year",
    "pickup_open",
    "pickup_close",
    "delivery_date_month",
    "delivery_date_day",
    "delivery_date_year",
    "delivery_open",
    "from_city",
    "from_state",
    "to_city",
    "to_state",
    "contact_num",
    "description_of_goods",
    "hazmat",
    "pieces",
    "weight",
    "effective_weight",
    "value",
    "transport_price",
    "transport_lbs",
    "customs_clearance",
    "service_level",
    "price_expression",
    "total",
    "special_charges",
    "quote_type",
    "weekdays",
    "alt_delivery_date_month",
    "alt_delivery_date_day",
    "alt_delivery_date_year",
    "alt_delivery_open",
    "alt_pickup_date_month",
    "alt_pickup_date_day",
    "alt_pickup_date_year",
    "alt_pickup_open",
    "alt_pickup_close",
    "alt_price_expression",
    "alt_total",
    "coo_charge",
    "dc_charges1",
    "aes_filing",
    "atac_fee",
    "prev_sed",
    "dc_charges2",
    "addl_cont",
    "bond_fee04",
    "bond_fee1",
    "cc_com",
    "cc_atac",
    "handling",
    "num_dims",
    "extension",
    "ocean_to_name_first",
    "ocean_to_name_last",
    "ocean_account_name",
    "commodity",
    "ocean_from",
    "ocean_to",
    "type_equipment",
    "transport_per_20",
    "transport_per_40",
    "handling_documentation",
    "transit_time",
    "frequency",
    "validity_date_month",
    "validity_date_day",
    "validity_date_year",
    "shipping_line",
    "ocean_extension",
    "form_template",
    "return_transport_price",
    "return_customs_clearance",
    "return_service_level",
    "return_price_expression",
    "credit_card"
  ];

  for (var i= 1; i <= document.main_form.num_dims.value; i++) {
    parameterList.push ("dim"+i+"x");
    parameterList.push ("dim"+i+"y");
    parameterList.push ("dim"+i+"z");
  }

  var parameters= "";
  for (var i= 0; i < parameterList.length; i++) {
    var name= parameterList[i];
    if (name == "") continue;
    if (!document.main_form[""+name]) continue;
    parameters+= "&" + name + "=" + encodeURIComponent (document.main_form[""+name].value);
  }

  // Radio buttons
  parameters+= "&pickup_type=" + encodeURIComponent (getRadioValue ("pickup_type"));
  parameters+= "&known_shipper=" + encodeURIComponent (getRadioValue ("known_shipper"));

  // Checkboxes
  parameters+= "&include_special_charges=" + (document.main_form["include_special_charges"].checked ? "on" : "");
  parameters+= "&alt_quote=" + (document.main_form["alt_quote"].checked ? "on" : "");
  parameters+= "&add_return=" + (document.main_form["add_return"].checked ? "on" : "");
  parameters+= "&hazmat=" + (document.main_form["hazmat"].checked ? "on" : "");

  if (typeof(documentsRequired) != 'undefined') {
      for (var i in documentsRequired) {
          parameters+= "&" + documentsRequired[i] + "=" + (document.main_form[documentsRequired[i]].checked ? "on" : "");
      }
  }

  var httpRequest= getHTTPRequest ();

  if (httpRequest) {
    httpRequest.onreadystatechange= function () { writeQuoteText (httpRequest); };
    httpRequest.open ("POST", "https://www.sosglobal.com/" + document.script + "?rm=get_quote_text", true);
    httpRequest.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader ("Content-length", parameters.length);
    httpRequest.setRequestHeader ("Connection", "close");
    httpRequest.send (parameters);
  }

  return void (0);
}

function getAverageMargin (accountId) {
  var httpRequest= getHTTPRequest ();

  if (httpRequest) {
    httpRequest.onreadystatechange= function () { writeAverageMargin (httpRequest); };
    httpRequest.open ("GET", "https://www.sosglobal.com/" + document.script + "?rm=get_average_margin&aid=" + accountId + "&ts=" + new Date ().getTime (), true);
    httpRequest.send (null);
  }

  return false;
}

function getRadioValue (radioName) {
  var radio= document.main_form[radioName];
  for (var i= 0; i < radio.length; i++) {
    if (radio[i].checked) {
      return radio[i].value;
    }
  }
}

function writeQuoteText (httpRequest) {
  var components= httpRequest.responseText.split (":|:");
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      document.main_form.subject.value= components[0];
      document.main_form.message.value= components[1];
    } else {
      alert ("There was a problem with the request, could not write quote");
    }
  }
}

function verifyQuoteForm (form) {
  if (document.sendType == 'send') {

    // var message= "";
    // message+= "TOTAL_";
    // message+= form.total.value;
    // message+= "_TOTAL";
    // alert (message);

    // if (form.total.value == 'undefined' || form.total.value == "") {
    if (!form.total.value) {
      alert ("You must enter a TOTAL (or estimate) for this Quote!");
      return false;
    }

    if (!form.margin.value) {
      alert ("You must enter a MARGIN % for this Quote!");
      return false;
    }

    if (form.to_email.value == "") {
      alert ("You must enter an e-mail address to send this quote to!");
      return false;
    }

    if (!checkQuoteEmailList(form.to_email)) {
      alert ("You have entered an invalid e-mail address in the Customer e-Mail field");
      return false;
    }

    if (form.routing_email && form.routing_email.value != "" && !checkQuoteEmailList(form.routing_email)) {
      alert ("You have entered an invalid e-mail address in the Internal Routing e-mail field");
      return false;
    }

    if (form.cc && form.cc.value != "" && !checkQuoteEmailList(form.cc)) {
      alert ("You have entered an invalid e-mail address in the CC To field; multiple addresses should be separated by commas");
      return false;
    }
  }


  if (form.subject.value == "") {
    alert ("You must enter a subject line for this quote");
    return false;
  }

  if (form.message.value == "") {
    alert ("You must enter text for this quote");
    return false;
  }

  if (document.sendType == 'send') {
    var quoteNote= document.getElementById('quote_note');

    if (quoteNote.style.display == 'block') {
        return true;
    }

    var accountId= document.main_form.account_id[document.main_form.account_id.selectedIndex].value;

    var httpRequest= getHTTPRequest ();

    if (httpRequest) {
      httpRequest.onreadystatechange= function () { writeQuoteNote (httpRequest); };
      httpRequest.open ("GET", "https://www.sosglobal.com/" + document.script + "?rm=get_quote_note&aid=" + accountId + "&ts=" + new Date ().getTime (), true);
      httpRequest.send (null);
    }

    return false;
  }

  return true;
}

function writeQuoteNote (httpRequest) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200 && httpRequest.responseText) {
      var quoteNote= document.getElementById('quote_note');
      quoteNote.innerHTML= httpRequest.responseText;
      quoteNote.style.display= 'block';
    } else {
        document.main_form.submit();
    }
  }
}

function writeAverageMargin (httpRequest) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200 && httpRequest.responseText) {
      var margin= document.getElementById('margin_average');
      if (margin) {
        margin.innerHTML= httpRequest.responseText;
      }
    }
  }
}

function verifyRequestForm (form) {
  if (form.account_id && form.account_id.value == "") {
    alert ("You must choose an account for this quote");
    return false;
  }

  if (form.to_email && form.to_email.value == "") {
    alert ("You must enter an e-mail address for this quote");
    return false;
  }

  return true;
}

function disableEnterKey (e) {
  var key;
  if (window.event) {
    key= window.event.keyCode;
  } else {
    key= e.which;
  }

  if (key == 13) {
    return false;
  } else {
    return true;
  }
}

function setEmail (email) {
  if (email == "") return;
  document.main_form.to_email.value= email;
}

function toggleAltQuote (checked, init) {
  var display= checked ? "" : "none";

  if (checked && !init) {
    document.main_form.alt_pickup_date_year.value= document.main_form.pickup_date_year.value;
    document.main_form.alt_pickup_date_month.value= document.main_form.pickup_date_month.value;
    updateMonth ("alt_pickup_date");
    document.main_form.alt_pickup_date_day.value= document.main_form.pickup_date_day.value;
    document.main_form.alt_pickup_open.value= document.main_form.pickup_open.value;
    document.main_form.alt_pickup_close.value= document.main_form.pickup_close.value;

    document.main_form.alt_delivery_date_year.value= document.main_form.delivery_date_year.value;
    document.main_form.alt_delivery_date_month.value= document.main_form.delivery_date_month.value;
    updateMonth ("alt_delivery_date");
    document.main_form.alt_delivery_date_day.value= document.main_form.delivery_date_day.value;
    document.main_form.alt_delivery_open.value= document.main_form.delivery_open.value;
  }

  document.getElementById ("alt_delivery_block").style.display= display;
  document.getElementById ("alt_pickup_block").style.display= display;
  document.getElementById ("alt_price_expr_block").style.display= display;
  document.getElementById ("alt_total_block").style.display= display;
}

function toggleReturn (checked, blockNum) {
  var display= checked ? "" : "none";

  if (typeof(blockNum) != 'undefined') {
      blockName= 'return_' + blockNum;
  } else {
      blockName= 'return';
  }

  document.getElementById (blockName + "_transport_price_block").style.display= display;
  document.getElementById (blockName + "_customs_clearance_block").style.display= display;
  document.getElementById (blockName + "_service_level_block").style.display= display;
  document.getElementById (blockName + "_price_expression_block").style.display= display;
}

function setCustomerQuoteDates (request) {
  request= typeof (request) != 'undefined' ? request : false;

  var day= new Date ();

  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 (!request) {
    document.main_form.alt_pickup_date_month.value= day.getMonth () + 1;
    document.main_form.alt_pickup_date_year.value= day.getFullYear ();
    updateMonth ("alt_pickup_date");
    document.main_form.alt_pickup_date_day.value= day.getDate ();
  }

  if (document.main_form.validity_date_month) {
    document.main_form.validity_date_month.value= day.getMonth () + 1;
    document.main_form.validity_date_year.value= day.getFullYear ();
    updateMonth ("validity_date");
    document.main_form.validity_date_day.value= day.getDate ();
  }

  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 ();

  if (!request) {
    document.main_form.alt_delivery_date_month.value= day.getMonth () + 1;
    document.main_form.alt_delivery_date_year.value= day.getFullYear ();
    updateMonth ("alt_delivery_date");
    document.main_form.alt_delivery_date_day.value= day.getDate ();
  }
}

function setExistingCustomerQuoteDates () {
  document.main_form.pickup_date_month.value= document.pickupDate.month;
  document.main_form.pickup_date_year.value= document.pickupDate.year;
  updateMonth ("pickup_date");
  document.main_form.pickup_date_day.value= document.pickupDate.day;

  if (document.validity) {
    document.main_form.validity_date_month.value= document.validity.month;
    document.main_form.validity_date_year.value= document.validity.year;
    updateMonth ("validity_date");
    document.main_form.validity_date_day.value= document.validity.day;
  }

  document.main_form.delivery_date_month.value= document.deliveryDate.month;
  document.main_form.delivery_date_year.value= document.deliveryDate.year;
  updateMonth ("delivery_date");
  document.main_form.delivery_date_day.value= document.deliveryDate.day;

  document.main_form.alt_pickup_date_month.value= document.altPickupDate.month;
  document.main_form.alt_pickup_date_year.value= document.altPickupDate.year;
  updateMonth ("alt_pickup_date");
  document.main_form.alt_pickup_date_day.value= document.altPickupDate.day;

  document.main_form.alt_delivery_date_month.value= document.altDeliveryDate.month;
  document.main_form.alt_delivery_date_year.value= document.altDeliveryDate.year;
  updateMonth ("alt_delivery_date");
  document.main_form.alt_delivery_date_day.value= document.altDeliveryDate.day;
}

function setAccount (accountId) {
  var select= document.getElementById ("account_id");

  if (select.selectedIndex > 0) {
    var option= select.options[select.selectedIndex];
    var accountName= option.text;
    if (accountName.substring (0, 1) == "*") accountName= accountName.substring (1);
    document.main_form.account_name.value= accountName;
    if (document.main_form.ocean_account_name) document.main_form.ocean_account_name.value= accountName;
    var watch= option.getAttribute ("watch");

    var marginText= document.getElementById('margin_text');
    if (marginText) {
        marginText.style.display= 'inline';
        document.getElementById('margin_customer').innerHTML= accountName;
        document.getElementById('margin_average').innerHTML= 'loading...';
        getAverageMargin(accountId);
    }

    if (watch) {
      var message= "";
      if (watch == "WATCH") {
        message+= "This Account is on A/R WATCH.";
      } else if (watch == "LIMIT") {
        message+= "This Account is near its Credit Limit.";
      } else if (watch == "OVER") {
        message+= "This Account is over its Credit Limit.";
      }
      message+= " Please contact Kathleen Rice or Ed Reno before sending this quote.";
      alert (message);
    }

    var autoCC= option.getAttribute ("auto_cc_list");
    autoCC= autoCC ? ", " + autoCC : "";

    document.getElementById ("auto_cc_list").innerText= autoCC;
  } else {
    var marginText= document.getElementById('margin_text');
    if (marginText) {
        marginText.style.display= 'none';
    }
  }

  var httpRequest= getHTTPRequest ();

  if (httpRequest) {
    httpRequest.onreadystatechange= function () { writeCustomerList (httpRequest); };
    httpRequest.open ("GET", "https://www.sosglobal.com/" + document.script + "?rm=get_customer_list&id=" + accountId, true);
    httpRequest.send (null);
  }

  return void (0);
}

function writeCustomerList (httpRequest) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      if (httpRequest.responseText) {
        document.getElementById ("email_choose_text").style.display= "inline";
        document.getElementById ("customer_select").innerHTML= httpRequest.responseText;
      } else {
        document.getElementById ("email_choose_text").style.display= "none";
        document.getElementById ("customer_select").innerHTML= "";
      }
    } else {
      alert ("There was a problem with the request, could not write quote");
    }
  }
}

function updateEffectiveWeight () {
  var weight= document.main_form.weight.value;

  var normalWeight= document.getElementById ("normal_weight");
  var dim1Weight= document.getElementById ("dim1_weight");
  var dim2Weight= document.getElementById ("dim2_weight");
  var dim3Weight= document.getElementById ("dim3_weight");

  var normal= -1;
  var dim1= -1;
  var dim2= -1;
  var dim3= -1;

  if (weight) {
    normal= weight;
    normalWeight.innerHTML= "" + weight + " lbs.";
  } else {
    normalWeight.innerHTML= "N/A";
  }

  for (var i= 1; i <= document.main_form.num_dims.value; i++) {
    var dimx= document.main_form["dim"+i+"x"];
    var dimy= document.main_form["dim"+i+"y"];
    var dimz= document.main_form["dim"+i+"z"];

    if (dimx && dimz && dimz && dimx.value && dimy.value && dimz.value) {
      if (dim1 < 0) dim1= 0;
      if (dim2 < 0) dim2= 0;
      if (dim3 < 0) dim3= 0;

      dim1+= Math.round (dimx.value * dimy.value * dimz.value / 250);
      dim2+= Math.round (dimx.value * dimy.value * dimz.value / 194);
      dim3+= Math.round (dimx.value * dimy.value * dimz.value / 166);
    }
  }

  dim1Weight.innerHTML= dim1 >= 0 ? "" + dim1 + " lbs." : "N/A";
  dim2Weight.innerHTML= dim2 >= 0 ? "" + dim2 + " lbs." : "N/A";
  dim3Weight.innerHTML= dim3 >= 0 ? "" + dim3 + " lbs." : "N/A";

  if (document.getElementById ("use_weight_normal").checked) {
    document.main_form.effective_weight.value= normal == -1 ? "" : normal;
  } else if (document.getElementById ("use_weight_dim1").checked) {
    document.main_form.effective_weight.value= dim1 == -1 ? normal : dim1;
  } else if (document.getElementById ("use_weight_dim2").checked) {
    document.main_form.effective_weight.value= dim2 == -1 ? normal : dim2;
  } else if (document.getElementById ("use_weight_dim3").checked) {
    document.main_form.effective_weight.value= dim3 == -1 ? normal : dim3;
  }
}

function fixPhoneNumber(field) {
    number= field.value.replace(/\D/g, '');

    console.log(number.length);
    if (number.length == 7) {
        number= number.substring(0, 3) + '-' + number.substring(3, 7);
    } else if (number.length == 10) {
        number= number.substring(0, 3) + '-' + number.substring(3, 6) + '-' + number.substring(6, 10);
    } else if (number.length > 10) {
        number= number.substring(0, 3) + '-' + number.substring(3, 6) + '-' + number.substring(6, 10) + ' ' + number.substring(10, number.length);
    }

    field.value= number;
}

function checkQuoteEmailList(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;
}

