/* 
 * JQuery URL Parser - v1.0
 * Parses URLs and provides easy access to information within them.

 * EXAMPLES OF USE:
 *
 * Get the domain name (host) from the current page URL
 * jQuery.url.attr("host")
 *
 * Get the query string value for 'item' for the current page
 * jQuery.url.param("item") // null if it doesn't exist
 *
 * Get the second segment of the URI of the current page
 * jQuery.url.segment(2) // null if it doesn't exist
 *
 * Get the protocol of a manually passed in URL
 * jQuery.url.setUrl("http://allmarkedup.com/").attr("protocol") // returns 'http'
 *
 */
 jQuery.url = function(){
	var segments = {};
	var parsed = {};
	var urlargs = {};
	/* Options object. Only the URI and strictMode values can be changed via the setters below. */
  var options = {
		url : window.location, // default URI is the page in which the script is running
		strictMode: false, // 'loose' parsing by default
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, // more intuitive, fails on relative paths and deviates from specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ //less intuitive, more accurate to the specs
		}
	};
	
  /* Deals with the parsing of the URI according to the regex above. */		
	var parseUri = function() {
		str = decodeURI( options.url );
		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;
		while ( i-- ) { uri[ options.key[i] ] = m[i] || ""; }
		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) uri[options.q.name][$1] = $2;
		});
		return uri;
	};

  /* Returns the value of the passed in key from the parsed URI. */		
	var key = function( key ) {
		if ( ! parsed.length ) setUp(); // if the URI has not been parsed yet then do this first...	
		if ( key == "base" ) {
			if ( parsed.port !== null && parsed.port !== "" ) return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
			else return parsed.protocol+"://"+parsed.host+"/";
		}
		return ( parsed[key] === "" ) ? null : parsed[key];
	};
	
	/* Returns the value of the required query string parameter. */		
	var param = function( item ){
		if ( ! parsed.length ) setUp(); // if the URI has not been parsed yet then do this first...	
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};
	
  /* Splits up the body of the URI into segments (i.e. sections delimited by '/') */
	var getSegments = function(){
		var p = parsed.path;
		var dot = p.lastIndexOf("."); 
    if( dot > -1 ) p = p.substr(0,dot);
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};

  /* 'Constructor' (not really!) function. Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. */	
	var setUp = function(){
		parsed = parseUri();
		getSegments();	
	};
	
	return {
    /* Sets the parsing mode - either strict or loose. Set to loose by default.*/
		setMode : function( mode ){
			strictMode = mode == "strict" ? true : false;
			return this;
		},
		
		/* Sets URI to parse if you don't want to to parse the current page's URI. */		
		setUrl : function( newUri ){
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},
		/* Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments. */	
		segment : function( pos ){
			if ( ! parsed.length ) setUp(); // if the URI has not been parsed yet then do this first...	
			if ( pos === undefined ) return segments.length;
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},
		attr : key, // provides public access to private 'key' function - see above
		param : param // provides public access to private 'param' function - see above
		
	};
	
}();