var dlgForm;
var systemCount = 0;
var maxSystems = 5;

function showForm(type, prod) {
  
  if (prod == null) prod = "";
  
  // get position
  var nav = document.getElementById("nav");
  var left = 0;
  var top = 0;
  while (nav != null) {
    left += nav.offsetLeft;
    top += nav.offsetTop;
    nav = nav.offsetParent
  }
  var scrollTop = 0;
  if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop;
  }
  else if (document.body && document.body.scrollTop) {
    scrollTop = document.body.scrollTop;
  }  
  top = scrollTop + 35;
  
  // get dialog title
  var title = type + " " + prod;
  var prodName = "";
  if (prod == "profoundui") prodName = "Profound UI";
  if (prod == "rpgsp") prodName = "RPGsp";
  if (prod == "genie") prodName = "Genie";
  if (prod == "rpgalive") prodName = "RPG-Alive for SEU";
  if (prod == "rpgalivegui") prodName = "RPG-Alive GUI";
  if (prod == "idata") prodName = "iData";
  if (type == "info") {
    title = "Request Information";
  }
  if (type == "demo") {
    title = "Schedule Live Demonstration";
  }
  if (type == "download") {
    title = "Download a 30-day Trial of " + prodName;
    if (prod == "idata") title = "Download Pre-Release of iData";
  }
  if (type == "order") {
    title = "Order " + prodName;
    if (prod == "rpgalive" || prod == "rpgalivegui") title = "Order RPG-Alive";
  }
  if (type == "sales") {
    title = "Contact Sales";
    if (prod == "idata") title = "Request Information about iData";
  }
  if (type == "support") {
    title = "Technical Support Form";
  }
  if (type == "partner") {
    if (prod == "reseller") {
      title = "Request Information about our Reseller Partnership Program";
    }
    if (prod == "integration") {
      title = "Request Information about Integration Partnerships";
    }    
  }
  
  dlgForm = new Dialog(top, left + 57, 525, 625, title, null, null, true);
  var content = dlgForm.addLabel(0, 10, "One moment... Loading content."); 
  content.id = "formContent";  // assign id so we can apply css
  ajax("/incForm.rpgsp?type=" + type + "&prod=" + prod + "&mode=ajax", function(response) {
    content.innerHTML = response;
    eval(ajax("/incFields.rpgsp"));
    refreshForm(type, prod);
    if (prod == "modsuite") {
      document.profoundForm.chkOffering10.checked = true;
      document.profoundForm.chkOffering20.checked = true;
      document.profoundForm.chkOffering30.checked = true;
    }
    addFocusBlurEffect(content);
    try {
      document.profoundForm.product.focus();
    }
    catch(e) {
      try {
        document.profoundForm.first.focus();
      }
      catch(e) {
      }
    }
    // if (type == "download" && prod == "idata") document.profoundForm.invitation.focus();
  });
}


