var bPfactoryJsDebug = false;
var sDebugText;           // for debug alert messages

function updateRedirect(sFormName, sNavToUrl)
{
  // Update the current form (e.g. sFormName = 'pam/gather') before redirecting to "sNavToUrl".
  // For example, when sNavToUrl = '../sequence/', redirect to the default aspx file in the "sequence" folder,
  // which would be at the same directory level as the current form's folder (e.g. pam\gather).

  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    document.forms[sFormName].elements['pf_redirect'].value = sNavToUrl;
    document.forms[sFormName].submit();
  }
  else if (sNavToUrl != null && sNavToUrl != '')  // no form to update
  {
    window.location.href = sNavToUrl;
  }
  return false;
 }


// ---------------------
// Code for doing popups
// ---------------------
var iPopupCounter = 0;


function destroyPopup(sWindowBase, iCounter, iWidth, iHeight)
{
  var sTxt = "height=" + iHeight + ",width=" + iWidth;
  if (iCounter > 0)
  {
    // Close the window only if the counter indicates that it already exists.
    // Otherwise, we needlessly open a new window, which can result in an annoying flash.
    var oOldWin = window.open("", sWindowBase + (iCounter - 1).toString(), sTxt);
    oOldWin.close();
    return true;
  }
  else
    return false;   // indicate nothing was done
}


function createPopup(sPopupType, sUrlName, sWindowBase, iWidth, iHeight)
{
  var sTxt;
  if (sPopupType == null || sPopupType == '')         // resizable without toolbar or menubar
    sTxt = "toolbar=no,location=no,menubar=no,resizable=yes,scrollbars=yes,width=";
  else if (sPopupType.toLowerCase() == 'standard')    // resizable with toolbar and menubar
    sTxt = "toolbar=yes,location=yes,menubar=yes,resizable=yes,scrollbars=yes,width=";
  else if (sPopupType.toLowerCase() == 'chromeless')  // fixed size, without toolbar or menubar
    sTxt = "toolbar=no,location=no,menubar=no,resizable=no,scrollbars=no,width=";
  sTxt += iWidth + ",height=" + iHeight;
  if (iPopupCounter > 0)
  {
    // Close the old window only if the counter indicates that it exists.
    if (destroyPopup(sWindowBase, iPopupCounter, iWidth, iHeight))
      iPopupCounter--;
  }
  var oPopup = window.open(sUrlName, sWindowBase + iPopupCounter.toString(), sTxt);
  if (oPopup && typeof(oPopup) != 'undefined')
  {
    if (iPopupCounter == 0)
      ++iPopupCounter;    // don't increment past 1
    oPopup.focus();
  }
}

// ----------------------------
// End of code for doing popups
// ----------------------------


function init_select(sTag, oValue, sFormName)
{
  var oElem;
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElem = oForm.elements[sTag];

    // If the element is undefined, try getElementById(), which requires the element to have "sTag" as its ID.
    if (typeof(oElem) == 'undefined')
      oElem = document.getElementById(sTag);

    if (oElem && typeof(oElem) != 'undefined')
    {
      // Must be a select element, whose types begin with "select".
      if (oElem.type.indexOf('select') > -1)
      {
        var oOptions = oElem.options;
        var i;
        for (i = 0; i < oOptions.length; i++)
        {
          if (oOptions[i].value == oValue)
          {
            oElem.selectedIndex = i;
            return;
          }
        }
        oElem.selectedIndex = 0;
      }
    }
  }
}


function init_select_by_text(sTag, sTextVal, sFormName)
{
  var oElem;
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElem = oForm.elements[sTag];

    // If the element is undefined, try getElementById(), which requires the element to have "sTag" as its ID.
    if (typeof(oElem) == 'undefined')
      oElem = document.getElementById(sTag);

    if (oElem && typeof(oElem) != 'undefined')
    {
      // Must be a select element, whose types begin with "select".
      if (oElem.type.indexOf('select') > -1)
      {
        var oOptions = oElem.options;
        var i;
        for (i = 0; i < oOptions.length; i++)
        {
          if (oOptions[i].text == sTextVal)
          {
            oElem.selectedIndex = i;
            return;
          }
        }
        oElem.selectedIndex = 0;
      }
    }
  }
}


