var hasSubnav = 0;
var hasExtra = 0;
$(document).ready(function() {
	if ($.browser.msie) return;
	
 	var bindBehaviors = function(scope) {
		$(function () {
			$('a:not(.ext)', scope).address();
		});
	};
	bindBehaviors(this);
	
	$.address.change(function(event) {
		// get page section
		var section = '';
		if (event.value != '/') {
			section = event.value.match(/\/([a-z\-]+)?/)[1];
		}
		
		// update the page title
		// NOTE: this is getting the tab link when clicking the first subnav link
		var link = $('a[href=' + event.value + ']');
		if (link.length > 0) {
			$.address.title(link.attr('title') + ' - Produxs');
		}

		// mark the subnav link
		if (link.parent().parent().is(".subnav")) {
			$('.subnav li a').removeClass('selected');
			link.addClass('selected');
		}

		// get tab href
		var tabhref = (section.length > 0 ? '/' + section + '.html' : '/');
		
		// get the current tab
		var tab = $("#tabnav a[class*='on']");
		if (tab.attr('href') == undefined) {
			$('#tabnav a[href=' + tabhref + ']').toggleClass('on');
		}
		else if (tab.attr('href') != tabhref) {
			// alert('tabchange: tabhref-' + tabhref + ', tab.href-' + tab.text());
			// tab has changed so toggle off the old tab
			tab.toggleClass('on');

			// remove the old subnav
			$('#subnav ul').remove();

			// toggle the new tab
			$('#tabnav a[href=' + tabhref + ']').toggleClass('on');
		}
		
		// determine what we have already
		hasSubnav = $('#' + section + '-subnav').length;
		hasExtra = $('#' + section + '-extra').length;

		// figure out what we are targetting
		var target ='#page';
		if (event.value.match(/\/principal/)) {
			if ($('#about-subsection').length) {target = '#about-subsection';}
			$('#mugshots div').removeClass('selected');
			$('#mugshots div a[href=' + event.value + ']').parent().addClass('selected');
		}
		else if (event.value.match(/\/work[\/|\.]/)) {
			if ($('#work-subsection').length) {target = '#work-subsection';}
			$('#clients div').removeClass('selected');
			$('#clients div a[href=' + event.value + ']').parent().addClass('selected');
		}

		// fetch the inner page
		$(target).fadeOut("slow", function() {
			var script = (event.value == '/' ? '/index.php' : event.value).replace('.html', '.php');
			$(this).load('/pages' + script + '?subnav=' + hasSubnav + '&extra=' + hasExtra, function() {
				$(this).fadeIn("slow", function() {
					bindBehaviors(this);
					bindBehaviors($('#' + section + '-subnav'));
					
					if (event.value.match(/\/work[\/|\.]/)) {
						$('#work-client-left a').lightBox({fixedNavigation:true});
					}
				});
			});
		});
	});
 });	

$.fn.replace = function(o) { return this.after(o).remove(); }; 
