$(function() {

  $("div.accordion").accordion({
    autoHeight: false,
    active: false,
    collapsible: true
  });

  $("input#investigator_name").livequery(function() {
    $(this).suggest('/investigators/suggest', {
      delay: 200,
      minchars: 3,
      maxCacheSize: 1000
    });
    $(this).parents("form:first").submit(function() {
      $("input#investigator_name", this).suggest_object().disable();
    });
  });

  $("form.edit_company").each(function() {
    $(this).data('originalData', $(this).formSerialize());
  });

  var wantedUri = null;

  $("#saveTabModal").dialog({
    autoOpen: false,
    title: "<strong>Save</strong> this tab?",
    modal: true,
    closeOnEscape: false,
    draggable: false,
    resizable: false,
    buttons: {
      "Yes": function() {
        $(this).dialog('close');
        $("#redirect_to").val(wantedUri);
        $("form.edit_company:first button[type=submit]:first").click();
      },
      "No": function() {
        $(this).dialog('close');
        window.location = wantedUri;
      },
      "Cancel": function() {
        $(this).dialog('close');
      }
    }
  });

  $("ol.tabs > li > a, ol.subtabs > li > a").click(function(e) {
    var form = $("form.edit_company:first");
    var link = $(this);
    if (form.length == 0) return true;
    if (form.formSerialize() == form.data('originalData')) return true;

    wantedUri = link.attr('href');
    $("#saveTabModal").dialog('open');

    return false;
  });


});
