// jQuery 'oninit' plugin
// Provides functionality similar to jquery's 'live'
// in jQuery 1.2.x. Also supports 'substituted' lookups

(function($) {
  // List of stored calls
  var call_list = [];

  // Register an oninit call
  jQuery.fn.oninit = function(selector, fn, args) {
    // Add the call to the list of calls
    call_list.push({ selector: selector, fn: fn, args: args });

    // Call when the document is ready
    // Register seperately for every call to oninit, to ensure that they
    // are called at the expected time, and not before other $(document).ready
    // hooks.
    $(document).ready(function() {
      var sel_ob = $(document).find(selector);
      if (sel_ob.length > 0) {
        fn.apply(sel_ob, args);
      }
    });
  }

  // Call all registered callbacks
  jQuery.fn.oninit_call = function() {
    var context = $(this);
    $.each(call_list, function() {
      var sel_ob = context.find(this.selector);
      if (sel_ob.length > 0) {
        this.fn.apply(sel_ob, this.args);
      }
    });
  }

  // Deep string replacement
  var deep_replace = function(args, find, newstring) {
    if (typeof(args) == 'string') {
      return args.replace(find, newstring);
    } else if (typeof(args) == 'object') {
      for (i in args) {
        args[i] = deep_replace(args[i], find, newstring);
      }
    }
    return args;
  }

  // Call all registered callbacks, with string replacements on selectors
  // Used for when inserting from a template
  jQuery.fn.oninit_sub_call = function(findstring, newstring, findstring2, newstring2) {
    var context = $(this);
    var find = new RegExp(findstring, "g");
    var find2 = null;
    if (typeof(findstring2) != 'undefined') {
      find2 = new RegExp(findstring2, "g");
    }
    $.each(call_list, function() {
      var selector = this.selector.replace(find, newstring);
      var copy_args = deep_replace(jQuery.extend(true, [], this.args), find, newstring);
      if (find2 != null) {
        selector = selector.replace(find2, newstring2);
        copy_args = deep_replace(copy_args, find2, newstring2);
      }
      if (selector != this.selector) {
        // Add a new callback to the list, with replacements performed, so that
        // we can match sub-callbacks that depend on this template and another
        // (see trac #1570)
        call_list.push({ selector: selector, fn: this.fn, args: copy_args });
      }
      var sel_ob = context.find(selector);
      if (sel_ob.length > 0) {
        this.fn.apply(sel_ob, copy_args);
      }
    });
  }
})(jQuery);

