// initialize everything after the document is finished loading
$(document).ready(function() {



  // put the browser focus on the form field, for easy adding of items
  $('#new_item').focus();



  // make all lists sortable, locked to the y axis, with a handle
  $("#list").sortable({
    axis: 'y',
    opacity: 0.8,
    handle: '.handle',

    // when a list item is moved, save the new ordering of the list
    update: function () {
      $.ajax({
        url: "services/update.php",
        type: "POST",
        data: $(this).sortable('serialize')
      }); // end ajax
    } // end change
  
  }); // end sortable



  // on submit of the form, add an item to the list
  $('#add').submit( function() {
  
    if($("#list").sortable("toArray")[0]) {
      // put the list into an array, for easier manipulation
      var item_array = $("#list").sortable("toArray");
    
      // strip out the "item_" prefix in each ID
      for(var i = 0; i < item_array.length; i++)
        item_array[i] = item_array[i].split("_")[1];
      
      // get the highest ID and increment by one
      var new_id = item_array.sort()[item_array.length-1];
      new_id++;
    }
    // otherwise, just set the ID to the next auto_increment id from the db (set in index.php)
    else
      var new_id = next_auto_increment_id;
  
    // get the text from the form, then clear it
    var new_text = $('#new_item').val();
    $('#new_item').val("");
    
    // last, add the new item to the list, using the new ID
    $('#list')
      .append("\t"+'<li id="item_' + new_id + '" class="item"><a href="#" id="remove_' + new_id + '" class="remove"></a><div class="handle"></div>' + new_text + '</li>' + "\n");
    
    $("#item_"+new_id).fadeIn(300);

    // attach the removal event to the current new X
    remove_item('#remove_'+new_id);

    $.ajax({
      url: "services/add.php",
      type: "POST",
      data: {text: new_text, position: new_id}
    }); // end ajax

    // return false, so that the form doesn't submit
    return false;
  }); // end submit



  // on click of the X, remove an item
  function remove_item(selector) {
    $(selector).click(function() {
    
      // remove the list item
      var parent = '#'+$(this).parent().attr('id');
      $(parent).fadeOut(300);
      
      var parent_id = parent.split("_")[1];
      
      $.ajax({
        url: "services/remove.php",
        type: "POST",
        data: {id: parent_id}
      }); // end ajax
    
      // return false, because there's nothing to link to
      return false;
    
    }); // end remove event
  } // end remove_item



  // attach the removal event to all X's after page load
  remove_item('.remove');

  
  
}); // end init
