
// Validate the currently entered phone number to ensure only valid characters are entered.
function validatePhone(e)
{
  var fieldSource = window.event.srcElement;
  var strCheck = '0123456789-xX(). ';

  var uniCode = (window.Event) ? e.which : e.keyCode;

  if( uniCode!=8 && uniCode!=9) // Allow backspace or delete key
  {
	  var key = String.fromCharCode(uniCode);  // Get key value from key code
 	  // Only allow valid char
	  if (strCheck.indexOf(key) == -1) {
		return false;  // Not a valid key
	  }
	  else
	  {
		return true;
	  }

  }

}

// Validate the currently entered SSN to ensure only valid characters are entered.
function validateSSN(event)
{
	var fieldSource = getFieldFromEvent(event);
	if(fieldSource == null) return;

  var strCheck = '0123456789-';

  var whichCode = event.which || event.keyCode;
  //alert(whichCode);

  if (whichCode == 13 || whichCode == 9)
  {
    formatSSN(event);  // Format before the form is submitted
    return true;  // Carriage Return
  }

  var key = String.fromCharCode(whichCode);  // Get key value from key code
	//alert(key);
  // Only allow valid char
	if(whichCode == 8) return true;

  if (strCheck.indexOf(key) == -1)
    return false;  // Not a valid key

  if (fieldSource.value.length > 11)
    return false;

  return true;
}

// Format the entered SSN to add dashes where appropriate.  This should only
// be called during onBlur.
function formatSSN(event)
{
	var fieldSource = getFieldFromEvent(event);
	if(fieldSource == null) return;

  var strCheck = '0123456789';

  var len = fieldSource.value.length;
  var aux = '';
  var sep = '';
  var idx = 0;

  for (var i = 0; i < len; i++)
  {
    sep = '';
    if (idx < 9)
    {
      if (strCheck.indexOf(fieldSource.value.charAt(i)) >= 0)
      {
        idx += 1;
        if (idx == 3 || idx == 5)
          aux += fieldSource.value.charAt(i) + "-";
        else
          aux += fieldSource.value.charAt(i);
      }
    }
  }

  if (aux.length == 3 || aux.length == 6)
  {
    aux += "-";
  }

  fieldSource.value = aux;
}

function validateDollarAmount(e)
{
  var fieldSource = window.event.srcElement;
  var strCheck = '0123456789.';

  var whichCode = (window.Event) ? e.which : e.keyCode;
  var key = String.fromCharCode(whichCode);  // Get key value from key code

  // Only allow characters from the list
  if (strCheck.indexOf(key) == -1)
    return false;

  return true;
}

// Pagination
// Get list of checkbox checked/or not
function SelectedPage(docObject, checkboxName)
{
  var result = '';
  for (var i=0; i < docObject.forms.length; i++)
  {
    for (var j=0; j < docObject.forms[i].elements.length; j++)
    {
      if (docObject.forms[i].elements[j].name == checkboxName)
      {
        if (result.length > 0)
          result += ',';

        result += docObject.forms[i].elements[j].checked;
      }
    }
  }
  //alert("result:" + result);

  return result;
}

//Pagination
//Attached GUI checkbox status to url for pagination.
//TODO: use value SelectableSearchValueListAdapter.SELECTED_REQUEST_ATTRIBUTE_KEY
//instead hard coded "selected"
function SelectedPaging(docObject, checkboxName, url)
{
  var result = SelectedPage(docObject, checkboxName);
  if (result.length > 0)
  {
    location.replace(url + "selected=" + result + "&amp;");
  }
  else
  {
    location.replace(url);
  }
}

function CollapsablePanel_ExpandCollapse(hideThis, changeThis, setThis, exText, colText)
{
  if(document.getElementById(hideThis).style.display == '')
  {
    document.getElementById(hideThis).style.display = 'none';
    if(document.getElementById(changeThis) != null)
      document.getElementById(changeThis).innerHTML = exText;
    document.getElementById(setThis).value = 'true';
  }
  else
  {
    document.getElementById(hideThis).style.display = '';
    if(document.getElementById(changeThis) != null)
      document.getElementById(changeThis).innerHTML = colText;
    document.getElementById(setThis).value = 'false';
  }
}

//
// Submits a form after setting a field to a certain value on the form.
// This is useful when a form has more than one button with the same value, but needs
// different processing on the server.  The field that gets set should typically be
// a hidden field.
//
// formObject - The form
// submitField - The field whose value should be updated.
// submitValue - The value to update the field with.
//
function submitForm(formObject, submitFieldId, submitFieldValue)
{
    // Find the field
    var submitField = document.getElementById(submitFieldId);

    // Substitute the value
    submitField.value = submitFieldValue;

    // Submit the form
    formObject.submit();
}

//
// Sets a field to a value on a form.
//
// formObject - The form
// formField - The field to set
// formValue - The value to set
//
function setFormValue(formObject, formField, formValue)
{
    // Update the submitField form element
    for (var i=0; i < formObject.elements.length; i++)
    {
      if (formObject.elements[i].name == formField)
      {
          formObject.elements[i].value = formValue;
      }
    }
}

//Used to expand and collapse the multiple fields within <div> tags.
//toggles the display value between block and none
//none: hide block:display
function expandOrCollapseIt(whichEl)
{
  whichEl.style.display = (whichEl.style.display == "block" ) ? "none" : "block";
}

// Expands or collapses a section by toggling the existing section state.
function expandOrCollapse(whichEl,imageName,hiddenFieldname)
{
  if (whichEl.style.display == "block")
    {
        collapseSection(whichEl, imageName, hiddenFieldname);
    }
  else
  {
        expandSection(whichEl, imageName, hiddenFieldname);
  }
}

// Expands a section
function expandSection(whichEl, imageName, hiddenFieldname)
{
    whichEl.style.display = "block";
  imageName.src = "../images/redArrowDown.gif";
    imageName.alt = "Expandable Section, Expanded";
    if (hiddenFieldname != null)
    {
        hiddenFieldname.value = "true";
    }
}

