// $Id: views_bookmark.js,v 1.1.2.12 2007/08/31 17:58:29 quicksketch Exp $
if (Drupal.jsEnabled) {
  $(document).ready(function () {

    // Helper function for flipping the bookmark link contents.
    function flipLink(element, settings) {
      // Get the current status by reading the class names.
      var current_class = $(element).attr('class');
      if (current_class.indexOf('views-bookmark-mark ') == -1) {
        // Add the mark link.
        var new_link = $(settings.mark);
      }
      else {
        // Add the unmark link.
        var new_link = $(settings.unmark);
      }

      // Reattach the behavior to the new link.
      if ($('a', new_link).size() > 0) {
        $('a', new_link).bind('click', function() { return bookmark_click(this, settings) });
	  }
	  else {
	  	$(new_link).bind('click', function() { return bookmark_click(this, settings) });
	  }

      if ($(element).parent('.views-bookmark-wrapper').length > 0) {
        $(element).parent().parent().empty().append(new_link);
	  }
	  else {
        $(element).parent().empty().append(new_link);
	  }
      $('.views-bookmark-message', new_link).fadeIn();
    }

    // Click function for each views bookmark link.
    var bookmark_click = function (element, settings) {
      // Remove the destination parameter.
      if (Drupal.settings.views_bookmark.clean_url == '1') {
        var request_url = element.href.slice(0, element.href.lastIndexOf('?')) + '/1';
      }
      else {
        var request_url = element.href.slice(0, element.href.indexOf('&')) + '/1';
      }

      // Send POST request
      $.ajax({
        type: 'POST',
        url: request_url,
        data: '',
        dataType: 'json',
        success: function (data) {
          // Display errors
          if (!data.status) {
            // Change link back
            flipLink(element, settings);
            return;
          }
        },
        error: function (xmlhttp) {
          alert('An HTTP error '+ xmlhttp.status +' occured.\n'+ element.href);
          // Change link back
          flipLink(element, settings);
        }
      });
      // Swap out the links.
      flipLink(element, settings);
      return false;
    }

    // On load, bind the click behavior for all links on the page.
    for (i in Drupal.settings.views_bookmark.bookmarks) {
      // This bind method is a little silly. We should just be able to pass
      // in the settings as additional data to the click method, but this
      // doesn't work in jQuery 1.0.4.
      $('a.'+ i).bind('click', function() {
        var matches = this.className.match(/(links_bookmark_[0-9]+)/);
		var vbid = matches[1];
		var matches = this.href.match(/mark\/([0-9]+)/);
		var nid = 'node_' + matches[1];

        return bookmark_click(this, Drupal.settings.views_bookmark.bookmarks[vbid][nid]);
      });
    }
  });
}