/*
 * jQuery AutoAjax plugin v1.5
 * File Date: 4/2/2008
 *
 * Copyright (c) 2008 Jim Salyer
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

$.extend({
  autoAjax: function(locals)
  {
    $('<div></div>').autoAjax(locals);
  }
});
 
$.fn.extend({
  autoAjax: function(locals)
  {
    // set up the options for the script
    var globals = {
      url: "",
      src: "",
      dest: "",
      processStyles: false,
      processScripts: false,
      excludeCSSFiles: [],
      excludeScriptFiles: [],
      beforeRequest: function(){},
      afterRequest: function(data){},
      error: function(xhr, txt, err){}
    };
    globals = $.extend(globals, locals);
    
    return $(this).each(function()
    {
      // initialize the global variables
      var el = $(this);
      var settings = {
        url: globals.url,
        beforeSend: $.isFunction(globals.beforeRequest) ? globals.beforeRequest : function(){},
        error: $.isFunction(globals.error) ? globals.error : function(xhr, txt, err){},
        success: function(data, txt)
        {
          // if we've run a successful request,
          // 1. get the data
          // 2. filter script tags out of it
          // 3. append it to the destination element
          var noScripts = data.replace(/<\/?script[^>]*>/g, "");
          var code = noScripts
          if (typeof(globals.src) == "string" && globals.src != "") code = $('<div></div>').append(code).find(globals.src).html();
          if (typeof(globals.dest) == "string" && globals.dest != "") $(globals.dest).html(code);
          
          if (globals.processStyles)
          {
            // load any styles from the source page
            var styles = $('<div></div>').append(noScripts).find("link[rel=stylesheet], style");
            styles.each(function()
            {
              var el = $(this);
              if (this.tagName.toLowerCase() == "link")
              {
                if (el.attr("rel") == "stylesheet" && $.inArray(el.attr("href"), globals.excludeCSSFiles) < 0)
                  $("head").append(el);
              }
              else
                $("head").append(el);
            });
          }
          
          if (globals.processScripts)
          {
            // run any scripts from the source page
            var scripts = data.match(/<script[^>]*>[\s\S]*?<\/script>/gi);
            if (scripts)
            {
              for (var i=0; i<scripts.length; i++)
              {
                var url = scripts[i].match(/src\s*\=\s*([^\s>]+)/i);
                if (url)
                {
                  // run the external scripts
                  url = url[1].replace(/['"]/g, "");
                  if ($.inArray(url, globals.excludeScriptFiles) < 0)
                  {
                    $.ajaxSetup({
                      async: false
                    });
                    $.getScript(url);
                    $.ajaxSetup({
                      async: true
                    });
                  }
                }
                else
                {
                  // run the internal scripts
                  var code = scripts[i].replace(/<\/?script[^>]*>/g, "");
                  eval(code);
                }
              }
            }
          }
          if ($.isFunction(globals.afterRequest)) globals.afterRequest(data); // run the afterRequest event handler (if applicable)
        }
      };
      
      // get the applicable element or elements and set up the script based upon element type
      if (el.attr("action"))
      {
        // submit the request for a form
        el.submit(function()
        {
          // process the form's action using Ajax
          $.ajax($.extend(settings, {
            data: el.serialize(),
            type: el.attr("method").toUpperCase(),
            url: el.attr("action")
          }));
          return false;
        });
      }
      else if (el.attr("href"))
      {
        // submit the request for a link
        el.click(function()
        {
          // process the link URL using Ajax
          $.ajax($.extend(settings, {
            url: el.attr("href")
          }));
          return false;
        });
      }
      else if (typeof(settings.url) == "string" && settings.url != "") // run an Ajax request independently
        $.ajax(settings);
    });
  }
});