
(function($) {
  var click_binding_list = [];

  /**
   * Some clickHandler code to avoid binding every single element. Instead bind to document.body
   */
  jQuery.fn.clickHandler = function(filter, callback) {
    click_binding_list.push({ filter: filter, callback: callback });
  }
  
  /**
   * Document-wide click binding
   */
  $(document.body).click(function(event) {
    var return_value = true;
    
    // Hack 'stopPropagation' tracking into existance for events here
    var oldStopPropagation = event.stopPropagation;
    var propagationStopped = false;
    event.stopPropagation = function() {
      propagationStopped = true;
			oldStopPropagation();
		};
    
    // Traverse up the DOM from the clicked element, and see if we have any matches
    var target = $(event.target);
    while ((target.size() > 0) && !propagationStopped) {
      for (i in click_binding_list) {
        // If the target is matched by the filter...
        if (target.is(click_binding_list[i].filter)) {
          // Then run the callback
          var this_return = click_binding_list[i].callback.apply(target.get(0), [event]);
          // Return false if any binding returned false
          if (this_return == false) return_value = false;
        }
      }
      target = target.parent();
    }
    
    // Restore old 'stopPropagation' in event
    event.stopPropagation = oldStopPropagation;
    
    return return_value;
  });
})(jQuery);


