// Reserve the "$" variable here for jQuery, in case someone later adds Prototype, Mootools, or some other JS library that uses the "$".
(function($) {
	// "Shortcuts" for JavaScript primitives, which helps scope chain traversal.
	// See presentation at <http://paulirish.com/2009/perf/>
	var TRUE = true,
		FALSE = false,
		NULL = null,
		window = self,
		undefined;
	var FLASH_VERSION_SUPPORTED = "9.0.124",
		NEW_WINDOW_TEXT = "(opens in a new window)",
		$html = $("html"); // Good practice only to query a selector once & save to memory. (Improves performance.) $ at beginning of variable makes it easier to remember it's jQuery & not just some variable.
	window.VSAUtil = { // These utilities are available globally, not just to this JS file.
		isIE: !$.support.htmlSerialize,
		isIE6: !$.support.htmlSerialize && parseInt($.browser.version, 10) === 6,
		hasFlash: typeof swfobject !== "undefined" && swfobject.hasFlashPlayerVersion(FLASH_VERSION_SUPPORTED),
		trackpage: function(url) {
			// Google Analytics:
			_gaq.push(["_trackPageview",url]);
			// Omniture:
			try {
				s.tl(TRUE,"o",url);
			} catch(e) {}
		},
		loadJS: function(args) {
			// Takes an array of URLs/paths to JavaScript files, e.g.: 
			// loadJS(["path/to/some.js","path/to/more.js"]);
			for(arg in args) {
				$("<script />")
					.attr({"src": args[arg]})
					.appendTo("head");
			}
		},
		loadCSS: function(args) {
			// Same as loadJS, but CSS files, with an optional list of 
			// media types (separated from the path by a pipe), e.g.: 
			// loadCSS(["path/to/some.css|screen","path/to/more.css|screen,print","path/to/additional.css"]);
			for(arg in args) {
				var argVals = args[arg].split("|"),
					cssSource = argVals[0],
					cssMedia = argVals[1] || "all";
				$("<link />")
					.attr({
						"rel": "stylesheet",
						"href": cssSource,
						"media": cssMedia
					})
					.appendTo("head");
			}
		},
		embedFlash: function(containerID, swf, width, height, flashvars, params, attributes) {
			if(!VSAUtil.hasFlash) { return; }
			else {
				var fvars = flashvars || {},
					fparams = params || {},
					fattrs = attributes || {};
				fparams.wmode = "transparent";
				var flashID = "flash-" + Math.floor(Math.random()*100000);
				var flashContainer = $('<div class="flash_"></div>').append('<div id="' + flashID + '" />');
				$("#" + containerID)
					.addClass("containsFlash_")
					.wrapInner('<div class="noFlash_"></div>')
					.prepend(flashContainer);
				swfobject.embedSWF(swf, flashID, width, height, FLASH_VERSION_SUPPORTED, NULL, fvars, fparams, fattrs);
			}
		},
		pngfix: function(selectors) {
			// Use DD_belatedPNG to fix transparent PNGs in IE6. Takes a 
			// string of jQuery-style selectors, or leave blank to apply 
			// to the "pngfix_" class. 
			// Call this OUTSIDE of $(document).ready().
			if(typeof DD_belatedPNG == "undefined") { return; }
			else {
				var elems = selectors || ".pngfix_";
				$(window).load(function() {
					var $elems = $(elems);
					if($elems.length) {
						$elems.each(function() {
							DD_belatedPNG.fixPng(arguments[1]);
						});
					}
					else { return; }
				});
			}
		},
		validEmail: function(elem) {
			return "" || /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(elem.value);
		}
	};
	$html.addClass("js-enabled");
	if(VSAUtil.hasFlash) {
		$html.addClass("flash-enabled");
	}
	
	// Document ready functions:
	$(function() { // Shortcut for $(document).ready()
		var div_content = document.getElementById("content"),
			$home_link = $("#home h1 a"),
			a_current = [
				"body:not(.hfeed) a.current_",
				"#about #nav-about a",
				"#products-services #nav-products-services a",
				"#support #nav-support a",
				"#insights:not(.category) #nav-insights a",
				"#newer-entries a.first-page",
				"#older-entries a.last-page"
			].join(",");
		// Link functions:
		$(a_current).click(function() { return FALSE; });
		$home_link.click(function() {
			featurebox.close();
			$home_link.css({cursor: ""});
			return FALSE;
		});
		$("a.social-network", div_content).each(function() {
			var $a = $(this);
			if($a.is("#on-linkedin")) {
				var a_components = $a.attr("href").split("?");
				var a_href = a_components[0] + "?mini=true&" + a_components[1];
				$a.attr({href: a_href});
			}
			$a.attr({
				target: "_blank",
				title: $a.text() + " " + NEW_WINDOW_TEXT
			});
		});
		// Make whole regions clickable:
		$("#connect,#support li,#contents li,#promotions li", div_content).click(function() {
			var $a = $(this).find("a:first");
			if($a.is('[href^="http"]')) {
				VSAUtil.trackpage("/external-link/" + $a[0].host + $a[0].pathname);
			}
			if($a.is('[rel="external"]')) {
				window.open($a[0].href);
			}
			else {
				window.location = $a[0].href;
			}
			return FALSE;
		});
		// Handle PDFs, other non-HTML links, and stuff that they want to open in a new window:
		var media_links = 'a[href$=".m4v"],a[href$=".wmv"],a[href$=".pdf"],a[href$=".jpg"]';
		// Open in a new window:
		$('a[rel="external"],' + media_links).each(function() {
			var $a = $(this),
				a_title = $a.attr("title");
			$a.attr({
				target: "_blank",
				title: function() {
					if(a_title != "") {
						return a_title + " " + NEW_WINDOW_TEXT;
					}
					else {
						return NEW_WINDOW_TEXT;
					}
				}
			});
		});
		// Track page views for external links & non-HTML files:
		$("a").click(function() {
 			var $a = $(this),
				anchor = $a[0];
			if($a.is(".social-network")) {
				VSAUtil.trackpage("/shared-link/" + anchor.host + document.location.pathname);
			}
			else if($a.is('[href^="http"]:not([href^="http://locator.star.com"])')) {
				VSAUtil.trackpage("/external-link/" + anchor.host + anchor.pathname);
			}
			else if($a.is(media_links)) {
				VSAUtil.trackpage(anchor.pathname);
			}
		});
		
		
		// Zebra-stripe a table:
		$(".events tbody tr:odd", div_content).addClass("odd_");
		
		
		// Make the "STAR Locator" header function like a label:
		$("#star-locator h2").click(function() {
			$("#txtLocate").focus();
		});
		
		// Bio show/hide toggle functionality:
		var div_leadership = document.getElementById("leadership"),
			showBio = "Show Bio",
			hideBio = "Hide Bio";
		$("li.vcard", div_leadership).each(function(n) {
			var $vcard = $(this),
				$person = $vcard.find("div.person"),
				$bio = $vcard.find("div.bio");
			$bio.attr({"tabindex": "-1"}); // Allow for programmatic focus of the details div.
			$("<a />") // Add "toggle" anchor to the DOM. (This markup is pointless without JavaScript, so added here.)
				.attr({
					href: "#",
					id: "toggleable-" + n
				})
				.text(showBio)
				.appendTo($person)
				.wrap('<p class="toggle" />') // End "toggle" anchor addition.
				.click(function() {
					var $toggle = $(this),
						stateText = showBio;
					$vcard.toggleClass("open_");
					$bio
						.stop()
						.slideToggle(300, function() {
							if($bio.is(":visible")) {
								$("html,body")
									.stop()
									.animate({scrollTop: $vcard.offset().top}, 300);
								stateText = hideBio;
								$bio.focus();
							}
							$toggle.text(stateText);
						});
					return FALSE;
				});
			VSAUtil.pngfix("a#toggleable-" + n);
		});		
		
		// Add placeholder text:
		$("input.autolabel")
			// .each(function() {})
			.each(function() {
				// If the browser supports the HTMl5 placeholder attribute, use it:
				if(!Modernizr.input.placeholder) {
					var $this = $(this),
						autolabel_default_class = "autolabel_empty",
						placeholder = $this.data("label", $('label[for="' + $this.attr("id") + '"]').text());
					if($this.closest("form").is("#cse-search-box")) {
						autolabel_default_class = "";
					}
					if(!$this.val()) {
						$this
							.val($this.data("label"))
							.addClass(autolabel_default_class);
					}
					$this
						.focus(function() {
							if($this.val() === $this.data("label")) {
								$this
									.val("")
									.removeClass(autolabel_default_class);
							}
						})
						.blur(function() {
							if($this.val() === "") {
								$this
									.val($this.data("label"))
									.addClass(autolabel_default_class);
							}
						})
				}
			})
			.closest("form")
				.submit(function() {
					if(!Modernizr.input.placeholder) {
						$(this)
							.find("input.autolabel")
								.each(function() {
									var $this = $(this);
									if($this.val() === $this.data("label")) {
										$this.val("");
									}
								});
					}
				});
		$("#frmLocate").submit(function() {
			var $locate = $("#txtLocate"),
				location_value = $locate.val();
			if(location_value === "" || location_value.length < 5 || (!Modernizr.input.placeholder && location_value === $locate.data("label"))) {
				alert("To use the STAR Locator:\nPlease enter a valid Zip code or address.");
				return FALSE;
			}
		});
		// UNIFORM the forms!
		$("form:not(#myform) input:checkbox,form:not(#myform) input:radio,form:not(#myform) select", div_content).uniform({
			selectClass: "selectbox",
			radioClass: "radiobutton",
			checkboxClass: "checkbox",
			checkedClass: "checked" // Uniform default.
		});
		
		// Home page feature lightbox and functionality:
		var $feature_wrap = $("div.wrap_", div_content),
			$features = $("#features", div_content);
		window.featurebox = {
			close: function() {
				$("#featurebox")
					.stop()
					.animate({opacity: 0}, {
						duration: 300,
						complete: function() {
							$feature_wrap.removeAttr("style");
							$("div.feature-clicked")
								.focus()
								.removeClass("feature-clicked");
							$(this).remove();
							$("#contentinfo").animate({opacity: 1}, { // hack to delay the resumption of the feature cycle
								duration: 750,
								complete: function() {
									$(this).removeAttr("style");
									$features.cycle("resume");
								}
							})
						}
					});
			},
			launch: function(swf,xml) {
				if(!swf) { return; }
				else {
					$features.cycle("pause");
					var window_height = $(window).height(),
						flash_file = "_files/flash/" + swf,
						flash_container = "featurebox-flash",
						flashvars = {},
						params = {
							quality: "high",
							scale: "noscale",
							allowscriptaccess: "always",
							bgcolor: "#ffffff",
							wmode: "opaque"
						},
						attributes;
					if(xml) {
						flashvars.xmlPath = "_files/flash/xml/" + xml;
					}
					$('<div id="' + flash_container + '" />')
						.appendTo("body")
						.wrap('<div id="featurebox"><div id="featurebox-bg" /></div>');
					$feature_wrap
						.stop()
						.animate({opacity: 0}, {
							duration: 200,
							complete: function() {
								$(this).css({
									opacity: "",
									visibility: "hidden"
								});
							}
						});
					var $featurebox = $("#featurebox");
					// Keep as much of the feature in the window as possible.
					// These integers are hard-coded but should probably be
					// dynamic. See the end of content.css for values.
					if(window_height < 560 && window_height > 460) {
						$featurebox.css({
							top: (window_height - 460),
							"z-index": 999
						});
					}
					else if(window_height <= 460) {
						$featurebox.css({
							top: 0,
							"z-index": 999
						});
					}
					$home_link.css({cursor: "pointer"});
					$featurebox
						.attr({tabindex: "-1"})
						.stop()
						.animate({opacity: 1}, {
							duration: 300,
							complete: function() {
								$featurebox.focus();
								swfobject.embedSWF(flash_file, flash_container, "940", "460", FLASH_VERSION_SUPPORTED, NULL, flashvars, params, attributes);
							}
						});
				}
			}
		};
		$features
			// Create cycle pager:
			.after('<div id="feature-pager" />')
			// Do the initial Cycle among features:
			.cycle({
				fx: "fade",
				timeout: 8000,
				speed: (VSAUtil.isIE ? 200 : 350), // Faster if it's IE, due to ClearType rendering issues
				pager: "#feature-pager",
				cleartypeNoBg: TRUE,
				activePagerClass: "current_"
			})
			// Launch the Flash feature:
			.find("div.feature")
				.each(function() {
					var $feature = $(this);
					if(VSAUtil.hasFlash) {
						$feature.attr({tabindex: "-1"});
					}
					else {
						var anchor_count = $feature.find("a:not(:first)").length;
						if(anchor_count > 1) {
							$feature.css({cursor: "default"});
						}
					}					
				})
				.click(function() {
					var $feature = $(this);
					if(VSAUtil.hasFlash) {
						var $a = $feature.find("a:first"),
							swf = $a.attr("data-swf"),
							xml = $a.attr("data-swf-xml"),
							feature_name = $a.attr("data-swf-name");
						$feature.addClass("feature-clicked");
						VSAUtil.trackpage("/homepage-feature/" + (feature_name ? feature_name : swf));
						featurebox.launch(swf,xml);
						return FALSE;
					}
					else {
						var $a = $feature.find("a:not(:first)");
						if($a.length == 1) {
							var anchor = $a[0],
								url = anchor.pathname;
							if($a.is('[rel="external"],[href^="http"]')) {
								url = "/external-link/" + anchor.host + url;
							}
							VSAUtil.trackpage(url);
							if($a.is(media_links + ',[rel="external"],[href^="http"]')) {
								window.open(anchor.href);
							}
							else {
								window.location = anchor.href;
							}
							return FALSE;
						}
					}
				})
				.end();
	});
		
	// IE helpers:
	if(VSAUtil.isIE) {
		$(window).load(function() {
			// Make sure the faked drop-shadow doesn't look weird in IE:
			var $content_nav_first = $("#content .nav li:first a"),
				$content_nav_header = $content_nav_first.closest("div").find("h3");
			if($content_nav_first.is(".current_")) {
				$content_nav_header.addClass("hover_");
			}
			else {
				$content_nav_first.bind("mouseenter mouseleave focus blur click", function() {
					$content_nav_header.toggleClass("hover_");
				});
			}
		});
	}
	if(VSAUtil.isIE6) {
		$(window).load(function() {
			$("#site-meta li:first,#insights div.article:first").addClass("first_");
			$("#utility button").bind("mouseenter mouseleave focus blur", function() {
				$(this).toggleClass("hover_");
			});
		});
		VSAUtil.pngfix(".pngfix_,.link a,a.link,p.more_,#home div.feature"); // Defaults to all elements with class="pngfix_"
		document.createElement("abbr");
	}
})(jQuery);