function isEarlyIE () {
	var browser = BrowserDetect.browser.toLowerCase();
	var version = BrowserDetect.version;
	
	if (browser == "explorer") {
		if (version < 7) return true;
	}
	
	return false;
}

function getValueFromQuery (variableName) {
	var query = document.location.search;
	var arr = query.substring(1, query.length).split("&");
	var i = arr.length;
	
	while (i--) {
		var pairArr = arr[i].split("=");

		if (pairArr[0] == variableName) {
			return pairArr[1];
			break;
		}
	}

	return false;
}

function fixArrowLinks () {
	var os = BrowserDetect.OS.toLowerCase();
	var browser = BrowserDetect.browser.toLowerCase();
	var mySrc = (isEarlyIE()) ? "/homepage/images/ie6/arrow.gif" : "/homepage/images/arrow.png";
	
	$(".arrow_link").each(function () {
		if (browser == "explorer") {
			//Remove class
			$(this).removeClass("arrow_link");
			
			//Inject img
			var img = $("<img />");
			
			img.attr({
				src: mySrc,
				width: 4,
				height: 7,
				border: 0,
				alt: ""
			});
			
			img.css("padding-left", "3px");
			$(this).after(img);
			
			return;
		}
		
		if (os == "mac" && browser == "firefox") {
			$(this).css("background-position", "right 5px");
		}
	});
}

function isFlashEnabled () {
	if (getValueFromQuery("noflash") == "1") return false;
	
	//wmode and ExternalInterface are browser dependant
	var os = BrowserDetect.OS.toLowerCase();
	var browser = BrowserDetect.browser.toLowerCase();
	var version = BrowserDetect.version;
	var flash = flashPlayer["major"];
	
	if (flash < 7) return false;
	if (isNaN(version)) return false;
	
	switch (browser) {
		case "explorer":
			if (version > 5) return true;
			break;
		case "netscape":
			if (version >= 8) return true;
			break;
		case "mozilla":
			if (version > 1.7) return true;
			break;
		case "safari":
			if (version >= 1.3) return true;
			break;
		case "firefox":
			if (os == "linux") {
				if (version >= 3) {
					if (flash >= 10) return true;
				}
			} else {
				if (version >= 1.3) return true;
			}
			break;
		case "opera":
			if (version >= 8) return true;
			break;
		case "chrome":
			return true;
			break;
	}
	
	return false;
}

function insertBottomCaps () {
	//Create another div to inject bottom caps into
	var caps = $("<div />");
	caps.attr({ id: "caps" });
	
	$(".module").each(function () {
		var div = $("<div />");
		
		if ($(this).hasClass("module-last")) {
			div.addClass("module-last");
		}

		div.addClass("module-bottoms");
		caps.append(div);
	});
	
	//Place the caps after the modules container
	$("#modules").after(caps);
}

function animateInterface (show, hide, button) {
	var w = "-" + hide.parent().css("width");
	
	if (hide.hasClass("embed-interface")) {
		//Displaying main content
		hide.hide("slide", { direction: "right" }, 200, function () {
			show.css("margin-left", w);
			
			show.animate({
				marginLeft: "0px"
			}, 300, function () {
				resetShareClick(true, button);
			});
		});
	} else {
		//Displaying share content
		hide.animate({
			marginLeft: w
		}, 200, null, function () {
			show.show("slide", { direction: "right" }, null, function () {
				resetShareClick(false, button);
			});
		});
	}
}

function toggleEmbedInterface (back, button) {
	button.unbind("click");
	
	var hideSelector = (back) ? ".embed-interface" : ".module-content";
	var showSelector = (back) ? ".module-content" : ".embed-interface";
	
	var hide = $(hideSelector, button.parent());
	var show = $(showSelector, button.parent());
	
	var id = button.parent().attr("id");
	var code = (back) ? id + "/share-back" : id + "/share";
	track(code);
	
	//Reset button rollovers
	initShareRollOver(!back, button);
	
	if (isEarlyIE()) {
		//IE 6 positioning screws up transitions
		hide.hide();
		show.show();
		
		//A brutal hack to fix problem of elements not positioning correctly until rolled over.
		//Adding position: relative to parent element accomplishes the same, but breaks links and form elements.
		var myInt = setTimeout(function () {
			$(".inner-content li", show).css("position", "relative");
			$(".inner-content li", show).css("top", "0");
			$(".inner-content li", show).css("left", "0");
		}, 5);
		
		resetShareClick(back, button);
	} else {
		animateInterface(show, hide, button);
	}
}

function resetShareClick (back, button) {
	button.click(function () {
		toggleEmbedInterface(!back, button);
	});
}

function initShareRollOver (back, button) {
	var myTitle = (back) ? "Back" : "Share This";
	button.attr({ title: myTitle });
	
	button.unbind("mouseover");
	button.unbind("mouseout");
	
	button.mouseover(function () {
		var pos = (back) ? "-81px 0" : "-27px 0";
		$(this).css("background-position", pos);
	});
	button.mouseout(function () {
		var pos = (back) ? "-54px 0" : "0 0";
		$(this).css("background-position", pos);
	});
	button.trigger("mouseout");
}

