/*globals $, document, maui_runtime, home_slide, Cufon */

var popup_manager = (function () {

	var popupStatus = 0,
		elements = {
			'bg'	: '#backgroundPopup',
			'popup'	: '#popupContact',
			'close'	: '#popupContactClose'
		};

	function loadPopup() {
		if (popupStatus === 0) {
			$(elements.bg).css({
				opacity: '0.7'
			}).fadeIn("slow");
			$(elements.popup).fadeIn("slow");
			popupStatus = 1;
		}
	}

	function disablePopup() {
		if (popupStatus === 1) {
			$(elements.bg).fadeOut("slow");
			$(elements.popup).fadeOut("slow");
			popupStatus = 0;
		}
	}

	function centerPopup() {
		var windowWidth = document.documentElement.clientWidth,
			windowHeight = document.documentElement.clientHeight,
			popupHeight = $(elements.popup).height(),
			popupWidth = $(elements.popup).width();
		$(elements.popup).css({
			position: 'absolute',
			top		: windowHeight / 2 - popupHeight / 2,
			left	: windowWidth / 2 - popupWidth / 2
		});
		//only need force for IE6
		$(elements.bg).css({
			height	: windowHeight
		});
	}
	
	function addBehaviour() {
		$(elements.close).click(function () {
			disablePopup();
		});
		$(elements.bg).click(function () {
			disablePopup();
		});
		$(document).keypress(function (e) {
			if (e.keyCode === 27 && popupStatus === 1) {
				disablePopup();
			}
		});
	}

	return {
		init : function () {
			centerPopup();
			loadPopup();
			addBehaviour();
		}
	};

}());

$(document).ready(function () {
	
	$("a[rel='external']").click(function () { 
		this.target = "_blank"; 
	});	

	$("#slideshow").each(function () {
		var that = $(this),
			images = that.children("img"),
			total_images = window.parseInt(images.size(), 10),
			loaded_images = 0;
		images.css({
			display	: 'none'
		});
		function preload() {
			var imgbox = [];
			function checkloaded(obj) {
				var img = new Image();
				img.onload = function () {
					loaded_images = loaded_images + 1;
					if (loaded_images === total_images) {
						that.css({
							display : 'block'
						}).cycle({
							fx: 'fade',	
							delay: 1000,
							height: 390
						});
					}
				};
				img.src = obj.src;
			}
			images.each(function () {
				imgbox.push(this);
				checkloaded(this);
			});
		}
		preload();
	});

	$('#cross-splash').each(function () {
		$(this).flash({ 
			src		: maui_runtime.theme_url + '/flash/main.swf',
			width	: 920,
			height	: 550 
		}, { version: 8 });
	});
	
	$('#credits').each(function () {
		$(this).click(function () {
			popup_manager.init();
		});
	});

	if (typeof (home_slide) === 'object') {
		$('.home-slide-container').each(function () {
			var pos = $(this).attr('id').replace('home-', '');
			$('#home-' + pos).crossSlide(
				{
					fade: 1
				}, 
				home_slide[pos]
			);
		});
	}

	Cufon.replace('.main-cats', {
		forceHitArea: true 
	});
	Cufon.replace('.main-title');
	Cufon.replace('.title');
	Cufon.now();

});
