$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:
// $(['img1.jpg','img2.jpg','img3.jpg']).preload();


function gotoNode(id) {
	var ajaxParms = {
		"type": "GET",
		"dataType": "json",
		"data": {"v":0},
		"success": receiveJson
	}
	if (id !== undefined) {
		ajaxParms.data.id = id;
		self.document.location.hash = "#"+id;
	}
	$.ajax(ajaxParms);
	return(false);
}


function receiveJson(json){
	for(var key in json) {
		if (json.hasOwnProperty(key)) {
			var vph = $("[vph][v="+key+"]");
			if (vph) {
				vph.attr('p',json['p']);
				vph.html(json[key]);
				// trigger receive on all children
				vph.trigger("receive");
				// fix PNG transparency, courtesy Microsoft
				// todo... bgsleight.fnLoadPngs();
			}
		}
	}
}

// header banner animation function
function slideSwitch() {
	// var $banner = $('#banner');
    var $active = $banner.children('.active');

    if ( $active.length == 0 ) {
	    $active = $banner.last();
	}

    var $next =  $active.next().length ? $active.next(): $banner.children().first();

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1750, function() {
            $active.removeClass('active last-active');
        });
}

// photos mouseover overlay show/hide effect
function initArticleSnippets (context) {
	mainBody = $("#body");

	$("#article-snippets .snippet, #body.home #article-photos .photo", context).mouseover(function() {
		var articleId = $(this).attr("article");
		var thisSnippet = $('#article-snippets > .snippet[article="'+articleId+'"]', mainBody);
		var thisPhotoOverlay = $('#article-photos > .photo[article="'+articleId+'"] .overlay', mainBody);
		thisSnippet.addClass("selected");
		thisPhotoOverlay.stop(true, false);
		thisPhotoOverlay.animate(
			{"opacity":0},
			50
		);
		return(false);
	});

	$("#article-snippets .snippet, #body.home #article-photos .photo", context).mouseout(function() {
		var articleId = $(this).attr("article");
		var thisSnippet = $('#article-snippets > .snippet[article="'+articleId+'"]', mainBody);
		var thisPhotoOverlay = $('#article-photos > .photo[article="'+articleId+'"] .overlay', mainBody);
		thisSnippet.removeClass("selected");
		thisPhotoOverlay.stop(true, false);
		thisPhotoOverlay.animate(
			{"opacity":1},
			200
		);
		return(false);
	});
}

function initNewsSnippets (context) {
	mainBody = $("#body");
	$(".preview", context).mouseenter(function() {
		var thisPreview = $(this);
		$(" > table", thisPreview).animate(
			{"opacity":1},
			50
		);
		$(".bg.over", thisPreview).animate(
			{"opacity":1},
			50
		);
		return(false);
	});

	$(".preview", context).mouseleave(function() {
		var thisPreview = $(this);
		$(" > table", thisPreview).animate(
			{"opacity":0.7},
			200
		);
		$(".bg.over", thisPreview).animate(
			{"opacity":0},
			200
		);
		return(false);
	});
}

function showOverlay(overlay) {
	var overlays = $("#overlays");
	var allOverlays = $(".overlay", overlays);
	var thisOverlay = $('.overlay[name="'+overlay+'"]', overlays);
	overlays.css("opacity",0);
	overlays.css("display","block");
	allOverlays.css("display","none");
	thisOverlay.css("display","block");
	overlays.animate(
		{
			opacity : "1",
		},
		{
			duration: 200,
			complete: function(){
				
			}
		}
	);
}

function showOverlays() {
	var overlays = $("#overlays");
	var isActive = overlays.attr("active");
	if (!isActive ) {
		overlays.css("opacity",0);
		overlays.css("display","block");
		overlays.animate(
			{
				opacity : "1",
			},
			{
				duration: 200,
				complete: function(){
					overlays.attr("active","1");
				}
			}
		);
	}
}

function hideOverlays() {
	var overlays = $("#overlays");
	overlays.animate(
		{
			opacity : "0",
		},
		{
			duration: 200,
			complete: function(){
				overlays.css("display","none");
				overlays.removeAttr("active");
			}
		}
	);	
}