function initEmbed () {
	$(".embed-button").each(function () {
		initShareRollOver(false, $(this));
		resetShareClick(true, $(this));
	});
	
	$(".embed-interface .code").click(function () {
		var field = $("input", $(this));
		
		var module = $(this).parent().parent().parent().parent();
		var tracking_code = module.attr("id") + "/embed-code-copied";
		
		if (module.attr("guid") != undefined) {
			var guid = module.attr("guid");
			var arr = guid.split("/");
			var filename = arr.pop();
			
			tracking_code += "/" + filename;
		}
		
		track(tracking_code);
		
		field.focus();
		field.select();
	});
	
	//iGoogle tracking
	$(".igoogle").click(function () {
		var module = $(this).parent().parent().parent().parent();
		track(module.attr("id") + "/igoogle");
	});
	
	//RSS tracking
	$(".rss").click(function () {
		var module = $(this).parent();
		track(module.attr("id") + "/rss-subscribe");
	});
	
	//Flickr
	$("#flickr .facebook").click(function () {
		track("flickr/facebook");
		fbs_click($(this).attr("href"));
		return false;
	});
}

function initCarousel () {
	//Set up scrolling
	$(".carousel-content").each(function () {
		//Inject arrows
		var id = $(this).attr("id");
		var parent_id = $(this).parent().parent().attr("id");
		
		var prev = $("<button>Previous</button>");
		prev.attr({
			title: "Previous",
			id: "prev_" + id
		});
		prev.addClass("prev");
		$(this).prepend(prev);
		
		var next = $("<button>Next</button>");
		next.attr({
			title: "Next",
			id: "next_" + id
		});
		next.addClass("next");
		$(this).append(next);
		
		//Tracking
		prev.click(function () {
			track("carousel/previous/" + parent_id);
		});
		next.click(function () {
			track("carousel/next/" + parent_id);
		});
		
		//Unhide
		$(this).css("display", "block");
		
		//Scroll
		$(".carousel", this).jCarouselLite({
			vertical: true,
			visible: 1,
			speed: 350,
			circular: false,
			mouseWheel: true,
			btnNext: "#next_" + id,
			btnPrev: "#prev_" + id,
			afterEnd: enableCarouselButton
		});
	});
	
	//Center vertically
	$(".carousel li").each(function () {
		//Replace content with a nested copy
		var div = $("<div />");
		div.html($(this).html());

		$(this).empty();
		$(this).append(div);
		
		//Add top padding
		var height = div.height();
		var total = $(this).height();
		
		//Truncate if space exceeded
		if (height > total) {
			div.expander({
			  slicePoint: 220, 
			  userCollapseText: false,
			  expandText: ''
			});

			height = div.height();
		}

		var padding = Math.floor((total - height) / 2) - 2;
		div.css("margin-top", padding + "px");
		
		if ($(this).is(":first-child")) {
			enableCarouselButton($(this));
		}
	});
}

function showIframe (id) {
	if (isEarlyIE()) return true;
	
	setTimeout(function () {
		var ref = "#" + id;
		$(ref).css("position", "relative");
		$(ref).css("top", "0");
	}, 500);
	
	return true;
} 

function enableCarouselButton (a) {
	var prev = $(("button.prev"), a.parent().parent().parent());
	var next = $(("button.next"), a.parent().parent().parent());
	
	if (a.is(":first-child")) {
		//First item; disable previous, enable next
		prev.removeClass("prev_hover");
		next.addClass("next_hover");
	} else if (a.is(":last-child")) {
		//Last item; enable previous, disable next
		prev.addClass("prev_hover");
		next.removeClass("next_hover");
	} else {
		//Neither first nor last; enable both
		prev.addClass("prev_hover");
		next.addClass("next_hover");
	}
}

function preload () {
	var folder = "/homepage/images/";
	
	if (isEarlyIE()) {
    	var arr = [
			"ie6/embed-button-facebook.png",
			"ie6/embed-button-igoogle.png",
			"ie6/embed-button-yahoo.png",
			"ie6/embed-button-facebook-hover.png",
			"ie6/embed-button-igoogle-hover.png",
			"ie6/embed-button-yahoo-hover.png",
			"ie6/arrow-top.gif",
			"ie6/arrow-top-hover.gif",
			"ie6/arrow-bottom.gif",
			"ie6/arrow-bottom-hover.gif"
		];
	} else {
		var arr = [
			"embed-button-facebook.png",
			"embed-button-igoogle.png",
			"embed-button-yahoo.png",
			"arrow-top.png",
			"arrow-top-hover.png",
			"arrow-bottom.png",
			"arrow-bottom-hover.png",
			"titles/add.png" 
		];
	}
	
	//Common
	arr.push("embed-bg.png");
	arr.push("trans-white-5.png");
	arr.push("input-bg.png");         
	
	//Create the container
	var container = $("<div />");
	container.hide();
	$("body").append(container);
	
	//Insert each image
	var i = arr.length;
	
	while (i--) {
		var img = $("<img />");
		var path = folder + arr[i];
		
		img.attr({ src: path });
		container.append(img);
	}
}

