////////////////////////////////
// On screen debug logger
////////////////////////////////
var x = 0, debug = false, d = function(msg) {
	if (debug == true) {
		x++;
		$("#log").css("display", "block").prepend("<div class=\"dmsg\">[" + x + "] " + msg + "</div>");
		$("#log .log-menu #log-clear").live("click", function(evt) { $("#log .dmsg").remove(); });
	} else { if ($("#log").length > 0) { $("#log").remove(); } }
}
////////////////////////////////
////////////////////////////////

var sectionObj = { "sections": [
	{ "section": "Home", "basepath": "/", "bgpos": "-2212px" }, 
	{ "section": "Company", "basepath": "/company/", "bgpos": "-1526px" }, 
	{ "section": "Portfolio", "basepath": "/portfolio/", "bgpos": "-900px" }, 
	{ "section": "News", "basepath": "/news/", "bgpos": "72px" }, 
	{ "section": "Lab", "basepath": "/lab/", "bgpos": "-3945px" }, 
	{ "section": "Contact", "basepath": "/contact/", "bgpos": "-3152px" }
]};

var loader = "<div id=\"loader\"><div class=\"overlay\"></div></div>";
var prevScrollTop = 0;
var loaderInDuration = 300;
var loaderOutDuration = 600;
var contentInDuration = 600;
var contentOutDuration = 600;
var player = null;
var flashObj;
var flashVersion = "10.0";
var enableFlash = true;
var currSection = getSection();
var prevSection = null;
var introPage = sectionObj.sections[currSection].section.toLowerCase();
var browserVersion = parseInt($.browser.version, 10);
var dHostname = getHostname();
var dLocation = getLocation();
var dHref = getHref();
var dPathname = getPathname();
var projectSlides = null;
var memberSlides = null;
var video;

