(function() {
	function getAnchor(url) {
		var arr = url.split(/#/);
		return (arr.length ? arr.pop() : "");
	}
	
	function select($elem) {
		$elem
			.children().removeClass("selected").end()
			.siblings().removeClass("selected").end()
			.addClass("selected");
	}
	
	function showAnchorContent(id) {
		var $section = $("#" + id);
		if (!$section.length) { return; }
		
		$("body").attr("class", $section.attr("id")); // only really used for the nav background
		
		if ($section.is(".section, .section-level2")) {
			// reset the section if clicking on it when already open
			if ($section.is(".section-level2") && $section.children("div.marquee:first").attr("id") == "currentMarquee") {
				$section.find("ul.nav li, div.section-level3").removeClass("selected");
			}
		
			$("#currentMarquee").removeAttr("id");
			$section.children("div.marquee:first").attr("id", "currentMarquee")
		}
		
		select($section);
	}
	
	// init
	$(function () {
		$(".nav li, .marquee .m li") // TODO refactor .m to be .nav (?)
			.addClass("clickable")
			.hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); })
			.click(function(e) {
				var url = $(this).find("a").attr("href");
				var hash = getAnchor(url);
				
				if (hash && $("#" + hash).length) {
					// hide icons when panel is opened
				 	if ($("#" + hash).is(".section-level3")) {
						$(this).siblings().andSelf().find(".icon img").addClass("hide");
					}
					// commenting this out leads to inaccurate location bar/bad accessible js on experience
					// leaving it in means dealing with repositioning to avoid scrolldown		
					//window.location.hash = "#" + hash;
					showAnchorContent(hash);
				} else {
					window.open(url); // credit help link
				}
				
				select($(this));
				
				// trigger custom analytics unless an actual link was pressed
				// TODO still sending double-beacons on tab clicks
				if ($(e.target).parents("a").length < 1) {
					$(this).trigger("navigation", [ { destination: url } ]);
				}
			})
			.bind("navigation", VISA.Analytics.event)
			.find("a") // suppress links in nav, handled by parent lis
				.click(function(e) { e.preventDefault(); });
		
		// close details panel when image is clicked (image contains 'close now' text) and restore icons
		$(".section-level3 img.panel").click(function() {
			$(".marquee .selected").removeClass("selected");
			$(".icon img.hide").removeClass("hide");
		});
		
		$("#logo").click(function(e) {
			showAnchorContent("landing");
			e.preventDefault();
		});
		
		// TODO deeplinking not working yet
//		if (location.hash) { showAnchorContent(getAnchor(location.hash)); }
	});
})();


$(document).ready(function() {
	// fix PNGs on IE6
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		DD_belatedPNG.fix("div.section-level3 .png-bg");
		DD_belatedPNG.fix("#giveBack div.section-level2 div.marquee div.w2");
		DD_belatedPNG.fix("div#giveBack div.giveBackReflect img");
		DD_belatedPNG.fix(".textMarquee .w1");
	}
	
	// convert lists-of-links to select boxes
	$("ul.select").each(function() {
		var $select = $("<select>")
		if (this.id) { $select.attr("id", this.id); }
		$(this)
			.prev(".select-tout").each(function() {
				$("<option>")
					.attr("value", "")
					.text($(this).text())
					.appendTo($select)
					.get(0).disabled = true; // will appear disabled if browser supports it
			}).remove();
		$(this)
			.find("a").each(function() {
				$("<option>")
					.attr("value", this.href)
					.text($(this).text())
					.appendTo($select);
			})
			.end()
			.replaceWith($select);
	});
	
	// open-new-window behavior for video & newsletter selects
	$("#chatzky_videos, #newsletter_archive").change(function() {
		var val = $(this).val();
		if (val) {
			window.open(val, "go_responsibly", "scrollbars=1,width=906,height=665");
		}
	});
	
	// timeout-based loader for large images
	var preload_backgrounds = {
/*
		"#giveBack div#americares div.w1": "img/feature/giveback_amer.png",
		"#giveBack div#feedingamerica div.w1": "img/feature/giveback_feed.png",
		"#giveBack div#handsOn div.w1": "img/feature/giveback_hands.png",
		"#giveBack div#oxfam div.w1": "img/feature/giveback_ox.png",
		"#giveBack div#teachforamerica div.w1": "img/feature/giveback_teach.png",
		"div#moneyMatters div.section-level2 div.section-level3 div.w1": "img/bg-level3-details.png"
*/
	};
	
	var preload_keys = [];
	$.each(preload_backgrounds, function(key) { preload_keys.push(key); });
	function timeout_preloader() {
		if (preload_keys.length < 1) return; // already finished
		var selector = preload_keys.pop();
		var url = preload_backgrounds[selector];
		(new Image()).src = url;
		$(selector).css("background-image", "url('" + url + "')");
		if ($.browser.msie && $.browser.version < 7) {
			DD_belatedPNG.fix(selector);
		}
		setTimeout(timeout_preloader, 100);
	}
	setTimeout(timeout_preloader, 100);

	// open some items in new tabs
	// TODO some of this is probably not necessary, since the analytics system should handle offsite links
	// TODO try limiting to PDF only
	$("a[href$='pdf'],a[href*='http://']:not([href*='.visa.'])").click(function(e) {
		if ($(this).hasClass("popup")) {
			window.open(this.href, "GoResponsibly", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=575,height=430");
		} else {
			window.open(this.href);
		}
		e.preventDefault();
	});
	
	// 'tab' switching behaviour for the children resources details panel
	$("a.tab").click(function(e) {
		var target = this.href.substr(this.href.lastIndexOf('#'));
		$(this).parents(".section-level3").find(".active").removeClass("active");
		$(target).add(this).addClass("active");
		
		$.each($(this).siblings(".tab").andSelf(), function() {
			if($(this).hasClass("active")) {
				$(this).find("img").eq(0).attr("src", $(this).find("img").eq(0).attr("src").replace("off", "on"));
			} else {
				$(this).find("img").eq(0).attr("src", $(this).find("img").eq(0).attr("src").replace("on", "off"));
			}
		});
		
		e.preventDefault();
	});

	// eliminate blur outlines.  bad for accessibility!  but Visa hates those outlines
	$("a").focus(function() { if(this.blur) { this.blur(); } });
	
	// apply 'section scoping' classes for analytics
	$(".section, .section-level2").addClass("analytics");
});

