// we don't want to pollute the window object with our stuff
(function($)
{
	// configuration
	var config = {
		animDuration : 250,
		metapanelOpacity : 0.5,
		cookiePath : '/',
		preloadImages : [
			twain.templateUrl+'images/extlink-12.png',
			twain.templateUrl+'images/submenu-top.png',
			twain.templateUrl+'images/submenu-body.png',
			twain.templateUrl+'images/submenu-bottom.png'
		]
	};

	// onload stuff
	$(function()
	{
		// some fancy CSS (which doesn't validate, nasty I know :P )
		$('<link rel="stylesheet" type="text/css" href="'+twain.templateUrl+'progressive-enhancements.css" />').appendTo('head');
		
		// remove class="nojs" from all nodes that have it
		$('.nojs').removeClass('nojs');
		
		// initiate the submenus
		if(!$.browser.opera && !$.browser.msie)
			subMenu();
		// fallback to CSS for Opera and MSIE, 'cause they don't do the JS method very well
		else
			$('#menu').addClass('nojs');
		
		// add rel="external" to external links
		linkMagic();

		// make clickable link from e-mail address
		mailLink();

		// setup custom font size
		fontSize.init();

		// alternating background color for table rows
		$('table tr:odd').css({backgroundColor:'#f8f4f4'});

		// tooltips
		$('.tooltip').tooltip({showBody:' | ',delay:0,fade:config.animDuration});

		// make the header image link home if not already there
		homeLink();

		// load Shadowbox
		loadShadowbox();

		// hide and show the metapanel
		metapanel.init();

		// fix some IE7 issues and tell IE6 users things won't work
		ie.fix7();ie.warn6();

		// preload some images
		imagePreloader.load(config.preloadImages);
	});

	// submenu stuff
	var subMenu = function()
	{
		$('#menu li').hoverIntent({
			timeout : 250,
			over : function()
			{
				$(this).find('ul').fadeIn(config.animDuration);
			},
			out : function()
			{
				$(this).find('ul').fadeOut(config.animDuration);
			}
		});
	};

	// link magic stuff
	var linkMagic = function()
	{
		$('#content a').each(function(i)
		{
			// add rel="external" to all external links that don't already have it and do not contain images
			var rel = this.rel, href = this.href, cont = this.innerHTML;
			if(rel.indexOf('external') < 0 && href.indexOf(window.location.hostname) < 0 && cont.indexOf('<img') < 0)
				this.rel = rel == '' ? 'external' : rel+' external';
			
			// handle footnote/reference links
			else if(href.indexOf(window.location.hostname) > 0 && href.indexOf('#') > 0 && rel == "footnote")
			{
				$(this).click(function(ev)
				{
					refId = this.href.substr(href.indexOf('#'));
					$('.ref').css({backgroundColor:'transparent'});
					$(refId).css({backgroundColor:'#deb'});
				});
				
			}
		});
	};

	// mail link stuff
	var mailLink = function()
	{
		$('.emailaddress').each(function()
		{
			$(this).removeClass('emailaddress').find('.hidden').remove();
			var mailAddress = $(this).text();

			$(this).empty().attr({title:''}).append('<a href="mailto:'+mailAddress+'">'+mailAddress+'</a>');
		});
		$('.imaddress').each(function()
		{
			$(this).attr('title', null).find('.hidden').remove();
		});
	};

	// home link stuff
	var homeLink = function()
	{
		if(window.location.href != twain.homeUrl)
		{
			$('#header').click(function(){
				window.location.href = twain.homeUrl;
			}).css({cursor:'pointer'}).attr({title:'Return to the home page'}).tooltip({delay:0,fade:config.animDuration});
		}
	};

	// font size stuff
	var fontSize = {
		fontSizeClass : 'normal',
		cookieName : 'twainFontSize',
		increase : 'larger text',
		decrease : 'smaller text',

		init : function()
		{
			fontSize.loadSetting();
			var text = fontSize.fontSizeClass == 'normal' ? fontSize.increase : fontSize.decrease;

			$('#menu>ul:first').append(
				'<li id="fontsize">'+text+'</li>'
			).find('#fontsize').click(fontSize.toggle);
			$('body').addClass(fontSize.fontSizeClass);
			
			if($.browser.mozilla && parseFloat($.browser.version) < 1.9)
				$('#fontsize').css({marginTop:'-19px'});
			if($.browser.msie && parseInt($.browser.version) < 8)
				$('#fontsize').css({marginTop:'-26px'});
		},

		toggle : function()
		{
			var bodyObj = $('body');

			if(bodyObj.hasClass('large'))
			{
				bodyObj.removeClass('large').addClass('normal');
				fontSize.fontSizeClass = 'normal';
			}
			else
			{
				bodyObj.removeClass('normal').addClass('large');
				fontSize.fontSizeClass = 'large';
			}
			$('#fontsize').text(fontSize.fontSizeClass == 'normal' ? fontSize.increase : fontSize.decrease);
			fontSize.saveSetting();
		},

		loadSetting : function()
		{
			fontSize.fontSizeClass = $.cookie(fontSize.cookieName) == 'large' ? 'large' : 'normal';
		},

		saveSetting : function()
		{
			$.cookie(fontSize.cookieName, fontSize.fontSizeClass, {expires:365,path:config.cookiePath});
		}
	};

	// Shadowbox stuff
	var loadShadowbox = function()
	{
		Shadowbox.init({
			animSequence : 'sync',
			resizeDuration : 0.25,
			fadeDuration : 0.1,
			flvPlayer : twain.templateUrl+'shadowbox/flvplayer.swf',
			handleUnsupported : 'remove'
		});
	};

	// metapanel stuff
	var metapanel = {
		init : function()
		{
			$('#sitemeta').show(0).hoverIntent({
				timeout : 500,
				over : metapanel.show,
				out : metapanel.hide
			}).css({opacity:config.metapanelOpacity});
		},

		show : function()
		{
			$('#metapanel').slideDown(config.animDuration).parent().animate({
				opacity : 1
			}, config.animDuration);
		},

		hide : function()
		{
			$('#metapanel').slideUp(config.animDuration).parent().animate({
				opacity : config.metapanelOpacity
			}, config.animDuration);
		}
	};

	// image preload stuff
	var imagePreloader = {
		loadedImages : new Array(),

		load : function(preloadImages)
		{
			for(i = 0, len = preloadImages.length; i < len; i++)
			{
				this.loadedImages[i] = new Image();
				this.loadedImages[i].src = preloadImages[i];
			}
		}
	};

	// IE7 fix and IE6 warning stuff
	var ie = {
		fix7 : function()
		{
			if($.browser.msie && parseInt($.browser.version) < 8)
			{
				$('<link rel="stylesheet" type="text/css" href="'+twain.templateUrl+'ie-fixes/ie.css" />')
					.appendTo('head');
				$('<script type="text/javascript" src="'+twain.templateUrl+'ie-fixes/IE8.js"></script>')
					.appendTo('head');
			}
		},
		warn6 : function()
		{
			if($.browser.msie && parseInt($.browser.version) < 7 && !$.cookie('IE6warningShown'))
			{
				$('body').append(
					'<div id="ie6warning" title="Click to hide">'
					+'This web site does not work correctly with Internet Explorer 6 or earlier. '
					+'You <i>really</i> <a href="http://browsehappy.com/" title="Browse Happy">ought to upgrade</a>!'
					+'</div>'
				).find('#ie6warning').click(function()
				{
					$(this).slideUp(config.animDuration, function()
					{
						$.cookie('IE6warningShown', 'true', {path:config.cookiePath});
						$(this).remove();
					});
				});
			}
		}
	};
})(jQuery);