// This uses a comma-separated list, as in the case of a "multiple" select element.
// Woe to you if a value has a comma in it.
function init_multi(sTag, oValue, sFormName)
{
  var oElem;
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElem = oForm.elements[sTag];

    // If the element is undefined, try getElementById(), which requires the element to have "sTag" as its ID.
    if (typeof(oElem) == 'undefined')
      oElem = document.getElementById(sTag);

    if (oElem && typeof(oElem) != 'undefined')
    {
      var oOptions = oElem.options;
      var oVals = oValue.split(",");
      var i, j;
      for (i = 0; i < oOptions.length; i++)
      {
        for (j = 0; j < oVals.length; j++)
        {
          // Allow for single quotes around items in list.
          if (oOptions[i].value == oVals[j] || "'" + oOptions[i].value + "'" == oVals[j])
          {
            oOptions[i].selected = true;
          }
        }
      }
    }
  }
}


function checkmark_all(oForm)
{
  // Checkmarks all checkboxes.  For more flexibility, use init_checkbox_array.
  var oElem;
  for (var i = 0; i < oForm.elements.length; i++)
  {
    oElem = oForm.elements[i];
    if (oElem.type == 'checkbox')
    {
      oElem.checked = true;
    }
  }
}


function init_checkbox_array(sTag, oValue, bSetChecked, sFormName)
{
  // If "oValue" is a comma-separated list, each "sTag" checkbox will be tested against each value.
  // Using null "oValue" sets all checkboxes to "bSetChecked" (true = checked, false = unchecked).
  // This function also works for a single checkbox.
  var bChecked = (bSetChecked == true ? true : false);  // Restrict to boolean
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    var oElemArr = oForm.elements[sTag];
    var bInverse = false;
    var bMatch;
    var i, j;
    var oChkboxes, oVals;

    if (oElemArr && typeof(oElemArr) != 'undefined')
    {
      if (oValue != null)
      {
        // If first char is "!", the oValue list contains "NOT IN" values.
        if (oValue.substring(0, 1) == "!")
        {
          bInverse = true;
          oValue = oValue.substring(1);     // Remove "!" before parsing
        }
      }

      oVals = (oValue == null ? null : oValue.split(","));

      oChkboxes = oElemArr;
      if (!oChkboxes.length)  // single checkbox
      {
        if (oValue == null || oChkboxes.value == oValue)
        {
          oChkboxes.checked = bChecked;
        }
      }
      else    // array of checkboxes with the same name
      {
        for (i = 0; i < oChkboxes.length; i++)  // for each checkbox in the group
        {
          if (oValue == null)
          {
            oChkboxes[i].checked = bChecked;
          }
          else
          {
            // See if this checkbox's value is in the parameter list of "selected" values.
            bMatch = false;
            for (j = 0; j < oVals.length; j++)
            {
              if (oChkboxes[i].value == oVals[j])
              {
                bMatch = true;
                break;
              }
            }
            if (bMatch)
            {
              // This "matching" checkbox is set to bChecked (normally true, which is checked), unless
              // the list contains "NOT IN" values, in which case it's set to the inverse of bChecked.
              oChkboxes[i].checked = (bInverse ? !bChecked : bChecked);
            }
            else if (bInverse)
            {
              // This checkbox's value isn't in the list, but the list contains "NOT IN" values,
              // so the checkbox is set to bChecked (normally true, which is checked).
              oChkboxes[i].checked = bChecked;
            }
          }
        }
      }
    }
  }
}


function enable_checkbox_array(sTag, oValue, bEnable, sFormName)
{
  // Enable or disable checkboxes named "sTag", depending on "bEnable" value.
  var oElemArr;
  var bDisabled = (bEnable == true ? false : true);   // Restrict to boolean
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElemArr = oForm.elements[sTag];
    var oVals = (oValue == null ? "" : oValue.split(","));
    var i, j;

    if (oElemArr && typeof(oElemArr) != 'undefined')
    {
      var oChkboxes = oElemArr;
      for (i = 0; i < oChkboxes.length; i++)
      {
        if (oVals != "")
        {
          for (j = 0; j < oVals.length; j++)
          {
            if (oChkboxes[i].value == oVals[j])
            {
              oChkboxes[i].disabled = bDisabled;
            }
          }
        }
      }
    }
  }
}


