String.prototype.backSlashTrim = function() {
  return this.replace(/^\/|\/$/g,"");
}

;(function($) {
  $.includeScript = function(scriptName) {
    var dSep="/";

    // private methods
    var internal = {

      // return the file name portion of a path
      // e.g. '/foo/bar/baz' returns 'baz'
      basename: function(file) {
        return String(file).split(dSep).pop();
      },

      // return the parent directory path of a file path.
      // e.g. '/foo/bar/baz' returns '/foo/bar'
      dirname: function(file) {
        var arr, len;
        arr = String(file).split(dSep);
        len = arr.length;
        return arr.slice(1,len - 1).join(dSep);
      },

      isAbsolutePath: function(file) {
        return String(file).split(dSep)[0] === "";
      },
      toAbsolutePath: function(file,dir) {
        if(internal.isAbsolutePath(file)) { 
          return file;
        }
        dir = String(dir).backSlashTrim();
        dir = dir ? "/" + dir : "";
        return dir + "/" + String(file).backSlashTrim();
      }      
    };

    return function() {
      var loc,parts,scheme,domain,path,absPathScript,
        loaded = false,
        // this is a simple pattern for a url, $1 = scheme, $2 = domain, $3 = path
        pattern = /^(http[s]?:\/\/)?([a-zA-Z0-9-\.]+)(\/.*)?$/;

      $(document).each(function(i) {
        loc = loc || this.location;
      });

      parts = String(loc).split(pattern);
      scheme = parts[1];
      domain = parts[2];
      path = parts[3];

      // get the absolute path of the script we want to load
      absPathScript = internal.toAbsolutePath(scriptName,internal.dirname(path));

      // check if the script we want to load is already loaded
      $('script[type="text/javascript"][src]').each(function(i) {
        var $script = $(this);
        if(String($script.attr('src')) == String(absPathScript)) {
          loaded = true;
        }
      });

      if(!loaded) {
        var head = document.getElementsByTagName('head')[0];
        var tag = document.createElement('script');
        tag.type = 'text/javascript';
        tag.src = absPathScript;
        head.appendChild(tag);
      }
      return !loaded;
    }();
  };

})(jQuery);

