//BGFade
$(document).ready(function() {

	//Background images
	var background_images = [
		'./ext/bgfade/images/image1_wide.jpg', 
		'./ext/bgfade/images/image2_wide.jpg', 
		'./ext/bgfade/images/image3_wide.jpg', 
		'./ext/bgfade/images/image4_wide.jpg', 
		'./ext/bgfade/images/image5_wide.jpg', 
		'./ext/bgfade/images/image6_wide.jpg'
	];
	var background_current = 0;
	var background_transition = 750; //Fade duration
	var background_allow = false;
	var background_overlay = 'bg';
	var background_overlay_menu = 'bg_menu';
	var background_overlay_menu_opts = 'bg_menu_opts';
	var background_auto = true;
	var background_auto_time = 5000;

	//Create overlay
	var link = document.createElement('div');
	link.setAttribute('id', background_overlay);
	$('body').append(link);
	$('#'+background_overlay).css({'position': 'absolute', 'top': '0', 'left': '0', 'width': '100%', 'height': '100%', 'z-index': '-1', 'background-image': 'none', 'background-repeat': 'no-repeat', 'opacity': '0'});

	//Preload backgrounds and do now allow switching until loaded
	$.preLoadImages(
		background_images, function(){
			background_allow = true;
			background_nav();
		}
	);

	//On window resize ensure overlay will cover whole area
	$(window).resize(function() {
		$('#'+background_overlay).css('width', $(window).width());
		$('#'+background_overlay).css('height', $(window).height());
	});
	$(window).resize();

	function background_switch() {
		if (background_allow) {
			background_allow = false;

			//Set overlay to body's background and make visible
			$('#'+background_overlay).css('background-image', $('body').css('background-image'));
			$('#'+background_overlay).fadeTo(0, 1);

			//Ensure the background is valid
			if (background_current >= background_images.length) {
				background_current = 0;
			}

			background_opt(); //Set menu opt

			//Set body's background to new image and fade out the overlay
			$('body').css('background-image', "url("+background_images[background_current]+")");
			$('#'+background_overlay).fadeTo(background_transition, 0, function(){
				//Afterwards stuff
				background_allow = true;
			});

			background_current++; //Select next image to fade to
			background_auto_scroll(); //Auto scroll (if enabled)
		}
	}

	//Set the relevant selected menu option
	function background_opt() {
		$('#'+background_overlay_menu+' li').removeClass(background_overlay_menu_opts+'_on');
		$('#'+background_overlay_menu+background_current).addClass(background_overlay_menu_opts+'_on');
	}

	//Auto scroll
	function background_auto_scroll() {
		if (background_auto) {
			if (background_current >= background_images.length) {
				var next_auto = 0;
			} else {
				var next_auto = background_current;
			}
			setTimeout("$('#"+background_overlay_menu+next_auto+"').dblclick();", background_auto_time);
		}
	}

	//Create the background navigator
	function background_nav() {
		var link = document.createElement('ul');
		link.setAttribute('id', background_overlay_menu);
		$('body').append(link);

		$(background_images).each(function(i){
			$('#'+background_overlay_menu).append('<li id="'+background_overlay_menu+i+'" rel="'+i+'" class="'+background_overlay_menu_opts+'">&nbsp;</li>');
		});
		
		//Manual interaction
		$('.'+background_overlay_menu_opts).bind("mouseover click", function(){
			background_auto = false;
			background_current = $(this).attr('rel');
			background_switch();
		});

		//The initial auto-scrolling
		$('.'+background_overlay_menu_opts).bind("dblclick", function(){
			if (background_auto) {
				background_current = $(this).attr('rel');
				background_switch();
			}
		});

		background_switch();
	}

});

/* jQuery.preloader - v0.95 - K Reeve aka BinaryKitten
*
* v0.95
* 	# Note - keeping below v1 as really not sure that I consider it public usable.
* 	# But it saying that it does the job it was intended to do.
* 	Added Completion of loading callback.
* 	Main Reworking With Thanks to Remy Sharp of jQuery for Designers
*
*
* v0.9
* 	Fixed .toString being .toSteing
*
* v0.8
*		Fixed sheet.href being null error (was causing issues in FF3RC1)
*
* v0.7
*		Remade the preLoadImages from jQuery to DOM
*
* v0.6
* 		Fixed IE6 Compatability!
*		Moved from jQuery to DOM
*
* v0.5
* 		Shifted the additionalimages loader in the preLoadAllImages so it wasn't called multiple times
* 		Created secondary .preLoadImages to handle additionalimages and so it can be called on itself
*/

(function ($) {
	$.preLoadImages = function(imageList,callback) {
		var pic = [], i, total, loaded = 0;
		if (typeof imageList != 'undefined') {
			if ($.isArray(imageList)) {
				total = imageList.length; // used later
					for (i=0; i < total; i++) {
						pic[i] = new Image();
						pic[i].onload = function() {
							loaded++; // should never hit a race condition due to JS's non-threaded nature
							if (loaded == total) {
								if ($.isFunction(callback)) {
									callback();
								}
							}
						};
						pic[i].src = imageList[i];
					}
			}
			else {
				pic[0] = new Image();
				pic[0].onload = function() {
					if ($.isFunction(callback)) {
						callback();
					}
				}
				pic[0].src = imageList;
			}
		}
		pic = undefined;
	};

	$.preLoadCSSImages = function(callback) {
		var pic = [], i, imageList = [], loaded = 0, total, regex = new RegExp("url\((.*)\)",'i'),spl;
		var cssSheets = document.styleSheets, path,myRules,Rule,match,txt,img,sheetIdx,ruleIdx;
		for (sheetIdx=0;sheetIdx < cssSheets.length;sheetIdx++){
			var sheet = cssSheets[sheetIdx];
			if (typeof sheet.href == 'string' && sheet.href.length > 0) {
				spl = sheet.href.split('/');spl.pop();path = spl.join('/')+'/';
			}
			else {
				path = './';
			}
			myRules = sheet.cssRules ? sheet.cssRules : sheet.rules;
			for (ruleIdx=0;ruleIdx < myRules.length;ruleIdx++) {
				Rule = myRules[ruleIdx];
				txt = Rule.cssText ? Rule.cssText : Rule.style.cssText;
				match = regex.exec(txt);
				if (match != null) {
					img = match[1].substring(1,match[1].indexOf(')',1));
					if (img.substring(0,4) == 'http') {
						imageList[imageList.length] = img;
					}
					else if ( match[1].substring(1,2) == '/') {
						var p2 = path.split('/');p2.pop();p2.pop();p2x = p2.join("/");
						imageList[imageList.length] = p2x+img;
					}
					else {
						imageList[imageList.length] = path+img;
					}
				}
			};
		};

		total = imageList.length; // used later
		for (i=0; i < total; i++) {
			pic[i] = new Image();
			pic[i].onload = function() {
				loaded++; // should never hit a race condition due to JS's non-threaded nature
				if (loaded == total) {
					if ($.isFunction(callback)) {
						callback();
					}
				}
			};
			pic[i].src = imageList[i];
		}

	};

	$.preLoadAllImages = function(imageList,callback) {
		if (typeof imageList != 'undefined') {
			if ($.isFunction(imageList)) {
				callback = imageList;
			}
			else if (!$.isArray(imageList)) {
				imageList = [imageList];
			}
		}
		$.preLoadCSSImages(function(){
			if (imageList.length > 0) {
				$.preLoadImages(imageList,function(){
					callback();
				});
			}
			else {
				callback();
			}
		});
	}
})(jQuery);
