$(function() {
  // Highlight the active left nav link
  $('ul.nav li').css('background', 'transparent url(/websites/eds/images/arrow-r-blue.png) no-repeat left 5px');
  $('ul.nav li:has(a)').css('background-image', 'none');

  // Adjust the spacing such that PDF links under lists are the same
  // distance from copy as those under paragraphs.
  $('.pdf-icon').each(function(){
    if ($(this).parent().prev().prev().get(0).tagName == 'UL'){
      $(this).css('margin-top', '-5px');
    }
  });

  new clientele.Typography();

  // Make the banner nav clickable areas cover the whole cell,
  // not just the area replaced by image headers.
  $('#banner-nav td a').each(function(){
    var target = $(this).attr('href');
    var cell = $(this).parent();
    cell.css('cursor', 'pointer').click(function(){
      location.href = target;
    });
  });

  // Set initial state - otherwise IE can get confused when displaying the page after a "back" click
  forkFormSwitch($('#fork-plan'));
  
  $('#fork-plan').change(function() {
    forkFormSwitch(this);
  })

  if ($('#aspnetForm').css('display') == 'none'){
    $('#nac-u').focus();
  }
});

function forkFormSwitch(select_element) {

  // alert($(select_element).val());
  
  if ($(select_element).val() == 'asp' && $('#aspnetForm').css('display') == 'none'){

    $('#ctl00_ContentPlaceHolder1_UserName').val($('#nac-u').val());
    $('#ctl00_ContentPlaceHolder1_Password').val($('#nac-p').val());

    $('#aspnetForm').show();
    $('#nac-form').hide();


    $('#ctl00_ContentPlaceHolder1_UserName').focus();      

  } else if (($(select_element).val() == 'regular') && $('#nac-form').css('display') == 'none') {

    $('#nac-u').val($('#ctl00_ContentPlaceHolder1_UserName').val());
    $('#nac-p').val($('#ctl00_ContentPlaceHolder1_Password').val());

    $('#aspnetForm').hide();
    $('#nac-form').show();

    $('#nac-u').focus();
  }
}

function forkFormValidate(el) {

  form_element = $(el).closest('form')

  if (form_element.attr('id') == 'aspnetForm'){
    if (checkForkFields('#ctl00_ContentPlaceHolder1_UserName', '#ctl00_ContentPlaceHolder1_Password')){
      if (postBackVersion){
        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('ctl00$ContentPlaceHolder1$btnLogin', '', true, '', '', false, false))
      }
      return true;
    }
  } else {
    if (checkForkFields('#nac-u', '#nac-p')){
      return true;
    }
  }

  return false;
}

function checkForkFields(username, password){
  var valid = true;
  if (!$(username).val().match(/\S/)){
    showForkError(username);
    valid = false;
  }
  if (!$(password).val().match(/\S/)){
    showForkError(password);
    valid = false;
  }
  return valid;
}

function showForkError(el){
  $(el).addClass('fork-error-field').siblings('.fork-error').css('visibility', 'visible');
  $(el).closest('form').find('.fork-error-instructions').css('visibility', 'visible');
}