function refreshForm() {

  // Show or hide fields based on rules in FORMFIELDP file
  var type = document.getElementById("type").value;
  var prod = document.getElementById("prod").value;
  var rows = document.getElementById("profoundFormTable").rows;
  
  var session = utils.getCookie("RPGSPSESSIONID");
  var loggingURL = "/incTop.rpgsp?PageName=" + prod + type + "&session=" + session + "&LO=Y"
  ajax(loggingURL, function() {});

  for (var rowIdx in rows) {
    var row = rows[rowIdx];
    var rowId = row.id;
    if (rowId != null && rowId != "") {
      rowId = rowId.substr(0, rowId.length - 1);
      var idx = type;
      if (prod != "") idx += "_" + prod;
      idx += "_" + rowId;
      var showField = fields[idx];
      if (showField == null && prod != "") {
        idx = type + "_" + rowId;
        showField = fields[idx];
      }
      if (showField == null) {
        idx = "_" + rowId;
        showField = fields[idx];
      }
      showField = (showField == "Y");
      if (showField) {
        row.style.display = "";
      }
      else {
        row.style.display = "none";
      }    
    }    
  }
  
  // Show product description based on selection
  var product = document.profoundForm.product.value;
  var desc = "";
  if (product == "rpgsp") desc = "Rapid Web Development";
  if (product == "genie") desc = "On-the-fly Modernization";
  if (product == "idata") desc = "iSeries Database Editing";
  if (product == "rpgalive") desc = "Code Editing SEU Add-on";
  if (product == "rpgalivegui") desc = "Stand-alone Code Editor";
  document.getElementById("prodDesc").innerHTML = desc;
  
  // determine if we need to ask for the iData invitation/scratch-off code
  // if (type == "download" && (prod == "idata" || product == "idata")) {
  //   show("invitation0");
  // }
  // else {
  //   hide("invitation0");
  // }
  
  // make comments area smaller for quote and demo
  if (type == "info" || type == "demo") {
    document.profoundForm.comments.rows = 3;
  }
  
  // Determine whether we need state or not
  var country = document.profoundForm.country.value;
  if (country == "United States" || country == "Canada") {
    show("state0");
  }
  else {
    hide("state0");
  }
    
  // Ask for additional source information if necessary
  var source = document.profoundForm.source.value;
  var infoRow = document.getElementById("sourceInfo0");
  var label = "";
  if (source == "Google") label = "What keywords were used?"
  if (source == "Yahoo") label = "What keywords were used?"
  if (source == "MSN/Bing") label = "What keywords were used?"
  if (source == "Trade Show") label = "Which One?"
  if (source == "Website") label = "Which Site?"
  if (source == "iModernize") label = "Which Issue?"
  if (source == "Referral") label = "By Whom?"
  if (source == "Other") label = "Details"
  if (source == "Existing Customer") label = "Which Product(s)?"
  if (label != "") {
    document.getElementById("sourceInfoLabel").innerHTML = label;
    show("sourceInfo0");
  }
  else {
    hide("sourceInfo0");
  }

  // Ask if price quote needed or live demo needed unless RPG-Alive
  if (type != "info" && type != "beta" && type != "WPSstudy" && type != "advisor" && type != "demo" && type != "support" && type != "partner" && type != "activation") {
    if (prod == "rpgalive" || prod == "rpgalivegui" || 
        document.profoundForm.product.value == "rpgalive" || 
        document.profoundForm.product.value == "rpgalivegui" ||
        prod == "Mass Conversion" || prod == "Modernization" || prod == "Web App Dev") { 
      hide("quote0");
      document.profoundForm.chkQuote.checked = false;
      hide("demo0");
      document.profoundForm.chkDemo.checked = false;
    }
    else {
      show("quote0");
      show("demo0");
    }
  }  
  
  // Show the correct number of system rows
  if (document.profoundForm.chkQuote.checked) {
    if (systemCount <= 0) systemCount = 1;
    if (systemCount > 5) systemCount = maxSystems;
    if (prod == "genie" || 
        document.profoundForm.product.value == "genie" || 
        document.getElementById("chkOffering20").checked ||   // offering 20 - genie
        document.getElementById("chkOffering50").checked) {   // offering 50 - modernization services
      show("users0");    
    } 
    else {
      hide("users0");
    }
  }
  else {
    systemCount = 0;
    hide("users0");
  }
  for (var i = 1; i <= 5; i++) {
    if (i <= systemCount) show("system" + i);
    else hide("system" + i);
    if (i == systemCount && i != maxSystems) show("addAnotherSystem" + i)
    else hide("addAnotherSystem" + i);
  }  

  // Ask for demo time if necessary
  if (document.profoundForm.chkDemo.checked) {
    show("demoTime0");
  }
  else {
    hide("demoTime0");
  }

  // Ask what type of project they are interested in for RPGsp
  if (type != "support" && type != "activation" && type != "WPSstudy") {
    if (prod == "rpgsp" || 
      document.profoundForm.product.value == "rpgsp" || 
      document.getElementById("chkOffering10").checked) {     // offering 10 - rpgsp
      show("projects0");
    }
    else {
      hide("projects0");
      document.profoundForm.projects.value = "";
    }
  }

  // Ask which language their green-screens are written in
  var projType = document.profoundForm.projects.value;
  if (projType == "Modernization" || projType == "Both") {
    show("greenScreenLanguage0");
    show("greenScreenLanguage1");
  }
  else {
    hide("greenScreenLanguage0");
    hide("greenScreenLanguage1");
  }

  // Ask which skills they have and additional project details
  if (projType != "") {
    show("skills0");
    show("skills1");
    show("projectDetails0");
  }
  else {
    hide("skills0");
    hide("skills1");
    hide("projectDetails0");
  }

  // Hide info we already have for activation
  if (type == "activation") {
    if (document.profoundForm.AskWhoThisIs.value == "N") {
      hide("first0");
      hide("last0");
      hide("company0");
      hide("phone0");
      hide("country0");
      hide("city0");
      hide("state0");
      hide("zip0");
    }
  }

  show("profoundFormTable");
  
  // This code fixes bug where IE doesn't handle "overflow-y : auto" in the css
  var formContent = document.getElementById("formContent");
  if (formContent != null) {
    if (document.getElementById("profoundFormTable").offsetHeight > 500) {
      formContent.style.overflowY = "scroll";
    }
    else {
      formContent.style.overflowY = "";
    }
  }  
}

