$(document).ready(function(){




	/* FOR FLASH VIDEO PLAYER*/
	$('.chooseNewVid').click(function(){

		var flash = getMovie('myContent');

		var activeVid = $(this).attr("href");

		flash.setVideo(activeVid);
		return false;


	});






	//modified existing fanBox hide/show js
	$('#fanbox_open').click(function(){
		$('#fanbox').show();
		$('#fanbox_close').show();
		$('#fanbox_open').hide();
	});

	$('#fanbox_close').click(function(){
		$('#fanbox').hide();
		$('#fanbox_close').hide();
		$('#fanbox_open').show();
	});



	//Switch the "Open" and "Close" state per click
	$("h3.trigger").toggle(function(){
		$(this).addClass("active");
		}, function () {
		$(this).removeClass("active");
	});

	//Slide up and down on click
	$('h3.trigger').click(function(){
		$(this).next('.toggle_container').slideToggle('slow'); return false;
	});


	//colorbox
	$(".modal-readStories").colorbox({iframe:true, innerWidth:883, innerHeight:612, opacity:.9, transition:"fade", initialWidth:208, initialHeight:13, scrolling:false,overlayClose: false,


									 onLoad:function(){
										 $("#cboxClose").removeClass("blackClose");
										 }
									 });

	$(".modal-submitStory").colorbox({iframe:true, innerWidth:545, innerHeight:836, opacity:.9, transition:"fade", initialWidth:208, initialHeight:13, scrolling:false,overlayClose: false,

									 onLoad:function(){
										 $("#cboxClose").addClass("blackClose");
										 }
									 });

	$("a[rel='printAds']").colorbox({width:"704px", height:"917px", transition:"none", overlayClose: false,

									 onLoad:function(){
										 $("#cboxContent").addClass("printBG");
										  $("#cboxClose").addClass("closeWindow");
										 }
									});





		//When page loads...
	$(".tab_content").hide(); //Hide all content

	$("ul.tabs li:first").addClass("gpActive").show(); //Activate first tab
	$("ul.tabs li.finalists").addClass("finalinActive");


	$(".tab_content:first").show(); //Show first tab content


	$("ul.tabs li.gpWinners").click(function() {
		$("ul.tabs li.finalists").removeClass("finalActive");
		$("ul.tabs li.finalists").removeClass("finalinActive");

		$("ul.tabs li.gpWinners").removeClass("gpinActive");
		$("ul.tabs li.gpWinners").removeClass("gpActive"); //Remove any "active" class

		$(this).addClass("gpActive"); //Add "active" class to selected tab
		$("ul.tabs li.finalists").addClass("finalinActive");

		$(".tab_content").hide(); //Hide all tab content


		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content

		$(activeTab).fadeIn(); //Fade in the active ID content
		//$(activeTab).show(); //Fade in the active ID content
		return false;
	});

	$("ul.tabs li.finalists").click(function() {
		$("ul.tabs li.gpWinners").removeClass("gpActive");
		$("ul.tabs li.finalists").removeClass("finalinActive");
		$("ul.tabs li.finalists").removeClass("finalActive"); //Remove any "active" class

		$("ul.tabs li.gpWinners").addClass("gpinActive");
		$(this).addClass("finalActive"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content


		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content

		$(activeTab).fadeIn(); //Fade in the active ID content
		//$(activeTab).show(); //Fade in the active ID content
		return false;
	});




	/* $('.scrollWindow').jcarousel({
			wrap: 'circular',
			scroll: 1


	});
*/


//scroller for Get Inspired page
//new scroller 8182010
  $('#getInspiredThumbs').carouFredSel({
	  visibleItems    : 4,
	  scroll: {
		  items:1
	  },
	  autoPlay		: false,
	  next : {
		  button		: $('#getInspiredThumbs_next'),
		  key			: 'right'
	  },
	  prev : {
		  button		: $('#getInspiredThumbs_prev'),
		  key			: 'left'
	  }
  });
  
  
  


	$(".contentArea").hide(); //Hide all content
	$(".contentArea:first").show(); //Show first tab content



$("#getInspiredThumbs li a").click(function() {
		$(".contentArea").hide(); //Hide all content
		var activeAreaURL = $(this).attr("href"); //Find the href attribute value to identify the active tab + content

		//$(activeImage).fadeIn(); //Fade in the active ID content

		var temp = activeAreaURL.split("#");
		var activeArea = "#" + temp[1];
		//alert(activeArea);
		$(activeArea).show();
		return false;
	});


	/*$(".scroller .scrollWindow li a").click(function() {
		$(".contentArea").hide(); //Hide all content
		var activeAreaURL = $(this).attr("href"); //Find the href attribute value to identify the active tab + content

		//$(activeImage).fadeIn(); //Fade in the active ID content

		var temp = activeAreaURL.split("#");
		var activeArea = "#" + temp[1];
		//alert(activeArea);
		$(activeArea).show();
		return false;
	});
*/






	/* MODAL*/



  //new scroller 8182010
  $('#fuelThumbs').carouFredSel({
	  visibleItems    : 3,
	  scroll: {
		  items:1
	  },
	  autoPlay		: false,
	  next : {
		  button		: $('#fuelThumbs_next'),
		  key			: 'right'
	  },
	  prev : {
		  button		: $('#fuelThumbs_prev'),
		  key			: 'left'
	  }
  });
  
  		
//$("#vidHolder").hide();



	//build the scrollers first before hiding anything, else there could be issues


/*
    $('.mycarousel').jcarousel({
			wrap: 'circular',
			scroll: 1


	});*/

	//var howMany = $('.storyMainContainer').size();
	
	var howMany = getQuerystring('total');


	//var whichStory = 1;

	//get the page the user wants to see
	//var whichStory = getQuerystring('story');
	//var whichStory = getQuerystring('curr');
	//var story = getQuerystring('story');
	
	
	if( $.url.attr("port") == '8888'){
		var baseURL = "http://" + $.url.attr("host") + ":" + $.url.attr("port") + "/" + $.url.segment(0) + "/" +$.url.segment(1);
	}else{
		var baseURL = "http://" + $.url.attr("host") + "/" + $.url.segment(0) + "/" +$.url.segment(1);
	}
	
	
	//var baseURL = "/" + $.url.segment(0) + "/" +$.url.segment(1);
	
	
	var whichStory = 1;
	if ($.url.segment(2) != null){
		whichStory = Number($.url.segment(2));
	}


	/*whichStory = $.trim(whichStory);
	 if (whichStory == ""){
		 var whichStory = story;
	 }*/

	$('.storyCount p').replaceWith('<p>' + whichStory + ' of ' + howMany + '</p>');


	

	
	/*$(".scroller .mycarousel a").click(function() {
		//whichID = "#story"+whichStory;
		whichID = "#story1";
		//$(".contentArea").hide(); //Hide all content
		//var activeImage = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(whichID + " .mid img").attr("src", $(this).attr("href"));

		//$(activeImage).fadeIn(); //Fade in the active ID content
		//$(activeImage).show();
		
		//alert(whichStory);
		return false;
	});*/
	
	
	$('#fuelThumbs li a').click(function() {
										 
		$('#vidHolder').show();  

		whichID = "#story1";
		
		if ($(this).attr("href").indexOf('story')  > 1 ){
			$('#vidHolder').hide();  

	
			//v$('.mid img').show();
			$('#imageHolder').show();

		  
		  $(whichID + " .mid img").attr("src", $(this).attr("href"));
		}else{

		  //$('.mid img').hide();
		  $('#imageHolder').hide();
		  //$('#vidHolder').show();  

		  //var flash = getMovie('vidContent');
  
		  var activeVid = $(this).attr("href");
		  //flash.setVideo(activeVid);
		  
		  var flashvars = {
			videoID: activeVid
			};
		  var params = {
			movie: "/swf/Video.swf",
			quality: "high",
			wmode: "transparent",
			allowScriptAccess: "sameDomain"
		  };
		  var attributes = {
			id: "vidContent",
			name: "vidContent"
		  };
		  swfobject.embedSWF("/swf/SmallVideo.swf", "vidContent", "342", "240", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);


		}

		return false;
	});
	



	//initialize  Prev/Next



	//SAFARI ISSUE
	//issues with Safari when using .hide()/.show(), trying the below instead


	$("#story"+whichStory+".storyMainContainer").css("z-index", "999");

	$(".storyMainContainer").removeClass("hideAll");




	//$("#modalWindow .next").find("a").attr("href","#story"+whichStory);
	$("#modalWindow .prev").find("a").attr("href","#story"+whichStory);
	
	$("#modalWindow .next").find("a").attr("href",baseURL+"/"+ (whichStory+1) + "/");
	$("#modalWindow .prev").find("a").attr("href",baseURL+"/"+ (whichStory-1) + "/");


	if (whichStory <= howMany){

			if (whichStory <= 1){
				$("#modalWindow .prev").hide();
			}
			if (whichStory > 1){
				$("#modalWindow .prev").show();
			}
			if (whichStory == howMany){
				$("#modalWindow .next").hide();
			}
	}
	
	
			
			


	$("#modalWindow .next").click(function() {
		
		$(".storyMainContainer").hide();
		$("#modalWindow .next").hide();
		  
	
		$('.storyMask').load(baseURL +'/' + (whichStory+1) +'/' + ' #story1', function(){
		  whichStory = whichStory + 1;
		  $('.storyCount p').replaceWith('<p>' + whichStory + ' of ' + howMany + '</p>'); 
		  $("#modalWindow .next").find("a").attr("href",baseURL+"/"+ whichStory + "/");
		  
		  $("#modalWindow .prev").show();
		  if (whichStory == howMany){
			$("#modalWindow .next").hide();
		  }else{
			$("#modalWindow .next").show();  
		  }
			
			$(".storyMainContainer").hide(); 
			$(".storyMainContainer").fadeIn();
			



			//new scroller 8182010
			$('#fuelThumbs').carouFredSel({
				visibleItems    : 3,
				scroll: {
					items:1
				},
				autoPlay		: false,
				next : {
					button		: $('#fuelThumbs_next'),
					key			: 'right'
				},
				prev : {
					button		: $('#fuelThumbs_prev'),
					key			: 'left'
				}
			});
			
			
			
				//check to see if this has video first
			    var activeVid = ($('#has_video').val() == undefined) ? '': $('#has_video').val();
				 
				if (activeVid != ''){
					//$('.mid img').hide();
					  $('#imageHolder').hide();
					  activeVid = $('#has_video').val();
					  var flashvars = {
						videoID: activeVid
						};
					  var params = {
						movie: "/swf/Video.swf",
						quality: "high",
						wmode: "transparent",
						allowScriptAccess: "sameDomain"
					  };
					  var attributes = {
						id: "vidContent",
						name: "vidContent"
					  };
					  swfobject.embedSWF("/swf/SmallVideo.swf", "vidContent", "342", "240", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
				}
								  
			
			$('#fuelThumbs li a').click(function() {
										 
				$('#vidHolder').show();  
		
				whichID = "#story1";
				
				if ($(this).attr("href").indexOf('story')  > 1 ){
					$('#vidHolder').hide();  
		
			
					//$('.mid img').show();
					$('#imageHolder').show();

				  
				  $(whichID + " .mid img").attr("src", $(this).attr("href"));
				}else{
		
				  //$('.mid img').hide();
				  $('#imageHolder').hide();
				  
				  //$('#vidHolder').show();  
		
				  //var flash = getMovie('vidContent');
		  
				  var activeVid = $(this).attr("href");
				  //flash.setVideo(activeVid);
				  
				  var flashvars = {
					videoID: activeVid
					};
				  var params = {
					movie: "/swf/Video.swf",
					quality: "high",
					wmode: "transparent",
					allowScriptAccess: "sameDomain"
				  };
				  var attributes = {
					id: "vidContent",
					name: "vidContent"
				  };
				  swfobject.embedSWF("/swf/SmallVideo.swf", "vidContent", "342", "240", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
		
		
				}
		
				return false;
			});
			
			
			/*//scroller crap
			$('.mycarousel').jcarousel({
				wrap: 'circular',
				scroll: 1
		    });
			
			$(".scroller .mycarousel a").click(function() {
				//whichID = "#story"+whichStory;
				whichID = "#story1";
				//$(".contentArea").hide(); //Hide all content
				//var activeImage = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
				$(whichID + " .mid img").attr("src", $(this).attr("href"));
		
				//$(activeImage).fadeIn(); //Fade in the active ID content
				//$(activeImage).show();
				
				//alert('test');
				return false;
			});*/
			
			
		
		});
		
		
		
		return false;
		
  	});
	$("#modalWindow .prev").click(function() {
		   
		$(".storyMainContainer").hide();
		$("#modalWindow .prev").hide();
		
		
		if(whichStory > 1){
		$('.storyMask').load(baseURL +'/' + (whichStory-1) +'/' + ' #story1', function(){
			  whichStory = whichStory - 1;
			  $('.storyCount p').replaceWith('<p>' + whichStory + ' of ' + howMany + '</p>'); 
			  $("#modalWindow .next").find("a").attr("href",baseURL+"/"+ whichStory + "/");
			  
			  $("#modalWindow .next").show();
			  if (whichStory == 1){
						$("#modalWindow .prev").hide();
			  }else{
					$("#modalWindow .prev").show();  
			  }
		  	
			  $(".storyMainContainer").hide(); 
			  $(".storyMainContainer").fadeIn();
			  
			
			
			//new scroller 8182010
			$('#fuelThumbs').carouFredSel({
				visibleItems    : 3,
				scroll: {
					items:1
				},
				autoPlay		: false,
				next : {
					button		: $('#fuelThumbs_next'),
					key			: 'right'
				},
				prev : {
					button		: $('#fuelThumbs_prev'),
					key			: 'left'
				}
			});
			
			
			
			//check to see if this has video first
			    var activeVid = ($('#has_video').val() == undefined) ? '': $('#has_video').val();
				 
				if (activeVid != ''){
					//$('.mid img').hide();
					  $('#imageHolder').hide();
					  activeVid = $('#has_video').val();
					  var flashvars = {
						videoID: activeVid
						};
					  var params = {
						movie: "/swf/Video.swf",
						quality: "high",
						wmode: "transparent",
						allowScriptAccess: "sameDomain"
					  };
					  var attributes = {
						id: "vidContent",
						name: "vidContent"
					  };
					  swfobject.embedSWF("/swf/SmallVideo.swf", "vidContent", "342", "240", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
				}
			
			
			$('#fuelThumbs li a').click(function() {
										 
				$('#vidHolder').show();  
		
				whichID = "#story1";
				
				if ($(this).attr("href").indexOf('story')  > 1 ){
					$('#vidHolder').hide();  
		
			
					//$('.mid img').show();
					$('#imageHolder').show();

				  
				  $(whichID + " .mid img").attr("src", $(this).attr("href"));
				}else{
		
				  //$('.mid img').hide();
				  $('#imageHolder').hide();

				  //$('#vidHolder').show();  
		
				  //var flash = getMovie('vidContent');
		  
				  var activeVid = $(this).attr("href");
				  //flash.setVideo(activeVid);
				  
				  var flashvars = {
					videoID: activeVid
					};
				  var params = {
					movie: "/swf/Video.swf",
					quality: "high",
					wmode: "transparent",
					allowScriptAccess: "sameDomain"
				  };
				  var attributes = {
					id: "vidContent",
					name: "vidContent"
				  };
				  swfobject.embedSWF("/swf/SmallVideo.swf", "vidContent", "342", "240", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
		
		
				}
		
				return false;
			});
			
			/* //scroller crap
			$('.mycarousel').jcarousel({
				wrap: 'circular',
				scroll: 1
		    });
			
			$(".scroller .mycarousel a").click(function() {
				//whichID = "#story"+whichStory;
				whichID = "#story1";
				//$(".contentArea").hide(); //Hide all content
				//var activeImage = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
				$(whichID + " .mid img").attr("src", $(this).attr("href"));
		
				//$(activeImage).fadeIn(); //Fade in the active ID content
				//$(activeImage).show();
				
				//alert(whichStory);
				return false;
			});*/
			
		  
		});
		}
		
		
		
		return false;
		
  	});
	
	
	/*$("#modalWindow .next").click(function() {
		$("#modalWindow .prev").show();

		whichStory++;

		$('.storyCount p').replaceWith('<p>' + whichStory + ' of ' + howMany + '</p>');

		if (whichStory <= howMany){

			$("#modalWindow .next").find("a").attr("href","#story"+whichStory);
			//$(this).attr("href","#story"+whichStory);

			if (whichStory == howMany){
				$("#modalWindow .next").hide();
			}
		}

		$(".storyMainContainer").hide(); //Hide all content

		var activeImage = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content

		$(activeImage).fadeIn();
		//$("#story2").show();

		return false;
	});
*/
	
	
	/*$("#modalWindow .prev").click(function() {
		$("#modalWindow .next").show();

		whichStory = whichStory-1;

		$('.storyCount p').replaceWith('<p>' + whichStory + ' of ' + howMany + '</p>');

		if (whichStory >= 1){

			$("#modalWindow .prev").find("a").attr("href","#story"+whichStory);
			//$(this).attr("href","#story"+whichStory);

				if (whichStory == 1){
					$("#modalWindow .prev").hide();

				}
		}


		$(".storyMainContainer").hide(); //Hide all content


		var activeImage = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeImage).fadeIn();

		return false;
	});*/




/* GET INSPIRED PHOTO SLIDER*/
/*
	//When page loads...
	$(".tab_content").hide(); //Hide all content
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content

	//On Click Event
	$("ul.tabs li").click(function() {

		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});
*/

/* GET INSPIRED VIDPLAYER*/


	//When page loads...
	$(".vidTab_content").hide(); //Hide all content
	$("ul.vidTabs li:first").addClass("active").show(); //Activate first tab
	$(".vidTab_content:first").show(); //Show first tab content

	//On Click Event
	$("ul.vidTabs li").click(function() {

		$("ul.vidTabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab






		//$(".vidTab_content").hide(); //Hide all tab content

		//var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content

		var flash = getMovie('theVideo');

		var activeVid = $(this).find("a").attr("href");

		flash.setVideo(activeVid);
		//$(activeVid).fadeIn(); //Fade in the active ID content

		return false;
	});


	/*  RANDOM QUOTE*/

	var whichQuote = 2;

	whichQuote = rand(5);

	$("#getInspired #quote").addClass("quote"+whichQuote);









});

/*FUNCTION TO OPEN MODAL FROM FLASH MAP*/

function openStoryModal(IDNUMBER){
	//alert(window.location.host);

	var whichStory = "http://" + window.location.host + "/read_the_stories/index/?story="+ IDNUMBER+"&curr="+ IDNUMBER;
	$.fn.colorbox({href:whichStory, iframe:true, innerWidth:883, innerHeight:612, opacity:.9, transition:"fade", initialWidth:208, initialHeight:13, scrolling:false,overlayClose: false});

}
/*FUNCTION TO OPEN MODAL FROM FLASH MAP*/





function getMovie(movieName) {
     return swfobject.getObjectById(movieName);
 }





function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

/* ===========================================================================
 *
 * JQuery URL Parser
 * Version 1.0
 * Parses URLs and provides easy access to information within them.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 *
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 *
 * ---------------------------------------------------------------------------
 *
 * CREDITS:
 *
 * Parser based on the Regex-based URI parser by Steven Levithan.
 * For more information (including a detailed explaination of the differences
 * between the 'loose' and 'strict' pasing modes) visit http://blog.stevenlevithan.com/archives/parseuri
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_url_parser/licence.txt
 *
 * ---------------------------------------------------------------------------
 *
 * 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 = {};

	/**
    * 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*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}

	};

    /**
     * Deals with the parsing of the URI according to the regex above.
 	 * Written by Steven Levithan - see credits at top.
     */
	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.
  	 *
	 * @param string key The key whose value is required
     */
	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.
  	 *
	 * @param string item The parameter whose value is required
     */
	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];
	};

    /**
     * '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();
	};

    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function()
	{
		var p = parsed.path;
		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("/");
	};

	return {

	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		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.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */
		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.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */
		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

	};

}();