// Collapses a section
function collapseSection(whichEl, imageName, hiddenFieldname)
{
    whichEl.style.display = "none";
    imageName.src = "../images/redArrowRight.gif";
    imageName.alt = "Expandable Section, Collapsed";
    if (hiddenFieldname != null)
    {
        hiddenFieldname.value = "false";
    }
}

function expandOrCollapseByName(whichEl,imagename,hiddenfieldname)
{
    var whichEl2 = document.getElementById(whichEl);
    var imagename2 = document.getElementById(imagename);
    var hiddenfieldname2 = document.getElementById(hiddenfieldname);
  //collapse
  if (whichEl2.style.display == "block") {
    whichEl2.style.display = "none";
    hiddenfieldname2.value="false";
    imagename2.src="../images/redArrowRight.gif";
        imagename2.alt="Expandable Section, Collapsed";
  }
  //expand
  else
  {
    whichEl2.style.display = "block";
    hiddenfieldname2.value="true";
    imagename2.src="../images/redArrowDown.gif";
        imagename2.alt="Expandable Section, Expanded";
  }
}

// Updates the site of change field when the source of change field gets update.
// When the selectField is equal to the selectValue, the updateField is updated with the updateValue
// and the updateField is disabled.  Otherwise, the updateField is re-enabled.
function updateSiteOfChange(selectField, selectedValue, updateField, updateFieldHidden, updateValue)
{
  if (selectField.value == selectedValue)
  {
    // Re-enable main field and disable hidden field
    updateField.disabled = false;
    updateFieldHidden.disabled = true;
  }
  else
  {
    // Update value and disable field
    updateField.value = updateValue;
    updateFieldHidden.value = updateValue;
    updateField.disabled = true;
    updateFieldHidden.disabled = false;
  }
}