function init_radio(sTag, oValue, sFormName)
{
  var i, oElemArr;
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElemArr = oForm.elements[sTag];

    if (oElemArr && typeof(oElemArr) != 'undefined')
    {
      var oRadios = oElemArr;
      if (!oRadios.length)    // single radio button (unlikely)
      {
        if (oRadios.value == oValue)
        {
          oRadios.checked = true;
        }
      }
      else
      {
        for (i = 0; i < oRadios.length; i++)
        {
          if (oRadios[i].value == oValue)
          {
            oRadios[i].checked = true;
            return;
          }
        }
      }
    }
  }
}


function changeimg(oImg, sName)
{
  if (document.images && document.images[sName])
    document.images[sName].src = oImg;
}


function dosort(sParam, oValue, sDir, sFormName)
{
  var oForm = document.forms[sFormName ? sFormName : 0];
  if (!oForm)
    alert("dosort: no form named " + sFormName);
  else
  {
    if (!oForm.elements)
      alert("dosort:" + sFormName + " not a form? ");
    if (!oForm.elements[sParam])
      alert("dosort: no element named " + sParam);
    if (!oForm.elements["pf_dir"])
      alert("dosort: no form named pf_dir");
  }
  if (!oForm ||
      !oForm.elements[sParam] ||
      !oForm.elements["pf_dir"])
    return;

  oForm.elements[sParam].value = oValue;
  if (sDir != null)
  {
    oForm.elements["pf_dir"].value = sDir;
  }

  if (oForm.validate)
    oForm.validate();

  if (!oForm.onsubmit || oForm.onsubmit())
    oForm.submit();
}


function dosubmit(sParam, oParVal, sFormName)
{
  if (bPfactoryJsDebug)
    sDebugText = 'dosubmit:\n';

  // Set the specified parameter in the form to "oParVal".
  // To set multiple parameters, pass in values delimited by "|" in "sParam" and "oParVal".
  var oForm = document.forms[sFormName ? sFormName : 0];
  if (!oForm)
  {
    alert("dosubmit: no form named " + sFormName);
    return;
  }
  else if (!oForm.elements)
  {
    alert("dosubmit: no elements found for form " + sFormName);
    return;
  }

  if (sParam.indexOf("|") < 0)
  {
    // Set a single parameter.
    if (!oForm.elements[sParam])
    {
      alert("dosubmit: no element named " + sParam + " found in form " + sFormName);
      return;
    }
    oForm.elements[sParam].value = oParVal;
    if (bPfactoryJsDebug)
      sDebugText += sParam + ' value set to ' + oForm.elements[sParam].value.toString() + '\n';
  }
  else
  {
    // Set multiple parameters.
    var sParArr = sParam.split("|");
    var oPvalArr = oParVal.split("|");
    for (var i = 0; i < sParArr.length; i++)
    {
      if (!oForm.elements[sParArr[i]])
      {
        alert("dosubmit: no element named " + sParArr[i] + " found in form " + sFormName);
        return;
      }
    }
    for (var i = 0; i < sParArr.length; i++)
    {
      oForm.elements[sParArr[i]].value = oPvalArr[i];
      if (bPfactoryJsDebug)
        sDebugText += 'Param ' + sParArr[i] + ': value set to ' + oForm.elements[sParArr[i]].value.toString() + '\n';
    }
  }

  if (oForm.validate)
    oForm.validate();

  if (bPfactoryJsDebug)
    alert(sDebugText);

  if (!oForm.onsubmit || oForm.onsubmit())      // could also (or instead) test oForm.submit?
    oForm.submit();
}


