/* prevent execution of jQuery if included more then once */
if(typeof window.jQueryBinder == "undefined") {

$.fn.bindMany = function(object, event) {
  event = event || "click";

  for(lookup in object) {
    selector = object[lookup];
    if(typeof selector == 'function') {          
      $(this).find(lookup).bind(event, selector);
    } else if(typeof selector == 'object') {
      for(sevent in selector) {
        func = selector[sevent];
        $(this).find(lookup).bind(sevent, func);
      }
    }
  }  
}

$.fn.defineTemplate = function(template, event_handlers, default_event) {
  //  Create a templates object where we store all our templates...
  if(!$.templates) $.templates = {};
  //  Clone our currently selected node, adding the event handlers in the "bindings" object
  var node = $(this).clone();
  $.templates[template] = {
    name: template, 
    node: node, 
    event_handlers: event_handlers, 
    default_event: default_event
  };
}

$.fn.applyTemplate = function(template) {
  if(typeof template == 'string') template = $.templates[template];
  $(this).bindMany(template.event_handlers, template.default_event);
}

$.fn.appendTemplate = function(template) {
  if(typeof template == 'string') template = $.templates[template];
  var node = template.node.cloneWithBindings(template.event_handlers, template.default_event);
  $(this).append(node);
  return node;
}

//  TODO: Rename cloneWithBindings
$.fn.cloneWithBindings = function(event_handlers, default_event) {
  default_event = default_event || "click";
  var result = $(this).clone();
  result.bindMany(event_handlers, default_event);
  return result;
}

$.fn.appendIfNotFound = function(f, element) {
  if($(this).find(f).length == 0)
    $(this).append(element);
  var element = $(this).find(f);
  return element;
}

function debug(category, message) {
  var table = $("#debug_console").appendIfNotFound("#debug_table", "<table id='debug_table' border='1'></table>");
  var row = table.append("<tr><td>" + category + "</td><td>" + message + "</td></tr>");
  row.text(message);
}
  
}

