Need help fixing navigation menu

Need help fixing navigation menu

I am using JQuery for a navigation menu which adds a "selected" class to its links depending on which page is active.

This is what the HTML code for the menu looks like:
  1.     <div id="nav">
  2.         <ul>
  3.             <li><a href="index.php">HOME</a></li>
  4.             <li><a href="gallery.php?categoryID=1">GALLERIES</a></li>
  5.             <li><a href="news.php">NEWS</a></li>
  6.             <li><a href="links.php">LINKS</a></li>
  7.             <li><a href="contact.php">CONTACT US</a></li>
  8.         </ul>
  9.     </div>
   
And this is the JQuery code:
  1.     var pageLocation = window.location.toString().split("/");
  2.     var pageName = pageLocation[pageLocation.length - 1];
  3.     var selectedLink = $("li:has(a[href="+pageName+"])");
  4.    
  5.     $("a[href="+pageName+"]").addClass("selected");

Now this works fine if you click on one of the links in the #nav div, but if you click on another link which is not in the #nav div then the menu becomes broken.

For example, if you go to my test site here:http://www.awais-muzaffar.co.uk/test/index.php and then click on galleries, and then click on the 12 Days of Christmas link below, you will observe that the navigation menu becomes broken.

How do I get around an issue like this?