//Array used to hold original versions of dropdowns that are modified on the form.
var dropDowns = new Array();

/// <summary>
/// This will filter out the dropdown with the indicated id based on the contents of an associated textbox.
/// </summary>
/// <param name="dropDownName">
/// The name of the dropdown to filter.
/// </param>
/// <param name="index">
/// The index of the dropdown with the indicated name. This would occur if the coding sheet accepted multiple
/// entries.
/// </param>
/// <remarks>
/// This script file should be placed in a sibling directory to the SID_NNN directories called IGAMScripts.
/// </remarks>
function DropDownFilter(dropDownName, index)
{
    //Get a reference to the dropdown.
    var dropDown = document.getElementsByName(dropDownName);
    if (dropDown != null) dropDown = dropDown[0];

    //Get a reference to the associated textbox used to enter the search criteria.
    var searchBox = document.getElementsByName(dropDownName + "_Search_" + index);
    if (searchBox != null) searchBox = searchBox[0];

    //Get a reference to the clone of the dropdown that has previously been made and stored in the dropDowns array.
    var clone;
    if (dropDown.arrayIndex >= 0) clone = dropDowns[dropDown.arrayIndex];
    
    if (dropDown != null && searchBox != null)
    { 
        //Clone the select list for later use if not already cloned.
        if (clone == null)
        {
            clone = dropDown.cloneNode(true);
            
            //Save clone in the dropDowns array.
            dropDown.arrayIndex = dropDowns.length;
            dropDowns[dropDowns.length] = clone;
        }

        //First remove all options.
        dropDown.innerHTML = "";  
            
        //Now add all entries that start with the indicated text.
        var text = Trim(searchBox.value);        
        if (text != "")
        {
            //Use a regular expression to look for matches.
            var reg = new RegExp("^" + text, "i");	//begins with

            if (searchBox.getAttribute('searchOperator') == "C")
                reg = new RegExp(text, "i"); 	//contains


            //Always add the first entry.
            dropDown.appendChild(clone.options[0].cloneNode(true));
            
            var len = clone.options.length;
            var tmp = null;
            var added = 0;
            for (var i = 1; i < len; i++)
            {
                var option = clone.options[i];
                if (reg.test(option.text))
                {
                    tmp = option.cloneNode(true);
                    dropDown.appendChild(tmp);
                    added++;
                }
            }
            
            //If we've only added one entry, auto-select this entry.
            if (added == 1)
                setTimeout('SelectFirstOption("' + dropDownName + '",' + index + ')', 100);
        }
        else
        {
            //Add back all the entries since the search text was cleared. For IE we have a very fast way.
            if (document.all) {
               //IE
               var tmp = clone.cloneNode(true);
               tmp.name = dropDownName;
               tmp.id = "";
               tmp.style.display = "";
               dropDown.outerHTML = tmp.outerHTML;               
            }
            else {
               //Other
               var len = clone.options.length;
               for (var i = 0; i < len; i++)
                   dropDown.appendChild(clone.options[i].cloneNode(true));
            }
        }             
    }
}


/// <summary>
/// This will clear the filter on the dropdown with the indicated id.
/// </summary>
/// <param name="dropDownName">
/// The name of the dropdown to filter.
/// </param>
/// <param name="index">
/// The index of the dropdown with the indicated name. This would occur if the coding sheet accepted multiple
/// entries.
/// </param>
function ClearDropDownFilter(dropDownName, index)
{
    //Get a reference to the associated textbox used to enter the search criteria.
    var searchBox = document.getElementsByName(dropDownName + "_Search_" + index);
    if (searchBox != null) searchBox = searchBox[0];
    
    //Clear this textbox and call the filter routine.
    searchBox.value = "";
    
    DropDownFilter(dropDownName, index);
}


/// <summary>
/// Trim spaces from the beginning and end of the string.
/// </summary>
/// <param name="str">
/// The string to trim.
/// </param>
/// <returns>
/// The string with all leading and trailing spaces removed.
/// </returns>
function Trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}


/// <summary>
/// Select the first real option in the dropdown. This will actually be the second option.
/// </summary> 
/// <param name="dropDownName">
/// </param>
function SelectFirstOption(dropDownName, index)
{
    //Get a reference to the dropdown.
    var dropDown = document.getElementsByName(dropDownName);
    if (dropDown != null) dropDown = dropDown[0];
    
    dropDown.selectedIndex = 1;
}

