(function($){
 /*
  Load ajax content for a link.
  */
  $.fn.ajaxContent = function (config) {
    config = $.extend({
      replaceThis : null,
      replacement : null,
      postback : null,
      append: false,
      onClick: false,
      args: null
    }, config || {});
    
    var links = $(this);
    
    if (links.size() > 1) {
      links.each(function() {
        $(this).ajaxContent(config);
      });
    }
    else if (links.size() == 1) {
      var link = $(this);
      
      var executeMe = function(config) {
        config.replaceThis = config.replaceThis == null ? link : $.isFunction(config.replaceThis) ? config.replaceThis() : $(config.replaceThis);
        config.replacement = config.replacement == null  ? $("<div></div>") : $.isFunction(config.replacement) ? config.replacement() : $(config.replacement);
        
        if (link.attr("href") != null) {
          var url = link.attr("href") ;
          url += (url.contains("?") ? "&" : "?") + "ajax=true" + (config.args ? "&" + config.args : "");
          if (link.attr("content_loaded")) {
            url += link.attr("content_loaded");
          }          
          var replacement = config.replacement;

          $.get(url, "", function(data, status, xmlHttpRequest) {
            if ((xmlHttpRequest == null && status == "success") || (xmlHttpRequest != null && xmlHttpRequest.status == 200)) {
              if (!config.append) {
                config.replaceThis.replaceWith(replacement);
              }
              else {
                config.replaceThis.append(replacement);
              }
              replacement.append(data);
			  
              if (config.postback != null) {
                // Set postback value
                replacement.find("input[name=postback]").attr("value", config.postback);
              }
              
              link.attr("content_loaded", "&content_loaded=true");
            }
          });
        }
      }
      
      if (config.onClick) {
        link.click(function() {
          executeMe(config);
          return false;
        })
      }
      else {
        executeMe(config);
      }
    }
  };
})(jQuery); 