$(document).ready(function() {
	
	if (DetectIphoneOrIpod() || DetectIpad() || DetectAndroidPhone()) {
		$("body").css("height", "100%");
	}
	
	$(window).bind("resize", function(evt) {
		$(".newsletter-msg").css("left", (($(window).width()/2)+160)+"px");
		if (enableFlash == false) { scrollBG(getSection()); }
	});
	$(window).bind("scroll", function(evt) { if (enableFlash == false) { scrollCheck(); } });
	
	/* HTML 5 history state */
	(function(window,undefined){
		var History = window.History, State = History.getState(), $log = $("#log");
		
		if (!History.enabled) {
			// HTML4 State change
			d("[HISTORY] Not Enabled");
			// check for hashchange event
			$(window).hashchange(function() {
				//if (window.console && window.console.log) { console.log("[EVENT] Hashchange"); }
				d("[EVENT] Hashchange");
				var hash = window.location.hash;
				loadContent(hash);
			});
			return false;
		}
		// HTML5 State change
		d("[HISTORY] Enabled");
		d("[History.getState] Initial:", State.data, State.title, State.url);
		
		// bind to state Change
		History.Adapter.bind(window, "statechange", function(){ 
			// log the state
			var State = History.getState();
			//if (window.console && window.console.info) { console.info("[EVENT] STATECHAGE\nState.data: "+State.data.toString()+"\nState.title: "+State.title+"\nState.url: "+State.url); }
			d("[EVENT] STATECHAGE\nState.data: "+State.data.toString()+"\nState.title: "+State.title+"\nState.url: "+State.url);
			// load resource state
			var loadMe = State.url;
			loadMe = loadMe.replace("http://www.neo-pangea.com", "");
			d("loadMe(" + loadMe + ")");
			loadContent(loadMe);
		});

	})(window);

	
	fixIE();
	init();

	
	// main nav/base nav event handler
	$(".main-nav a, .base-nav a").live("click", function(evt) {
		evt.preventDefault();
		//if (window.console && window.console.log) { console.log("[EVENT] CLICK\n->mainnav->basenav"); }
		d("[EVENT] CLICK\n->mainnav->basenav");
		
		var href = $(this).attr("href");
		var title = $(this).attr("title");
		var index = $(this).index();
		
		prevSection = sectionObj.sections[getSection()].section.toLowerCase();
		routeRequest($(this), null, "Neo-Pangea : "+title, href);

		return false;
	});
	
	// content link(s) event handler
	$("#content a[target!='_blank']").live("click", function(evt) {
		evt.preventDefault();
		//if (window.console && window.console.log) { console.log("[EVENT] CLICK\n->contentlink->!_blank"); }
		d("[EVENT] CLICK\n->contentlink->!_blank");
		
		var href = $(this).attr("href");
		var title = $(this).attr("title");
		var rel = $(this).attr("rel");
		var index = $(this).index();
		
		if (rel == "email") {
			if (window.console && window.console.log) { console.log("[EVENT] CLICK\n->contentlink->mailto"); }
			document.location = href;
			return false;
		} else {
			// ensure link is not voided
			if (href != "javascript:void(0);") {
				prevSection = sectionObj.sections[getSection()].section.toLowerCase();
				routeRequest($(this), null, "Neo-Pangea : "+title, href);
				return false;
			}
		}
	});
	
	// scale thumbnail
	$(".thumb.scale").live("hover", function(evt) {
		$(this).toggleClass("scale-over");
	});
	
	// scale thumbnail on related link hover
	$(".info .cta a").live("hover", function(evt) {
		$(this).parent().parent().parent().parent().find("div.thumb").toggleClass("scale-over");
	});
	
	// mailing list subscribe widget submit handler
	$("#frmNewsletter input[name='submit']").live("click", function(evt) {
		evt.preventDefault();
		var email = $("#frmNewsletter input[name='emailaddress']").val();
		var listId = $("#frmNewsletter input[name='listID']").val();
		var doUpdate = $("#frmNewsletter input[name='doUpdate']").val();
		
		if (email) {
			var dataString = "listID="+listId+"&emailaddress="+email+"&firstname=&lastname=&doUpdate="+doUpdate;
			$.ajax({
				type: "POST", 
				url: "/assets/scripts/subscribe.php", 
				data: dataString, 
				dataType: "json", 
				success: function(data) {
					$("#frmNewsletter input[name='emailaddress']").val("");
					var status = data.response.status;
					var msg = data.response.message;
					$(".newsletter-msg").css("left", (($(window).width()/2)+160)+"px");
					$(".newsletter-msg span").empty().text(msg);
					$(".newsletter-msg").animate({
						top: "66px", 
						opacity: 1.0
					}, 420, "easeInOutQuad", function() {
						setTimeout(function() {
							$(".newsletter-msg").animate({
								top: "-55px", 
								opacity: 0.0
							}, 420);
						}, 8000);
					});
				}
			});
		} else {
			return false;
		}
	});
	
	// mailing list subscribe page submit handler
	$("#subscription input[name='submit']").live("click", function(evt) {
		evt.preventDefault();
		
		var email = $("#subscription input[name='emailaddress']").val();
		var fname = $("#subscription input[name='firstname']").val();
		var lname = $("#subscription input[name='lastname']").val();
		var listId = $("#subscription input[name='listID']").val();
		var doUpdate = $("#subscription input[name='doUpdate']").val();
		
		if (email) {
			var dataString = "listID="+listId+"&emailaddress="+email+"&firstname="+fname+"&lastname="+lname+"&doUpdate="+doUpdate;
			$.ajax({
				type: "POST", 
				url: "/assets/scripts/subscribe.php", 
				data: dataString, 
				dataType: "json"
			});
		} else { return false; }
	});
	
	// mailing list unsubscribe page submit handler
	$("#unsubscribe input[name='submit']").live("click", function(evt) {
		evt.preventDefault();
		var email = $("#unsubscribe input[name='emailaddress']").val();
		var listId = $("#unsubscribe input[name='listID']").val();
		var doUpdate = $("#unsubscribe input[name='doUpdate']").val();
		
		if (email) {
			var dataString = "listID="+listId+"&emailaddress="+email+"&doUpdate="+doUpdate;
			$.ajax({
				type: "POST", 
				url: "/assets/scripts/unsubscribe.php", 
				data: dataString, 
				dataType: "json"
			});
		} else { return false; }
	});
	
	// portfolio filters bar
	$("#portfolio-filter .filters a").live("click", function(evt) {
		$("#portfolio-filter .filters a").removeClass("active");
		$(this).addClass("active");
	});

});


