var $fields;

function load_form() {
  $fields.each(function(){
    var love = $.cookie('last_call_' + $(this).attr('name'));
    if (love)
      $(this).val(love);
  });
}

function save_form() {
  $fields.each(function(){
    $.cookie('last_call_' + $(this).attr('name'), $(this).val());
  });
}

$(function(){
  $fields = $("tr.field :input");
  load_form();
  $("#id_my_phoneno").focus();

  /* only show "email recording" checkbox if recording is enabled */
  $("#id_record").change(function() {
    if ($(this).val() == "no-announce" || $(this).val() == "announce")
      $("#row_email_recording").show();
    else
      $("#row_email_recording").hide();
  }).change();

  $("#webcall").submit(function(){
    $fields.css("background", "")
           .css("color", "")
           .css("font-weight", "");
    var data = this.elements;
    $.ajax({
      type:     "GET",
      url:      api_url,
      dataType: "json",
      data:     $(this).serialize(),
      success:
        function(json){
          if ($("#success").css('display') != 'none')
            $("#success").slideUp('fast');
          if ($("#error").css('display') != 'none')
            $("#error").slideUp('fast');
          if (json.is_error) {
            $("#error p").html(json.message);
            $("#error").slideDown();
            $("#id_" + json.field).css("background", "#CD321D")
                                  .css("color", "white")
                                  .css("font-weight", "bold")
                                  .show().focus();
          } else {
            $("#success h2.instruct span").html(json.access_number_pretty);
            $("#success").slideDown();
            save_form();
          }
        }
    });
    return false;
  });
});
