/*
 ==================================================================================================
 Copyright (c) 2011 Adam Jakielski (http://www.39thRonin.com)
 
 Author : 	Adam Jakielski
 Purpose : 	Compares the current URL with the URL's in a selection of anchors you provide and
		applies a class of your choice to the first match.
 Version : 	1.6 - Now works happily with jQuery 1.6.1
 ==================================================================================================
*/

function apply_page_anchor_class(anchors, class_to_apply)
{
	function format_pathname(pathname)
	{
		/*
	 		This takes those pesky file extensions out of the equation.
	 		Got anchors with the same filename but different extension? 
	 		Change the filenames so they are not only distinguishable by file extension :/
	 		(for eg. pic.jpg, pic.png should be changed to pic_jpg.jpg, pic_png.png)
		*/
		if(pathname.substr(pathname.length-1,1) != '/')
		{
			if(pathname.split('/').pop().indexOf('.') > 0)
				pathname = pathname.substr(0, pathname.lastIndexOf('.'));
		}
		
		/*
	 		This adds a forward slash to the beginning of the pathname if it's missing one.
	 		by doing this we avoid the mismatch when using IE
		*/
		if(pathname.substr(0,1) != '/')
		{
			pathname = '/'+pathname;
		}		
		
		return pathname;
	}
	
	function check_anchors(pathname, search, hash)
	{
		var found = false;
		
		$(anchors).each(function()
		{
			var this_pathname 	= format_pathname($(this)[0].pathname);
			var this_search 	= $(this)[0].search;
			var this_hash		= $(this)[0].hash;
			
			if(!search)	search 	= '';
			if(!hash)	hash 	= '';
			
			if	(this_pathname + this_search + this_hash == pathname + search + hash) found = true;
			else if	(this_pathname + this_hash + this_search == pathname + hash + search) found = true;
			
			if(found==true)
			{
				$(this).addClass(class_to_apply);
				return false;
			}	
		});
		
		if(found) return true;
	}
	
	var pathname 	= format_pathname(document.location.pathname);
	var search 	= document.location.search;
	var hash 	= document.location.hash;
		
	/* 
		A - First we check for an exact match
		B - Then we check minus the hash
		C - Then we'll try various combinations of the search/query strings, with and then without the hash.
			Using anchors with more than one query string? Not accounted for those yet :(
		D - Then as last resorts, we check without search/query strings;
		E - And then lastly using only the pathname
	*/
	
	if (check_anchors(pathname, search, hash)) return;	// A
	if (check_anchors(pathname, search, false)) return;	// B
	if (search)						// C
	{
		search_strings = search.substring(1).split("&");
		
		if(search_strings.length>1)
		{
			for (x in search_strings)
			{
				if(check_anchors(pathname, '?'+search_strings[x], hash)) {return;}
				if(check_anchors(pathname, '?'+search_strings[x], false)) {return;}
			}
		}
	}
	if (check_anchors(pathname, false, hash))	return; // D
	if (check_anchors(pathname, false, false))	return;	// E
}
