$(function() {
	$("a[rel]").each(function() { assign_handlers(this); });
});


/**
  Assigns an onclick handler to 'node' if 'node' has an approiately formatted
  rel attribute. The format for the rel attribute is a whitespace seperated
  list of handler calls, where a handler call is one of the following:
    name
    name(arg1, arg2, ...)
  In either case, the onclick event handler for the node will call the function
  handler_name with the approiate arguments. The argument passed to the onclick
  (if any) is passed to the handler as the first argument. In the second
  case above, this would be equivalent to calling handler_name(evt, arg1, arg2).
  The return values of the handler calls are aggregated and returned by the
  onclick handler. If the handler call returns 'undefined', then nothing is
  done, otherwise it's boolean value is logically ANDed with the previous
  results.
*/
function assign_handlers(node) {
  if (node.rel == '') return;
  
  var old_rel = '', rel = node.rel;
  var regexps = [
    /^\s*(\w+)\((.*?)\)/, // Handler with arguments
    /^\s*(\w+)/           // Handler without arguments
  ];
  var functions = [], args = [];
  while (rel.length > 0 && rel != old_rel) {
    var re, match = null;
    for (var i=0; i<regexps.length && !match; i++) {
      re = regexps[i];
      match = rel.match(re);
    }
    old_rel = rel;
    rel = rel.replace(re, '');
    
    if (!match) continue;
    
    var fname = 'handle_' + match[1];
    var fargs = match.length > 2 ? match[2].split(/,\s*/) : [];
    
    if(match.length > 2 && match[2].match(/,$/) && $.browser.msie) {
      fargs.push("");
    }
    
    if (typeof window[fname] == 'undefined') continue;
    
    functions.push(fname);
    args.push(fargs);
  }
  delete regexps;
  delete rel;
  
  if (functions.length == 0) return;
  $(node).click(function(evt) {
  	var ret_val = true;
	var evt = window.event ? window.event : evt;
	
    for (var i=0; i<functions.length; i++) {
      var fname = functions[i];
      
      var fargs = [evt].concat(args[i]);
      var result = window[fname].apply(node, fargs);
      if (typeof result != 'undefined') ret_val = ret_val && result;
    }
    return ret_val;
  });
}

function handle_external() {
	this.setAttribute("target","_blank");
	return true;
}