// nav
function initNav() {
	var navSprite = $("#nav .sprite");
	var allNavDropdowns = $(".dropdown", navSprite);
	var currNav = "";
	$(">a", navSprite).mouseenter(function(){
		newCurrNav = $(this).attr("name");
		if (newCurrNav != currNav) {
			currNav = newCurrNav;
			currNavDropdown = $(".dropdown[name='"+currNav+"']", navSprite);
			allNavDropdowns.stop().animate(
				{
					"opacity":0
				},{
					"duration":0,
					"complete":function(){
						allNavDropdowns.css("display","none");
						currNavDropdown.css("opacity","0");
						currNavDropdown.css("display","block");
						currNavDropdown.stop().animate(
							{
								"opacity":1
							},{
								"duration":0
							}
						);
					}
				}
			);
		}
	});
	// leave navigation
	$(navSprite).mouseleave(function(){
		currNav = "";
		allNavDropdowns.stop().animate(
			{
				"opacity":0
			},{
				"duration":200,
				"complete":function(){
					allNavDropdowns.css("display","none");
				}
			}
		);
	});
}

// photo slide navigation
function initPhotoSlide(context) {
	var photoSlideInProgress = false;
	var photoSlideCurrPage = 1;
	var photoSlidePages = $(".photo-slide .photos img").length;

	$(".photo-slide .next", context).click(function(){
		if (!photoSlideInProgress && (photoSlideCurrPage<photoSlidePages)) {
			photoSlideInProgress = true;
			var photoSlide = $(this).closest(".photo-slide");
			var photoPane = $(".photos", photoSlide);
			photoPane.animate(
				{
					left : "-=376",
				},
				{
					duration: 400,
					complete: function(){
						photoSlideCurrPage ++;
						photoSlideInProgress = false;
					}
				}
			);
		}
	});
	$(".photo-slide .prev", context).click(function(){
		if (!photoSlideInProgress && (photoSlideCurrPage>1)) {
			photoSlideInProgress = true;
			var photoSlide = $(this).closest(".photo-slide");
			var photoPane = $(".photos", photoSlide);
			photoPane.animate(
				{
					left : "+=376",
				},
				{
					duration: 400,
					complete: function(){
						photoSlideCurrPage --;
						photoSlideInProgress = false;
					}
				}
			);
		}
	});
}

function initOverlay(ovr) {
	var form = $("form", ovr);
	$('[close-button]').click( function() {
		hideOverlays();
	});
	var targetNodeId = parseInt(form.attr("submit-to"));
	$('[submit-button]').click( function() {
		$.ajax({
			type: "POST",
			dataType: "json", // data coming back from the server
			url: "?id="+targetNodeId+"&v=0",
			data: form.serialize(),
			success: receiveJson
			/*
			success: function(result) {
				$(ovr).html(result.OVERLAY);
				initOverlay(ovr);
			}
			*/
		});
	});
	$('input:checkbox').screwDefaultButtons({
		checked: "url(img/checkbox-on.png)",
		unchecked: "url(img/checkbox-off.png)",
		width: 22,
		height: 22
	});
}

var onHashChange = function(event) {
	//get hash function
	var getHashValue = function() {
		var arr = window.location.hash.split("#");
		var hasValue = arr[1];
		//sets default
		if (typeof hasValue == "undefined") {
			return false;
		}

		var hashLen = hasValue.indexOf("?");
		if(hashLen>0){
			hasValue = hasValue.substring(0,hashLen);
		}
		return hasValue;
	}

	//last hash
	var lastHash = getHashValue();

	//checker
	(function watchHash() {
		var hash = getHashValue();

		if (hash !== lastHash) {
			event();
			lastHash = hash;
		}
		
		var t = setTimeout(watchHash, 100);

	})();
} 

// --------- start init -------------


$.elementReady("nav", function(){
	initNav();
});

// global variables
var slideTimer;	// holds a handle to the header slide timer

$(function(){
	if (window.location.hash.length > 1) {
		gotoNode(window.location.hash.substring(1));
	}

	onHashChange(function() {
		gotoNode(window.location.hash.substring(1));
	});

	// wire VPHs for receiving data
	$("[vph]").bind("receive", function(){
		var p = $(this).attr('p');
		var v = $(this).attr('v');
		if (!p) {
			p = "home";
		}
		switch(v) {
			case "MAIN":
			switch(p) {
				case "home":
					// start header banner animation
					$banner = $('#banner');
					clearInterval(slideTimer);
					slideTimer = setInterval( "slideSwitch()", 12800 );
					// init snippets animation
					initArticleSnippets(this);
				break;
				case "article":
				case "opportunity":
				case "event":
					initPhotoSlide(this);
				break;
				case "events":
				case "conferences":
				case "news":
				case "opportunities":
				case "current_events":
				case "future_events":
				case "announcement":
					initNewsSnippets(this);
				break;
				default:
					// write here some code to make sure there is content in here.. load home page if nothing loaded!
				break;
			}
			break;
			case "OVERLAY":
				initOverlay(this);
			break;
		}
	});
	// trigger receive on all VPHs on initial load
	$("[vph]").trigger("receive");
});

	