/// <summary>
/// Used when a contact field is changed to determine whether we should show/hide required icons
/// </summary>
/// <param name='e'>
/// Inupt element user has changed the value on
/// </param>
function contactRequiredUpdate(e)
{
   //First, get the contact entity this element was for
   if (e != null)
   {
     var attr = e.getAttribute('CONTACT_ENTITY');
     var isPopulated = false;
   }

   if (attr != null && attr != '')
   {
      //If this contact has a field populated on another page, don't even bother cause nothing
      // we do on this page will change the required state of the contact's fields
      if (typeof(populatedContacts) != 'undefined' && populatedContacts != '')
      {
         var contactArray = populatedContacts.split(',');
         if (contactArray != null)
         {
            for (var i = 0; i < contactArray.length; i++)
            {
               if (contactArray[i] == attr) return;
            }
         }         
      }

      //Get the required icon divs for this same entity, if there are any
      var currentElement = null;
      var iconDiv = null;
      var iconDivs = new Array();

      for (var j = 0; j < document.forms.length; j++)
      {
         for (var i = 0; i < document.forms[j].elements.length; i++)
         {
            currentElement = document.forms[j].elements[i];

            //Is this a field for the contact we're looking at?
            if (currentElement.getAttribute('CONTACT_ENTITY') == attr)
            {
               //If so, lets try and find an icon div for it.
               iconDiv = document.getElementById(currentElement.name + '_ICON_DIV');
               if (iconDiv != null)
               {
                  iconDivs[iconDivs.length] = iconDiv;
               }

               //Also look for an error div (holding the validation error text on review page)
               iconDiv = document.getElementById(currentElement.name + '_ERROR_DIV');
               if (iconDiv != null)
               {
                  iconDivs[iconDivs.length] = iconDiv;
               }

               //Also, make sure to note the contact has data if this element does
               if (currentElement.type == 'checkbox')
               {
                  if (currentElement.checked)
                  {
                     isPopulated = true;
                  }
               }
               else if (currentElement.type == 'select-one')
               {
                  if (currentElement.value.toString() != '0' && currentElement.value.toString() != '')
                  {
                     isPopulated = true;
                  }
               }
               else if (currentElement.value.toString() != '') 
               {
                  isPopulated = true;
               }
            }
         }
      }

      //Do we have any required icon divs?  If not, we've got nothing to do.  If so, and they 
      //currently show and the element is populated, there's nothing to change.  Similairly, if 
      // they're currently hidden and the element is empty, there's nothing to change
      if (iconDivs.length == 0 || (iconDivs[0].style.display == 'none' && !isPopulated) || (iconDivs[0].style.display == 'block' && isPopulated)) 
      {
         return;
      }

      //If we're still here, we need to go through all of the divs and set them to hidden/visible 
      for (var i=0; i < iconDivs.length; i++)
      {
         iconDivs[i].style.display = (isPopulated ? '' : 'none');
      }
    
   }

   return;
}


/// <summary>
/// Used when an Org PC contact field is changed to update an associated Request PC field
/// </summary>
/// <param name='e'>
/// Org PC Inupt element user has changed the value on
/// </param>
/// <param name='pcFieldID'>
/// ID of the Request PC field we need to update
/// </param>
function updateRequestPCField(e,pcFieldID)
{
   if (e != null && pcFieldID != null && pcFieldID != '')
   {
      var pcField = document.getElementById(pcFieldID);
     
      if (pcField != null)
      {
         //Some browsers don't support innerText (ex. Firefox), so we need to check
         //which property we need to update
         var hasInnerText = ((document.getElementsByTagName("body")[0].innerText != undefined) ? true : false);

         if (e.type == 'checkbox')
         {
            if (hasInnerText)
            {
               pcField.innerText = (e.checked ? 'Yes' : '');
            }

            else
            {
               pcField.textContent = (e.checked ? 'Yes' : '');
            }
         }

         else if (e.type == 'select-one')
         {
            if (hasInnerText)
            {
               pcField.innerText = (e.selectedIndex == 0 ? '' : e.options[e.selectedIndex].text);
            }

            else
            {
               pcField.textContent = (e.selectedIndex == 0 ? '' : e.options[e.selectedIndex].text);
            }
         }

         else
         {
            (hasInnerText ? pcField.innerText = e.value : pcField.textContent = e.value);
         }
      }
   }
}

///<summary>
///Used by onchange of code table dropdowns when percentages have been included.  Enables/disables
///the percentage text box for the passed-in dropdown
///</summary>
///<param name='e'>
///code table dropdown that's just been changed
///</param>
function updatePctInputs(e)
{
   if (e != null)
   {
      var pctElem = document.getElementsByName(e.name + '_PCT');
      
      if (pctElem != null)
      {
         if (e.selectedIndex == 0)
         {
            //they've set the dropdown to none.  set pct to 0 and disable
            pctElem[0].value = '0';
            pctElem[0].disabled = true;
         }

         else
         {
            //they've picked a code so let them set a percentage
            pctElem[0].disabled = false;
         }

         //Run through all dropdowns for the table and figure out if only one is left with a value selected
         pctElem = null;
         var runningElem = null;
         var rootName = e.name.substring(0,e.name.lastIndexOf('.'));

         for (i = 0; i < 99 ; i++)
         {
            runningElem = document.getElementsByName(rootName + '.' + i);
            //If we finally hit an index that doesn't exist, we've exhausted the dropdowns for this code table; get out
            if (runningElem == null || runningElem.length == 0)
               break;
            else if (runningElem[0].selectedIndex > 0)
            {
               //We found one that's populated; have we already found one that's populated?
               if (pctElem == null)
               {
                  //Nope: make a note of this one
                  pctElem = document.getElementsByName(runningElem[0].name + '_PCT');
               }
               else
               {
                  //Yup: there are at least two populated, so don't go changing anything
                  pctElem = null;
                  break;
               }
            }  
         }
            
         //if we found one and only one dropdown populated, set it's percent box to 100%
         if (pctElem != null) pctElem[0].value = '100';

      }
   }
}

///<summary>
///will prevent entry of any character other than 0 through 9 (exceptions built in for control keys)
///</summary>
///<param name='e'>
///event that fired off a call here
///</param>
function integersOnly(e)
{

  if (window.event)
    key = window.event.keyCode;
  else if (e)
    key = e.which;
  else
    return true;

  keychar = String.fromCharCode(key);

  // control keys
  if ((key==null) || (key==0) || (key==8) || 
     (key==9) || (key==13) || (key==27) )
    return true;

  // numbers
  else if (("0123456789").indexOf(keychar) > -1) 
    return true;

  else
    return false;
}

///<summary>
///Will make sure the value is a number (if not, sets to 0) and no more than 100 (if so, sets to 100)
///</summary>
///<param name='e'>
///control that we're validating the number for
///</param>
function validatePctInput(e)
{
   if (isNaN(e.value))
      e.value=0;
   else if (Number(e.value) > 100)
      e.value = 100;
}