// Function that trims blanks from Strings
function trimString(str)
{
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
String.prototype.trim = trimString;

// Updates additional search criteria text to indicate whether
function updateAdditionalCriteriaText(criteria, expandCollapseElement, additionalTextElement, additionalText)
{
    if (expandCollapseElement.style.display == "none")
    {
        // Element is now collapsed
        if (dataSpecified(criteria))
        {
            additionalTextElement.value = additionalText;
        }
        else
        {
            additionalTextElement.value = "";
        }
    }
    else
    {
        // Element is now expanded
        additionalTextElement.value = "";
    }
}

// Function that determines if data is specified in the passed in Array of elements.
// Text boxes and radio buttons are the only controls currently supported.
function dataSpecified(dataArray)
{
    // Boolean to hold whether additional data has been specified
    var additionalDataSpecified = false;

    // Loop through all fields in the array
    for (var i=0; i < dataArray.length; i++)
    {
        // Get current field
        var field = dataArray[i];
		if(!field) continue;

        // See if data was specified for field
        if (field.type == 'radio')
        {
            // If the "All" radio button is not checked, assume selection criteria is present
            if (!field.checked)
            {
                additionalDataSpecified = true;
            }
        }
        else
        {
            if (field.type == 'text')
            {
                // If there is data in a text field, assume selection criteria is present
                if (field.value.trim().length > 0)
                {
                    additionalDataSpecified = true;
                }
            }
        }

    }

    return additionalDataSpecified;
}

// Sets target field value from the a source field value.
function setField(formObject,targetField,sourceField)
{
    if(formObject != null)
    {
      var ssn = formObject.ssn.value;
      var field =  formObject.elements;
      if(field.length != null && field.length > 0)
      {
            for(var i = 0, len=field.length; i < len; i++)
            {
                if(field[i].name == targetField)
                {
                    field[i].value = sourceField.value;
                    return;
                }
            }
      }
    }
}

function switchSection(selectedCountry,idUSASection,idNonUSASection)
{
  if(selectedCountry == null) return;
  var domestic = document.getElementById(idUSASection);
  var foreign = document.getElementById("idNonUSASection");
  if(selectedCountry.value == "USA")
  {
      domestic.style.display = "block";
      foreign.style.display = "none";
  }
  else
  {
      domestic.style.display = "none";
      foreign.style.display = "block";
  }
}

// The following are AJAX related functions for City and State lookup.

function getHttpObject()
{
    if (window.XMLHttpRequest)
    {
      return new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    {
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}

var xmlHttpReq = getHttpObject();
function lookupDisability(event)
{
  if (xmlHttpReq == null) return;

	var code = getFieldFromEvent(event);
	if(code == null) return;

	var index = code.id.split('-')[1];

    for (var i=0; i < code.form.elements.length; i++)
    {
      if (code.form.elements[i].name == "selectedDisabilityIndexes" && code.form.elements[i].value == index)
      {
        if (code.value.length >= 4)
        {
          code.form.elements[i].checked = true;

          var fieldName = "disDescription[" + index + "]";
          document.getElementById(fieldName).value = "Looking up description...";

          var param = code.value + ":" + fieldName;
          var url = "/esr/ratedDisabilityCodeLookup.do?disabilityCode=" + encodeURI(param);
          xmlHttpReq.open("GET", url, true);
          xmlHttpReq.onreadystatechange = handleRDHttpResponse;
          xmlHttpReq.send(null);
        }
        else
        {
          code.form.elements[i].checked = false;
          document.getElementById("disDescription[" + index + "]").value = "";
        }
      }
    }

}

function handleRDHttpResponse()
{
  if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
  {
    if (xmlHttpReq.responseText.indexOf('invalid') == -1)
    {
      var xmlDocument = xmlHttpReq.responseXML;
      var val = xmlDocument.getElementsByTagName('codeLookup');
      var fieldName = val.item(0).getElementsByTagName('field');
      var key = val.item(0).getElementsByTagName('key');
      var value = val.item(0).getElementsByTagName('value');

      document.getElementById(fieldName.item(0).firstChild.data).value = value.item(0).firstChild.data;
    }
    else
    {
      alert("Invalid Rated Disability Code.");
    }
  }
}

function powCaptivityDays(index)
{
  if(xmlHttpReq == null) return;

  var fieldName = "powCaptivityDays[" + index + "]";
  document.getElementById(fieldName).value = "";

  var powCaptureDateFieldName = "powCaptureDate[" + index + "]";
  var powCaptureDate = document.getElementById(powCaptureDateFieldName).value;

  var powReleaseDateFieldName = "powReleaseDate[" + index + "]";
  var powReleaseDate = document.getElementById(powReleaseDateFieldName).value;

  if(powCaptureDate != null && powCaptureDate.length >= 6 && powReleaseDate != null && powReleaseDate.length >= 6)
  {
    var param = powCaptureDate + ":" + powReleaseDate + ";" + fieldName;
    var url = "/esr/powCaptivityDays.do?days=" + encodeURI(param);
    xmlHttpReq.open("GET", url, true);
    xmlHttpReq.onreadystatechange = handlePOWDaysHttpResponse;
    xmlHttpReq.send(null);
  }
}

function handlePOWDaysHttpResponse()
{
    if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
    {
      if(xmlHttpReq.responseText.indexOf('invalid') == -1)
      {
        var xmlDocument = xmlHttpReq.responseXML;
        var val = xmlDocument.getElementsByTagName('captivityDays');

        if (val == null)
        {
          return;
        }
        if (val.item(0) == null)
        {
          return;
        }

        var fieldName = val.item(0).getElementsByTagName('field');
        var days = val.item(0).getElementsByTagName('days');

      if (days.item(0).firstChild.data != null)
        document.getElementById(fieldName.item(0).firstChild.data).value = days.item(0).firstChild.data;
      }
    }
}

function lookupCampLocation(code, index)
{
    if(xmlHttpReq == null) return;
    if(code != null && code.value != null && code.value.length >= 0)
    {
      document.getElementById("powCampCode[" + index + "]").value = "Look up for code: " + code.value + " ...";
      //document.getElementById("powCampName[" + index + "]").value = "";
      document.getElementById("powCampCity[" + index + "]").value = "";

    var param = code.value + ":" + index;
    var url = "/esr/powCampCodeLookup.do?campCode=" + encodeURI(param);
      xmlHttpReq.open("GET", url, true);
      xmlHttpReq.onreadystatechange = handleCampHttpResponse;
      xmlHttpReq.send(null);
  }
}

function handleCampHttpResponse()
{
    if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
    {
      if(xmlHttpReq.responseText.indexOf('invalid') == -1)
      {
        var xmlDocument = xmlHttpReq.responseXML;
        var val = xmlDocument.getElementsByTagName('codeLookup');

        if (val == null)
        {
          alert("Invalid POW Camp Location Code.");
          return;
        }
        if (val.item(0) == null)
        {
          alert("Invalid POW Camp Location Code.");
          return;
        }

        var fieldName = val.item(0).getElementsByTagName('index');
        var code = val.item(0).getElementsByTagName('code');
        var name = val.item(0).getElementsByTagName('name');
        var city = val.item(0).getElementsByTagName('city');

      document.getElementById("powCampCode[" + fieldName.item(0).firstChild.data +"]").value = code.item(0).firstChild.data;
      //document.getElementById("powCampName[" + fieldName.item(0).firstChild.data +"]").value = name.item(0).firstChild.data;
      document.getElementById("powCampCity[" + fieldName.item(0).firstChild.data +"]").value = city.item(0).firstChild.data;
      }
      else
      {
        alert("Invalid POW Camp Location Code.");
      }
    }
}

// Key press processing on the main zip code field
function lookupCityStateKeyPress(zipCode)
{
    var cityField = document.getElementById('city');
    var countyField = document.getElementById('county');
    var stateField = document.getElementById('state');
    var suggestionBox = document.getElementById('idSuggestionBox');
    return lookupCityStateKeyPressImpl(zipCode, suggestionBox, cityField, countyField, stateField);
}

// Key press processing on the secondary zip code field
function lookupCityStateKeyPress2(zipCode)
{
    var cityField = document.getElementById('city2');
    var countyField = document.getElementById('county2');
    var stateField = document.getElementById('state2');
    var suggestionBox = document.getElementById('idSuggestionBox2');
    return lookupCityStateKeyPressImpl(zipCode, suggestionBox, cityField, countyField, stateField);
}

// Key press processing on the zip code field
function lookupCityStateKeyPressImpl(zipCode, suggestionBox, cityField, countyField, stateField)
{
    var fieldSource = window.event.srcElement;
    var keyCode = window.event.keyCode;

    // Enter key
    if (keyCode == 13)
    {
        // Update the zip code based on the current selection
        var selIndex = suggestionBox.selectedIndex;
        if ((selIndex >= 0) && (suggestionBox.options.length > 0) && (selIndex <= suggestionBox.options.length - 1))
        {
            // Update the values with the user's selection
            updateCityState(suggestionBox, cityField, countyField, stateField);

            // Return false so the return key isn't further processed.
            return false;
        }
    }

    // Return true so the last key typed actually gets processed
    return true;
}

// Key up processing on the main zip code field
function lookupCityStateKeyUp(zipCode)
{
    var prevZipField = document.getElementById('prevZip');
    var cityField = document.getElementById('city');
    var countyField = document.getElementById('county');
    var stateField = document.getElementById('state');
    var suggestionBox = document.getElementById('idSuggestionBox');
    lookupCityStateKeyUpImpl(zipCode, prevZipField, suggestionBox, cityField, countyField, stateField, handleZipHttpResponse);
}

// Key up processing on the secondary zip code field
function lookupCityStateKeyUp2(zipCode)
{
    var prevZipField = document.getElementById('prevZip2');
    var cityField = document.getElementById('city2');
    var countyField = document.getElementById('county2');
    var stateField = document.getElementById('state2');
    var suggestionBox = document.getElementById('idSuggestionBox2');
    lookupCityStateKeyUpImpl(zipCode, prevZipField, suggestionBox, cityField, countyField, stateField, handleZipHttpResponse2);
}

// Key up processing on the zip code field
function lookupCityStateKeyUpImpl(zipCode, prevZipCodeField, suggestionBox, cityField, countyField, stateField, callbackFunction)
{
    var fieldSource = window.event.srcElement;
    var keyCode = window.event.keyCode;
    var key = String.fromCharCode(keyCode);  // Get key value from key code

    // Escape
    if (keyCode == 27)
    {
        // Hide the suggestion box
        hideZipCodeSuggestionBox(suggestionBox);
        return;
    }

    // Down arrow key
    if (keyCode == 40)
    {
        // Select the next option in the suggestion box
        var selIndex = suggestionBox.selectedIndex;
        if (selIndex < suggestionBox.options.length - 1)
        {
            suggestionBox.selectedIndex = selIndex + 1;
        }
        return;
    }

    // Up arrow key
    if (keyCode == 38)
    {
        // Select the previous option in the suggestion box
        var selIndex = suggestionBox.selectedIndex;
        if (selIndex > 0)
        {
            suggestionBox.selectedIndex = selIndex - 1;
        }
        return;
    }

    // Only perform the lookup if the user's selection has changed
    // This is done by comparing the current entry with the previously entered entry
    var prevZipCodeValue = prevZipCodeField.value;
    var currentZipValue = fieldSource.value;
    if (prevZipCodeValue != currentZipValue)
    {
        performZipCodeLookup(currentZipValue, suggestionBox, cityField, countyField, stateField, callbackFunction);
    }
    prevZipCodeField.value = currentZipValue;

    // If there are not 5 characters entered, remove any suggestions box that might be visible
    if (currentZipValue.length != 5)
    {
        hideZipCodeSuggestionBox(suggestionBox);
    }
}

// Initiates the zip code lookup on the server if a valid zip code format is found
function performZipCodeLookup(zipCode, suggestionBox, cityField, countyField, stateField, callbackFunction)
{
    // Ensure we have 5 characters
    if (zipCode.length == 5)
    {
        // Ensure each character is a valid digit
        var validValues = '0123456789';
        var zipCodeValid = true;
        for (var i=0; i < zipCode.length; i++)
        {
            if (validValues.indexOf(zipCode.charAt(i)) == -1)
            {
                zipCodeValid = false;
            }
        }

        // If the zip code has a valid format, do the lookup
        if (zipCodeValid)
        {
            if(xmlHttpReq != null)
            {
                hideZipCodeSuggestionBox(suggestionBox);
                cityField.value = '';
                countyField.value = '';
                stateField.value = '';

                var url = "/esr/zipCodeLookup.do?zipCode=" + encodeURI(zipCode);
                xmlHttpReq.open("GET", url, true);
                xmlHttpReq.onreadystatechange = callbackFunction;
                xmlHttpReq.send(null);
            }
        }
    }
}

// Callback that handles the processing when the main zip code lookup returns from the server
function handleZipHttpResponse()
{
    var cityField = document.getElementById('city');
    var countyField = document.getElementById('county');
    var stateField = document.getElementById('state');
    var suggestionBox = document.getElementById('idSuggestionBox');
    handleZipHttpResponseImpl(suggestionBox, cityField, countyField, stateField);
}

// Callback that handles the processing when the secondary zip code lookup returns from the server
function handleZipHttpResponse2()
{
    var cityField = document.getElementById('city2');
    var countyField = document.getElementById('county2');
    var stateField = document.getElementById('state2');
    var suggestionBox = document.getElementById('idSuggestionBox2');
    handleZipHttpResponseImpl(suggestionBox, cityField, countyField, stateField);
}

// Callback that handles the processing when the zip code lookup returns from the server
function handleZipHttpResponseImpl(suggestionBox, cityField, countyField, stateField)
{
    if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
    {
      if(xmlHttpReq.responseText.indexOf('invalid') == -1)
      {
          var xmlDocument = xmlHttpReq.responseXML;
          var cityCountyState = xmlDocument.getElementsByTagName('zipCodeLookup');

            // If there are no options in the response, just return
          if ((cityCountyState == null) || (cityCountyState.length == 0))
            {
                return;
            }

          if(cityCountyState.length == 1)
          {
                // There is one option in the response so just select it
            var key = cityCountyState.item(0).getElementsByTagName('key');
            populateCityState(key.item(0).firstChild.data, cityField, countyField, stateField);
          }
          else
          {
            // There is more than one option in the response to show the suggestions
            suggestionBox.options.length = 0;
            suggestionBox.size = cityCountyState.length; // Number of drop down slots displayed
            for(var i=0; i < cityCountyState.length; i++)
            {
                var key = cityCountyState.item(i).getElementsByTagName('key').item(0).firstChild.data;
                var value = cityCountyState.item(i).getElementsByTagName('value').item(0).firstChild.data;
                suggestionBox.options[i] = new Option(value,key);
            }
            suggestionBox.style.display = "block";

            // Set the selected index to the first value
            suggestionBox.selectedIndex = 0;
          }
      }
    }
}

// Updates the suggested values based on a selected option in the suggestion box
function updateCityState(suggestionBox, cityField, countyField, stateField)
{
    // Populate the fields based on the user's selection
    if(suggestionBox != null)
    {
     populateCityState(suggestionBox.value, cityField, countyField, stateField)
    }

    // Hide the suggestions box
    hideZipCodeSuggestionBox(suggestionBox);

    // Set the focus to the next field after the County (zip code field + 7)

    // Get the current form and it's elements
    var currentForm = suggestionBox.form;
    var formElements = currentForm.elements;

    // Default the new element (i.e. the next field) to the suggestion box
    var newElement = suggestionBox;

    // Loop through the form elements
    var keepLooping = true;
    for (var i=0; ((keepLooping) && (i < formElements.length)); i++)
    {
        // Assign the new element to the next element in the form
        newElement = formElements[i];
        if (newElement == suggestionBox)
        {
            // We found the suggestion box so take 7 fields after it.
            var j = i + 7;
            if (j > formElements.length - 1)
            {
                // If we ran out of fields, just use the last field in the form
                j = formElements - 1;
            }
            newElement = formElements[j];
            keepLooping = false;
        }
    }

    // Set the focus on the new element
    newElement.focus();
}

// Hides the zip code suggestion box and removes its entries
function hideZipCodeSuggestionBox(suggestionBox)
{
    // If the size isn't set to 0 here, the next time the suggestion box is displayed with the same
    // size, it will display where it was previously displayed as opposed to where it is currently
    // displayed (i.e. if the user scrolls the page up or down, it will display in the wrong location).
    suggestionBox.size = 0;
    suggestionBox.options.length = 0;
    suggestionBox.style.display = "none";
}

// Hides the zip code suggestion box but leaves the entries
function hideZipCodeSuggestionBoxLeaveSelections(suggestionBox)
{
    suggestionBox.size = 0;
    suggestionBox.style.display = "none";
}

// Populates the city, state, and county fields based on the user's selection
function populateCityState(zipCodeReturnValue, cityField, countyField, stateField)
{
    if ((zipCodeReturnValue != null) && (zipCodeReturnValue.length > 0))
    {
      var tokens = zipCodeReturnValue.split(',');
        cityField.value = tokens[0];
        countyField.value = tokens[1];
        stateField.value = tokens[2];
    }
}

// Sets target field value from the a source field value.
function copyFieldData(sourceField, targetField)
{
  targetField.value = sourceField.value;
}

// Searches all forms for the specified field and returns the
// first form that contains that field.  If no form has the specified
// field defined, null will be returned.
function searchForFormByFieldName(searchField)
{
    var returnForm = null;
    for (var i=0; ((i < document.forms.length) && (!returnForm)); i++)
    {
        searchField = eval("document.forms[i]." + searchField);
        if (searchField)
        {
            returnForm = document.forms[i];
        }
    }
    return returnForm;
}

// Searches all forms for the specified field and returns the field on the
// first form that contains that field.  If no form has the specified
// field defined, null will be returned.
function searchForFieldByFieldName(searchField)
{
    var returnField = null;
    for (var i=0; ((i < document.forms.length) && (!returnField)); i++)
    {
        returnField = eval("document.forms[i]." + searchField);
    }
    return returnField;
}

// Presents a confirmation dialog box to the user and
// returns true or false depending on the user's selection.
function confirmMessage(message)
{
  return confirm(message);
}

var singleSelect = true;  // Allows an item to be selected once only
var sortSelect = true;  // Only effective if above flag set to true
var sortPick = true;  // Will order the picklist in sort sequence
function addSelectedItems(sourceId,targetId)
{
  var sourceList = document.getElementById(sourceId);
    var selectedIndex = sourceList.selectedIndex;
    var selectedOptions = sourceList.options;
    var targetList = document.getElementById(targetId);
    var targetOptions = targetList.options;
    var targetOLength = targetOptions.length;

    // An item must be selected
    while (selectedIndex > -1)
    {
        targetOptions[targetOLength] = new Option(sourceList[selectedIndex].text);
        targetOptions[targetOLength].value = sourceList[selectedIndex].value;

        // If single selection, remove the item from the select list
        if (singleSelect)
        {
            selectedOptions[selectedIndex] = null;
        }
        selectedIndex = sourceList.selectedIndex;
        targetOLength = targetOptions.length;
    }
    sortSelectItems(targetList);
    if (selectedOptions[0] != null)
    {
      selectedOptions[0].selected = true;
    }
}

function sortSelectItems(selectList)
{
    if(selectList != null) {
    var options = selectList.options;
      var length = options.length;
    var index = 0;
    while(index < length-1)
    {
      if(options[index].value > options[index+1].value) {
          var tempText = options[index].text;
          var tempValue = options[index].value;

          options[index].text = options[index+1].text;
          options[index].value = options[index+1].value;

          options[index+1].text = tempText;
          options[index+1].value = tempValue;
      }
      index = index + 1;
    }
    }
}

//update expand/collapse state for the list and their children based on prefixes
//prefix - prefix for the list
//childPrefix is the prefix for the children to be appended to parentid
function expandCollapseLists(blockPrefix, imagePrefix, hiddenPrefix, childPrefifx)
{
  var count = 0;
  var blockId = blockPrefix + count;
  var imageId = imagePrefix + count;
  var hiddenId = hiddenPrefix + count;

  var blockCtrl = document.getElementById(blockId);
  var imageCtrl = document.getElementById(imageId);
  var hiddenCtrl = document.getElementById(hiddenId);

  while (blockCtrl != null)
  {
    expandOrCollapse(blockCtrl, imageCtrl, hiddenCtrl)
      //alert("expanding child " + elementId);
//    elementCtrl.style.display = newState;
    //expand grand children if child prefix is not null
    if (childPrefifx != null)
    {
      var grandChildBlockPrefix = blockId + childPrefifx;
      var grandChildImagePrefix = imageId + childPrefifx;
      var grandChildHiddenPrefix = hiddenId + childPrefifx;
      //alert("expanding grand child " + grandChildPrefix);
      expandCollapseLists(grandChildBlockPrefix, grandChildImagePrefix, grandChildHiddenPrefix, null);
    }
    count++;

    blockId = blockPrefix + count;
    imageId = imagePrefix + count;
    hiddenId = hiddenPrefix + count;

    blockCtrl = document.getElementById(blockId);
    imageCtrl = document.getElementById(imageId);
    hiddenCtrl = document.getElementById(hiddenId);
  }
}

//update expand/collapse state for the control and its children based on prefixes
//parentId - id for the control to be expanded
//childPrefix is the prefix for the children to be appended to parentid
function expandCollapseParentChildren(parentId, childPrefifx, newState)
{
  var elementCtrl = document.getElementById(parentId);
  if (elementCtrl != null)
  {
    // Expand Collapse Parent
    elementCtrl.style.display = newState;

    // Expand/collapse grand children if child prefix is not null
    if (childPrefifx != null)
    {
      var grandChildPrefix = parentId + childPrefifx;
      expandCollapseLists(grandChildPrefix, null, newState);
    }
  }
}

//Check all check boxes with the same name.
function checkAll(checkAll) {
 	var selectName = checkAll.name;
  if (checkAll.name == "confAddressType") selectName = "selectedConfAddrCategories";
  var checkBoxes = document.getElementsByName(selectName);
  for (var i=0; i < checkBoxes.length; i++)
  {
    checkBoxes[i].checked = checkAll.checked;
  }
}

// If the sourceBox is getting checked, then uncheck the target box.
// This is used to use check boxes to simulate radio buttons when you want the ability
// to have the user not have a radio button selection.
function uncheckOtherBox(sourceBox, targetBox)
{
    if (sourceBox.checked)
    {
        targetBox.checked = false;
    }
}

// Formats the entered phone number using a mask
function formatPhoneNumber(phoneNumber)
{
    var phonestr = new String(phoneNumber.value);
	phonestr = phonestr.replace(/[^0-9]+/g,'');
	if(phonestr.length == 0){
		var fName = phoneNumber.name;
		document.getElementById(fName).value = phonestr;
    	return;
    }

	// Ensure something was entered
    if (phonestr.length > 0)
    {
       	if (xmlHttpReq != null)
        {
            var url = "/esr/formatPhoneNumber.do?phoneNumber=" + encodeURI(phonestr) +
                      "&fieldName=" + phoneNumber.name;
            xmlHttpReq.open("GET", url, true);
            xmlHttpReq.onreadystatechange = handlePhoneFormatResponse;
            xmlHttpReq.send(null);
        }
    }
}

// Callback that handles the processing when the phone format method returns from the server
function handlePhoneFormatResponse()
{
    if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
    {
      if (xmlHttpReq.responseText.indexOf('invalid') == -1)
      {
            // Get the phone number tag
            var xmlDocument = xmlHttpReq.responseXML;
          var phoneNumberTag = xmlDocument.getElementsByTagName('phoneNumber');

            // If there is no phone number tag present, just return
          if ((phoneNumberTag == null) || (phoneNumberTag.length == 0))
            {
                return;
            }

            // Get the formatted phone number and fieldName that will hold its value
            var valueTag = phoneNumberTag.item(0).getElementsByTagName('value');
            var fieldNameTag = phoneNumberTag.item(0).getElementsByTagName('fieldName');
            var phoneNumber = valueTag.item(0).firstChild.data;
            var fieldName = fieldNameTag.item(0).firstChild.data;

            // Update the field with the formatted phone number
            document.getElementById(fieldName).value = phoneNumber;
      }
    }
}

// Formats the passed in dateTime in the specified format and updates the passed in field with the value.
// If dateTime is null, the current date/time will be used.
// If formatPattern is null, a default format of MM/DD/YYYY will be used.
function formatDateTime(dateTime, formatPattern, field)
{
    // Default the format if it wasn't specified
    if (formatPattern == null)
    {
        formatPattern = "MM/dd/yyyy";
    }

    if (xmlHttpReq != null)
    {
        var url = "/esr/formatDateTime.do?fieldName=" + field.name +
            "&formatPattern=" + formatPattern;
        if (dateTime != null)
        {
            url = url + "&dateTime=" + dateTime;
        }
        xmlHttpReq.open("GET", url, true);
        xmlHttpReq.onreadystatechange = handleFormatDateTimeResponse;
        xmlHttpReq.send(null);
    }
}

// Callback that handles the processing when the formatDateTime method returns from the server
function handleFormatDateTimeResponse()
{
    if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
    {
      if (xmlHttpReq.responseText.indexOf('invalid') == -1)
      {
            // Get the date/time tag
            var xmlDocument = xmlHttpReq.responseXML;
          var dateTimeTag = xmlDocument.getElementsByTagName('dateTime');

            // If there is no date/time tag present, just return
          if ((dateTimeTag == null) || (dateTimeTag.length == 0))
            {
                return;
            }

            // Get the formatted date/time and fieldName that will hold its value
            var valueTag = dateTimeTag.item(0).getElementsByTagName('value');
            var fieldNameTag = dateTimeTag.item(0).getElementsByTagName('fieldName');
            var dateTime = valueTag.item(0).firstChild.data;
            var fieldName = fieldNameTag.item(0).firstChild.data;

            // Update the field with the date/time
            document.getElementById(fieldName).value = dateTime;
      }
    }
}

// Ensures that a carriage return doesn't submit a form.
function noCR()
{
  return !(window.event && window.event.keyCode == 13);
}

// Adds an event listener that supresses the carriage return key
function addNoCREventListener()
{
  // Add a key press event listener to disable the enter key
  addEvent(document, 'keypress', noCREventHandler);
}

// Adds an event generically.
// object: the object to add the event to (e.g. document).
// eventType: the event type to add (e.g. keypress).
// functionName: the function name to call when the event occurs.
// Returns true if the event is addedd successfully or false if not.
function addEvent(object, eventType, functionName)
{
  if (object.addEventListener)
  {
    object.addEventListener(eventType, functionName, false);
    return true;
  }
  else
  {
    if (object.attachEvent)
    {
      var returnValue = object.attachEvent("on" + eventType, functionName);
      return returnValue;
    }
    else
    {
      return false;
    }
  }
}

//CCR12712 prevent duplicate Add person submissions
//disable Add button upon form submit
function disableAdd()
{
	var elem = document.getElementById("addPersonBtn");
	setTimeout(function() {elem.setAttribute('disabled','disabled');}, 10);
}

// Event handler that will return false if the carriage return key code is present on the event or true if not.
function noCREventHandler(event)
{
  // Note that the target type is used to allow the carriage return to pass through when
  // the target is empty.  This is the case for the expand/collapse sections which require the return
  // key to expand/collapse a section.
  var target = event.target || event.srcElement;
  var keyCode = event.keyCode || event.which;
  return !((keyCode == 13) && (target.type != ''));
}

// Checks if any async messages are available to be displayed to the user
function getAsyncMessages()
{
  // ***** TODO *****
  // Uncomment to get async messages, but server timeout will not occur.
  return;
    if (xmlHttpReq != null)
    {
        var url = "/esr/getAsyncMessages.do";
        xmlHttpReq.open("GET", url, true);
        xmlHttpReq.onreadystatechange = handleGetAsyncMessagesResponse;
        xmlHttpReq.send(null);
    }
}

// need this since still in IE quirks mode
function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName('*');
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function pageSetup() {
	applyFocusListenersToDom();
	getESCache().sessionTimeout = document.getElementById("serverSessionTimeout").innerHTML;
	if((typeof getESCache().disableSessionTimers === 'undefined') || ! getESCache().disableSessionTimers) {
           configureSessionTimeout();
     }

	 // now that focus/blur handlers applied; sequentially give focus to something here on page load
	 setTimeout(function() {
		var elements = getElementsByClassName(document.body, 'initfocus');
		if(elements != null && elements.length > 0) {
			elements[0].focus();
		} else {
			var defaultElement = document.getElementById('es-header-skip');
			if(defaultElement) {
				defaultElement.focus();
			}
		}
	}, 500);
}

function applyFocusListenersToDom() {
	doApplyFocusStyles(document.getElementsByTagName('input'));
	doApplyFocusStyles(document.getElementsByTagName('a'));
	doApplyFocusStyles(document.getElementsByTagName('select'));
}

function doApplyFocusStyles(domTargets) {
	for (var i = 0; i < domTargets.length; i++) {
		var node = domTargets[i];

		// append new focus handler onto any existing ones
		addEvent(node, 'focus', focusHandler);

		// append new blur handler onto any existing ones
		addEvent(node, 'blur', blurHandler);
	}
}

function startsWith(str, prefix) {
	return str.indexOf(prefix) == 0;
}

function isMenuLinkId(linkId) {
	return startsWith(linkId, 'es-menu-');
}
function isHeaderLinkId(linkId) {
	return startsWith(linkId, 'es-header-');
}
function isTabsLinkId(linkId) {
	return startsWith(linkId, 'es-tabs-');
}

function isTabLink(element) {
	//return isTabsLinkId(element.id);
	return containsCssClass(element, 'tabLink');
}

function isHelpLink(element) {
	//return isTabsLinkId(element.id);
	return containsCssClass(element, 'helpFocus');
}

function containsCssClass(element, targetCssClass) {
	return (' ' + element.className + ' ').indexOf(' ' + targetCssClass + ' ') > -1;
}

function focusHandler(event) {
	doFocusHandler(getFieldFromEvent(event));
}
function doFocusHandler(node) {
	//alert('focus given to: ' + node.name);

	node.className += ' focusBase';

	if(node.type == 'submit') {
		// since ES uses a certain style of button creation with graphics on either side, then need special look here
		node.className += ' focusButton';
	} else if(node.href) {
		//console.log('link: ' + node.href);
		if(!startsWith(node.id, 'ContentArea')) {
			node.className += ' focusLinkBase';

			// now check for special links
			if(isTabLink(node)) {
				node.className += ' focusLinkWithBorder';
			}
			if(isHelpLink(node)) {
				node.className += ' helpFocusWithBorder';
			}
		}
	} else {
		node.className += ' focusInput';
	}

}

function blurHandler(event) {
	doBlurHandler(getFieldFromEvent(event));
}

function doBlurHandler(node) {
	if(node.className) {
		node.className = node.className.replace( /(?:^|\s)focusBase(?!\S)/g , '' );
	}

	if(node.type == 'submit') {
		node.className = node.className.replace( /(?:^|\s)focusButton(?!\S)/g , '' );
	} else if(node.href) {
		// now check for special links
		if(isTabLink(node)) {
			node.className = node.className.replace( /(?:^|\s)focusLinkWithBorder(?!\S)/g , '' );
			node.className = node.className.replace( /(?:^|\s)focusLinkBase(?!\S)/g , '' );
		}
		else if(isHelpLink(node)) {
			node.className = node.className.replace( /(?:^|\s)helpFocusWithBorder(?!\S)/g , '' );
			node.className = node.className.replace( /(?:^|\s)focusLinkBase(?!\S)/g , '' );
		}
		 else {
			node.className = node.className.replace( /(?:^|\s)focusLinkBase(?!\S)/g , '' );
		}
	} else {
		node.className = node.className.replace( /(?:^|\s)focusInput(?!\S)/g , '' );
	}
}

// Callback that handles the processing when the getAsyncMessages method returns from the server
function handleGetAsyncMessagesResponse()
{
    if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
    {
      if (xmlHttpReq.responseText.indexOf('invalid') == -1)
      {
        // Get the user messages tag
        var xmlDocument = xmlHttpReq.responseXML;
        var userMessagesTag = xmlDocument.getElementsByTagName('userMessages');

        // If there is no user messages tag present, just return
        if ((userMessagesTag != null) && (userMessagesTag.length > 0))
        {
          // Get the <UL> tag so we can add our additional messages
          var ulElement = document.getElementById("asyncMessageUlContent");

          // Iterate through each message value
          var messageTagList = userMessagesTag.item(0).getElementsByTagName('value');
          for (var i=0; i < messageTagList.length; i++)
          {
              // Get a message
              var messageTag = messageTagList[i];
              var message = messageTag.firstChild.data;

              // Create the <LI> element for the message
              var liElement = document.createElement("li");

              // Append the message text to the <LI> tag
              liElement.appendChild(document.createTextNode(message));

              // Append the <LI> tag to the <UL> tag
              ulElement.appendChild(liElement);
          }

          // Make sure the async message block is visible and not hidden
          var asyncMessageContent = document.getElementById("asyncMessageContentId");
          asyncMessageContent.style.display = "block";
        }
      }

      // Ask to be called back (get the next set of messages) again in 15 seconds
      setTimeout("getAsyncMessages()", 15000);
    }
}

// Formats the entered phone number using a mask
function sendAsyncMessage(sessionId, toUsername, fromUsername, messageField)
{
    // Ensure something was entered
    if (messageField.value.length > 0)
    {
        if (xmlHttpReq != null)
        {
          var url = "/esr/sendAsyncMessage.do?message=" + messageField.value;
          if (sessionId != null)
          {
              url = url + "&sessionId=" + sessionId;
          }
          if (toUsername != null)
          {
              url = url + "&toUsername=" + toUsername;
          }
          if (fromUsername != null)
          {
              url = url + "&fromUsername=" + fromUsername;
          }
          messageField.value = "";
          messageField.focus();
          xmlHttpReq.open("GET", url, true);
          xmlHttpReq.onreadystatechange = handleSendAsyncMessageResponse;
          xmlHttpReq.send(null);
        }
    }
}

// Callback that handles the processing when the send user message method returns from the server
function handleSendAsyncMessageResponse()
{
  if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
  {
    if (xmlHttpReq.responseText.indexOf('invalid') == -1)
    {
      // Get the user messages tag
      var xmlDocument = xmlHttpReq.responseXML;
      var userMessagesTag = xmlDocument.getElementsByTagName('userMessage');

      // If there is no user messages tag present, just return
      if ((userMessagesTag == null) || (userMessagesTag.length == 0))
      {
        return;
      }

      // Get the <UL> tag so we can add our additional messages
      var ulElement = document.getElementById("asyncMessageUlContent");

      // Iterate through each message value
      var messageTagList = userMessagesTag.item(0).getElementsByTagName('value');
      for (var i=0; i < messageTagList.length; i++)
      {
        // Get a message
        var messageTag = messageTagList[i];
        var message = messageTag.firstChild.data;

        // Create the <LI> element for the message
        var liElement = document.createElement("li");

        // Append the message text to the <LI> tag
        liElement.appendChild(document.createTextNode(message));

        // Append the <LI> tag to the <UL> tag
        ulElement.appendChild(liElement);
      }

      // Make sure the async message block is visible and not hidden
      var asyncMessageContent = document.getElementById("asyncMessageContentId");
      asyncMessageContent.style.display = "block";
    }
  }
}

// Displays a message if the field is empty (i.e. the length of it's value is 0)
function displayMessageIfFieldEmpty(field, msg)
{
  if (field != null && field.value.length == 0)
  {
    alert(msg);
  }
}

function getFieldFromEvent(event) {
//console.log(event);
//console.log(window.event);

	// note: would really not like to use  "window.event", since not cross-browser and sometimes event not predicatble in IE
	// developer note: please pass in the event explicitly from the calling code!
	var targetEvent = event || window.event;

	//console.log(targetEvent);
	if(targetEvent == null) return;
	var field = targetEvent.target || targetEvent.srcElement;
	return field;
}

// Takes the text in the passed in field and converts it to uppercase.
function toUpperCase(field)
{
	if(field == null) return;

	field.value = field.value.toUpperCase();
}

function updateEmploymentFields(formObject, status_retired)
{
  	enableDateOfRetirement(formObject, status_retired);
 }


 // Enable or Disable the Date of Retirement field based on Employment status
 function enableDateOfRetirement(formObject, status_retired)
 {

    // Re-enable main field and disable hidden field
   	if (formObject.idEmploymentStatus.value == status_retired)
   	{
    	formObject.idDateOfRetirement.disabled = false;
    	formObject.idDateOfRetirementHidden.disabled = true;
  	}
  	else
  	{
    	// Update value and disable field
   		formObject.idDateOfRetirementHidden.disabled = false;
     	formObject.idDateOfRetirementHidden.value = formObject.idDateOfRetirement.value;
   		formObject.idDateOfRetirement.disabled = true;
   	}
 }

/* Unable to do this since the html value is not a field and cannot be cleared...
function clearFieldsIfUnemployed(formObject, status_unemployed, status_unknown)
 {

    if (formObject.employmentStatus.value == status_unemployed ||
        formObject.employmentStatus.value == status_unknown)
  	{
	  	formObject.employerName.value = "";
	  	formObject.idEmployerNameHidden.value = "";
	  	formObject.employerAddress.value = "";
	  	formObject.idEmployerAddressHidden.value = "";
	  	formObject.employerPhone.value = "";
	  	formObject.idEmployerPhoneHidden.value = "";
	  	formObject.idDateOfRetirement.value = "";
 	  	formObject.idDateOfRetirementHidden.value = "";
  	}
 }*/

 /*CodeCR13140-508 - Provide an alert and give sufficient time to indicate more time is required- Scripts for Dialog Box */

 function configureSessionTimeout(sessionTimeout) {
       //WebLogic session timeout is stored as number of seconds.  So 3600 is 60 minutes.
       //Calculate session timeout by dividing by 60, then subtracting 5 minutes.  This
       // is when the popup should display.
       getDialogDisplayTime() ;
       showESTimeoutDialog();
}

 function pingServer()
{

    if (xmlHttpReq != null)
    {
        var url = "/esr/getAsyncMessages.do";
        xmlHttpReq.open("GET", url, true);
        xmlHttpReq.onreadystatechange = handleGetAsyncMessagesResponse;
        xmlHttpReq.send(null);
    }
}



 function showBackgroundDisableForESDialog(div)
 {
 	document.getElementById(div).style.display='block';
 	return false
 }

 function hideBackgroundDisableForESDialog(div)
 {
 	document.getElementById(div).style.display='none';
 	return false
 }

 function showESDialog() {
 	showBackgroundDisableForESDialog('ESDialogBackgroundLayer_1') ;
	ESDialog.style.display = 'block';
	okButton.focus();
}
function extendSession()
{
	 pingServer() ;
	 hideESTimeoutDialog();
}


function showESTimeoutDialog() {
	setTimeout("showESDialog();",Number(getDialogDisplayTime())) ;
	setTimeout("hideESTimeoutDialog(); window.location = window.location.href;",getDialogHideTime()) ;

}

function hideESTimeoutDialog() {
	hideBackgroundDisableForESDialog('ESDialogBackgroundLayer_1') ;
	ESDialog.style.display = 'none';
}

function getESCache() {
      if(typeof esCache === 'undefined') {
        esCache = {};
      }
       return esCache;
}

function getDialogDisplayTime()
{
	   dialogDisplayTime = (Number(getESCache().sessionTimeout)/60 - 5) * 60000;
	   return dialogDisplayTime ;
}

function getDialogHideTime()
{
	   dialogHideTime = ((Number(getESCache().sessionTimeout)/60)+1.00)*60000 ;
	   return dialogHideTime ;
}