function init() {
	// enable flash BG based on if NOT a smartphone, OR NOT able to perform, OR NOT disabled by var
	enableFlash = (DetectIphoneOrIpod() || DetectIpad() || DetectAndroidPhone() || (parseInt(perf) > perfLimit) || (enableFlash == false)) ? false : true;
	// bring in main header & fire up the rest
	bringInHeader();
	
	$(".newsletter-msg").css("left", (($(window).width()/2)+160)+"px");
	
	// check for flash scene content, animate appropriate element
	if (enableFlash == true) {
		d("{bringInHeader} Flash Enabled->TRUE [flashcontent]");
		
		// remove background image, set color
		$("body").css("background", "none").css("background-color", "#000000");
		//if (window.console && window.console.log) { console.log("SECTION: "+sectionObj.sections[getSection()].section.toLowerCase().toString()); }
		
		// check if flash is installed
		if (swfobject.hasFlashPlayerVersion(flashVersion)) {
			var s = sectionObj.sections[getSection()].section.toLowerCase().toString();
			if (!s) { s = sectionObj.sections[0].section.toLowerCase().toString(); }
			initFlashScene(s);
		} else {
			enableFlash = false;
			d("{bringInHeader} Flash Enabled->FALSE [bgimage]");
			// remove scene
			$("#flashcontent").remove();
			// add background image
			$("body").css("background", "url('/assets/images/fpo-scene-bg.jpg') no-repeat fixed 50% "+sectionObj.sections[getSection()].bgpos+" #000000");
			// scroll to requested section
			scrollBG(getSection(), true, "init 1");
			fixIPosition();
		}
	} else {
		d("{bringInHeader} Flash Enabled->FALSE [bgimage]");
		// remove scene
		$("#flashcontent").remove();
		// add background image
		$("body").css("background", "url('/assets/images/fpo-scene-bg.jpg') no-repeat fixed 50% "+sectionObj.sections[getSection()].bgpos+" #000000");
		//scrollBG(getSection(), true, "init 2");
		//showContent("{init}");
		fixIPosition();
	}

}

/* ROUTE REQUEST */
function routeRequest(el, data, title, href) {
	if ($.browser.msie && parseInt($.browser.version, 10) < 9) {
		d("{routeRequest} trigger->loadContent()->setHash() 'IE" + browserVersion + " based browser detected... C'mon Man!'");
		d("href:" + href);
		loadContent(href);
		setHTML4Hash(el, title);
	} else {
		d("{routeRequest} tigger->History.pushState() 'Nice! At least you're smart enough to use a real modern browser!'");
		History.clearQueue();
		History.pushState(null, title, href);
	}
}

/* LOAD CONTENT */
function loadContent(path, fromInit) {
	var doc = path + " #content";
	if (window.console && window.console.info) { console.info("LOADING CONTENT\ndoc: " + doc + " [" + fromInit + "]"); }
	d("[LOADING CONTENT]<br />doc: "+doc);
	
	scrollWindow();
	showLoader();

	$("#content").fadeOut(contentOutDuration, function() {
		$("#page").load(doc, "", function() { 
			if (window.console && window.console.info) { console.info("CONTENT LOADED"); }
			d("[CONTENT LOADED]");

			if (enableFlash == true && swfobject.hasFlashPlayerVersion(flashVersion)) {
				//if (window.console && window.console.info) { console.info("[TRANSITION] flash"); }
				//if (window.console && window.console.info) { console.info("flashObj->loadPage('" + sectionObj.sections[getSection()].section.toLowerCase() + "')")"); }
				d("[TRANSITION] flash");
				d("flashObj->loadPage('" + sectionObj.sections[getSection()].section.toLowerCase() + "')");
				flashObj = swfobject.getObjectById("flashcontent");//getFlashObject("flashcontent");
				flashObj.loadPage(sectionObj.sections[getSection()].section.toLowerCase().toString());
			} else {
				hideLoader();
				//if (window.console && window.console.info) { console.info("[TRANSITION] background image"); }
				d("[TRANSITION] background image");
				scrollBG(getSection(), true, "loadContent");
			}
			
			//setTitle();
			updateNav(sectionObj.sections[getSection()].section);
			
			// track pageview in GA
			_gaq.push(["_trackPageview", path]);
		});
	}).css("display", "none");
}

