// called whenever the form is rendered, to set everything up
function carRefresh()
{
  var carRtnSub = 0;

  // listener for "return" key being pressed
  $('#carform').keypress(function(e){
    if(e.which == 13) {
      if(carRtnSub) {
        return false;
      } else {
        carRtnSub = true;
        if(jQuery.browser['msie']) {
          $('#carform').submit();
        }
      }
    }
  });

  // strip out alt text on submission so error validation can do its thang
  /*
   * this MUST appear above the ajaxForm line so it can clear things out
   * before ajaxForm submits
   */
  $('#carform').submit(function(){
    $(this).addClass('dim');
    $('#carform .submit_btn').addClass('show_loading');
    $('#carform input:text').each(function(){
      var curval = $(this).val();
      var altval = $(this).attr('alt');
      if(curval==altval){
        $(this).val("");
      }
    });
  });
  
  // ajaxify the form
  $('#carform').ajaxForm({
    target: '#bce_bodycopy',
    success: function() {
      carScrollToTop();
    }
  });
  
  // load up all text field alt text on page load
  $('#carform input:text').each(function(){
    var curval = $(this).val();
    var altval = $(this).attr('alt');
    if (curval == "" || curval == altval) {
      $(this).css({"color":"#CCC"});
      $(this).val(altval);
    } else {
      $(this).css({"color":"#525252"});
    }
  });
  
  // if focus, clear if necessary
  $('#carform input:text').focus(function(){
    var curval = $(this).val();
    var altval = $(this).attr('alt');
    $(this).css({"color":"#525252"});
    if(curval==altval){
      $(this).val("");
    }
  });
  
  // if blur, put default text back and gray if necessary
  $('#carform input:text').blur(function(){
    var curval = $(this).val();
    var altval = $(this).attr('alt');
    if(curval==""){
      $(this).css({"color":"#CCC"});
      $(this).val(altval);
    }
  });
  
  // check to see if .name and .csz error wrappers have errors in them and need to be displayed
  var tot1 = $('.name_error ul').size();
  if( tot1>=1 ){
    $('.name_error').css({"display":"block"});  
  }
  var tot2 = $('.csz_error ul').size();
  if( tot2>=1 ){
    $('.csz_error').css({"display":"block"}); 
  }
  
  if($('#car_previous_contact_recruiter').val()=="true"){
    $('#car_rsid').show();
  }

  // hook into the 3 fields that help to calculate target height and weight
  $('.birthday select, #car_gender, #car_CarExtra_height_inches, #car_prior_service').change(function() {
    carTryAjaxHeightWeight();
  });
  
  // Make sure that if the user changes the feet value, we don't let them choose inches < 10
  $("#car_CarExtra_height_feet").change(function() {
    var feet_value = $(this).val(),
        $inches = $("#car_CarExtra_height_inches"); 
    if ( feet_value == 4)
    {
      $inches.find('option').each(function (index, ele) {
        if (ele.value < 10)
        {
          ele.disabled = 'disabled';
        }
      });
    
      if ($inches.val() < 10)
      {
        $inches.val(10);
      }
    }
    else
    {
      $inches.find('option').each(function (index, ele) {
        option = $(this);
        if (option.attr('value') < 10)
        {
          option.removeAttr('disabled');
        }
      });
    }
    
    carTryAjaxHeightWeight();
  });
  
  // Inches change function exists because of IE7
  $("#car_CarExtra_height_inches").change(function() {
    var feet_value = $("#car_CarExtra_height_feet").val();
    var inches_value = $(this).val();
    if (feet_value == 4)
    {
       if (inches_value < 10)
       {
          $(this).val(10);
       }
    }
    carTryAjaxHeightWeight();
  }); // carExtraHeightInches onChange

  // call the function once to start, in case we're coming back after validation error
  carTryAjaxHeightWeight();

  // move the rsid field to be right after the recruiter checkbox (inside an li)
  var li = $('#car_previous_contact_recruiter').parent();
  $('<li class="rsid_landing" style="display:none"></li>').insertAfter(li);
  $('#car_rsid').appendTo('#carform .checkbox_list li.rsid_landing').show();

  // logic to display the rsid field if previous_contact has recruiter
  // this must be click and no change, because change doesn't fire until
  // the checkbox loses focus (#fail)
  $('#carform .checkbox_list input[type=checkbox]').click(checkIfRsidShouldShow);

  // call the function to start, in case we're coming back after validation error
  checkIfRsidShouldShow();
} /* end carRefresh() */ 

