/*
 * Special event for image load events
 * Needed because some browsers does not trigger the event on cached images.

 * MIT License
 * Paul Irish     | @paul_irish | www.paulirish.com
 * Andree Hansson | @peolanha   | www.andreehansson.se
 * 2010.
 *
 * Usage:
 * $(images).bind('load', function (e) {
 *   // Do stuff on load
 * });
 * 
 * Note that you can bind the 'error' event on data uri images, this will trigger when
 * data uri images isn't supported.
 * 
 * Tested in:
 * FF 3+
 * IE 6-8
 * Chromium 5-6
 * Opera 9-10
 */
(function ($) {
	$.event.special.load = {
		add: function (hollaback) {
			if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
				// Image is already complete, fire the hollaback (fixes browser issues were cached
				// images isn't triggering the load event)
				if ( this.complete || this.readyState === 4 ) {
					hollaback.handler.apply(this);
				}

				// Check if data URI images is supported, fire 'error' event if not
				else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
					$(this).trigger('error');
				}
				
				else {
					$(this).bind('load', hollaback.handler);
				}
			}
		}
	};
}(jQuery));

/*
 * Here is a jQuery plug-in function to preload images
 * From http://stackoverflow.com/questions/476679/preloading-images-with-jquery
 * Usage: $(['img1.png', 'img2.png']).preload();
*/

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

/* Common Mongoose script functions */

function selectCurrentMenuItem()
{
	// adorn current menu item, based on document URL
	var currDoc = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
	$('#menubar a[href=' + currDoc + ']').addClass('current');
}

function ieHelpers()
{
	// several hacks to get IE6+ to behave correctly
	
	// this fixes PNGs with alpha channels
	$(document).pngFix('images/empty.gif');
	
	// this fixes CSS menus that don't cascade correctly
	if (jQuery.browser.msie && jQuery.browser.version == '6.0')
		$('ul.topnav li').hover(
			function() { $(this).addClass('ie6hoverhelper'); },
			function() { $(this).removeClass('ie6hoverhelper'); }
		);

	//if (jQuery.browser.msie && jQuery.browser.version != '6.0')
	//	doPositionDropShadow();
}

function doPositionDropShadow()
{
	var mb = $('#mainbody'), img = $('#dropshadow');
	var mbpos = mb.offset();
	
	// dimensions and offset carefully chosen to lay out perfectly
	mbpos.top += 5;
	mbpos.left += 5;
	img.height(mb.height() + 5);
	img.width(mb.width());
	img.offset(mbpos);
}

function doAnimate()
{
	// do nothing here, but override in page
}

function doTickerInner()
{
	var revealer = $('.revealer');
	
	revealer.show();
	// clear pending animations, to help FF/Chrome with repeats
	revealer.clearQueue();
	// put revealer in the "hide" position
	revealer.css('margin-left', '0px');
	// move revealer to right to show hidden text
	revealer.animate({ 'margin-left': '970px' }, 10000, 'linear', function() {
		// hide revealer so "cursor" is not displayed 
		$('.revealer').hide();
		// queue up another reveal
		setTimeout('doTickerInner()', 5000);
	});
}

function doTicker()
{
	// common ticker revealer for most pages
	// make sure to clip revealer as it is moved
	$('#blockfooter').css('overflow', 'hidden');
	// start animation
	doTickerInner();
}

function doNonFlashCommonFade()
{
	// use well-known fadeIn/Out classes to do transitions
	$('.fadeOut').delay(1500).fadeOut(1500, function(){
		$('.fadeIn').fadeIn(1500, null);	
	});
}

function doCommonFade()
{
	if (false /* jQuery.browser.webkit */) {
		// skip Flash detection and go right to jQuery-based animation
		$('#maingraphic').css('visibility', 'visible');
		doNonFlashCommonFade();
	}
	else {
		// infer swf file name from current document
		var currDoc = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
		currSwf = 'swf/' + currDoc.replace(/html/, 'swf');
	
		// use Flash where available, and revert to jQuery animation if it fails
		swfobject.embedSWF(currSwf, 'maingraphic', '974px', '198px', '9.0.0', false, {}, { loop: "false", wmode: "transparent" }, {}, function(e) {
				$('#maingraphic').css('visibility', 'visible');
				if (!e.success)
					doNonFlashCommonFade();
			});
	}
}

function imgLoaded(ev)
{
	imgRemaining--;
	if (imgRemaining <= 0)
		doAnimate();
}

var imgRemaining = 0;

// call common "onPageLoaded" function on each page, once DOM is complete
$(document).ready(function(){
	// some common stuff first...
	ieHelpers();
	selectCurrentMenuItem();
	
	if ($.browser.msie)
		$('html').addClass('msie');
	else if ($.browser.webkit)
		$('html').addClass('webkit');
	else if ($.browser.mozilla)
		$('html').addClass('mozilla');
	else if ($.browser.opera)
		$('html').addClass('opera');
	
	// the default jQuery frame rate is pretty quick...slow it down to ease CPU burden
	jQuery.fx.interval = 33;	// msec per frame
	
	// now call into the page
	onPageLoaded();
	
	// lastly hook into image loading and perform animations, to ensure we
	// only start animations after all images are loaded
	if (!$.browser.msie) {
		var img = $('img');
		imgRemaining = img.length;
		if (imgRemaining > 0)
			img.bind('load', imgLoaded);
	}
	else
		doAnimate();
});