/* SHOW CONTENT */
function showContent(where) {
	hideLoader();
	
	if (window.console && window.console.info) { console.info("SHOWING CONTENT [" + where + "]" ); }
	
	d("SHOWING CONTENT [" + where + "]");
	$("#content").fadeIn(contentInDuration, function() {
		// init captionize
		$(".caption").captionize();
		
		// init lightbox
		$(".lightbox").lightBox({
			overlayBgColor: "#000000", 
			overlayOpacity: 0.7, 
			imageLoading: "/assets/images/np-loading.png", 
			imageBtnClose: "/assets/js/plugins/lightbox/images/lightbox-btn-close.png", 
			imageBtnPrev: "/assets/js/plugins/lightbox/images/lightbox-btn-prev.png", 
			imageBtnNext: "/assets/js/plugins/lightbox/images/lightbox-btn-next.png", 
			imageBlank: "/assets/js/plugins/lightbox/images/lightbox-blank.gif"
		});
		
		// force Facebook plugin parsing if object found
		if (typeof FB  != "undefined"){
			FB.XFBML.parse();
		}
		
		// office slideshow
		if ($("#office-slideshow").length > 0) {
			initOfficeSlides();
		}
		
		// member slides 
		if ($(".team-members").length > 0) {
			initMemberSlides();
		}
		
		// portfolio feature slides 
		if ($("#portfolio-feature .feature-media").length > 0) {
			initFeatureSlides();
		}
		
		// portfolio detail slides
		if ($(".portfolio-post .portfolio-media .media").length > 0) {
			initProjectSlides();
		}
		
		// portfolio wall
		if ($("#portfolio-items").length > 0) {
			// kill right margin on every 3rd line item (end of row)
			$("#portfolio-items li:nth-child(3n)").css("margin-right", "0px");
			// enable cycle slides
			initLandingSlides();
		}
		
		if ($("#portfolio-filter .filters").length > 0) {
			var qs = getQueryString()["category"];

			$("#portfolio-filter .filters a").removeClass("active");
			
			if (qs) {
				//if (window.console && window.console.log) { console.log("qs exists: "+qs); }
				$("#portfolio-filter .filters a[rel='"+qs+"']").addClass("active");
			} else {
				//if (window.console && window.console.log) { console.log("qs does not exist: "+qs); }
				$("#portfolio-filter .filters a[rel='all']").addClass("active");
			}
		}
		
		// featured germinations
		if ($(".germinations .items").length > 0) {
			// kill right margin on every 3rd line item (end of row)
			//$(".germinations .items li:nth-child(3n)").css("margin-right", "0px");
			// enable cycle slides
			initHomeSlides();
		}
		
		$(".video-poster a").live("click", function(evt) {
			if (!DetectIphoneOrIpod() && !DetectIpad()) {
				evt.preventDefault();
				$(this).parent().css("display", "none");
				
				video = $(this).parent().parent().find(".video-player object").get(0);
				video.play2();
			}
		});
		
		// set rel attr on email links
		$("a[href^='mailto:']").attr("rel", "email");
		
		// init addThis (work around for ajax control reinit)
		var script = "http://s7.addthis.com/js/250/addthis_widget.js#domready=1";
		if (window.addthis) { window.addthis = null; }
		$.getScript(script);
		
		fixIHeight();
		
	}).css("display", "block");
}

/* UPADTE ACTIVE NAV */
function updateNav(section) {
	$(".main-nav a, .base-nav li").removeClass("active");
	$(".main-nav a[title='" + section + "']").addClass("active");
	$(".base-nav a[title='" + section + "']").parent().addClass("active");
}


/* FLASH SCENE */
function initFlashScene(introPage) {
	
	if ($("#flashcontent").length == 0) {
		$("#flashscene").append("<div id=\"flashcontent\"></div>");
	}
	
	d("{initFlashScene} ["+introPage+"]");
	
	var flashvars = {
		loadersXml: "/assets/xml/loaders.xml",
		estimatedBytes: "999999",
		page: introPage
	};
	
	if (swfobject.getQueryParamValue("estimatedBytes")){
		flashvars.estimatedBytes = swfobject.getQueryParamValue("estimatedBytes");
	}
	
	var params = {
		menu: "false", 
		quality: "high", 
		wmode: "opaque", 
		bgcolor: "#000000", 
		allowscriptaccess: "always", 
		salign: "t", 
		align: "t"
	};
	
	var attributes = {
		id: "flashcontent", 
		name: "flashcontent"
	};

	swfobject.embedSWF("/assets/swf/preloader.swf", "flashcontent", "100%", "100%", "10.0.0", "/assets/js/swfobject/expressInstall.swf", flashvars, params, attributes);
	
	flashObj = swfobject.getObjectById("flashcontent");//getFlashObject("flashcontent");
	/*
	var hash = window.location.hash;
	var href = window.location.href;
	if (hash) {
		if (window.console && window.console.info) { console.info("{initFlashScene} hash found: "+hash); }
		d("{initFlashScene} hash found: "+hash);
		loadContent(hash.replace("#", ""));
	}*/
}