// sees if we have enough information to ajax in the height and weight info
function carTryAjaxHeightWeight()
{
  var birthdayMonth = $('#car_birthday_month').val();
  var birthdayDay = $('#car_birthday_day').val();
  var birthdayYear = $('#car_birthday_year').val();
  
  var gender = $('#car_gender').val();
  var inches = $('#car_CarExtra_height_inches').val();
  var feet = $('#car_CarExtra_height_feet').val();
  if (feet && inches)
  {
    var height = parseInt(inches) + (parseInt(feet) * 12);
  }
  var priorService = $('#car_prior_service').val();

  // this is jank, but we need to translate the true/false strings
  if (priorService == 'true')
  {
    priorService = 1;
  }
  else if (priorService == 'false')
  {
    priorService = 0;
  }
  
  if (birthdayMonth
    && birthdayDay
    && birthdayYear
    && gender
    && height)
  {
    $.ajax({
      url:      '/ajax/fitness/height-weight',
      dataType: 'json',
      data: {
        gender:         gender,
        height:         height,
        birth_year:     birthdayYear,
        birth_month:    birthdayMonth,
        birth_day:      birthdayDay,
        prior_service:  priorService
      },
      success: function(json){
        if (json['minWeight'])
          $('#fitness_min_weight').html(json['minWeight']);
        else
          $('#fitness_min_weight').html('&mdash;');
          
        if (json['maxWeight'])
          $('#fitness_max_weight').html(json['maxWeight']);
        else
          $('#fitness_max_weight').html('&mdash;');
      }
    });
  }
}

function carScrollToTop()
{
  // if form is returned due to errors or whatever, scroll page back up top
  $.scrollTo('#header', 500 );		
}

// talk to a recruiter?
function show_rsid_opt(val){
  // it's actually the parent li that's shown/hidden
  if(val)
  {
    $('#car_rsid').parent().slideDown(500);
  }
  else
  {
    $('#car_rsid').parent().slideUp(500);
    $('#car_previous_contact_rsid').val('');
  }
}

// checks whether or not the rsid field should be shown and shows/hides it
function checkIfRsidShouldShow()
{
  show_rsid_opt($("#car_previous_contact_recruiter").is(":checked"));
}

// adds an onblur behavior to validate the email address
function registerCarEmailListener(url)
{
  var carEmailInput = $('#carform #car_email');

  // post back to check for dups on email blur
  carEmailInput.blur(function() {
    $.ajax({
      url:  url,
      type: 'POST',
      dataType: 'json',
      data:   {
        email:  carEmailInput.val()
      },
      success: function(data, textStatus, XMLHttpRequest) {

        var carEmailErrorWrapper = $('#carform .email-error-holder');
        // copy in the content to the email wrapper div
        carEmailErrorWrapper.html(data.error_content);

        // toggle the error class based on validity
        if(data.valid)
        {
          $('.form_row', carEmailErrorWrapper.parent()).removeClass('form_row_error');
        }
        else
        {
          $('.form_row', carEmailErrorWrapper.parent()).addClass('form_row_error');
        }
      }
    });
  });

  carEmailInput.keydown(function() {
    $(this).parent().removeClass('form_row_error');
    $('#carform .email-error-holder').html('');
  });
}

