

/*
 * Enliven dynamic elements
 */
function enliven(thisBlock) {
  var targetBlock, links;
  targetBlock = thisBlock.nextSiblings()[0];

  thisBlock.descendants().findAll(function(el){return el.hasClassName && el.hasClassName('collapsable');}).invoke('hide');

  new Ajax.Autocompleter('empName', 'employeeList', 'employees/');

  links = thisBlock.descendants().findAll(function(el){return el.hasClassName && el.hasClassName('subMenuLink')});
  // Expands the clicked option's menu
  function loadSubMenu(e) {
    Effect.toggle(Event.element(e).readAttribute('id').slice(0, -4)+'Menu', 'blind');
    Event.stop(e);
  }
  for (i=0; i<links.length; i++) {
    links[i].observe('click', loadSubMenu.bindAsEventListener());
  }

  links = thisBlock.descendants().findAll(function(el){return el.hasClassName && el.hasClassName('narrowedMenuLink')});
  // loads the href of the link into the middle container
  for (i=0; i<links.length; i++) {
    links[i].observe('click', function(e){
      new Ajax.Updater(targetBlock, this + '/embed',
        {
          method: 'get',
          onComplete: function(){
            enliven(targetBlock);
          }
        } );
      Event.stop(e);
    });
  }

  if ($('contactForm')) {
    $('fromEmail').observe('change', checkAuth);
  }

  checkAuth();
}

// Check to see if NISD authentication form fields should be shown
function checkAuth(){
  /* This is currently duplicated code from Contact.class.php
   * It should be refactored to hit that instead of duplicating logic
    return (
      (
        $this->isInsideNISD($_SERVER['REMOTE_ADDR']) or
        substr($fromEmail, -9)==="@nisd.net"
      ) and
      $contactId!=140 and
      $destination!='Email Reinstatement'
    );
   */
  if ($('contactForm')) {
    var isInsideNISD         = !!$F('isInsideNISD'); // Cast to boolean
    var isNISDemail          = $F('fromEmail').slice(-9)=='@nisd.net';
    var isTestingAndEvalDept = $F('type')=='department' && $F('contactId')==140;
    var isAbuseEmail         = $F('type')=='department' && $F('contactId')==110 && $F('destination')=='Email Reinstatement';

    if ((isInsideNISD || isNISDemail) && !isTestingAndEvalDept && !isAbuseEmail) {
      $('authFields').show();
    } else {
      $('authFields').hide();
    }
  }
}

Event.observe(window, 'load', function(){
  if ($$('div.menu').length) {
    enliven($$('div.menu')[0]);
  }

  if ($('contactForm')) {
    $('fromEmail').observe('change', checkAuth);
  }

  checkAuth();
});