/* FLASH SCENE CALLBACKS */
function transitionComplete() {
	if (window.console && window.console.info) { console.info("[CALLBACK] transitionComplete called from flash"); }
	d("[CALLBACK] transitionComplete called from flash");
	showContent("{transitionComplete->flash}");
}
function transitionStart() {
	if (window.console && window.console.info) { console.info("[CALLBACK] transitionStart called from flash"); }
	d("[CALLBACK] transitionStart called from flash");
	hideLoader();
}

/* COMPANY PAGE TEAM SLIDES */
function initMemberSlides() {
	memberSlides = $(".team-members").cycle("destroy").cycle({
		fx: "fade", 
		timeout: 16000, 
		delay: -500,  
		speedIn: 1500, 
		speedOut: 600,
		slideExpr: "div.team-member", 
		cleartype: !$.support.opacity, 
		cleartypeNoBg: true, 
		pause: 1, 
		sync: 0, 
		pauseOnPagerHover: 1, 
		pager: $(".team-slide-nav ul"), 
		pagerAnchorBuilder: function(idx, slide) {
			// return sel string for existing anchor
			return ".team-slide-nav ul li:eq(" + (idx) + ")";
		}
	});
	// enable keyboard control of slideshow
	$(document).bind("keypress", function(evt) {
		switch(evt.keyCode) {
			case 37:
				memberSlides.cycle("prev");
			break;
			case 39: 
				memberSlides.cycle("next");
			break;
		}
	});
}

/* CONTACT PAGE MINI MAP */
function initMiniMap(targetEl, lat, lng, zoom) {
	// create map
	var latlng = new google.maps.LatLng(lat, lng);
	var mapOptions = {
		zoom: zoom, 
		center: latlng, 
		disableDefaultUI: true,
		mapTypeId: google.maps.MapTypeId.TERRAIN
	};
	var map = new google.maps.Map(document.getElementById(targetEl), mapOptions);
	
	// style map
	var style = [{ stylers: [{ hue: "#ffaa00" }, { saturation: 12}] }];
	var styleOptions = {
		map: map, 
		name: "nmap"
	};
	var styledMap = new google.maps.StyledMapType(style, styleOptions);
	map.mapTypes.set("neomap", styledMap);
	map.setMapTypeId("neomap");
	
	// drop it like it's hot
	var image = new google.maps.MarkerImage("/assets/images/np-cropper.png",
		new google.maps.Size(34.0, 34.0),
		new google.maps.Point(0, 0),
		new google.maps.Point(17.0, 17.0)
	);
	var shadow = new google.maps.MarkerImage("/assets/images/np-cropper-shadow.png",
		new google.maps.Size(52.0, 34.0),
		new google.maps.Point(0, 0),
		new google.maps.Point(17.0, 17.0)
	);
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		icon: image,
		shadow: shadow
	});
}

/* CONTACT PAGE OFFICE SLIDES */
function initOfficeSlides() {
	$("#office-slideshow").cycle("destroy").cycle({
		fx: "fade", 
		timeout: 6000, 
		delay: -500, 
		speedIn: 1500, 
		speedOut: 2000, 
		slideExpr: "img", 
		pager: $(".media-nav ul"), 
		pagerChild: "li", 
		pauseOnPagerHover: 1, 
		pagerAnchorBuilder: function(idx, slide) {
			var sld = $(slide);
			var vid = false;
			var label = "";
			
			// inject video label if video exists and has not been added previously
			if (sld.hasClass("video-js-box") && vid === false) {
				label = "<span class=\"label\">Videos:</span>";
				vid = true;
			} else {
				label = "";
				vid = false;
			}

			// return sel string for existing anchor
			return label+"<li><a href=\"javascript:void(0);\"></a></li>";
		}
	});
	// enable keyboard control of slideshow
	$(document).bind("keypress", function(evt) {
		switch(evt.keyCode) {
			case 37:
				$("#office-slideshow").cycle("prev");
			break;
			case 39: 
				$("#office-slideshow").cycle("next");
			break;
		}
	});
}

