
function updateCookie (key, val) {
  // by default will expire at end of session
  document.cookie = key + "=" + val + "; path=/;";
}

// everything in here ic executed after the page finishes loading
$(document).ready(function(){
  // add event handlers for the nav header toggles
  $("#anav h4").click(function (e) {
    // after the slide, set a cookie so we know it's hidden
    $(e.target).next().slideToggle("normal", function() {
      if ( $(this).css("display") == "none" ) {
        updateCookie($(this).parent().attr("id"),1);
      } else {
        updateCookie($(this).parent().attr("id"),0);
      }
    }); 
  });

  // click for the search toggle
  $("#search_toggle span:first").click(function() {
    $("#search_form").toggle();
  })

  // click for the search toggle
  $(".closex").click(function() {
    $(this).parent('div').toggle();
  });

  // click handler for editable tables
  $(".areclist table").click(function(e) {
    tableCellEdit(e);
  });

  // click handler for subtable toggle
  $(".subtable_toggle").click(function(e) {
    var tbl = this.id.slice(this.id.indexOf('_')+1,this.id.length);
    $('#reclist_'+tbl).toggle();
    $(this).toggleClass('closed');
  });

  // click handler for the document
  // this is so we know when to close an open editing box
  $(document).click(function(e) {
    closeTableCellEdit(e);
  });

  // event handlers for autocomplete inputs
  var autocompletes = $('input.autocomplete');
  for (var i=0;i<autocompletes.length;i++) {
    var settings = {};
    var field = autocompletes[i].id;
    var field_val = autocompletes[i].value;
    autocompletes[i].value = '';
    var field_name = $("#" + field + '_name').attr('value');
    if (field_val != '' && field_name) {
      settings.prePopulate = [{'id':field_val ,'name':field_name}];
    }
    var field_info = $('#autocomplete_params_' + field).attr('value');
    var tokenLimit = field_info.match(/autocomplete_max:[0-9]+/);
    if (tokenLimit) {
      tokenLimit = tokenLimit[0];
      tokenLimit = tokenLimit.match(/[0-9]+$/);
      tokenLimit = tokenLimit[0];
      settings.tokenLimit = tokenLimit;
    }
    var src = "?dbgui=ajax_autocomplete";
    src += '&field=' + field;
    src += '&field_info=' + field_info;
    src += '&dbgui_key=' + dbgui_key;
    $(autocompletes[i]).tokenInput(src,settings);

  }
});

function tableCellEdit(e) {
  if (e.target.nodeName.toLowerCase() !== 'span' && e.target.className !== 'editable') {
    return;
  }
  $('#asavebox').remove();
  var fieldInfo = {};
  fieldInfo.dbgui = 'edit_ajax';
  fieldInfo.rec_action = 'update';
  fieldInfo.table_name = e.currentTarget.id; // the id of the table
  var field_to_edit = $(e.target).closest('td').attr('class'); // class of the td
  if (field_to_edit.indexOf(' ') >= 0) {
    field_to_edit = field_to_edit.slice(0, field_to_edit.indexOf(' ')); // only need the first class
  }
  fieldInfo.selector = 'tr#'+ $(e.target).closest('tr').attr('id') + ' td.' + field_to_edit + ' span';
  fieldInfo.field_to_edit = field_to_edit;
  var unique_fields_str = $(e.target).closest('tr').attr('id'); // the id of the tr
  var unique_field_list = unique_fields_str.split("xm1xzx");
  for (var i=0;i<unique_field_list.length; i++ ) {
    var unique_field = unique_field_list[i].split('-');
    fieldInfo['_hide_' + unique_field[0]] = unique_field[1];
  }
  var old_value = $(e.target).text();
  if (old_value === '\u2014') { // this is unicode for the em dash, default html when there's nothing in the db
    old_value = '';
  }
  var html = "<div id='asavebox'><input type='text' class='text' value='" + old_value + "' /> <input type='button' class='button save' value='Save' /> <input type='button' class='button cancel' value='Cancel' /> </div>";
  $(e.currentTarget).after(html);

  // set the width of the input based in size of text
  if (old_value.length > 5) {
    var new_width = old_value.length * 8;
    if (new_width > 200) {
      new_width = 200;
    }
    $('#asavebox input:eq(0)').css({'width':new_width+'px','display':'block'});
  }

  var box_left = e.pageX-18;
  // styles for the box, position based on where the click happend
  if (e.pageX + $('#asavebox').width() >= $(window).width()) {
    box_left = $(window).width() - $('#asavebox').width() - 20;
    if ((e.pageX + ($('#asavebox').width()/2) >= $(window).width()) && old_value.length < 6) {
      $('#asavebox input:eq(0)').css({'float':'right'});
    }
  }
  $('#asavebox').css({
    'top' : (e.pageY-14) + 'px',
    'left': box_left + 'px'
  });
  $('#asavebox input:eq(0)').focus();
  // the cancel button event
  $('#asavebox input:eq(2)').click(function(e) {
    $('#asavebox').remove();
  });
  // the save button event
  $('#asavebox input:eq(1)').click(function(e) {
    fieldInfo[field_to_edit] = $('#asavebox input:eq(0)').attr('value');
    fieldInfo.new_value = $('#asavebox input:eq(0)').attr('value');
    $('#asavebox input').attr('disabled','disabled');
    $.get("", fieldInfo, tableCellSaved, 'json');
  });

  e.stopPropagation();
}

function tableCellSaved(result) {
  if (result.success === 'Y') {
    if (result.value == '') {
      $(result.selector).text('0');
    } else {
      $(result.selector).text(result.value);
    }
    $('#asavebox').remove();
  } else if (result.success === 'N') {
    $('#asavebox').text(result.error);
    setTimeout("$('#asavebox').fadeOut('slow');", 1000);
  }
}

function closeTableCellEdit(e) {
  if (!$(e.target).parents("#asavebox").length && $(e.target).attr('id') !== 'asavebox' ) {
    $('#asavebox').remove();
  }
}

function expandAllSubtables() {
  $('.areclist').show();
  $('.subtable_toggle').removeClass('closed');
}

function collapseAllSubtables() {
  $('.areclist').hide();
  $('.subtable_toggle').addClass('closed');
}