function showHelp(helpObj, helpType) {
  var left = 0;
  var top = 0;
  var obj = helpObj;
  while (obj != null) {
    left += obj.offsetLeft;
    top += obj.offsetTop;
    obj = obj.offsetParent
  }
  var formContent = document.getElementById("formContent");
  if (formContent != null) {
    top = top - formContent.scrollTop;
  }
  var buttons = ["Close"];
  var actions = [function() { dlgHelp.close(); }];
  var height = 100;
  var width = 360;
  if (helpType == "system") height = 135;
  var dlgHelp = new Dialog(top + 15, left - width, height, width, "Help", buttons, actions, true);
  var helpText = "";
  if (helpType == "pgroup") helpText = "To look up your iSeries or System i Processor Group, use the WRKLICINF (Work with License Information) command.";
  if (helpType == "model") helpText = "To look up your iSeries or System i Model Number, use the command DSPSYSVAL QMODEL.";
  if (helpType == "system") helpText = "The System Name appears on the System i Sign On Screen. <br><br> To look up the Serial Number and Processor Group, use the WRKLICINF (Work with License Information) command.";
  var content = dlgHelp.addLabel(10, 10, helpText); 
}

function show(id) {
  document.getElementById(id).style.display = "";
}

function hide(id) {
  document.getElementById(id).style.display = "none";
}

function submitForm(mode) {
  if (!validateForm()) return;
  
  var type = document.getElementById("type").value;
  var prod = document.getElementById("prod").value;
  if (prod == null || prod == "") prod = document.profoundForm.product.value;
  
  var downloadLink = "";
  if (type == "download") {
    if (prod == "rpgsp") downloadLink = "/RPGspSetup.exe";
    if (prod == "genie") downloadLink = "/GenieSetup.exe";
    if (prod == "idata") downloadLink = "/iDataSetup.exe";
    if (prod == "atrium") downloadLink = "/AtriumSetup.exe";
    if (prod == "rpgalive") {
      downloadLink = "/RPGAliveCA.exe";
      // to do -- different editions of RPG-Alive for SEU must be handled here
    }
    if (prod == "rpgalivegui") downloadLink = "/RPGAliveGUISetup.exe";
    document.profoundForm.downloadLink.value = downloadLink;
    if (downloadLink != "") location.href = downloadLink;
  }  
  
  var form = document.profoundForm;
  if (mode == "ajax") {
    ajaxSubmit(form, function(response) {
      var formContent = document.getElementById("formContent");
      formContent.innerHTML = response;
      formContent.style.overflowY = "hidden";
    });
  }
  else {
    form.submit();
  }
}

function validateForm() {
  var type = document.profoundForm.type.value;
  var prod = document.profoundForm.prod.value;
  var product = document.profoundForm.product.value;
  // if (type == "download" && (prod == "idata" || product == "idata")) {
  //   msg = "Please enter a valid invitation or scratch off code for the iData Pre-Release Download.\nIf you do not have one, please contact Profound Logic Software.";
  //   if (!isFilledIn("invitation", msg)) return false;
  //   if (ajax("/scratchoff.rpgsp?code=" + encodeURIComponent(document.profoundForm.invitation.value)) == 'false') {
  //     alert(msg);
  //     return false;
  //   }
  // }
  if (document.getElementById("marketing0").style.display == "none") document.getElementById("chkReceiveMarketing").checked = false;
  if (type == "download" && !isFilledIn("product", "Please select a product.")) return false;
  if (!isFilledIn("first", "Please enter first name.")) return false;
  if (!isFilledIn("last", "Please enter last name.")) return false;
  if (!isFilledIn("company", "Please enter company.")) return false;
  if (!isFilledIn("email", "Please enter a valid email address.")) return false;
  if (!isFilledIn("phone", "Please enter telephone.")) return false;
  if (!isFilledIn("address1", "Please enter address.")) return false;
  if (!isFilledIn("country", "Please select a country.")) return false;
  if (!isFilledIn("city", "Please enter city.")) return false;
  if (!isFilledIn("state", "Please enter state / province.")) return false;
  if (!isFilledIn("zip", "Please enter zip / postal code.")) return false;
  return true;
}

function isFilledIn(fieldName, errMsg, rowId) {
  if (rowId == null) rowId = fieldName + "0";
  var row = document.getElementById(rowId);
  if (row == null || row.style.display == "none") return true;
  var field = document.profoundForm.elements[fieldName];
  if (field == null) return true;
  if (field.value == "" || (fieldName == "email" && !utils.isEMailValid(field.value))) {
    if (errMsg == null) errMsg = "Please fill in required information.";
    alert(errMsg);
    field.focus();
    return false;
  }
  return true;
}

function validateContactForm() {
  if (document.contactForm.comments.value == "") {
    alert("Please fill out the contact form before clicking the send button.");
    return false;
  }
  return true;
}