/* PORTFOLIO LANDING PAGE FEATURE SLIDES */
function initFeatureSlides() {
	//if (window.console && window.console.log) { console.log(title, client, url, urltext); }
	$("#portfolio-feature .feature-media").cycle("destroy");
	var featureSlides = $("#portfolio-feature .feature-media").cycle("destroy").cycle({
		activePagerClass: "activeFeature", 
		fx: "fade", 
		timeout: 6000, 
		speedIn: 800, 
		speedOut: 1200, 
		slideExpr: "div.item", 
		next: $(".feature-nav-next a"), 
		prev: (".feature-nav-prev a"),
		sync: 1
	});
	// enable keyboard control of slideshow
	$(document).bind("keypress", function(evt) {
		switch(evt.keyCode) {
			case 37:
				featureSlides.cycle("prev");
			break;
			case 39: 
				featureSlides.cycle("next");
			break;
		}
	});
}

/* HOME PAGE */
function initHomeSlides() {
	$(".germinations .items .thumb").each(function() {
		var $this = $(this);
		$this.cycle("destroy").cycle({
			fx: "fade", 
			delay: 1500, 
			speed: 3000, 
			timeout: 5500,
			speedOut: 2000, 
			easing: "easeInOutQuad", 
			slideExpr: ".images img", 
			pause: 1, 
			sync: 1
		});
	});
}

/* PORTFOLIO LANDING PAGE THUMB SLIDES */
function initLandingSlides() {
	$("#portfolio-items .thumb").each(function() {
		var $this = $(this);
		$this.cycle("destroy").cycle({
			fx: "fade", 
			timeout: 2400, 
			speedIn: 600, 
			speedOut: 1200,
			easing: "easeInOutQuad", 
			slideExpr: ".images img", 
			sync: 1
		}).cycle("pause").live("mouseenter mouseleave", function(evt) {
			if (evt.type == "mouseenter") {
				$this.cycle("resume");
			} else {
				$this.cycle("pause");
			}
		});
		
		// enable cycle resume/pause on link hover
		$this.parent().find(".cta a").live("mouseenter mouseleave", function(evt) {
			if (evt.type == "mouseenter") {
				$this.cycle("resume");
			} else {
				$this.cycle("pause");
			}
		});
	});
}


/* PORTFOLIO DETAIL PAGE SLIDES */
function initProjectSlides() {
	var vid = false;
	player = null;
	var label = "";

	var projectSlides = $(".portfolio-post .portfolio-media .media").cycle("destroy").cycle({
		fx: "fade", 
		timeout: 6000, 
		delay: -500,  
		speedIn: 1500, 
		speedOut: 2000,
		sync: 1, 
		cssBefore: {
			display: "block", 
			visibility: "visible"
		}, 
		cssAfter: {
			display: "block", 
			visibility: "hidden"
		},
		pager: $(".portfolio-post .portfolio-media .media-nav ul"), 
		pagerChild: "li", 
		pagerAnchorBuilder: function(idx, slide) {
			var sld = $(slide);
			
			// inject video label if video exists and has not been added previously
			if (sld.hasClass("video-wrapper") && vid == false) {
				label = "<span class=\"label\"> ~ Videos:</span>";
				vid = true;
			} else {
				label = "";
			}

			// return sel string for existing anchor
			return label+"<li><a href=\"javascript:void(0);\"></a></li>";
		}, 
		onPagerEvent: function() {
			if (player && player != null) {
				var state = player.getState();
				if (state == "playing") {
					player.pause();
					$(".portfolio-post .portfolio-media .media").cycle("resume");
				}
			}
		}
	});
	
	// enable keyboard control of slideshow
	$(document).bind("keypress", function(evt) {
		switch(evt.keyCode) {
			case 37:
				$(".portfolio-post .portfolio-media .media").cycle("prev");
			break;
			case 39: 
				$(".portfolio-post .portfolio-media .media").cycle("next");
			break;
		}
	});
	// pause slides if video is clicked
	$(".video-js-box, .portfolio-media .media, .media object").live("click mousedown", function(evt) {
		//if (window.console && window.console.log) { console.log("I should be pausing right now..."); }
		$(".portfolio-post .portfolio-media .media").cycle("pause");
		projectSlides.cycle("pause");
	});
	
	// resume slides if video playback ended
	$("video.video-js").bind("ended onended", function(evt) {
		if (window.console && window.console.log) { console.log("Video has ended..."); }
		document.getElementById($(this).attr("id")).pause();
		document.getElementById($(this).attr("id")).currentTime = 0.1;
		
		$(".portfolio-post .portfolio-media .media").cycle("resume");
		projectSlides.cycle("resume");
		return false;
	});

	
}

