//public/javascripts/application.js

// This sets up the proper header for rails to understand the request type,
// and therefore properly respond to js requests (via respond_to block, for example)
$.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

$(document).ready(function() {

  // UJS authenticity token fix: add the authenticy_token parameter
  // expected by any Rails POST request.
  $(document).ajaxSend(function(event, request, settings) {
    // do nothing if this is a GET request. Rails doesn't need
    // the authenticity token, and IE converts the request method
    // to POST, just because - with love from redmond.
    if (settings.type == 'GET') return;
    if (typeof(AUTH_TOKEN) == "undefined") return;
    settings.data = settings.data || "";
    settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  });

});


    function remove_fields(link) {  
        $(link).prev("input[type=hidden]").val("1");  
        $(link).closest(".fields").hide();  
    }  
      
    function add_fields(link, association, content) {  
        var new_id = new Date().getTime();  
        var regexp = new RegExp("new_" + association, "g");  
        $(link).parent().before(content.replace(regexp, new_id));  
   }  
function hijackDeleteBookmarkLinks() {
  $('#posted a.warning-delete').bind('click', function() {
    var deleteLink = $('#posted');
    $.ajax({
      type: 'POST',
      url: deleteLink.attr('href'),
      success: function(){deleteLink.parent().remove()}
    });
    return false;
  });
};

function hijackAddBookmarkForm() {
  $('#new_post').submit(function() {
    $(this).ajaxSubmit({
      target: '#posted',
      clearForm: true,
      success: hijackDeleteBookmarkLinks,
      error: displayError
    });
    return false;
  });
};

function displayError(request, errorType) {
  var msg = '<div class="error">'+request.responseText+'(click to close)</div>';
  $('#posted').append(msg);
  $('.error').click(function(){$(this).hide()});
};

$(function() {
  hijackAddBookmarkForm();
  hijackDeleteBookmarkLinks();
});

