var pdf; // global ref to the pdf filename
var formSent = false;
var blueCover;
var formButtons;
var formProgress;
var formMsg;
var downloadForm; // container div
var theForm; // actual form
var facade;
var alreadyCentered;

function disableFormInputs() {
  for (var i = 0; i < theForm.elements.length; i++) {
    if (typeof theForm.elements.item(i).disabled == 'boolean') {
      theForm.elements.item(i).disabled = true;
    }
  }
}

function enableFormInputs() {
  for (var i = 0; i < theForm.elements.length; i++) {
    if (typeof theForm.elements.item(i).disabled == 'boolean') {
      theForm.elements.item(i).disabled = false;
    }
  }
}

function checkResults(xmlDom) {
if (typeof xmlDom == 'object') {
    var response = xmlDom.getElementsByTagName('methodResponse').item(0);
  }

  if (typeof response == 'object' && typeof response.firstChild == 'object' && typeof response.firstChild.nodeName == 'string') {
    // hide progress
    facade.hideElm(formProgress);

    // make sure we know about the warning msg row
    if (typeof formMsg != 'object') {
      formMsg = facade.getElm('formMsg');
    }

    // empty old msgs
    var formMsgTd = formMsg.getElementsByTagName('TD').item(0);
    while (formMsgTd.hasChildNodes()) {
      var oldNode = formMsgTd.removeChild(formMsgTd.lastChild);
      oldNode = null;
    }

    // show the msg row
    facade.showElm(formMsg);

    // check for a failure in submission
    if (response.firstChild.nodeName == 'fault') {
      var members = response.firstChild.getElementsByTagName('member');
      var faultCodeMember = members.item(0);
      var faultCodeValue = faultCodeMember.childNodes.item(1);
      var faultCodeType = faultCodeValue.firstChild;
      var faultCode = faultCodeType.firstChild.nodeValue;

      var errMsg = '';
      switch (faultCode) {
        case '3':
          errMsg = 'Please make sure that all form fields are complete.';
          break;

        case '2':
          errMsg = 'You have entered an incorrect validation code. Please try again.';
          break;

        default:
          errMsg = 'We were unable to send your request. Please try again.';
          break;
      }


      // add the new msg
      formMsgTd.appendChild(document.createTextNode(errMsg));

      // show the form buttons again
      facade.showElm(formButtons);

      // and we'll need to use the form inputs again
      enableFormInputs();
    }
    // check for success
    else if (response.firstChild.nodeName == 'params') {
      // make sure that we know the user has already filled out the form
      formSent = true;

      // now notify the user that the download was successfull
      formMsgTd.style.color = 'green';
      formMsgTd.appendChild(document.createTextNode('Thank you. The catalog request has been submitted successully.'));
      formMsgTd.appendChild(document.createElement('BR'));
      formMsgTd.appendChild(document.createTextNode('This catalog request will close momentarily.'));

      // close the form
      var t = setTimeout('hideDownloadForm()', 5000);
    }
  }
  // notify the user of a failure
  else {
    alert('The form failed to submit your data. Our webmaster has been notified.');
  }
}

function showDownloadForm() {
  if (typeof facade != 'object') {
    facade = new Facade();
  }

  // get the container element for downloadForm
  if (typeof blueCover != 'object') {
    blueCover = facade.getElm('overlay');

    // make sure the blue cover's the full height
    blueCover.style.height = (facade.getTotalHeight() - 0) + 'px';
  }

  // now show it
  facade.showElm(blueCover);

  // opacity fix for IE
  if (document.all) {
    try {
      blueCover.style.filter = 'alpha(opacity=40)';
    } catch (e) {}
  }

  // get the container element for downloadForm
  if (typeof downloadForm != 'object') {
    downloadForm = facade.getElm('dlFormContainer');
  }

  // position it
  //facade.positionElmPercent(downloadForm, 50, 50);
  
  // put it close to the top and center it
  if (!alreadyCentered) {
    try {
      alreadyCentered = true;
      //facade.centerElmX(downloadForm);
      downloadForm.style.top = '110px';
      downloadForm.style.left = '75px';
      alreadyCentered = true;
    } catch(e) {}
  }

  // now show it
  facade.showElm(downloadForm);

  // keep it positioned
  //window.onscroll = function (e) {facade.positionElmPercent(downloadForm, 50, 50);}
}

function hideDownloadForm() {
  facade.hideElm(downloadForm);
  facade.hideElm(blueCover);
}

function downloadPDF(pdfName) {
  // make the filename global
  pdf = pdfName;

  // show the download form
  if (formSent === false) {
    showDownloadForm();
  }

  // start the pdf
downloadwindow = window.open('/saveas.php?fileName=' + pdfName,'','toolbar=no,location=no,menubar=no,width=250,height=150');	
downloadwindow.blur()
//document.location.href = '/pdf.php?fileName=' + pdfName;
}