function flashText () {
	//Only IE 6 gets the Flash replacement
	if (!isEarlyIE()) return;
	
	var css = [
		"* { color: #ffffff; }",
		"a { color: #ffffff; text-decoration: none; }",
		"a:hover { text-decoration: underline; }"
	];    
	
	var i = 0;
	
	$(".module h2").each(function () {
		$("*", $(this)).removeAttr("id");
		
		var name = "flash_replace_" + i;		
		var so = new SWFObject("homepage/whitney_semibold.swf", name, 170, 19, "8");
		
		//target attribute seems to screw things up
		$("a", $(this)).removeAttr("target");
		var txt = escape($(this).html());
		
		so.addParam("menu", "false");
		so.addParam("wmode", "transparent");
		so.addVariable("txt", txt);
		so.addVariable("css", css.join(" "));
		so.write(this);
		
		$(this).css("display", "block");
		
		i++;
	});
}

function fbs_click (url) {
	var props = "toolbar=0,status=0,width=626,height=436";
	window.open(url, "sharer", props);
}

function setShareId (str, type) {
	//Add an id to the share buttons
	switch (type) {
		case "sia":
			//Add an attribute for easy tracking access
			$("#sia").attr({ guid: str });
			
			//Reset Facebook link
			var link = $("#sia .facebook");
			var href = link.attr("href");
			var new_href = href + escape("&guid=" + str);
			
			link.unbind("click");
			
			link.click(function () {
				var arr = str.split("/");
				var filename = arr.pop();
				track("sia/facebook/" + filename);
				
				fbs_click(new_href);
				return false;
			});
			
			//Reset embed code
			var swf = "http://www.calacademy.org/module/sia/sia_embed.swf?context=embed&autoPlay=0&windowTarget=_top&guid=" + str;
			var embed = getFlashEmbedString(swf, 300, 320);                     
			var input = $("#sia .code input"); 
			input.attr({ value: embed });
			
			break;
	}
	
	return false;
}

function getFlashEmbedString (swf, w, h) {
	return "<object width=\"" + w + "\" height=\"" + h + "\"><param name=\"movie\" value=\"" + swf + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"" + swf + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" + w + "\" height=\"" + h + "\"></embed></object>";
}           

function track (str) {
	var myCode = tracking_prefix + str;
	
	$.post("/homepage/php/Track.php", {
		dotrack: "1",
		code: myCode
	});
	
	pageTracker._trackEvent(myCode, location.href);
	
	return true;
} 

function initFlashHover () {
	//Add a cursor hover event handler; called from Flash via ExternalInterface
	var flash = "homepage_header";
	var browser = BrowserDetect.browser.toLowerCase();
	var swf = (browser == "explorer") ? window[flash] : document[flash];
	
	//Kill thumbs when hovering outside of Flash
	$("#flash_homepage_header").hover(null, function () {
		swf.mouseWithin("0");
	});
	
	var os = BrowserDetect.OS.toLowerCase();
	if (os == "windows") return true;
	
	//Kill and disable thumbs when over nav; reenable when leaving
	$("#dropdown_nav").hover(
		function () {
			swf.enableThumbs("0");
		},
		function () {
			swf.enableThumbs("1");
		}
	);
	
	return true;
}

function isBuggyLocalConnection () {
	//http://kb2.adobe.com/cps/497/cpsid_49735.html
	var os = BrowserDetect.OS.toLowerCase();
	if (os != "mac") return false;
	
	if (flashPlayer["major"] >= 10) {
		if (flashPlayer["rev"] >= 32 || flashPlayer["minor"] > 0) {
			return true;
		}
	}
	
	return false;
}

function positionExtendedHours () {
    if ($(".extended_hours").length == 0) return;

	var l = $(".logo").offset().left + 1;
	$(".extended_hours").css("left", l);
	$(".extended_hours").css("display", "block");
}

var flashPlayer = deconcept.SWFObjectUtil.getPlayerVersion();
var flashHoverResult;

if (flashPlayer["major"] >= 8) {
	if (isEarlyIE()) {
		//For Flash text replacement
		document.write("<style> .module h2 { display: none; } </style>");
	}
}

//Hide carousel content until init
document.write("<style> .carousel-content { display: none; } </style>");

$(document).ready(function () {
	if (flashPlayer["major"] >= 8) flashText();
	preload();
	fixArrowLinks();
	insertBottomCaps();
	initEmbed();
	initCarousel();
	centerMenu();
	
	$(window).resize(positionExtendedHours);
	positionExtendedHours();
});