/* SCROLL ANIMATIONS */
function scrollCheck() {
	var scrollTop = $(window).scrollTop();
	var currBGPos;
	var browserVersion = parseInt($.browser.version, 10);

	if ($.browser.msie && (browserVersion == 8 || browserVersion == 7)) {
		currBGPos = $("body").css("backgroundPositionX") + " " + $("body").css("backgroundPositionY");
	} else {
		currBGPos = $("body").css("background-position");
	}

	currBGPos = currBGPos.split(" ");
	var currBGPosX = currBGPos[0];
	currBGPosX = currBGPosX.replace("px", "").replace("%", "");
	var currBGPosY = currBGPos[1];
	currBGPosY = currBGPosY.replace("px", "").replace("%", "");
	
	if (scrollTop > prevScrollTop){
		$("body").stop().animate({ backgroundPosition: "50% " + (parseInt(currBGPosY)+6) + "px" }, 600);
	} else {
		$("body").stop().animate({ backgroundPosition: "50% " + (parseInt(currBGPosY)-6) + "px" }, 600);
	}
	
	prevScrollTop = scrollTop;
}

function scrollWindow(x, y) {
	$(window).scrollTop(0);
}

function scrollBG(pos, oninit, callee) {
	$("body").animate({ 
		backgroundPosition: "50% "+sectionObj.sections[pos].bgpos 
	}, 2020, "easeInOutQuad", function() {
		if ($("#content").css("display") == "none" || callee == "init 1" || callee == "init 2") {
			showContent("{scrollBG} -> " + callee);
		}
	});
}

function calcImageCenter() {
	var imageWidth = 1280;
	var windowWidth = $(window).width();
	var imageMargin = (windowWidth - imageWidth) / 2;
	if (window.console && window.console.log) { console.log("imageMargin: " + imageMargin); }
	return imageMargin;
}

function bringInHeader() {
	$("#header").delay(250).animate({top: "0px", opacity: 1.0}, 1420, "easeInBack", function() {
		var hash = window.location.hash;
		var href = window.location.href;
		if (hash != "") {
			loadContent(hash.replace("#", ""), true);
		} else {
			loadContent(href, true);
		}
	});
}


function getSection() {
	var currPath = getHref();//getPathname();
	if (currPath.search(/company/i) != -1) { return 1;
	} else if (currPath.search(/portfolio/i) != -1) { return 2;
	} else if (currPath.search(/news/i) != -1) { return 3;
	} else if (currPath.search(/lab/i) != -1) { return 4;
	} else if (currPath.search(/contact/i) != -1 || currPath.search(/mailing-list/i) != -1) { return 5;
	} else { return 0; }
}
function setSection() {
	currSection = getSection();
}

function getHostname() {
	return document.location.hostname;
}
function setHostname() {
	dHostname = getHostname();
}

function getLocation() {
	return document.location;
}
function setLocation() {
	dLocation = getLocation();
}

function getHref() {
	return document.location.href;
}
function setHref() {
	dHref = getHref();
}

function getPathname() {
	return document.location.pathname;
}
function setPathname() {
	dPathname = getPathname();
}

function getHash() {
	return window.location.hash;
}
function setHash() {
	dHash = getHash();
}

function setHTML4Hash(el, title) {
	window.location.hash = el.attr("href").substr(0, el.attr("href").length);
	setTitle(title);
}

function setTitle(title) {
	if (title) {
		document.title = title;
	} else {
		document.title = sectionObj.sections[getSection()].section;
	}
}



