/******************************************************************************
 ** JQuery URI parser - parse string into an object conforming to window.location
 ** 
 ** Usage:
 **     var uri = new $.uri("http://example.com/foo/bar?x=1&y=2#stuff");
 ** 
 ** <alan at rubensteintech dot com>
 *****************************************************************************/

;(function ($) { // protect the namespace

$.uri = function( str, base_uri ) {

  var self = this;

  if (str == null)
    str = '';
  if (base_uri == null)
    base_uri = window.location;

  self.protocol = base_uri.protocol;
  self.hash = '';
  self.search = '';
  self.host = base_uri.host;
  self.hostname = base_uri.hostname;
  self.port = base_uri.port;
  self.pathname = '';

  str = str.replace(/^([A-Za-z0-9]+:)\/\//, function(m, p1) {
    self.protocol = p1; return '';
  });

  str = str.replace(/(#.*)$/, function(m, p1) {
    self.hash = p1; return '';
  });

  str = str.replace(/(\?.*)$/, function(m, p1) {
    self.search = p1; return '';
  });

  str = str.replace(/^\[?([A-Z-a-z0-9-\.]+)\]?(:(\d+))?/, function(m, p1, p2, p3) {
    self.hostname = p1;
    self.port = p3;
    return '';
  });

  if (str.indexOf('/') == 0) {
    self.pathname = str;
  }

  // normalization

  if (self.port == null) self.port = '';
  if (self.protocol == 'http:' && self.port == '80') self.port = '';
  if (self.protocol == 'https:' && self.port == '443') self.port = '';
  if (self.search == '?') self.search = '';
  if (self.hash == '#') self.hash = '';
  if (self.pathname == '') self.pathname = '/';

  // derived fields

  self.host = self.hostname;
  if (self.port != '') self.host += ':' + self.port;

  self.origin = self.protocol + '//' + self.host;
  self.href = self.origin + self.pathname + self.search + self.hash;

  return self;
};

})(jQuery); // function ($)

