// $Id

Drupal.voteForIdeaAutoAttach = function() {
  var vdb = [];
  $('div.vote-idea-active').each(function () {
    // Read in the path to the PHP handler
    uri = $(this).attr('title');
    // Remove the title, so no tooltip will display
    $(this).removeAttr('title');
    // remove href link
//    $(this).html('');
    // Create an object with this uri. Because
    // we feed in the span as an argument, we'll be able
    // to attach events to this element.
    if (!vdb[uri]) {
      vdb[uri] = new Drupal.VDB(this, uri);
    }
  });
}

/**
 * A Vote DataBase object
 */
Drupal.VDB = function(elt, uri, id) {
  var db = this;
  // By making the span element a property of this object,
  // we get the ability to attach behaviours to that element.
  this.elt = elt;
  this.uri = uri;
  this.id = $(elt).attr('id');
  this.dir1 = this.id.indexOf('vote_up') > -1 ? 'up' : 'down';
  this.dir2 = this.dir1 == 'up' ? 'down' : 'up';
  $(elt).click(function() {
    // Ajax GET request for vote data
    $.ajax({
      type: "GET",
      url: db.uri,
      success: function (data) {
        // extract the cid so we can change other elements for the same cid
        var cid = db.id.match(/[0-9]+$/);
        var pid = 'vote_points_' + cid;
        //update the voting arrows
        $('#vote-idea-plus' + cid)
          .css({ visibility:"visible", top:"70px", left:"30px" } )
          .animate({ top:40, left:15, opacity:0.8 }, { duration:4000 })
          .animate({ top:4, left:0, opacity:0.1 }, { duration:2000 })
          .fadeOut(10, function() {
            // update classes
            $('#' + db.id)
            .removeClass('vote-idea-active')
            .addClass('vote-idea-inactive')
            .unbind();
            // update the points
            $('#' + pid).html(data);
          });
      },
      error: function (xmlhttp) {
        alert('An HTTP error '+ xmlhttp.status +' occured.\n'+ db.uri);
      }
    });
  });
}

// Global killswitch
if (Drupal.jsEnabled) {
  $(document).ready(Drupal.voteForIdeaAutoAttach);
}
