var players = [];
var indeed_conversion_id = '9212920946988558';
var indeed_conversion_label = '';


$(document).ready(function() {

	// Set up Google Analytics
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	$.getScript(gaJsHost + "google-analytics.com/ga.js", function() {
		try {
			window.pageTracker = _gat._getTracker("UA-1500309-7");
			window.pageTracker._trackPageview();
		} catch (err) { }
	});

	if ($(".visual-thin").children().length == 0) {
		$(".visual-thin").hide();
		$(".info-wide").css("width", "511px");
	}

	// Set up tabs
	$('ul.tabs').tabs("div.panes > div");

	// Expand the clickable area on the featured news bubbles
	$("div.news-bubble").click(function() {
		var href = $(this).find("a:first").attr("href");
		document.location.href = href;
		trackEvent("Links", "Click Bubble", href);
	});

	initIntroAnim();
	// initMenuSizeChanger();
	initMenuDropDowns();
	initWindowShade();
	initTeam();
	initPortfolio();
	initSlide();
	setupLinkTracking();

	// Highlight active path
	var path = location.pathname;
	if (path) {
		$('a[href$="' + path + '"]').addClass('active').parents().filter("li").addClass("active").find('ul').slideDown();
	}

	path = path.toLowerCase();

	if ((path.indexOf("/ls") >= 0) || (path.indexOf("/life-sciences") >= 0)) {
		$(".logo").css({ 'background-image': 'url(/Site/Images/logo-ls.gif)' });
	}

	$("#remote-button").click(function() {
		$("#form1").attr("action", "http://na.ntrsupport.com/web/sassig.asp");
	});

	// Embed Vimeo videos
	$('.main-content a[href*="vimeo.com"]').each(function() {
		// Grab video ID from the url
		var videoID = $(this).attr('href').match(/vimeo\.com\/(.+)+/);
		if (videoID.length) {
			videoID = videoID[1];
			$(this).replaceWith('<div id="vimeo-embed-' + videoID + '">You need Flash player 8+ to view this video.</div>');
			var params = { allowScriptAccess: 'always', allowfullScreen: 'false', wmode: 'transparent' };
			var attrs = { id: 'vimeo-video-' + videoID }
			// Embed the youtube video using SWFObject script
			swfobject.embedSWF('http://vimeo.com/moogaloop.swf?clip_id=' + videoID + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=D6E03D&amp;fullscreen=0', 'vimeo-embed-' + videoID, '527', '290', '9', null, null, params, attrs);
		}
	});

	// Qtips
	try {
		$("#items a").each(function() {
			var path = $(this).attr("href");
			$(this).qtip({ api: { onShow: function() { trackEvent("Portfolio", "Hover", path); } }, show: { delay: 0, effect: { type: "slide", length: 0} }, position: { adjust: { x: 0, y: -8 }, corner: { target: 'topMiddle', tooltip: 'bottomMiddle'} }, style: { width: 250, background: '#D6D28E', border: { width: 2, radius: 4, color: "#D6D28E" }, tip: { corner: 'bottomMiddle', color: '#D6D28E'}} }).find("img").attr("title", "");
		});
		$("#gallery a").each(function() {
			var path = $(this).attr("href").replace("#", "/");
			$(this).qtip({ api: { onShow: function() { trackEvent("Portfolio", "Hover", path); } }, show: { delay: 0, effect: { type: "slide", length: 0} }, position: { adjust: { x: 0, y: -8 }, corner: { target: 'topMiddle', tooltip: 'bottomMiddle'} }, style: { width: 250, background: '#D6D28E', border: { width: 2, radius: 4, color: "#D6D28E" }, tip: { corner: 'bottomMiddle', color: '#D6D28E'}} }).find("img").attr("title", "");
		});
	}
	catch (ex) { }

	$("#Twitter a").qtip({ content: { prerender: true, text: '<div id="tweet"><img src="/Media/Images/Twitter-Bird?width=50" style="float: right;" /><h4>Follow us on Twitter</h4></div>' }, api: { onRender: function() { getTweets(); }, onShow: function() { trackEvent("Social Media", "Hover", "Twitter"); } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true, delay: 100 }, position: { corner: { target: 'bottomMiddle', tooltip: 'topMiddle'} }, style: { width: 200, background: '#D6D28E', textAlign: 'center', border: { width: 2, radius: 4, color: "#A04235" }, tip: { corner: 'topMiddle', color: '#A04235'}} }).attr("title", "").css("opacity", 0.5).hover(function() { $(this).stop().animate({ opacity: 1.0 }) }, function() { $(this).stop().animate({ opacity: 0.5 }) });
	$("#LinkedIn a").qtip({ content: { prerender: true, text: '<h4>Find us on Linked In</h4><p><a href="http://www.linkedin.com/companies/57729/Aloysius+Butler+%26+Clark?trk=pro_other_cmpy&goback=.hom"><img src="/Media/Images/LinkedIn-Screenshot" border="0" /></a></p>' }, api: { onShow: function() { trackEvent("Social Media", "Hover", "Linked In"); } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true, delay: 100 }, position: { corner: { target: 'bottomMiddle', tooltip: 'topMiddle'} }, style: { background: '#D6D28E', textAlign: 'center', border: { width: 2, radius: 4, color: "#A04235" }, tip: { corner: 'topMiddle', color: '#A04235'}} }).attr("title", "").css("opacity", 0.5).hover(function() { $(this).stop().animate({ opacity: 1.0 }) }, function() { $(this).stop().animate({ opacity: 0.5 }) });
	$("#Facebook a").qtip({ content: { prerender: true, text: '<h4>Find us on Facebook</h4><p><a href="http://www.facebook.com/pages/Wilmington-DE/Aloysius-Butler-Clark/32183238287"><img src="/Media/Images/Facebook-Screenshot" border="0" /></a></p>' }, api: { onShow: function() { trackEvent("Social Media", "Hover", "Facebook"); } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true, delay: 100 }, position: { corner: { target: 'bottomMiddle', tooltip: 'topMiddle'} }, style: { background: '#D6D28E', textAlign: 'center', border: { width: 2, radius: 4, color: "#A04235" }, tip: { corner: 'topMiddle', color: '#A04235'}} }).attr("title", "").css("opacity", 0.5).hover(function() { $(this).stop().animate({ opacity: 1.0 }) }, function() { $(this).stop().animate({ opacity: 0.5 }) });
	$("#Blog a").qtip({ content: { prerender: true, text: '<div id="blogpost">&amp; Another Thing (Blog)</div>' }, api: { onRender: function() { getBlogPosts(); }, onShow: function() { trackEvent("Social Media", "Hover", "Blog"); } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true, delay: 100 }, position: { corner: { target: 'bottomMiddle', tooltip: 'topMiddle'} }, style: { width: 330, background: '#D6D28E', textAlign: 'center', border: { width: 2, radius: 4, color: "#A04235" }, tip: { corner: 'topMiddle', color: '#A04235'}} }).attr("title", "").css("opacity", 0.5).hover(function() { $(this).stop().animate({ opacity: 1.0 }) }, function() { $(this).stop().animate({ opacity: 0.5 }) });
	$("#YouTube a").qtip({ content: { prerender: true, text: '<h4>View our YouTube channel</h4><p><a href="http://www.youtube.com/user/AloysiusButlerClark"><img src="/Media/Images/YouTube-Screenshot" border="0" /></a></p>' }, api: { onShow: function() { trackEvent("Social Media", "Hover", "You Tube"); } }, show: { delay: 0, effect: { type: "slide", length: 0} }, hide: { fixed: true, delay: 100 }, position: { corner: { target: 'bottomMiddle', tooltip: 'topMiddle'} }, style: { background: '#D6D28E', textAlign: 'center', border: { width: 2, radius: 4, color: "#A04235" }, tip: { corner: 'topMiddle', color: '#A04235'}} }).attr("title", "").css("opacity", 0.5).hover(function() { $(this).stop().animate({ opacity: 1.0 }) }, function() { $(this).stop().animate({ opacity: 0.5 }) });

	// Colorboxes
	$(".main-column a[href*='blog.a-b-c.com']").each(function() {
		var $anchor = $(this);
		var path = $anchor.attr("href");
		var $el = $("<div></div");
		$el.load("/Utilities/Proxy.ashx?url=" + path + " .about-post", function() {
			$anchor.colorbox({ html: $el.html(), title: '<span id="blog-links">Agree? Disagree? <a class="blog" target="_blank" href="' + path + '#respond">Talk back on our blog</a>.<span class="sep"></span>Stay in touch: <a class="rss" target="_blank" href="http://blog.a-b-c.com/feed">Receive RSS updates.</a></span>', onComplete: function() { trackPageview(path); trackEvent("Blog", "View", path); }, initialWidth: 300, initialHeight: 300, width: 900, maxHeight: $(window).height() - 50, opacity: 0.1 });
		});
	});

	$("a[href*='mindmeister.com']").each(function() {
		var link = $(this).attr("href");
		var cbWidth = 800; // $(window).width()-50;
		var cbHeight = 600; // $(window).height()-50;
		var url = "http://www.mindmeister.com/maps/public_map_shell/37083067/?width=" + cbWidth + "&height=" + cbHeight + "&zoom=0";
		$(this).colorbox({ iframe: true, href: url, title: 'This map is interactive. Explore above.', onComplete: function() { trackEvent("Links", "Click MindMeister", link); }, initialWidth: 300, initialHeight: 300, innerWidth: cbWidth, innerHeight: cbHeight, opacity: 0.1 });
	});

	// <iframe width="600" height="400" frameborder="0" src="http://www.mindmeister.com/maps/public_map_shell/37083067/ways-to-use-social-media?width=600&height=400&zoom=0" scrolling="no" style="overflow:hidden"></iframe>

	$("#gallery a").each(function() {
		var $anchor = $(this);
		var $el = $("<div><div id='slide-area'><div class='slides-container'><div class='slides-container-btm'><div class='smpleft'></div><div class='smpmid'><div class='smplogo'></div><div id='slides'></div></div><div class='smpright'><ul id='thumbs'></ul></div></div></div></div></div");
		// $(this).colorbox({ html: $el.html(), title: "<a href='/Portfolio'>View more portfolio samples</a>", initialWidth: 300, initialHeight: 300, width: 940, height: 600, opacity: 0.1,
		$(this).colorbox({ html: $el.html(), initialWidth: 300, initialHeight: 300, width: 940, height: 600, opacity: 0.1,
			onComplete: function() {
				injectSample($anchor.attr("href").replace("#", "/"), "#slides", "#thumbs");
			}
		});
	});

	$("#fp-links a").click(function() {
		var $anchor = $(this);
		var htmlStart = "<div id='enews' align='center'>";
		var htmlEnd = "</div>";
		$anchor.colorbox({ open: true, title: 'Fresh Perspectives: ' + $(this).text(), html: htmlStart + "Loading..." + htmlEnd, initialWidth: 300, initialHeight: 300, width: 640, height: 600, opacity: 0.1 });
		$("#enews").load("/Utilities/Proxy.ashx?url=" + $(this).attr("href"), function() {
			$("#enews a").attr("target", "_blank")
		});
		return false;
	});

	$("a[href$='mp3']").each(function() {
		insertMP3player(this);
	});
});

function insertMP3player(element) {
	var newId = $(element).attr("href").substring($(element).attr("href").lastIndexOf('/') + 1).split('.')[0];
	if (newId != undefined && newId.length > 1) {
		$(element).wrap('<div id="' + newId + '" />');
		embedAudio($(element).attr("href"), $("#" + newId), 520, 50);
	}
}

function trackEventFull(category, action, label, value){
	if (document.location.href.indexOf("test.") > -1 ){
		window.status = "Event: " + category + ", " + action + ", " +  label + ", " + value;
	}
	try { window.pageTracker._trackEvent(category, action, label, value); } catch(err){ }
}

function trackEvent(category, action, label){
	if (document.location.href.indexOf("test.") > -1 ){
		window.status = "Event: " + category + ", " + action + ", " +  label;
	}
	try { window.pageTracker._trackEvent(category, action, label); } catch(err){ }
}

function trackPageview(url)
{
	if (document.location.href.indexOf("test.") > -1 ){
		window.status = "Page: " + url;
	}
	try { window.pageTracker._trackPageview(url); } catch(err){}
}

/** Portfolio Functions **/

function initPortfolio() {
	// make sample icons scrollable
	window["scrollAPI"] = $("#scrollable").scrollable({
		size: 12,
		loop: false,
		api: true
	});
	
	// set up links on portfolio sample icons
	$("#items a", "#scrollable").css({ opacity: 0.5 }, 250).hover(
		function() {
			$(this).stop().animate({ opacity: 1.0 }, 250);
		},
		function() {
			// Only dim it out if isn't currently active (because it was clicked on)
			if (!$(this).hasClass('active')) {
				$(this).stop().animate({ opacity: 0.5 }, 250);
			}
		}
	).each(function() {
		$(this).click(function() {
			$("#items a[class*='active']", "#scrollable").stop().animate({ opacity: 0.5 }, 250).removeClass("active");
			var hash = "#" + $(this).attr('href').replace("/Portfolio/", "");
			if (window.location.hash != hash) {
				launchSlideSample($(this).attr('href'), "#slides", "#thumbs", true);
				window.location.hash = "#" + $(this).attr('href').replace("/Portfolio/", "");
			}
			else {
				$(this).addClass("active").animate({ opacity: 1.0 }, 250);
			}
			return false;
		});
	});
	
	$(".center a", "#slider").click(function() {
		$(".center a", "#slider").removeClass("active");
		var className = $(this).attr("class");
		if (className.length) {
			$(this).addClass("active");
			filterPortfolio(className);
		}
		else {
			showAllPortfolio();
		}
		return false;
	});

	var qs = $.deparam.querystring();
	var filterPrefix = "";
	var filterValue = "";

	if (qs["ind"]) {
		filterPrefix = "ind";
		filterValue = qs["ind"];
	}
	else if (qs["exp"]) {
		filterPrefix = "exp";
		filterValue = qs["exp"];
	}
	else if (qs["med"]) {
		filterPrefix = "med";
		filterValue = qs["med"];
	}
	else if (qs["src"] && qs["src"] == "hr") {
		$("<script type='text/javascript' src='http://conv.indeed.com/pagead/conversion.js'></script>").appendTo("body");
	}
	// this is part of the contact form, and really should be moved elsewhere
	

	if (filterValue != "") {
		setTimeout(function() {
			setInitialPortfolioFilter(filterPrefix, filterValue);
		}, 1000);
	}
	else{
		// window.status = "Loading a random portfolio sample";
		preloadPortfolioSample("a:random");
	}
}

function preloadPortfolioSample(selector) {
	// Preload portfolio sample?
	if (window.location.hash){
		window.status = "Loading specific portfolio sample";		
		var sample = window.location.hash.replace("#", "");
		$selected = $("#items a[href='/Portfolio/" + sample + "']:first");
		if (window["scrollAPI"] != null){
			// window["scrollAPI"].seekTo($("#items a").index($selected))
		}
		launchSlideSample("/Portfolio/" + sample, "#slides", "#thumbs", true);
	}
	else{
		var $selected = $("#items").find(selector);
		if ($selected.attr("href") != "undefined"){		
			if (window["scrollAPI"] != null){
				// window["scrollAPI"].seekTo($("#items a").index($selected))
			}
			launchSlideSample($selected.attr("href"), "#slides", "#thumbs", false);
		}
	}
}

function generateThumbnail(thumb, documentName) {
	// If we have a document name to work with
	if (documentName)
	{
		var str = '';
		
		// If the thumbnail is available, use it
		if (thumb) {
			str = '<li><img src="/getattachment/' + thumb + '/' + documentName + '?height=50&width=50" /></li>';
		}
		// Otherwise use a placeholder
		else {
			var str = '<li><img src="/Site/Images/blank-work" /></li>';
		}
		
		return str;
	}
}

function assignSampleValues(data) {
	if (data) {
		// trackEvent("Portfolio", "View", data["Title"]);
		trackPageview(data["NodeAliasPath"]);
		var desc = "";
		desc += '<h1>' + data["Title"] + '</h1>';
		desc += data["Overview"];
		$(".slides-container div.smpleft").html(desc);
		$(".slides-container div.smplogo").html('<img class="logo" src="/getattachment/' + data['Logo'] + '/' + data['DocumentName'] + '" />');
	}
}

function filterPortfolio(className) {
	// GA
	trackEvent("Portfolio", "Filter", className);
	
	$("div.item", "#scrollable").each(function() {
		if (!$(this).hasClass(className)) {
			$(this).stop().animate({width: 0, margin: "0px"}, 750, function(){
				$(this).fadeOut('fast').hide();
			}).find("a").addClass("hidden");
		}
		else {
			$(this).stop().css("margin", "1px").fadeIn('fast').animate({width: 65}, 750).find("a").removeClass("hidden");
		}
	});
	window["scrollAPI"].reload().seekTo(0);
}

function showAllPortfolio() {
	// GA
	trackEvent("Portfolio", "Filter", "all");
	
	$("div.item", "#scrollable").each(function() {
		$(this).stop().animate({width: 65, margin: "1px"}, 750).fadeIn('fast');;
	});
}

function launchSlideSample(aliasPath, container, thumbSelector, closeFilter) {
	$("a[href='" + aliasPath + "']").addClass("active").animate({ opacity: 1.0 }, 250);
	
	// First, close any open filters/sliders
	if (closeFilter){
		$(".slide-block").removeClass("active").find(".block").slideUp({ duration: 150, easing: "swing" });
	}
	
	$(".slides-container").animate({"marginTop": "880px"}, 750, function(){
		/*$("#loader").show();*/
		injectSample(aliasPath, container, thumbSelector);
	});
}

function injectSample(aliasPath, container, thumbSelector){
	// initialize variables
	var classNames = "ABC.WorkSample";
	var properties = "DocumentName|Title|Subtitle|Overview|Logo|NodeAliasPath";
	var output = '';

	$.ajax({
		type: "POST",
		url: "/Utilities/DocumentProperties.ashx?nodealiaspath=" + aliasPath + "&classnames=" + classNames + "&properties=" + properties,
		data: '',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (msg) {

			// set the values for the slide description
			// TODO: Refactor this to be generic?
			assignSampleValues(msg[0]);

			// * Begin get slides *

			classNames = "ABC.WorkSampleSlide";
			properties = "DocumentName|NodeID|Title|Thumbnail|Content|ContentUrl|ContentType|UseZoomer|NodeAliasPath|imageHeightFor_Content|imageWidthFor_Content";
			output += '<div id="slidecontainer">'
			output += '<div id="slideitems">'
			// ajax call with properties set correctly
			$.ajax({
				type: "POST",
				url: "/Utilities/DocumentProperties.ashx?nodealiaspath=" + aliasPath + "/%" + "&classnames=" + classNames + "&properties=" + properties,
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function (msg) {
					//remove thumbnails
					$(thumbSelector).html('');

					// write the content associated with each slide
					for (var i = 0; i < msg.length; i++) {
						output += writeSlide(msg[i], thumbSelector);
					}
					output += "</div>"; //sampleitems
					output += "</div>"; //samplecontainer

					// write the slide content to the DOM
					$(container).html(output);

					$("#slideitems .item").click(function () {
						window["scrollAPI2"].stop();
					});

					// Hook up video handler
					$("#slideitems .videoPane a").each(function () {
						embedVideo($(this).attr("href"), "#" + $(this).parents("div").attr("id"));
					});

					// Hook up audio handler
					$("#slideitems .audioPane a").each(function () {
						embedAudio($(this).attr("href"), "#" + $(this).parents("div").attr("id"), 530, 319);
					});

					// hook up functions to execute after the content is loaded into the DOM
					$("div#slidecontainer img:first").load(function () { centerFirstSlide(); showSample(); $("#loader").hide(); });
					$("div#slidecontainer img").batchImageLoad({ loadingCompleteCallback: function () { slidesLoaded(); } });
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					// Do nothing for now
					alert(textStatus + errorThrown);
				}
			});

		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			// Do nothing for now
			alert("Portfolio sample not loaded.");
		}
	});
}

function centerFirstSlide(){	
	$("div.item img:first", "#slideitems").each(function() {
		var itemHeight = $(this).height();
		var parentHeight = $(this).parent().height();
		var currentStyle = ($(this).attr("style")) ? $(this).attr("style") : '';
		if ((itemHeight) && (parentHeight)) {
			var top = Math.round(((parentHeight - itemHeight) / 2));
			$(this).attr("style", currentStyle + '; margin-top:' + top + 'px;');
		}
	});
}

function centerSlides() {
	$("div.item img", "#slideitems").each(function() {
		var itemHeight = $(this).height();
		var parentHeight = $(this).parent().height();
		var currentStyle = ($(this).attr("style")) ? $(this).attr("style") : '';
		if ((itemHeight) && (parentHeight)) {
			var top = Math.round(((parentHeight - itemHeight) / 2));
			$(this).attr("style", currentStyle + '; margin-top:' + top + 'px;');
		}
	});
}

function showSample(){
	$(".slides-container").animate({ "marginTop": "0px"}, 750);
}

function hideSample(){
}

function setInitialPortfolioFilter(prefix, value) {
	$("a." + prefix + "-" + value).addClass("active").parents("div.block").slideDown({ duration: 500, easing: "easeOutBack" });
	filterPortfolio(prefix + "-" + value);
	// window.status = "Loading first non-hidden portfolio sample.";
	preloadPortfolioSample("a:not(.hidden)");
}

// set up zoomer after slides have loaded
function slidesLoaded() {
	// set the style properties on small zoomer content
	$("div.zoomsmallcontent img").each(function() { zoomerSmallValues(this); });
	
	// center all slides
	centerSlides();
	
	// make the slides scroll
	window["scrollAPI2"] = $("#slidecontainer").scrollable({ size: 1, loop: true, onBeforeSeek: function(e, i){activateThumb(i)} }).autoscroll({ autoplay: false, steps: 1, interval: 4000, api: true }); //.navigator({ navi: "#thumbs", naviItem: "li", activeClass: "active" });
	$("#thumbs li:first-child").addClass("active");
	$("#thumbs li").click(function(){
		$(this).siblings("li").removeClass("active");
		$(this).addClass("active");
		window["scrollAPI2"].seekTo($("#thumbs li").index($(this)));
	});
	
	// set zoomer up on applicable slides
	//$("div.zoomcontainer").anythingZoomer({
	//	doDoubleClick: false
	//});
}

function activateThumb(index){
	// Stop playing media
	for (var i=0; i < window.players.length; i++){
		var player = document.getElementById(window.players[i]);
		if (player != null){
			player.pauseVideo();
		}
	}
	
	$("#thumbs li").removeClass("active");
	var $li = $("#thumbs li:eq(" + index + ")");
	$li.addClass("active");
	var page = $li.find("img").attr("src");
	page = page.substring(page.lastIndexOf("/")).replace("?height=50&width=50", "");
	trackPageview(location.pathname + window.location.hash.replace("#", "/") + page);
}

function writeSlide(obj, thumbSelector) {

	var documentName = obj["DocumentName"];
	var nodeID = obj["NodeID"];
	var content = obj["Content"];
	var contentUrl = obj["ContentUrl"];
	var contentType = obj["ContentType"];
	var useZoomer = obj["UseZoomer"];
	var height = obj["imageHeightFor_Content"];
	var width = obj["imageWidthFor_Content"];
	
	// need the document name and content to proceed
	if (!documentName) { return; }

	// Add the thumbnail
	$(thumbSelector).append(generateThumbnail(obj["Thumbnail"], documentName));

	var output = "";

	// process based on content type
	switch (contentType) {
		case "Audio":
			output = '<div id="audio-' + nodeID + '" class="item audioPane" style="width:530px; height:400px;"><a href="/getattachment/' + content + '/' + documentName + '" target="_blank">Listen to Audio</a></div>';
			break;
		case "Image":
			if (false){
			//if (useZoomer == "True") {
				output = '<div class="item zoomcontainer">';
				output += '<div class="zoomsmallcontent">';
				output += '<img src="/getattachment/' + content + '/' + documentName + '?width=530&num=' + Math.floor(Math.random()*999) + '"/>';
				output += '</div>'; // zoomsmallcontent
				output += '<div class="zoompane">';
				output += '<div class="zoomlargecontent">';
				output += '<img src="/getattachment/' + content + '/' + documentName + '"' + ' style="height:' + height + 'px;' + 'width:' + width + 'px;" />';
				output += '</div>'; // zoomlargecontent
				output += '</div>'; // zoompane
				output += '</div>'; // zoomcontainer
			}
			else {
				output = '<div class="item slideimage"><img src="/getattachment/' + content + '/' + documentName + '?width=530&num=' + Math.floor(Math.random()*999) + '" /></div>'
			}
			break;
		case "Video":
			output = '<div id="video-' + nodeID + '" class="item videoPane" style="width:530px; height:400px;"><a href="' + contentUrl + ' " target="_blank">Video Video</a></div>';
			break;
		default:
			output = '<div class="item slideimage">No slide.</div>';
			break;
	}
	return output;
}

function zoomerSmallValues(obj) {
	var objHeight = $(obj).height();
	var objWidth = $(obj).width();
	var strOut = "height:" + objHeight + "px; " + "width:" + objWidth + "px;";
	$(obj).attr("style", strOut);
	// reset for parent-of-parent
	strOut = "height:" + (objHeight + 10) + "px; " + "width:" + objWidth + "px;";
	$(obj).parent().parent().attr("style", strOut);
}

/****/

function initIntroAnim() {
	if ($("#intro").length){
		// Settings are all the same
		var flashvars = {};
		var flashparams = { wmode: "transparent" };
		var flashatts = {};
		
		// If the full animation hasn't been seen, show it
		var introAnim = $.cookie('introAnim2');
		if ((introAnim == null) || (!introAnim.length)) {
			// GA:
			trackEvent("Flash", "View", "Homepage Animation Full");
			
			swfobject.embedSWF("/Media/Flash/ABCintro.swf", "intro", "620", "320", "9.0.0", false, flashvars, flashparams, flashatts, null);
			$.cookie("introAnim2", "seenIt", { path: '/' });
		}
		// Otherwise show the shorter, alternate version
		else {
			// GA:
			trackEvent("Flash", "View", "Homepage Animation Short");
			swfobject.embedSWF("/Media/Flash/ABCintro-Alt.swf", "intro", "620", "320", "9.0.0", false, flashvars, flashparams, flashatts, null);
		}
	}
}

function getTweets() {
	$("#tweet").tweet({
		username: "abcadvertising",
		join_text: "auto",
		avatar_size: 32,
		count: 1,
		auto_join_text_default: "",
		auto_join_text_ed: "",
		auto_join_text_ing: "",
		auto_join_text_reply: "",
		auto_join_text_url: "",
		loading_text: "Loading latest tweet..."
	});
}

function getTweetsByUsername(userName) {
	$("#twitter-" + userName).tweet({
		username: userName,
		join_text: "auto",
		avatar_size: 32,
		count: 1,
		auto_join_text_default: "",
		auto_join_text_ed: "",
		auto_join_text_ing: "",
		auto_join_text_reply: "",
		auto_join_text_url: "",
		loading_text: "Loading latest tweet..."
	});
}

function getBlogPosts() {
	jQuery.getFeed({
		url: '/Utilities/Proxy.ashx?url=http://blog.a-b-c.com/feed',
		success: function(feed) {
			var text = "<h4><img src='/Media/Images/blog-lamp?width=75' style='float: right;' />&amp; Another Thing (Blog)</h4>";
			for (var i = 0; i < feed.items.length && i < 1; i++) {
				text += "<h5>" + feed.items[i].title + "</h5>";
				text += "<p>" + feed.items[i].description + "</p>";
				text += "<p><a href='" + feed.items[i].link + "'>Read at blog.a-b-c.com</a></p>";
				$("#blogpost").html(text);
			}

		}
	});
}

function initWindowShade() {
	var animLength = 250;

	// Set up the window shade for e-mail updates
	$("p.open-close a", "#shade").toggle(
		function() {
			// GA:
			trackEvent("E-News", "Shade", "Open");
		
			$("#shade").addClass("active").animate({ top: "-90px" }, animLength, "easeOutBack");
			$(this).find("span").text("Close");
		},
		function() {
			// GA:
			trackEvent("E-News", "Shade", "Close");
			
			$("#shade").removeClass("active").animate({ top: "-172px" }, animLength, "easeInBack");
			setTimeout(function() {
				$("#shade").find("p.open-close span").text("Stay in touch with e-mail updates.")
			}, animLength);
		}
	);
}

/** Team Functions **/

function addTweetsToTeamMember(userName) {
	if ($(".individual-twitter", "#thumb-" + userName).length > 0){
		var twitterUN = $(".individual-twitter", "#thumb-" + userName).attr("id").match(/-(.+)/)[1];
		if (twitterUN.length > 1) {
			getTweetsByUsername(twitterUN);
		}
	}
}

function initTeam() {
	// Highlight questions when hovering over headshots
	$("li", "#team-headshots").hoverIntent(function() {
		var username = $(this).attr("id").match(/-(.+)/)[1];
		
		// GA:
		trackEvent("Team", "Headshot Hover", username);
			
		$("a", "#team-questions").removeClass("active");
		var question = $("a:first", "#question-" + username);
		question.addClass("active");
		question.parents().filter("li").highlightFade({ color: "#AFAC74", speed: 1000 });
		$(".txt-area:first").stop().scrollTo(question, 250, { easing: "swing", offset: -75 });
	}, function() {
		// null
	});

	// Hook up light box to headshots
	$("li a[rel='team']", "#team-headshots").each(function() {
		var username = $(this).parents("li").attr("id").match(/-(.+)/)[1];
		var path = "/Team/" + username;
		$(this).colorbox({ onComplete: function() { addTweetsToTeamMember(username); trackPageview(path); }, initialWidth: 300, initialHeight: 300, width: 600, height: 340, current: 'Team member {current} of {total}.', rel: 'team', html: "<div class='team-bio'>" + $("#" + $(this).parents("li").attr("id").replace("thumb-", "content-")).html() + "</div>", opacity: 0.1 });
	});

	// Hook up events to questions
	$("li a", "#team-questions").click(function() {
			var username = $(this).parents().filter("li:first").attr("id").match(/-(.+)/)[1];
			trackPageview("/Team/" + username);
			$("a:first", "#thumb-" + username).click();
		}).hoverIntent(function() {
			var username = $(this).parents().filter("li:first").attr("id").match(/-(.+)/)[1];
			trackEvent("Team", "Question Hover", username);
			$("img", "#team-headshots").removeClass("active");
			$("img", "#thumb-" + username).addClass("active");
		}, function() {
	});

	// Clear active state on questions
	$("li", "#team-questions").hover(function() {
		$("a", "#team-questions").removeClass("active");
	});

	// Scroll up
	$("#arrow-prev").click(function() {
		$(".txt-area:first").scrollTo({ top: '-=345px', left: '0px' }, 250, { easing: "swing" });
		return false;
	});

	// Scroll down
	$("#arrow-next").click(function() {
		$(".txt-area:first").scrollTo({ top: '+=345px', left: '0px' }, 250, { easing: "swing" });
		return false;
	});
}

function initMenuDropDowns() {
	$('li ul', '#nav').hide().parents('li').find('a:first').click(function(event) {
		event.preventDefault();
		//$('li ul', '#nav').slideUp();
		$(this).parents('li').find('ul').slideDown();
	});

	$('#nav li a[href="/Contact"]').parents('li').find('ul li:first').before('<li><a href="/Contact">Let\'s Talk</a></li>');

	$('#nav li a[href="/Healthcare"]').parents('li').css({marginTop: '20px'});
}

function initMenuSizeChanger() {
	// Main Nav
	$("li ul li", "#nav").hover(function() {
		if (!$(this).hasClass("active")) {
			$(this).stop().css("fontSize", "12px").animate({ fontSize: "16px" }, 100);
		}
	}, function() {
		$(this).stop().animate({ fontSize: "12px" }, 100);
	});

	$("#nav > li").hover(function() {
		if (!$(this).hasClass("active")) {
			$(this).stop().css("fontSize", "15px").animate({ fontSize: "22px" }, 100);
		}
	}, function() {
		$(this).stop().animate({ fontSize: "15px" }, 100);
	});

	// Sub Nav
	$("#side-nav > li").hover(function() {
		if (!$(this).hasClass("active")) {
			$(this).stop().css("fontSize", "12px").animate({ fontSize: "18px" }, 100);
		}
	}, function() {
		$(this).stop().animate({ fontSize: "12px" }, 100);
	});

	$("li ul li", "#side-nav").hover(function() {
		if (!$(this).hasClass("active")) {
			$(this).stop().css("fontSize", "12px").animate({ fontSize: "14px" }, 100);
		}
	}, function() {
		$(this).stop().animate({ fontSize: "12px" }, 100);
	});
}

function initSlide() {
	var _holder = $(".slider");
	var _itemClass = "slide-block";
	var _slideClass = "block";
	var _durOut = 500;
	var _durIn = 150;

	_holder.each(function() {
		var _item = $(this).find("." + _itemClass);
		_item.not(".active").find("." + _slideClass).slideUp(0);
		_item.each(function() {
			var _link = $(this).find("a.open-close");
			_link.click(function() {
				if (!$(this).parents("." + _itemClass).hasClass("active")) {
					_item.each(function() {
						$(this).removeClass("active");
						$(this).find("." + _slideClass).slideUp({ duration: _durIn, easing: "swing" });
					});
					$(this).addClass("selected");
					$(this).parents("." + _itemClass).addClass("active");
					$(this).parents("." + _itemClass).find("." + _slideClass).slideDown({ duration: _durOut, easing: "easeOutBack" });
					trackEvent("Portfolio", "Filter Open", _link.text());
				};
				return false;
			});
		})
	});
}

function embedVideo(videoURL, previewContainer) {
	if (videoURL.indexOf('youtube') >= 0) {
		var videoID = videoURL.match(/watch\?v=(.+)+/)[1].replace(" ", "");
		var content = '<div id="youtube-embed-' + videoID + '">You need Flash player 8+ to view this video.</div>';
		$(previewContainer).html(content);
		var params = { allowScriptAccess: 'always' };
		var attrs = { id: 'ytplayer-' + videoID };
		swfobject.embedSWF('http://www.youtube.com/v/' + videoID + '?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer-' + videoID, 'youtube-embed-' + videoID, '530', '319', '8', null, null, params, attrs);
		// Stop the click event from propagating so Mac browsers don't advance the slides when the video area is clicked
		$(previewContainer).click(function(e) {
			e.stopImmediatePropagation();
		});
	}
}

function onYouTubePlayerReady(playerId){
	window.players.push(playerId);
}

function embedAudio(audioURL, previewContainer, width, height) {
	try {
		previewContainer = $(previewContainer);
		var pcID = previewContainer.attr('id');
		var audioID = "player-" + pcID;
		var content = $('<div id="audio-embed-' + audioID + '">You need Flash player 8+ to listen to this audio.</div>');
		previewContainer.replaceWith(content); //content.replaceAll(previewContainer);//previewContainer.html(content);
		var params = { allowScriptAccess: 'always', allowfullScreen: 'false' };
		var attrs = { id: pcID };
		var vars = { soundFile: audioURL, playerID: "plyr-" + pcID };
		swfobject.embedSWF('/Media/Flash/player.swf', 'audio-embed-' + audioID, width, height, '8', null, vars, params, attrs);
		// Stop the click event from propagating so Mac browsers don't advance the slides when the audio player is clicked
		$(previewContainer).click(function(e) {
			e.stopImmediatePropagation();
		});
	}
	catch(e){}
}

function setupLinkTracking() {
	$("a[href^='mailto:']").each(function() {
		$(this).click(function() {
			var href = $(this).attr("href");
			trackEvent("Links", "Contact", href);
		});
	});
}

/**
 *  Plugin which is applied on a list of img objects and calls
 *  the specified callback function, only when all of them are loaded (or errored).
 *  @author:  H. Yankov (hristo.yankov at gmail dot com)
 *  @version: 1.0.0 (Feb/22/2010)
 *	http://yankov.us
 */

(function($) {
$.fn.batchImageLoad = function(options) {
	var images = $(this);
	var originalTotalImagesCount = images.size();
	var totalImagesCount = originalTotalImagesCount;
	var elementsLoaded = 0;

	// Init
	$.fn.batchImageLoad.defaults = {
		loadingCompleteCallback: null, 
		imageLoadedCallback: null
	}
	var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
		
	// Start
	images.each(function() {
		// The image has already been loaded (cached)
		if ($(this)[0].complete) {
			totalImagesCount--;
			if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
		// The image is loading, so attach the listener
		} else {
			$(this).load(function() {
				elementsLoaded++;
				
				if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);

				// An image has been loaded
				if (elementsLoaded >= totalImagesCount)
					if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
			});
			$(this).error(function() {
				elementsLoaded++;
				
				if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
					
				// The image has errored
				if (elementsLoaded >= totalImagesCount)
					if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
			});
		}
	});

	// There are no unloaded images
	if (totalImagesCount <= 0)
		if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);

jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
	random: function(a, i, m, r) {
		if (i == 0) {
			jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
		};
		return i == jQuery.jQueryRandom;
	}
});