function onchange_search(sTag, sFormName, iIndx)
{
  var oElem;
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElem = oForm.elements[sTag];

    // If the element is undefined, try getElementById(), which requires the element to have "sTag" as its ID.
    if (typeof(oElem) == 'undefined')
      oElem = document.getElementById(sTag);

    if (oElem && typeof(oElem) != 'undefined' && oElem.value)
    {
      var oOp = oForm.elements[sTag + "op"];
      if (oOp && typeof(oOp) != 'undefined')
      {
        if (oOp.selectedIndex <= 0)
          oOp.selectedIndex = (iIndx == null ? 2 : iIndx);
      }
    }
  }
}


function search_select(sTag, sFormName)
{
  var oElem;
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElem = oForm.elements[sTag];

    // If the element is undefined, try getElementById(), which requires the element to have "sTag" as its ID.
    if (typeof(oElem) == 'undefined')
      oElem = document.getElementById(sTag);

    if (oElem && typeof(oElem) != 'undefined')
    {
      var oOp = oForm.elements[sTag + "op"];
      if (oOp && typeof(oOp) != 'undefined')
      {
        oOp.value = (oElem.selectedIndex > 0 ? "=" : "ANY");   // Assumes first option is null (selects all)
      }
    }
  }
}


// This uses a comma-separated list, as in the case of a "multiple" select element.
function search_multi(sTag, sFormName)
{
  var oElem;
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    oElem = oForm.elements[sTag];

    // If the element is undefined, try getElementById(), which requires the element to have "sTag" as its ID.
    if (typeof(oElem) == 'undefined')
      oElem = document.getElementById(sTag);

    if (oElem && typeof(oElem) != 'undefined')
    {
      var oOp = oForm.elements[sTag + "op"];
      if (oOp && typeof(oOp) != 'undefined')
      {
        oOp.value = (oElem.selectedIndex > 0 ? "IN" : "ANY");  // Assumes first option is null (selects all)
      }
    }
  }
}


function navigate_to_project(sParamName, sElementName, sFormName, sProjUrl)
{
  var oForm = document.forms[sFormName];
  if (oForm && typeof(oForm) != 'undefined' && oForm.elements && typeof(oForm.elements) != 'undefined')
  {
    var oElem = oForm.elements[sElementName];
    if (oElem && oElem.value != null && oElem.value != '')
    {
      window.location.href = sProjUrl + '/?' + sParamName + '=' + oElem.value;
    }
  }
}


function addToFavorites(sUrlAddress, sPageName)
{
  if (window.external)
  {
    window.external.AddFavorite(sUrlAddress, sPageName);
  }
  else
  {
    alert("Sorry! Your browser doesn't support this function.");
  }
}


function isBlank(oObj)
{
  var oPattern = /\S/;    // tests true for any non-whitespace char
  return (oObj == null || !oPattern.test(oObj));
}


function showThumb(sNumber, sTitle, oThumbImg)
{
  if (sNumber.indexOf("|") >= 0)
  {
    // Set multiple parameters.
    var sNumberArray = sNumber.split("|")
    sNumber = sNumberArray[0];
    sTitle = sNumberArray[1];
    oThumbImg = sNumberArray[2];
  }

  //alert("at showThumb: \nsNumber = " + sNumber + "\nsTitle = " + sTitle + "\noThumbImg = " + oThumbImg);

  var oElem = document.getElementById('illoView');
  oElem.firstChild.nodeValue = (sNumber != null && sNumber != "" ? sNumber + " - " + sTitle : "No preview available for this entry");
  changeimg((oThumbImg != null && oThumbImg != "" ? oThumbImg : "../shared/spacer.gif"), "thumb");
}


function zeroPad(nNumberToPad, nTotalDigits)
{
  // Unlike C#'s ToString, e.g. ToString("00"), the JavaScript toString method doesn't offer zero padding.
  var sLeadingStr = '';
  var sNumToPad = nNumberToPad.toString();
  if (nTotalDigits > sNumToPad.length)
  {
    for (i = 0; i < (nTotalDigits - sNumToPad.length); i++)
    {
      sLeadingStr += '0';
    }
  }
  return sLeadingStr + sNumToPad;
}