/* STROBE MEDIA PLAYBACK EVENT LISTENERS */
function videoComplete() {
	if (window.console && window.console.log) { console.log("The video has completed playback..."); }
	$(".video-poster").css("display", "block");
	player = null;
	
	if ($(".portfolio-post .portfolio-media .media").length > 0) {
		$(".portfolio-post .portfolio-media .media").cycle("resume");
		projectSlides.cycle("resume");
	}
}
function videoPlaying() {
	if (window.console && window.console.log) { console.log("The video has started playback..."); }
	if ($(".portfolio-post .portfolio-media .media").length > 0) {
		$(".portfolio-post .portfolio-media .media").cycle("pause");
		projectSlides.cycle("pause");
	}
}
function videoMediaPlayerStateChange(evt, pid) {
	if (window.console && window.console.log) { console.log("The video player state has changed... ["+evt+"]"); }
	if (evt == "playing" || evt == "buffering") {
		if ($(".portfolio-post .portfolio-media .media").length > 0) {
			$(".portfolio-post .portfolio-media .media").cycle("pause");
			projectSlides.cycle("pause");
		}
	}
	
	if (evt == "ready") {
		if ($(".portfolio-post .portfolio-media .media").length > 0) {
			$(".portfolio-post .portfolio-media .media").cycle("resume");
			projectSlides.cycle("resume");
		}
	}
}
function videoPaused() {
	//if (window.console && window.console.log) { console.log("The video has been paused..."); }
}
function videoLoadStarted() {
	//if (window.console && window.console.log) { console.log("The video has started loading..."); }
}
function videoBuffering() {
	//if (window.console && window.console.log) { console.log("The video is buffering..."); }
}	
function videoEmptied() {
	//if (window.console && window.console.log) { console.log("The video is emptied..."); }
}	
function videoCurrentTimeChange(time, pid) {
	//if (window.console && window.console.log) { console.log("The video has current time change... ["+time+"]"); }
}	
function videoDurationChange(time, pid) {
	//if (window.console && window.console.log) { console.log("The video has duration change... ["+time+"]"); }
}	
function videoPlayerCallback(playerId) {
	if (player == null) {
		if (window.console && window.console.log) { console.log("Player callback fired [" + playerId + "]"); }
		player = document.getElementById(playerId);
		//player.addEventListener("play", "videoPlaying");
		player.addEventListener("mediaPlayerStateChange", "videoMediaPlayerStateChange");
		player.addEventListener("pause", "videoPaused");
		player.addEventListener("complete", "videoComplete");
		player.addEventListener("load", "videoLoadStarted");
		player.addEventListener("waiting", "videoBuffering");
		player.addEventListener("emptied", "videoEmptied");
		player.addEventListener("currentTimeChange", "videoCurrentTimeChange");
		player.addEventListener("durationChange", "videoDurationChange");
	}
}

/* LOADER */
function showLoader() {
	if ($("#loader").length == 0) { $("body").append(loader); }
	$("#loader").css("display", "block").animate({
		opacity: 1.0
	}, loaderInDuration, "easeInOutQuad");
}
function hideLoader() {
	$("#loader").animate({
		opacity: 0.0
	}, loaderOutDuration, "easeInOutQuad", function() {
		$("#loader").css("display", "none");
	});
}


/* UTLITIES */
function getFlashObject(movieName) {
	if (window.document[movieName]) {
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet") == -1) {
		if (document.embeds && document.embeds[movieName])
			return document.embeds[movieName]; 
	} else { // if (navigator.appName.indexOf("Microsoft Internet") != -1)
		return document.getElementById(movieName);
	}
}

function getQueryString() {
	var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
	while (m = re.exec(queryString)) { result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); }
	return result;
}

function setQueryString(str) {
	var qs = "?"+str, href = window.location.href
	href = href.replace(/\?.*$/, "");
	window.location.href = href+qs;
}

function fixIE() {
	$("body").css("backgroundPosition", "50% " + sectionObj.sections[getSection()].bgpos);
}

function fixIHeight() {
	if (navigator.platform == "iPad" || navigator.platform == "iPhone" || navigator.platform == "iPod") {
		/*var h = ($("#content").height() - 300) + "px";
		if (window.console && window.console.log) { console.log("h: " + h); }
		$("html, body, #page-wrapper").css("height", h);*/
	};
}

function fixIPosition() {
	if (navigator.platform == "iPad" || navigator.platform == "iPhone" || navigator.platform == "iPod") {
		$("html, body, .fadeout, .dimmer").css("position", "static");
	};
}