/**
* build the XML RPC from all of the form inputs and send it if it validates
*/
function sendData() {
  // make sure we have access to the form
  if (typeof theForm != 'object') {
    theForm = facade.getElm('dlForm');
  }

  if (validateForm(theForm)) {
    // make it look like it's working
    disableFormInputs();

    // hide msgs
    if (typeof formMsg != 'object') {
      formMsg = facade.getElm('formMsg');
    }
    facade.hideElm(formMsg);

    // hide buttons
    if (typeof formButtons != 'object') {
      formButtons = facade.getElm('formButtons');
    }
    facade.hideElm(formButtons);

    // show progress
    if (typeof formProgress != 'object') {
      formProgress = facade.getElm('formProgress');
    }
    facade.showElm(formProgress);

    // build RPC
    var catRequestRPC =  new XML_RPC();

    catRequestRPC.methodName = 'catalogRequest';
    catRequestRPC.addScalar('string', theForm.captchaId.value);
    catRequestRPC.addScalar('string', theForm.captcha.value);
    catRequestRPC.addScalar('string', theForm.firstName.value);
    catRequestRPC.addScalar('string', theForm.lastName.value);
    catRequestRPC.addScalar('string', theForm.title.value);
    catRequestRPC.addScalar('string', theForm.company.value);
    catRequestRPC.addScalar('string', theForm.address.value);
    catRequestRPC.addScalar('string', theForm.city.value);
    catRequestRPC.addScalar('string', theForm.state.value);
    catRequestRPC.addScalar('string', theForm.zip.value);
    catRequestRPC.addScalar('string', theForm.country.value);
    catRequestRPC.addScalar('string', theForm.phone.value);
    catRequestRPC.addScalar('string', theForm.email.value);
    catRequestRPC.addScalar('string', theForm.bizType.value);
    catRequestRPC.addScalar('string', theForm.numStores.value);
    catRequestRPC.addScalar('string', pdf);
    catRequestRPC.buildPayload();

    // send the request
    var req = new XML_Request();
    req.sendRequest(catRequestRPC.payload, checkResults, '/rpc2/catalogRequest.php');

  }
}

function validateForm(theForm) {
  if (theForm.firstName.value == "") {
    alert("Please enter your first name.");
    theForm.firstName.focus();
    return (false);
  }

  if (theForm.firstName.value.length < 3) {
    alert("Please enter a valid first name");
    theForm.firstName.focus();
    return (false);
  }

  if (theForm.lastName.value == "") {
    alert("Please enter your last name.");
    theForm.lastName.focus();
    return (false);
  }

  if (theForm.lastName.value.length < 3) {
    alert("Please enter a valid last name");
    theForm.lastName.focus();
    return (false);
  }

  if (theForm.title.value == "") {
    alert("Please enter your title.");
    theForm.title.focus();
    return (false);
  }

  if (theForm.title.value.length < 3) {
    alert("Please enter a valid title.");
    theForm.title.focus();
    return (false);
  }

  if (theForm.company.value == "") {
    alert("Please enter your company.");
    theForm.company.focus();
    return (false);
  }

  if (theForm.company.value.length < 3) {
    alert("Please enter a valid company.");
    theForm.company.focus();
    return (false);
  }

  if (theForm.address.value == "") {
    alert("Please enter your address.");
    theForm.address.focus();
    return (false);
  }

  if (theForm.address.value.length < 3) {
    alert("Please enter a valid address");
    theForm.address.focus();
    return (false);
  }

  if (theForm.city.value == "") {
    alert("Please enter your city");
    theForm.city.focus();
    return (false);
  }

  if (theForm.city.value.length <3) {
    alert("Please enter a valid city.");
    theForm.city.focus();
    return (false);
  }

  if (theForm.state.value == "") {
    alert("Please enter your state.");
    theForm.state.focus();
    return (false);
  }

  if (theForm.state.value.length <2) {
    alert("Please enter a valid state.");
    theForm.state.focus();
    return (false);
  }

  if (theForm.country.value == "") {
    alert("Please enter your country.");
    theForm.country.focus();
    return (false);
  }

  if (theForm.country.value.length < 2) {
    alert("Please enter a valid Country.");
    theForm.country.focus();
    return (false);
  }

  if (theForm.zip.value == "") {
    alert("Please enter your zip code.");
    theForm.zip.focus();
    return (false);
  }

  if (theForm.zip.value.length < 3) {
    alert("Please enter a valid zip code.");
    theForm.zip.focus();
    return (false);
  }

  if (theForm.phone.value == "") {
    alert("Please enter your phone number.");
    theForm.phone.focus();
    return (false);
  }

  if (theForm.phone.value.length < 3) {
    alert("Please enter a valid phone number.");
    theForm.phone.focus();
    return (false);
  }

  substremail = theForm.email.value.split("@")
  if (substremail.length > 1) {
    index = substremail[1].indexOf(".");
    if (index == -1) {
      alert("Please enter your email address.");
      theForm.email.focus();
      return false;
    }
  } else {
    alert("Please enter your email address.");
    theForm.email.focus();
    return false;
  }

  if (theForm.bizType.value == "") {
    alert("Please enter a valid type of business.");
    theForm.bizType.focus();
    return (false);
  }

  if (theForm.bizType.value.length < 3) {
    alert("Please enter a valid type of business.");
    theForm.bizType.focus();
    return (false);
  }

  if (theForm.numStores.value == "") {
    alert("Please enter your number of stores.");
    theForm.numStores.focus();
    return (false);
  }

  if (theForm.numStores.value.length < 0) {
    alert("Please enter a valid number of stores.");
    theForm.numStores.focus();
    return (false);
  }

  var checkOK = "0123456789-.,";
  var checkStr = theForm.numStores.value;
  var allValid = true;
  var decPoints = 0;
  var allNum = "";
  for (i = 0;  i < checkStr.length;  i++) {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++) {
      if (ch == checkOK.charAt(j)) {
        break;
      }
    }
    if (j == checkOK.length) {
      allValid = false;
      break;
    }
    if (ch == ".") {
      allNum += ".";
      decPoints++;
    } else if (ch != ",") {
      allNum += ch;
    }
  }
  if (!allValid) {
    alert("Please enter only numbers in the \"Number of Stores\" field.");
    theForm.numStores.focus();
    return (false);
  }

  if (decPoints > 1) {
    alert("Please enter a valid number of stores.");
    theForm.numStores.focus();
    return (false);
  }

  if (theForm.captcha.value.length != 4) {
    alert("Please enter the form validation code.");
    theForm.captcha.focus();
    return (false);
  }

  return (true);
}