var site = {
	colWidth			: 120,			// 1 column grid width
	rowHeight			: 108,
	topButtonPageMin	: 1042,
	animationSpeed		: 600,			// animation time 0.6 seconds
	quickAnimationSpeed	: 250,
	blockCleaner		: null,			// timeout interval to remove hidden blocks
	data				: [],			// current view content
	greyLevels			: 9,
	inlineId			: 0,
	selectedIndex		: null,			// active block when in inline content viewer mode
	gallery				: null,			// current collection being viewed
	inCollection		: false,
	addedMap			: false,
	map					: null,
	
	imgPath				: "/services/imageresizer.php",
	xhrSearch			: null,			// ajax search calls
	xhrJSON				: null,
	searchDelay			: 150,			// delay between key and actual search
	searchTimeout		: null,			// reference to setTimeout for search
	
	firstTracking		: true,			// the first we visit the page GA is called once in the html and again in the json (this prevents double calls)
	
	lastLayoutPosition	: 0,
	resultsPerPage		: 20,
	allowInfinite		: false,
	duplicates			: [],
	currentPage			: 1,
	totalPages			: 1,
	autoCenter			: true,
	truncateBlockTitles : true,
	
	videoId				: 0,
	
	hideCollectionTimeout	: null,
	priorToCollection	: null,
	
	isSafari			: false,
	isChrome			: false,
	isiPad				: false,
	isiPhone			: false,
	isiPod				: false,
	isIE				: false,
	
	videoOptions : {
		plugins : ["flash"],
		pluginPath : "/swf/",
		flashName : "flashmediaelement.swf",
		features: ['playpause','progress','volume'],
		alwaysShowControls : true,
		hideControlsAtStartup : false,
		startVolume : 1
	},
	
	init : function() {
		site.isiPad = navigator.userAgent.match(/iPad/i) != null;
		site.isiPhone = navigator.userAgent.match(/iPhone/i) != null;
		site.isiPod = navigator.userAgent.match(/iPod/i) != null;
		site.isChrome = navigator.userAgent.match(/Chrome/i) != null;
	
		// Setup isotope
		$("#blocks").isotope({
			masonry : {
				columnWidth : site.colWidth
			},
			animationEngine : 'best-available',
			itemPositionDataEnabled: true
		});
		
		// Initialize the social plugin
		social.init(site.socialContentLoaded);

		// Safari has issues with Media Element being dynamically generated, so use Flash for video
		var ua = navigator.userAgent.toLowerCase();
		
		if( $.browser.webkit && !site.isChrome && !( site.isiPad || site.isiPhone || site.isiPod ) ) {
			site.videoOptions.mode = "shim";
			site.isSafari = true;
		}
		
		if( $.browser.mozilla ) {
			site.videoOptions.mode = "shim";
		}
		
		if( $.browser.msie ) {
			if(initialPath == "") {
				initialPath = "/home";
			}
			
			site.isIE = true;
		}
		
		site.formatWorkMenu();
		site.initPageChange();			// Path.js Hashbang/History API listeners
		site.initEvents();				// Block event listeners
		site.goto(initialPath);			// Load initial content
		
		$("body").append('<div id="top"><div class="button"></div></div>');
		$("#top div.button").live('click', site.resetScroll);
	},
	
	formatWorkMenu : function() {
		var work = $("header li.work ul li");
		var max = Math.ceil(work.length / 3);
		
		var list1 = $("<ul class=\"col1\"></ul>");
		var list2 = $("<ul class=\"col2\"></ul>");
		var list3 = $("<ul class=\"col3\"></ul>");
		
		for(var i = 0; i < work.length; i++) {
			var list = Math.floor(i / max);
			
			switch(list) {
				case 0:
					list1.append( work[i] );
				break;
				case 1:
					list2.append( work[i] );
				break;
				case 2:
					list3.append( work[i] );
				break;
			}
		}
		
		$("header li.work ul").remove();
		$("header li.work").append("<div></div>");
		$("header li.work div").append(list1, list2, list3);
	},
	
	trackPageChange : function() {
		if(!site.firstTracking) {
			var thisUrl = site.normalizeRoute();
			
			try {
				_gaq.push(['_trackPageview', thisUrl]);
			} catch(err) {
				// Can't track with Google Analytics
			}
		}
		
		site.firstTracking = false;
	},
	
	initPageChange : function() {
		Path.map("/blog(/:article)").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/client").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/collection/:collection(/:item)").enter(site.enterCollection).to(site.fetchCollection).exit(site.exitCollection);
		Path.map("/company").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/capability(/:capability)").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/history").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/people(/:person)").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/news(/:article)").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/work(/:medium)").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("/search(/:term)").to(site.fetchSearch).exit(site.cleanUp);
		Path.map("/contact").to(site.showContact).exit(site.cleanUp);
		Path.map("/home").to(site.fetchBlocks).exit(site.cleanUp);
		Path.map("").to(site.fetchBlocks).exit(site.cleanUp);
		
		Path.history.listen(true);
	},
	
	initEvents : function() {
		// Initialize video
		$(".videoHolder").live('click', site.replaceVideo);
	
		// Look at all of these events, we must be popular
		$(window).scroll(site.scrollListener);
		$(window).resize(site.resize);
		$("#searchfield").keyup(site.liveSearch);
		$("#searchsubmit").click(site.gotoSearch);
		$("body").click(site.monitor);
		
		$("nav.primary > ul > li:has(ul)").live('mouseenter', site.showSecondaryNav);
		$("nav.primary > ul > li:has(ul)").live('mouseleave', site.hideSecondaryNav);
		
		// block event listeners for exploring content
		$("#blocks div.block").live('mouseenter', site.animateShowBlockInfo);
		$("#blocks div.block").live('mouseleave', site.animateHideBlockInfo);
		$("#blocks div.block").live('click', site.blockClick);
		
		$("#blocks div.collection .close").live('click', site.closeCollection);
		$("#collection .galleryClose").live('click', site.closeCollection);
		$("#blocks div.collection .view").live('click', site.openCollection);
		$("#blocks div.inline .close").live('click', site.exitInlineViewer);
		$("#blocks .blogArticle .close").live('click', site.exitBlogArticle);
		
		$("#viewerControls .navleft, #viewerControls .navright").live('click', site.switchInlineContent);
		
		// collection's gallery nav
		$("#collection .gallery .prev").live('click', site.gotoPrevGalleryItem);
		$("#collection .gallery .next").live('click', site.gotoNextGalleryItem);
		
		// share functionality
		$("#share li a").live('click', site.share);
		$("#share .close").live('click', site.hideShare);
		$(".share").live('click', site.showShare);
		
		// People
		$("#person-background").live('click', site.removePersonOverlay);
		$("#person .close").live('click', site.removePersonOverlay);
		
		// Inline content viewer pagination
		$("#blocks div.inline div.details ul.internal li").live('click', site.scrollInlineContent);
		
		// Convert any internal links to use Path's navigation method
		$("a").live('click', site.linkProxy);
	},
	
	replaceVideo : function(e) {
		var video = {};
		video.name = $(this).attr("id").replace(/_video/, "");
		video.mp4 =  $(this).data("mp4");
		video.webm =  $(this).data("webm");
		
		$(this).replaceWith(ich.videoTag(video));
	},
	
	resetScroll : function(e) {
		$("html, body").animate({scrollTop: 0});
	},
	
	showSecondaryNav : function(e) {
		$(this).css({paddingBottom: "0px"});
		$("div", this).css({paddingBottom: "20px"});
		$("ul, div", this).show();
	},
	
	hideSecondaryNav : function(e) {
		$(this).css({paddingBottom: "20px"});
		$("div", this).css({paddingBottom: "0px"});
		$("ul li ul").hide();
	},
	
	showLoader : function(type) {
		$(".indicator").addClass("loading");
	},
	
	hideLoader : function(type) {
		$(".indicator").removeClass("loading");
	},
	
	socialContentLoaded : function() {
		var items = $("#blocks .social");
		for(var i = 0; i < items.length; i++) {
			if(i < social.data.length) {
				$( items[i] ).addClass( social.data[i].type ).data("url", social.data[i].url);
				$( ".label", items[i] ).html( social.data[i].type );
				$( ".excerpt",  items[i] ).html( social.data[i].message ).ellipsis();
				
				$(items[i]).append('<a class="outbound" href="'+social.data[i].url+'" target="_blank">&nbsp;</a>');
			} else {
				$(items[i]).addClass("empty");
			}
		}
	},
	
	exitBlogArticle : function() {
		site.goto("/blog");
	},
	
	resize : function() {
		site.updateGalleryLayout();
		
		var scrollY = $(window).scrollTop();
		var scrollLockY = 110;
		
		if(scrollY >= scrollLockY && !site.inCollection) {
			var pageWidth = $(window).width();
			if(pageWidth > site.topButtonPageMin) {
				site.showTopButton();
			} else {
				site.hideTopButton();
			}
		} else {
			site.hideTopButton();
		}
	},
	
	adjustLogo : function() {
		var scrollY = $(window).scrollTop();
		var scrollLockY = 110;
		var finalBgY = 0;
		
		
		if(site.inCollection) {
			$("nav.primary li.home").css({backgroundPosition: "14px "+finalBgY+"px"});
			site.hideTopButton();
		} else {
			if(scrollY < scrollLockY) {
				var y = scrollLockY - scrollY + finalBgY;
				$("nav.primary li.home").css({backgroundPosition: "14px "+y+"px"});
				
				site.hideTopButton();
			} else {
				$("nav.primary li.home").css({backgroundPosition: "14px "+finalBgY+"px"});
				
				var pageWidth = $(window).width();
				if(pageWidth > site.topButtonPageMin) {
					site.showTopButton();
				} else {
					site.hideTopButton();
				}
			}
		}
		
	},
	
	hideTopButton : function(e) {
		$("#top div").stop().animate({marginLeft: "-41px"});
	},
	
	showTopButton : function(e) {
		$("#top div").stop().animate({marginLeft: "0px"});
	},
	
	scrollListener : function(e) {
		var scroll = $(window).scrollTop() + $(window).height();
		var max = $("body").height();
		
		if(scroll >= max) {
			if(site.allowInfinite) {
				site.fetchBlocks(site.resultsPerPage * site.currentPage);
			}
		}
		
		site.adjustLogo();
	},
	
	cleanUp : function() {
		site.hideSecondaryNav();
	
		site.stopAllVideos();
	
		site.removeInlineNavigation();
		//site.animateHideCollection();
		site.hideShare();
		
		$("#person-background").hide();
		$("#person").hide();
	},
	
	fetchBlocks : function(startingPoint, forcedPath) {
		// Don't track on inifinite scroll
		if(!startingPoint) {
			site.trackPageChange();
		}
		
		site.allowInfinite = false;
		site.showLoader("blocks");
	
		// we're out of a collection, lets make sure we aren't forcing the mini logo upon people
		site.inCollection = false;
		site.adjustLogo();
		site.hideSearch();
		
		var data = {format : "json"};
		var start = (startingPoint) ? startingPoint : 0;
		
		site.cancelRequest();
		
		site.xhrJSON = $.ajax({
			url: site.normalizeRoute(forcedPath) + "/P" + start,
			dataType: "json",
			success: site.parseResults
		});
	},
	
	createImage : function(path, width, height, focalX, focalY, zoom) {
		if(path) {
			// default the focal point to the center
			focalX = (focalX) ? focalX : 50;
			focalY = (focalY) ? focalY : 50;
			
			// If a zoom is defined then add it to the image string
			var z = (zoom) ? "&zoom=" + zoom : "";
			
			// clean path
			var pattern = /(https?)\:\/\//;
			path = path.replace(pattern, "");
			path = path.substr(path.indexOf('/'));
		
			var finalPath = site.imgPath + "?src=.." + path + "&width=" + width + "&height=" + height + "&fx=" + focalX + "&fy=" + focalY + z;
			
			return finalPath;
		} else {
			return "";
		}
	},
	
	/**
	* @param	content	content array to search
	* @param	amount	the # of elements at the start of the content array that might be duplicated, if 0 then use the site.duplicates array
	*/
	removeDuplicates : function(content, amount) {
		var unique = [];
	
		// Find the duplicates
		if(amount > 0 && content.length >= amount) {
			for(var i = 0; i < amount; i++) {
				unique.push(content[i].path);		
			}
			
			site.duplicates = unique;
		} else {
			unique = site.duplicates;
		}
		
		
		var remove = [];
		for(var i = amount; i < content.length; i++) {
			var found = false;
			for(var j = 0; j < unique.length; j++) {
				if(content[i].path == unique[j]) {
					found = true;
					break;
				}
			}
			
			if(found) {
				remove.push(i);
			}
		}
		
		// remove duplicates
		for(var i = remove.length-1; i >= 0; i--) {
			content.splice(remove[i], 1);
		}
	},
	
	/**
	* Method that parses through the search result's JSON object and build blocks
	*
	* @param	data	json object
	*/
	parseResults : function(data) {
		site.hideLoader("blocks");
	
		if(data.results.content) {
			site.animateHideCollection();
			
			// Test if there are multiple pages
			site.currentPage = data.results.current_page || 1;
			site.totalPages = data.results.total_pages || 1;
			site.priorToCollection = Path.routes.current;
			
			var startFrom = 0;
			
			if(site.totalPages > 1 && site.currentPage > 1) {
				startFrom = site.data.results.content.length;
				
				// merge paginated results
				site.data.results.content = site.data.results.content.concat(data.results.content);
			} else {
				site.data = data;
			}
			
			var content = data.results.content;
			var section = data.results.section;
			var blockLayout = null;
			var reuseFirstBlock = true;
			var autoOpenFirstBlock = false;
			var title = data.results.title || "";
			var isBlogArticle = false;
			var hasSocial = false;
			var hideNav = false;
			
			var layoutOptions = {};
			layoutOptions.useSocialBlocks = false;
			layoutOptions.displayBlockInsteadOfDate = false;
			layoutOptions.useHomepageWorkRules = false;
			
			site.setHeadlineTitle(title);
			
			// Display spotlight
			if(section == "homepage") {
				var spotlight = data.results.spotlight;
				
				if(spotlight.video.mp4) {
					site.showHeadlineVideo(spotlight);
				} else {
					site.showHeadlineImage(spotlight);
				}
				
				$("#headline .content").animate({top: "0px"}, site.animationSpeed);
				
				blockLayout = site.layout.homepage.content;
				layoutOptions.viewStyle = "none";
				layoutOptions.displayBlockInsteadOfDate = true;
				
				// remove duplicate work
				if(site.currentPage == 1) {
					layoutOptions.useSocialBlocks = true;
					site.removeDuplicates(content, 3);
					site.lastLayoutPosition = 0;
				} else {
					layoutOptions.useHomepageWorkRules = true;
					site.removeDuplicates(content, 0);
				}
				
				$("body").removeClass("work blog company contact");
				document.title = "The Martin Agency";
			} else {
				site.hideHeadlineVideo();
				
				switch(section) {
					case "company":
						blockLayout = site.layout.company.content;
						hideNav = true;
						layoutOptions.viewStyle = "none";
						content[0].view = "inline";
						content[0].single = true;
						autoOpenFirstBlock = true;
						site.autoCenter = false;
						
						$("body").removeClass("work blog contact").addClass("company");
						document.title = "Company | The Martin Agency";
					break;
					case "capability":
						blockLayout = site.layout.company.content;
						
						$("body").removeClass("work blog contact").addClass("company");
					break;
					case "news":
						blockLayout = site.layout.news.content;
						
						$("body").removeClass("work blog contact").addClass("company");
						document.title = "What's Up | The Martin Agency";
					break;
					case "people":
						blockLayout = site.layout.people.content;
						
						$("body").removeClass("work blog contact").addClass("company");
						document.title = "What We're Like | The Martin Agency";
					break;
					case "clients":
						blockLayout = site.layout.client.content;
						reuseFirstBlock = site.layout.client.reuseFirst;
						
						$("body").removeClass("work blog contact").addClass("company");
						document.title = "Who's With Us? | The Martin Agency";
					break;
					case "history":
						layoutOptions.viewStyle = "inline";
						blockLayout = site.layout.company.content;
						autoOpenFirstBlock = true;
						hideNav = false;
						site.autoCenter = false;
						
						$("body").removeClass("work blog contact").addClass("company");
						document.title = "Where We're From | The Martin Agency";
					break;
					case "blog":
						var current = Path.routes.current;
						isBlogArticle = current.match( /\/blog\/(.*)/g );
						
						blockLayout = site.layout.blog.content;
						reuseFirstBlock = site.layout.blog.reuseFirst;
						
						$("body").removeClass("work company contact").addClass("blog");
						document.title = "Shockoe Therapy | The Martin Agency";
					break;
					case "work":
						if(site.currentPage == 1) {
							layoutOptions.useSocialBlocks = true;
						}
					
						if(content.length >= 1 && content.length <= 5) {
							blockLayout = site.layout.work["content" + content.length];
						} else {
							blockLayout = site.layout.work.content;
						}
						
						$("body").removeClass("blog company contact").addClass("work");
						document.title = "Work | The Martin Agency";
					break;
					default:
						blockLayout = site.layout.blocks.content;
						
						$("body").removeClass("work blog company contact");
						document.title = "The Martin Agency";
				}
				
				// remove duplicate work
				if(site.currentPage == 1) {
					if(data.results.social) {
						layoutOptions.useSocialBlocks = true;
					}
					site.removeDuplicates(content, 1);
					site.lastLayoutPosition = 0;
				} else {
					site.removeDuplicates(content, 0);
				}
			}
			
			if(site.currentPage < site.totalPages) {
				site.allowInfinite = true;
			}
			
			// Mark old content for removal
			if(site.currentPage == 1) {
				$("html, body").scrollTop(0);
				site.markForRemoval();
			}
						
			// Select Block Layout
			var currentBlock = 0;
			
			// Create HTML code
			var nodes = content.length;
			
			site.selectedIndex = null;
			layoutOptions.reuseFirstBlock = reuseFirstBlock;
			
			if(!isBlogArticle) {
				site.layoutBlocks(section, content, startFrom, blockLayout, layoutOptions);
				
				if(section != "blog") {
					if(autoOpenFirstBlock) {
						site.createInlineContent(0, null, hideNav);
					} else {
						if(section == "people") {
							var current = Path.routes.current;
						
							for(var i = 0; i < content.length; i++) {
								if(content[i].path == current) {
									site.createPersonOverlay(i, null);
									break;
								}
							}
						} else {
							var current = Path.routes.current;
							
							for(var i = 0; i < content.length; i++) {
								if(content[i].path == current) {
									site.createInlineContent(i, null, false);
									break;
								}
							}
						}
					}
				}
			} else {
				// render blog article
				var imgHeightMin = 432;
				var imgHeightMax = 540;
				
				if(site.isIE) {
				var cover = ich.blogHeadline2({title: content[0].title,
												date: content[0].date,
												author: content[0].author.name,
												image: site.createImage(content[0].cover.image, 720, 432),
												formats: site.formatForCDN( content[0].cover.formats ),
												video: (content[0].cover.formats.mp4 != "") ? true :  false});
				} else {
				var cover = ich.blogHeadline({title: content[0].title,
												date: content[0].date,
												author: content[0].author.name,
												image: site.createImage(content[0].cover.image, 720, 432),
												formats: site.formatForCDN( content[0].cover.formats ),
												video: (content[0].cover.formats.mp4 != "") ? true :  false});
				}
				
				$("#blocks").isotope('insert', $(cover));
				
				for(var i = 0; i < content[0].content.length; i++) {
					var data = {copy: content[0].content[i].text.copy};
					var imageWidth = 0;
					var offset = 0;
					
					if(content[0].content[i].image.src) {
						if(content[0].content[i].image.height < imgHeightMin) {
							var w = imageWidth = Math.ceil(imgHeightMin / content[0].content[i].image.height * content[0].content[i].image.width);
						
							data.imageWidth = w;
							data.imageHeight = imgHeightMin;
							data.image = site.createImage(content[0].content[i].image.src, w, imgHeightMin);
						} else if(content[0].content[i].image.height > imgHeightMax) {
							var w = imageWidth = Math.ceil(imgHeightMax / content[0].content[i].image.height * content[0].content[i].image.width);
						
							data.imageWidth = w;
							data.imageHeight = imgHeightMax;
							data.image = site.createImage(content[0].content[i].image.src, w, imgHeightMax);
						} else {
							data.imageWidth = imageWidth = content[0].content[i].image.width;
							data.imageHeight = content[0].content[i].image.height;
							data.image = content[0].content[i].image.src;
						}
					}

					if(content[0].content[i].headline) {
						data.headline = content[0].content[i].headline.copy;
						data.position = content[0].content[i].text.layout;
						
						var position = Number(content[0].content[i].text.layout);
						
						// Center in area
						if(position == 1) {
							offset = Math.round( (720 - imageWidth)/2 ) + 240;
						} else if(position == 4) {
							offset = Math.round( (720 - imageWidth)/2 );
						}
						
						if(content[0].content[i].headline.layout.toLowerCase() == "external") {
							data.external = "external";
							data.position2 = Number(content[0].content[i].text.layout) + 1;
							
							if(data.position == 4) {
								data.position--;
								data.position2--;
							}
							
							// Center in area
							if(position == 1) {
								offset = Math.round( (480 - imageWidth)/2 ) + 480;
							} else if(position == 4) {
								offset = Math.round( (480 - imageWidth)/2 );
							}
						}
					}
					
					data.offset = offset;
					
					$("#blocks").isotope('insert', $(ich.blogArticle(data)));
				}
			}
			
			// Load Social Content
			if(layoutOptions.useSocialBlocks) {
				var socialSearch = data.results.social;
			
				social.load(socialSearch.twitter, socialSearch.facebook);
			}
			
			$("#blocks").isotope({filter:':not(.remove, .contact)'});
			site.blockCleaner = setTimeout(site.removeBlocks, site.animationSpeed);
			
			// Activate video on any blocks
			site.setVideoPlayers(false, true);
		}
	},
	
	layoutBlocks : function(section, content, start, layout, options) {
		var socialBarCreated = false;
		var current = site.lastLayoutPosition;	// current position in layout array
		var e = 0;	// empty counter
		var blogCount = (current == 0) ? 0 : 1;
		
		for(var i = 0; i < content.length; i++) {
			var special = (layout[current].empty || layout[current].social);
						
			while(special) {
				var block;				
				if(layout[current].empty) {
					block = site.createBlock(e, {type:"empty"}, layout[current].w, layout[current].h);
					e++;
					
					$("#blocks").isotope("insert", $(block));
				} else if(layout[current].social && options.useSocialBlocks && !socialBarCreated) {
					// if this is a social bar AND we have data AND we haven't already done this
					for(var j = 0; j < layout[current].amount; j++) {
						block = site.createBlock(j, {type:"social"}, layout[current].w, layout[current].h);
						
						$("#blocks").isotope("insert", $(block));
					}
					
					socialBarCreated = true;
				}
				
				// Next block
				current++;
				if(current >= layout.length) {
					current = options.reuseFirstBlock ? 0 : 1;
				}
				
				// Is the next one special too
				special = (layout[current].empty || layout[current].social);
			}
			
			if(section == "homepage" && content[i].type == "work" && options.useHomepageWorkRules && layout[current].skipable) {
				var skipable = (layout[current].skipable || layout[current].social || layout[current].empty);
				
				while(skipable) {
					// Next block
					current++;
					if(current >= layout.length) {
						current = options.reuseFirstBlock ? 0 : 1;
					}
					
					// Is the next one special too
					skipable = (layout[current].skipable || layout[current].social || layout[current].empty);
				}
			}
			
			var bWidth = layout[current].w;
			var bHeight = layout[current].h;
			
			if(section == "homepage") {
				switch(content[i].type) {
					case "news":
						bWidth = bHeight = 2;
					break;
					case "blog":
						var longest = (bHeight > bWidth) ? "height" : "width";
												
						if(blogCount == 0) {
							bHeight = 3;
							bWidth = 8;
						} else if(blogCount%2 == 0) {
							bHeight = 4;
							bWidth = 4;
						} else {
							bHeight = 3;
							bWidth = 4;
						}
						
						blogCount++;
					break;
				}
				
				if(layout[current].pass) {
					options.useHomepageWorkRules = true;
				}
			}
			
			// !HACK - This needs to be done on the backend
			if(section == "homepage" && content[i].type == "news" && !content[i].feature) {
				// don't show non-featured content on the homepage
			} else {
				var block = site.createBlock(start+i, content[i], bWidth, bHeight, options.viewStyle, options.displayBlockInsteadOfDate);
				$("#blocks").isotope('insert', $(block));
			}
					
			// Next block
			current++;
			if(current >= layout.length) {
				current = options.reuseFirstBlock ? 0 : 1;
			}
			site.lastLayoutPosition = current;
		}
		
		// Check to see if the social bar has been create
		if(options.useSocialBlocks && !socialBarCreated) {
			// find the social bar layout
			var found = false;
			
			for(var i = 0; i < layout.length; i++) {
				if(layout[i].social) {
					found = true;
					break;
				}
			}
			
			if(found) {
				// Next block
				for(var k = current; k < layout.length; k++) {
					if(layout[k].social) {
						for(var j = 0; j < layout[k].amount; j++) {
							block = site.createBlock(j, {type:"social", id:j}, layout[k].w, layout[k].h);
							$("#blocks").isotope("insert", $(block));
						}
						
						socialBarCreated = true;
						break;
					} else {
						// eveything else is empty
						block = site.createBlock(e, {type:"empty"}, layout[k].w, layout[k].h);
						e++;
					}
				}
			}
		}
		
		if(site.truncateBlockTitles) {
			$("#blocks .block.isotope-item .title").ellipsis();
		}
	},
	
	/**
	* Method that formats JSON object into something we can use for Mustache
	*/
	createBlock : function(id, block, width, height, viewStyle, labelAsType) {
		var node = null;
		var data = {};
		data.title = block.title;
		data.width = width;
		data.height = height;
		data.grey = site.setGreyLevel(id);
		data.id = id;
		data.path = block.path;
		
		switch(block.type) {
			case "capability":
				data.excerpt = block.excerpt;
				
				node = ich.capability(data);
			break;
			case "client":
				data.image = block.image.thumb;
				data.image_gray = block.image.thumb_gray;
			
				node = ich.client(data);
			break;
			case "people":
				data.image = block.image.animation;
				data.image2 = block.image.thumb;
			
				node = ich.people(data);
			break;
			case "history":
				data.image = site.createImage( block.image.src, width * site.colWidth, height * site.rowHeight, block.image.focalX, block.image.focalY );
				data.excerpt = block.excerpt;
				
				node = ich.history(data);
			break;
			case "news":
				if(block.image.src) {
					data.image = site.createImage( block.image.src, width * site.colWidth, height * site.rowHeight, block.image.focalX, block.image.focalY );
					block.narrow = false;
				}
				data.excerpt = block.excerpt;
				data.view = viewStyle ? viewStyle : "inline";
				data.date = (labelAsType) ? "News" : block.published;
			
				node = ich.news(data);
			break;
			case "simple":
				data.view = viewStyle ? viewStyle : "inline";
				
				node = ich.simple(data);
			break;
			case "work":
				data.image = site.createImage( block.image.src, width * site.colWidth, height * site.rowHeight, block.image.focalX, block.image.focalY );
				data.client = block.client;
				data.external = block.external;
				
				node = ich.work(data);
			break;
			case "blog":
				data.image = site.createImage( block.image.src, width * site.colWidth, height * site.rowHeight );
				data.excerpt = block.excerpt;
				data.author = block.author.name;
				data.date = (labelAsType) ? "Blog" : block.date;
				
				node = ich.blog(data);
			break;
			case "empty":
				node = ich.empty(data);
			break;
			case "social":
				node = ich.social(data);
			break;
		}
	
		return node;
	},
	
	setGreyLevel : function(id) {
		var grey = (id + 1) % site.greyLevels;
		
		return (grey == 0) ? 9 : grey;
	},
	
	removeBlocks : function() {
		// Fix safari
		if ($.browser.webkit) {
			var blocks = document.getElementById("blocks");
			var images = blocks.getElementsByTagName("img");
			
			for(var i = 0; i < images.length; i++) {
				images[i].style.display = "none";
				images[i].offsetHeight;
				images[i].style.display = "block";
			}
		}
	
		$("#blocks").isotope('remove', $("#blocks div.remove"));
	},
	
	removeVideo : function() {
		$("#headline .content").empty();
	},
	
	/**
	* Show the block's information overlay (if available)
	*/
	animateShowBlockInfo : function(e) {
		var slide = $(this).hasClass("work");
		var blog = $(this).hasClass("blog");
		var social = $(this).hasClass("social");
		var readMoreHeight = (social) ? 15 : 22; // 7 margin top + line-height
		
		try {
			var orgHeight = $(".summary", this).height();	// If too much text use the auto-ellipsis plug-in
			var lineHeight = Math.floor( $(".summary .excerpt", this).css("line-height").replace(/[^-\d\.]/g, '') );	// line-height in nearest whole pixel
			
			// Find actual height
			var fullHeight = $(".summary", this).css({display: 'block'}).height("auto").height();
			var excerptHeight = $(".summary .excerpt", this).height();
			$(".summary", this).height(orgHeight);
			
			var overflow = fullHeight - orgHeight + readMoreHeight;
			
			if(site.truncateBlockTitles) {
				$(".summary .title", this).ellipsis();
			}
			
			if(overflow > 0) {
				var lines = Math.floor((excerptHeight-overflow)/lineHeight);
				lines = (lines > 0) ? lines : 0;
				
				$(".excerpt", this).height( Math.floor(lines * lineHeight) ).ellipsis().css({"overflow":"hidden"});
			}
		} catch(err) {
			// oh well
		}
		
		if(slide) {
			$(".summary", this).stop(false).animate({left: '0px'}, site.quickAnimationSpeed);
		} else {
			if(blog) {
				$(".summary", this).stop(false).css({display: 'block'}).animate({opacity:1}, site.quickAnimationSpeed);
			} else {
				$(".summary", this).stop(false).css({left: '0px', display: 'block'}).animate({opacity:1}, site.quickAnimationSpeed);
			}
		}
	},
	
	/**
	* Hide the block's information overlay (if available)
	*/
	animateHideBlockInfo : function(e) {
		var slide = $(this).hasClass("work");
		
		if(slide) {
			$(".summary", this).stop(false).animate({left: '-240px'}, site.quickAnimationSpeed);
		} else {
			$(".summary", this).stop(false).animate({opacity:0}, site.quickAnimationSpeed);
		}
	},
	
	/**
	* Action to be performed when a block is clicked, this varies by block type
	*/
	blockClick : function(e) {
		var view = $(this).attr("data-view") || "";
		
		if(view == "inline") {
			// inline content viewer
			var index = Number($(this).attr("data-id"));
			
			site.createInlineContent(index, this);
		} else if(view == "overlay") {
			// people viewer
			var index = Number($(this).attr("data-id"));
			
			site.createPersonOverlay(index, this);
		} else {
			if(! ($(this).hasClass("blogArticle") || $(this).hasClass("social")) ) {
				// major navigation changes
				site.goto( $(this).attr("data-path") );
			}
		}
	},
	
	showContact : function() {
		site.animateHideCollection();
	
		site.allowInfinite = false;
		site.cancelRequest();
		site.trackPageChange();
	
		site.hideHeadlineVideo();
		site.setHeadlineTitle("Get in Touch");
		
		$("#blocks .contact").removeClass("hidden");
		site.hideLoader("blocks");
		
		$("html, body").scrollTop(0);
		
		try {
			var center = new google.maps.LatLng(39.135641,-75.713607);
		
			if(!site.addedMap) {
				var richmond = new google.maps.LatLng(37.534767,-77.434047);
				var newyork = new google.maps.LatLng(40.736515,-73.993167);
				
				var myOptions = {
					zoom: 7,
					center: center,
					scrollwheel: false,
					streetViewControl: false,
					panControl: false,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				};
				
				site.map = new google.maps.Map(document.getElementById("map"), myOptions);
				
				new google.maps.Marker({position: richmond, map: site.map, title: "Richmond"});
				new google.maps.Marker({position: newyork, map: site.map, title: "New York"});
				
				site.addedMap = true;
			} else {
				site.map.panTo(center);
			}
		} catch(err) {
			// errors
		}
		
		$("#blocks").isotope({filter:'.contact'});
		
		$("body").removeClass("work blog company").addClass("contact");
		document.title = "Contact | The Martin Agency";
	},
	

	
	

	/***********************************************************************
	*                                                                      *
	*                        Block Helper Functions                        *
	*                                                                      *
	***********************************************************************/
	formatForCDN : function(formats) {
		if(formats.mp4) {
			formats.mp4 = formats.mp4.replace("http://www.martinagency.com/", "http://d347rp92p23t8u.cloudfront.net/");
		}
		
		if(formats.webm) {
			formats.webm = formats.webm.replace("http://www.martinagency.com/", "http://d347rp92p23t8u.cloudfront.net/");
		}
		
		return formats;
	},
	
	showHeadlineVideo : function(content) {
		var video = {
			name : "frontpage" + site.videoId++,
			width : 960,
			height : 540,
			image : content.image,
			formats : site.formatForCDN( content.video ),
			ipad : site.isiPad
		};
		
		$("#headline").addClass("full").animate({height: video.height+"px"}, site.animationSpeed);
		$("#headline .content").append(ich.video(video));
	},
	
	showHeadlineImage : function(content) {
		$("#headline").animate({height: "540px"}, site.animationSpeed);
		$("#headline .content").append('<img src="'+content.image+'" width="960" height="540">');
	},
	
	hideHeadlineVideo : function(hideAll) {
		site.stopAllVideos();
		
		if(hideAll) {
			$("#headline").removeClass("full").animate({height: "0px"}, site.animationSpeed);
		} else {
			$("#headline").removeClass("full").animate({height: site.rowHeight+"px"}, site.animationSpeed);
		}
		$("#headline .content").animate({top: "-540px"}, {duration:site.animationSpeed, complete:site.removeVideo});
	},
	
	setHeadlineTitle : function(title) {
		$("#headline .location").html(title);
	},
	
	markForRemoval : function() {
		clearTimeout(site.blockCleaner);				// reset the cleaner so we don't see weird result
		$("#blocks").children().addClass("remove");
		$("#blocks .contact").removeClass("remove");
	},
	
	
	
	
	/***********************************************************************
	*                                                                      *
	*                          Navigation Methods                          *
	*                                                                      *
	***********************************************************************/
	/**
	* Convert any hard coded internal links to use Path to control navigation
	*/
	linkProxy : function(event) {
		var href = $(this).attr("href");
		
		if(href[0] == "/") {
			event.preventDefault();
			site.goto(href);
		}
	},
	
	normalizeRoute : function(forcedPath) {
		var file = "/";
		
		if((Path.routes.current == "" || Path.routes.current == null) && forcedPath) {
			file = forcedPath;
		} else {
			file = Path.routes.current;
		}
		
		return file.replace("#","");
	},
	
	gotoSearch : function(e) {
		site.cancelSearch();
		
		if($("#searchfield").val() != "") {
			site.goto("/search/" + $("#searchfield").val());
		}
	},
	
	goto : function(href) {
		href = (href == "/" || href == "") ? "/home" : href;
		
		Path.history.pushState({}, "", href);
	},

	
	
	
	/***********************************************************************
	*                                                                      *
	*                         People Functionality                         *
	*                                                                      *
	***********************************************************************/
	createPersonOverlay : function(index, block) {
		var videoWidth = 720;
		var videoHeight = 432;
		if(block) {
			var position = $(block).data('isotope-item-position');
		} else {
			var position = {x: 0, y: 0};
		}
		
		// !shouldn't hardcode, but one of the animations affects the top value when coming from the home page $("#blocks").offset().top
		var top = 172 + position.y; 		
		$("#person, #person-background").remove();
		$("body").append('<div id="person"></div>');
		$("body").append('<div id="person-background"></div>');
		$("#person").css({
			top : top,
			marginLeft : -480 + position.x
		});
		
		$("#person-background").css({
			top : $("#blocks").offset().top,
			height: $("#blocks").height()
		}).hide().fadeIn();
		
		$("#person").attr("data-x", -480 + position.x);
		
		var expandX = -480 + position.x;
		if((position.x + videoWidth) > 960) {
			expandX -= ((position.x + videoWidth) - 960);
		}
		
		var expandY = 0;
		if((position.y + videoHeight) > $("#blocks").height() && $("#blocks").height() > (site.rowHeight * 4)) {
			expandY = $("#blocks").height() - (position.y + videoHeight);
		}
		
		$("#person").animate({
			width: videoWidth,
			height: videoHeight,
			marginLeft: expandX,
			marginTop: expandY
		});
		
		var data = {
			name : "person_video" + site.videoId++,
			width : videoWidth,
			height : videoHeight,
			image : site.data.results.content[index].image.src,
			formats : site.formatForCDN( site.data.results.content[index].video ),
			ipad : site.isiPad
		};
		
		if(site.isIE) {
			$("#person").append(ich.video(data));
			$("#person").append('<div class="close"><img src="/imgs/buttons/close.png" alt="close" width="19" height="19" /></div>');
			
			site.setVideoPlayers(true);
		} else {
			$("#person").append(ich.videoHolder(data));
			$("#person").append('<div class="close"><img src="/imgs/buttons/close.png" alt="close" width="19" height="19" /></div>');
		}
		
		
	},
	
	removePersonOverlay : function() {
		$("#person-background").fadeOut();
		$("#person").animate({
			width: 120,
			height: 108,
			marginLeft: $("#person").attr("data-x"),
			marginTop: 0
		}, {complete: site.removePersonVideo});
	},
	
	removePersonVideo : function() {
		$("#person").empty();
		$("#person").hide();
	},
	
	
	
	/***********************************************************************
	*                                                                      *
	*                          Share Functionality                         *
	*                                                                      *
	***********************************************************************/
	share : function() {
		var service = $(this).parent().attr("class");
		var fullUrl = "";
		var thisUrl = serverPath.replace("/index.php", "") + site.normalizeRoute();
		
		switch(service) {
			case "facebook":
				fullUrl = "http://www.facebook.com/sharer.php?u=" + thisUrl;
			break;
			case "twitter":
				fullUrl = "http://twitter.com/share?text=" + encodeURIComponent("Check out this great work ") + "&url=" + thisUrl;
			break;
			case "linkedin":
				fullUrl = "http://www.linkedin.com/shareArticle?mini=true&url=" + thisUrl;
			break;
			case "google":
				fullUrl = "https://plusone.google.com/_/+1/confirm?hl=en&url=" + thisUrl;
			break;
		}
		
		window.open(fullUrl, "MartinShareService", "width=600, height=440, status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=1");
	},

	showShare : function(e) {
		var offset = $(this).offset();
		var left = offset.left - ($(window).width() - 960)/2;
		var shift = -480 + left;
		
		// URL to share
		var thisUrl = serverPath.replace("/index.php", "") + site.normalizeRoute();
		$("#url").val(String(thisUrl));
		
		$("#share").css({top: offset.top-112, marginLeft: shift-257})
		$("#share").show();
	},
	
	hideShare : function() {
		$("#share").hide();
	},
	
	
	
	/***********************************************************************
	*                                                                      *
	*                          Search Results Page                         *
	*                                                                      *
	***********************************************************************/
	
	monitor : function(e) {
		if (!e) var e = window.event;
		var target = (window.event) ? e.srcElement : e.target;
	
		if($.browser.msie) {
			var search = document.getElementById("search").contains(target);
			var share = document.getElementById("share");
			var share = (share) ? share.contains(target) : false;
			
			if( ! search || (target && share)) {
				$("#search").hide();
				site.hideShare();
			}
		} else {
			if( ! ($.contains( document.getElementById("search"), target) ||
		    	(e.target && ($.contains( document.getElementById("share"), target) || document.getElementById("share") == target) )) ) {
				$("#search").hide();
				site.hideShare();
			}
		}
	},
	
	/**
	* Method to query the server for JSON search results
	*
	* @param	term	The search string
	* @param	isLive	Whether this is for the live search drop down (true) or the search results page (false)
	*/
	search : function(term, isLive) {
		// cancel search and content calls
		site.cancelRequest();
		
		// Only do a search if there is something to search for
		if(term.length > 0) {
			site.xhrSearch = $.ajax({
				url: "/search/" + term,
				dataType: "json",
				live: isLive ? isLive : false,
				term: term,
				success: site.parseSearch
			});
		} else {
			$("#search").hide();
			
			if(!isLive) {
				site.parseSearch(null);
			}
		}
	},
	
	/**
	* Method to cancel any active XMLHTTPRequest search calls
	*/
	cancelSearch : function() {
		clearTimeout(site.searchTimeout);
	
		if(site.xhrSearch) {
			site.xhrSearch.abort();
		}
	},
	
	liveSearch : function(e) {
		var code = e.keyCode ? e.keycode : e.which;
		var live = !(e.keyCode == 13);	// If the enter key is pressed then we go to the full search result page not the drop down
		var term = $(this).val();
	
		site.cancelSearch();
		site.searchTimeout = setTimeout(function() { site.search( term, live ) }, site.searchDelay );
	},
	
	fetchSearch : function() {
		site.showLoader("search");
	
		site.trackPageChange();
	
		var term = this.params["term"] || "";
	
		site.cancelSearch();
		site.search( term, false );
	},
	
	parseSearch : function(data) {
		site.hideLoader("search");
	
		$("#search").hide();
	
		if(data.results.content) {
			site.animateHideCollection();
		
			var results = data.results.content;
			
			$("#search").empty();
			
			if(this.live) {
				var showSeeMore = false;	// if we have search results show the see more button
				var max = 3;
				site.data = data;
				
				for(type in results) {
					if(results[type].length > 0) {
						var items = "<h3>"+type+" ("+results[type].length+")</h3><ul>";
						
						for(var j = 0; j < results[type].length; j++) {
							items += '<li><a href="'+results[type][j].path+'">'+results[type][j].title+'</a></li>';
							
							if(j >= max) {
								break;
							}
						}
						
						items += "</ul>";
						
						$("#search").append(items);
						
						showSeeMore = true;
					}
				}
				
				if(showSeeMore) {
					$("#search").append('<a href="/search/' + this.term + '" class="seemore">See more results</a>');
					$("#search").show();
				} else {
					$("#search").hide();
				}
			} else {
				site.priorToCollection = Path.routes.current;
				
				$("#search").hide();
				$("#searchfield").val("");
				
				// we're out of a collection, lets make sure we aren't forcing the mini logo upon people
				site.inCollection = false;
				site.adjustLogo();
				
				var title = data.results.title || "";
				site.setHeadlineTitle(title);
				site.hideHeadlineVideo();	// stop video and adjust headline
				
				// Mark old content for removal
				site.markForRemoval();
				
				var id = 0;
				
				// Add search results
				for(type in results) {
					if(results[type].length > 0) {
						for(var j = 0; j < results[type].length; j++) {
							var block = site.createSearchResultBlock(j, results[type][j]);
							$("#blocks").isotope('insert', $(block));
						}
						
						var empty = site.createBlock(0, {type: "empty"}, 8, 1);
						$("#blocks").isotope('insert', $(empty));
					}
				}
				
				$("#blocks").isotope({filter:':not(.remove, .contact)'});
				site.blockCleaner = setTimeout(site.removeBlocks, site.animationSpeed);
				
				// Shorten all the titles
				$("#blocks .block.isotope-item .title").ellipsis();
				$("#blocks .block.isotope-item .excerpt").ellipsis();
				
				$("body").removeClass("work blog company contact");
			}
		}
	},
	
	hideSearch : function() {
		$("#search").hide();
	},
	
	createSearchResultBlock : function(id, block) {
		var bg = 2;
		var bgAlt = 5;
	
		var node = null;
		var data = {};
		data.id = id;
		
		data.type = block.type;
		data.title = block.title;
		data.client = block.client || "";
		data.excerpt = block.excerpt || "";
		data.path = block.path;
		
		if(block.image && data.type == "work") {
			data.image = site.createImage( block.image.src, site.colWidth*2, site.rowHeight, block.image.focalX, block.image.focalY );
			if( (Math.floor(id/2) % 2) == 1 ) {
				data.grey = site.setGreyLevel(bgAlt);
			} else {
				data.grey = site.setGreyLevel(bg);
			}
		} else {
			var add = (id % 8 >= 4) ? 1 : 0;
			
			if( ((id + add) % 2) == 1 ) {
				data.grey = site.setGreyLevel(bgAlt);
			} else {
				data.grey = site.setGreyLevel(bg);
			}
		}
		
		node = ich.search(data);
		
		return node;
	},
	
	
	
	
	/***********************************************************************
	*                                                                      *
	*                         Inline Content Viewer                        *
	*                                                                      *
	***********************************************************************/
	
	formatInlineData : function(index, newer, viewerId) {
		newer = newer ? newer : false;
		
		var inline = $.extend(true, {}, site.data.results.content[index]);
		inline.id = (viewerId >= 0) ? viewerId : null;
		inline.newer = (newer != undefined) ? newer : null;
		
		if(inline.type == "news") {
			inline.share = true;
		}
		
		
		if(inline.image.src) {
			// Build inline image
			if(inline.image.width > 480) {
				inline.image.height = Math.floor(inline.image.height * 480 / inline.image.width);
				inline.image.width  = 480;
			}
			
			inline.image.src = site.createImage(inline.image.src, inline.image.width, inline.image.height);
		} else {
			inline.image = null;
		}
		
		return inline;
	},
	
	createInlineContent : function(index, block, hideNav) {
		$("#blocks div").removeClass("selected");
		$(block).addClass("selected").addClass("visited");
		
		if(index != site.selectedIndex) {
			var animationDelay = 50;
			var existing = (site.selectedIndex != null);
			var inline = site.formatInlineData(index, false, site.inlineId);
			
			// Remove existing inline viewer
			if(existing) {
				site.exitInlineViewer();
				
				setTimeout(function() { $("#blocks").isotope('insertAbove', $(ich.inline(inline)), block)}, site.animationSpeed);
				
				setTimeout(function() { site.animateResizeInlineView(inline.id, hideNav); }, animationDelay + site.animationSpeed);
			} else {
				$("#blocks").isotope('insertAbove', $(ich.inline(inline)), block);
				
				setTimeout(function() { site.animateResizeInlineView(inline.id, hideNav); }, animationDelay);
			}
			
			// Get ready for the next one
			site.selectedIndex = index;
			site.inlineId++;
		}
		
		site.styleInlineNav(index);
	},
	
	switchInlineContent : function(e) {
		var direction = $(this).hasClass("navleft") ? -1 : 1;
		var index = site.selectedIndex + direction;
		
		if(index < site.data.results.content.length && index >= 0) {
			var inline = site.formatInlineData(index, true);
			var content = $(ich.inlinePartial(inline));
			
			$(".viewer.inline .container").addClass("old");
			$("#blocks div").removeClass("selected");
			$("#blocks div[data-id='"+index+"']").addClass("selected").addClass("visited");
		
			if(direction == 1) {
				// Next
				$(".viewer.inline .container.old").css({marginLeft: "960px"});
				$(".viewer.inline .animation-wrapper").append(content);
				$(".viewer.inline .container.old").animate({marginLeft: "0px"}, site.animationSpeed);
			} else {
				// Previous
				$(".viewer.inline .container.old").css({marginLeft: "0px"});
				$(".viewer.inline .animation-wrapper").prepend(content);
				$(".viewer.inline .container.new").animate({marginLeft: "960px"}, site.animationSpeed);
			}
			
			// Adjust container height
			var container = site.setInlineHeight(".viewer.inline .container.new");
			
			var h = Number($(".inline .animation-wrapper").height());
			h = (container.height > h) ? container.height : h;
			
			$(".inline, .viewer.inline .container").css({height: h});
			$(".inline, .viewer.inline .container.new").css({height: container.height});
			$(".inline .animation-wrapper").animate({height: container.height});
			$("#blocks").isotope('reLayout');
			
			// Position and animate in next and back buttons for the inline content viewer
			$("#viewerControls").css({height: container.height});
			$("#viewerControls .wrapper").animate({height: container.height});
			
			site.selectedIndex = index;
			
			setTimeout(function() {
				$(".viewer.inline .container.old").remove();
				$(".viewer.inline .container.new").removeClass("new").css({marginLeft: "960px"});
			}, site.animationSpeed);
		}
		
		site.styleInlineNav(index);
	},
	
	styleInlineNav : function(index) {
		if(index <= 0) {
			$(".navleft").addClass("disabled");
		} else {
			$(".navleft").removeClass("disabled");
		}
		
		if(index >= (site.data.results.content.length - 1)) {
			$(".navright").addClass("disabled");
		} else {
			$(".navright").removeClass("disabled");
		}
	},
	
	exitInlineViewer : function(e) {
		site.removeInlineNavigation();
		$("#blocks div").removeClass("selected");

		setTimeout(function() {
			$(".inline").removeClass("no-animation");
			$(".inline").addClass("remove");
			$("#blocks").isotope({filter:':not(.remove, .contact)'});
		}, site.quickAnimationSpeed);	
		
		site.selectedIndex = null;
	},
	
	/****************************  ANIMATIONS  ****************************/
	scrollInlineContent : function(e) {
		$(this).siblings().removeClass("selected");
		$(this).addClass("selected");
	
		var page = $(".inline .container article").height() * $(this).index();
		$(".inline .container article").animate({scrollTop:page});
	},
	
	animateShowInlineView : function(e) {
		$("#blocks").isotope('insertAbove', $(ich.inline({})), this);
		setTimeout(site.animateResizeInlineView, 100);
	},
	
	setInlineHeight : function(container) {
		$(container).css("height", "auto");
	
		var viewableHeight = $(window).height();
		var containerHeight = $(container).height();
		
		if(containerHeight > viewableHeight) {
			// Display Pagination controlls
			$(container + " ul.internal").show();
		
			// Determine the maximum content height
			var articleBuffer = $(container + " .details").outerHeight(true) - $(container + " article").height();
			var maxHeight = viewableHeight - $("header").height() - articleBuffer;
			maxHeight = Math.floor( maxHeight / 20 ) * 20;
			maxHeight = (maxHeight > 500) ? 500 : maxHeight;
			
			// Determine amount of pages
			var articleHeight = $(container + " article").height();
			var pages = Math.ceil( articleHeight / maxHeight );
			
			// Scroll to top of content (just in case)
			$(container + " article").css({height: maxHeight, overflow: "hidden"}).scrollTop(0);
			
			// Add pagination
			for(var i = 0; i < pages; i++) {
				if(i == 0) {
					$(container + " ul.internal").append('<li class="info selected">'+i+'</li>');
				} else {
					$(container + " ul.internal").append('<li class="info">'+i+'</li>');
				}
			}
			
			return {center: 0, height: maxHeight+articleBuffer};	
		} else {
			// its small emough to center
			return {center: Math.round((viewableHeight - containerHeight)/2) - 32, height: containerHeight};
		}
	},
	
	animateResizeInlineView : function(id, hideNav) {
		site.removeBlocks();
	
		var container = site.setInlineHeight("#inline"+id+" .container");
		
		$("#inline"+id+" .container").height("0px");
		$("#inline"+id).height(container.height);
		$("#inline"+id+" .container").animate({height: container.height});
		$("#blocks").isotope('reLayout');
		
		var offsetBlocks = 172; // When moving from homepage to anyplace the dynamic method screws up //$("#blocks").offset().top || 0;
		var offsetRow = $("#inline"+id).data('isotope-item-position').y || 0;
		
		$("#blocks div[data-id='"+site.selectedIndex+"']").addClass("selected").addClass("visited");
				
		// !Scroll to Top
		if(site.autoCenter) {
			$("html, body").delay(site.animationSpeed).animate({scrollTop:offsetBlocks+offsetRow-64-container.center});
		} else {
			site.autoCenter = true;
		}
		
		// Position and animate in next and back buttons for the inline content viewer
		if(!hideNav) {
			$("#viewerControls .wrapper").height( container.height );
			$("#viewerControls").css({top: offsetBlocks+offsetRow}).show();
			$("#viewerControls .navleft .icon, #viewerControls .navright .icon").delay(site.animationSpeed).animate({marginLeft: "0px"}, site.quickAnimationSpeed);
		}
	},
	
	removeInlineNavigation : function() {
		$("#viewerControls .navleft .icon").stop().animate({marginLeft: "31px"}, site.quickAnimationSpeed);
		$("#viewerControls .navright .icon").stop().animate({marginLeft: "-31px"}, site.quickAnimationSpeed);
	},
	
	
	
	
	/***********************************************************************
	*                                                                      *
	*                           Collection Viewer                          *
	*                                                                      *
	***********************************************************************/
	// !Collection Viewer
	/**
	* Parse a JSON object into the collection viewer
	*/
	parseCollection : function(data) {
		site.hideLoader("collection");
	
		if(data.results.content) {
			var content = data.results.content;
			
			// Hide Homepage Video Player
			site.hideHeadlineVideo(true);

			// Mark old content for removal
			site.markForRemoval();
			
			// Gather all the collection data
			if(content.length > 0) {
				var collectionData = content[0];
				collectionData.mediums = site.createMediumList(collectionData);
				
				var collection = ich.collection(collectionData);
				$("#blocks").isotope('insert', $(collection));
				
				var h = $("#blocks .collection .content-wrapper").outerHeight(true) + "px";
				$("#blocks .collection ").height(h);
				$("#blocks .collection .animation-wrapper").height(0).animate({height: h});
			}
			
			// Create the gallery
			site.gallery = content[0];
			site.createGallery();
			
			$("#blocks").isotope({filter:'.collection'});
			site.blockCleaner = setTimeout(site.removeBlocks, site.animationSpeed);
			setTimeout(site.resize, site.animationSpeed);
			
			site.jumpToCorrectItem();
			
			$("body").removeClass("blog company contact").addClass("work");
			document.title = content[0].title + " | Work | The Martin Agency";
		}
	},
	
	/**
	* Helper function that builds a unique list of media associated with the collection
	*/
	createMediumList : function(data) {
		var mediums = [];
		
		for(var i = 0; i < data.collection.length; i++) {
			var type = data.collection[i].medium;
			
			// Search for duplicates
			var found = false;
			for(var j = 0; j < mediums.length; j++) {
				if(mediums[j] == type) {
					found = true;
					break;
				}
			}
			
			// Only add unique items
			if(!found) {
				mediums.push(type);
			}
		}
		
		mediums.sort();
		
		return mediums.join(", ");
	},
	
	
	/******************************  ROUTES  ******************************/
	enterCollection : function() {
		site.trackPageChange();
	
		// If we're navigating within the same collection don't allow PathJS to call the to and exit methods
		if(!site.withinSameCollection()) {
			site.jumpToCorrectItem();
		
			return false;
		}
	},
	
	exitCollection : function() {
		// If we're navigating outside the collection then remove the collection viewer
		if(site.withinSameCollection()) {
			site.cleanUp();
		}
	},
	
	fetchCollection : function(forcedPath) {
		site.allowInfinite = false;
	
		site.showLoader("collection");
	
		// show mini logo when in the collection
		site.inCollection = true;
		site.adjustLogo();
	
		site.cancelRequest();
		
		site.xhrJSON = $.ajax({
			url: site.normalizeRoute(forcedPath),
			dataType: "json",
			success: site.parseCollection
		});
	},
	
	/**
	* Method to determine if the user is navigating within the same
	* collection, but using the routes.
	*/
	withinSameCollection : function() {
		var prev = Path.routes.previous;
		
		if(prev != "" && prev != null) {
			var prevParts = prev.split("/");
			var currParts = Path.routes.current.split("/");
			
			if(prevParts.length >= 3 && currParts.length >= 3) {
				if( prevParts[1] == currParts[1] && prevParts[2] == prevParts[2] ) {
					return false;
				}
			}
		}
		
		return true;
	},
	
	collectionItem : function() {
		var currParts = Path.routes.current.split("/");
		
		if(currParts.length == 4) {
			return currParts[3];
		} else {
			return null;
		}
	},
	
	jumpToCorrectItem : function() {
		var item = site.collectionItem();
		
		if(!isNaN( item ) && item != null) {
			site.animateShowCollection();
			site.gotoGalleryItem(item - 1);
		} else {
			site.animateHideCollection();
		}
	},
	
	
	
	/****************************  ANIMATIONS  ****************************/
	
	/**
	* Hide the collection's gallery via CSS animations
	*/
	animateHideCollection : function(e) {
		site.stopAllVideos();
	
		$("#collection").addClass("initial");
		site.hideCollectionTimeout = setTimeout(function() {
			$("#collection").hide();
		}, 500);
		
		$("#blocks, footer").show();
		$("#collection .mejs-controls").hide();
	},
	
	/**
	*Show the collection's gallery via CSS animations
	*/
	animateShowCollection : function(e) {
		$("#collection").show();
		clearTimeout(site.hideCollectionTimeout);
		
		setTimeout(function() {
			$("#collection").removeClass("initial");
			$("#collection .mejs-controls").show();
		}, 50);
		
		$("#blocks, footer").hide();
	},
	
	
	
	/*****************************  ACTIONS  ******************************/
	
	/**
	* Open the collection's gallery view
	*/
	openCollection : function(e) {
		var path = Path.routes.current + "/1";
		path = path.replace("#","");
		
		site.animateShowCollection();
		site.goto(path);
	},
	
	/**
	* Hide the collection and jump to the work
	*/
	closeCollection : function(e) {
		//site.animateHideCollection();
		
		if(site.priorToCollection) {
			site.goto(site.priorToCollection);
		} else {
			site.goto("/work");
		}
	},
	
	closeGallery : function(e) {
		site.stopAllVideos();
		site.goto(site.galleryPath);
	},
	
	setVideoPlayers : function(skipTimeout, autoHideControls, noShim) {
		site.videoOptions.hideControlsAtStartup = (autoHideControls ? autoHideControls : false);
		
		if(site.isSafari || $.browser.mozilla) {
			setTimeout(function(){ site.styleVideoPlayers(noShim) }, 100 ); // site.animationSpeed+100
		} else {
			site.styleVideoPlayers(noShim);
		}
	},
	
	styleVideoPlayers : function(noShim) {
		var v = site.videoOptions;
		v.shim = (noShim) ? false : site.videoOptions.shim;
	
		$("video").mediaelementplayer(site.videoOptions);
		
		site.updateGalleryLayout();
	},
	
	
	
	
	/***********************************************************************
	*                                                                      *
	*                             Gallery View                             *
	*                                                                      *
	***********************************************************************/
	galleryNavThumbWidth	: 157,
	currentGalleryItem		: 0,
	totalGalleryItems		: 0,
	galleryPath				: "",
	resizeGalleryTimer		: null,
	
	createGallery : function() {
		// Clear any existing gallery
		site.clearGallery();
		
		// Build the new gallery
		var size = site.gallery.collection.length;
		var basePath = site.gallery.path;
		site.totalGalleryItems = size;	
		site.galleryPath = basePath;	
		
		$("#collection .header .client h2").html(site.gallery.client);
		$("#collection .header .campaign h2").html(site.gallery.title);
		
		// Build Navigation
		$("#collection .navigation ul.internal").append('<li class="info"><a href="'+basePath+'">Info</a></li>');
		
		$("#collection .gallery .prev ul").append('<li><img src="/imgs/buttons/nav-gallery-title.png"></li>');
		
		for(var i = 0; i < size; i++) {
			// create gallery items
			if(site.gallery.collection[i].type == "video") {
				var video = {};
				video.name = "collection_video" + site.videoId++;
				video.width = 960;
				video.height = 540;
				video.formats = site.formatForCDN( site.gallery.collection[i].video );
				video.image = site.createImage(site.gallery.collection[i].image, video.width, video.height);
				video.ipad = site.isiPad;
				
				$("#collection .gallery ul.content").append( $("<li>").append(ich.video(video)) );
			} else {
				$("#collection .gallery ul.content").append('<li><img src="'+site.gallery.collection[i].image+'"></li>');
			}
						
			
			// create nav
			$("#collection .gallery ul.nav").append('<li><img src="'+site.createImage(site.gallery.collection[i].thumb, 157, 100)+'"></li>');
			$("#collection .navigation ul.internal").append('<li class="item"><a href="'+basePath+'/'+(i+1)+'"></a></li>');
		}
		
		$("#collection .gallery .next ul").append('<li><img src="/imgs/buttons/nav-gallery-title.png"></li>');
		
		$("#collection .gallery .nav").width(site.galleryNavThumbWidth * (size+1));
		site.updateGalleryLayout();
		site.gotoGalleryItem(0);
		
		$("html, body").scrollTop(0);
		site.setVideoPlayers();
	},
	
	updateGalleryLayout : function() {
		var w = $(window).width();
		var minW = (w < 960) ? 960 : w;
		var h = $(window).height() - 130 - 66;
	
		$("#collection .gallery .content").width( w * site.totalGalleryItems );
		$("#collection .gallery .content li").width( w );
		$("#collection .gallery").height( h );
		
		
		var videos = $("#collection .gallery .video-item");
		for(var i = 0; i < videos.length; i++) {			
			if((h/9*16) > minW) {
				var newH = (Math.round(minW/16*9));
				$(videos[i]).height(newH).css("margin-top", (h-newH)/2);
				$(videos[i]).width(minW);
				
				var offset = -33 - (h - newH)/2;
				$("#collection .mejs-controls").css("bottom", offset);
			} else {
				$(videos[i]).height(h).css("margin-top", 0);
				$(videos[i]).width(Math.round(h/9*16));
				
				$("#collection .mejs-controls").css("bottom", -33);
			}
			
			if(site.isiPad) {
				$(videos[i]).height(450).css("margin-top", (h-450)/2);
				$(videos[i]).width(800);
				
				var offset = -33 - (h - 450)/2;
				$("#collection .mejs-controls").css("bottom", offset);
			}
		}
		
		// Fix images
		var images = $("#collection .gallery .content li > img");
		for(var j = 0; j < images.length; j++) {
			var image = $( images[j] );
			image.css({width : "auto", height: "100%", "margin-top" : "0px"});
		
			if( image.width() > w ) {
				image.css({width : "100%", height: "auto"});
				image.css({"margin-top": (h - image.height())/2 });
			}
		}
		
		
		$("#collection .gallery .content").addClass("no-animation");
		$("#collection .gallery .content").css({marginLeft: (-w * site.currentGalleryItem) +"px"});
		
		// Need to remove the class a fraction of a second after we set the margins
		clearTimeout(site.resizeGalleryTimer);
		site.resizeGalleryTimer = setTimeout(function() { $("#collection .gallery .content").removeClass("no-animation"); }, 25);
	},
	
	clearGallery : function() {
		$("#collection .navigation ul.internal").empty();
		$("#collection .gallery ul").empty();
	},
	
	/*****************************  ACTIONS  ******************************/
	gotoNextGalleryItem : function() {
		var nextItem = site.currentGalleryItem + 2;
		
		if(nextItem > 0 && nextItem <= site.totalGalleryItems) {
			site.goto(site.galleryPath + "/" + (nextItem));
		} else {
			site.goto(site.galleryPath);
		}
	},
	
	gotoPrevGalleryItem : function() {
		var prevItem = site.currentGalleryItem;
		
		if(prevItem > 0 && prevItem <= site.totalGalleryItems) {
			site.goto(site.galleryPath + "/" + (prevItem));
		} else {
			site.goto(site.galleryPath);
		}
	},
	
	gotoGalleryItem : function(index) {
		$("#collection .gallery .content").css({marginLeft: (-$(window).width() * index) +"px"});
		
		$("#collection .gallery .prev ul").css({'margin-left' : -site.galleryNavThumbWidth * index });
		$("#collection .gallery .next ul").css({'margin-left' : -site.galleryNavThumbWidth * (index+1) });
		
		site.currentGalleryItem = index;
		
		$("#collection .footer .navigation .internal li").removeClass("selected");
		$("#collection .footer .navigation .internal li:nth-child("+(index+2)+")").addClass("selected");
		
		$("#collection .footer .caption .wrapper").html("<span>"+site.gallery.collection[index].caption+"</span>");
		$("#collection .header .title h2").html(site.gallery.collection[index].title);
		
		site.stopAllVideos();
	},
	
	stopAllVideos : function() {
		// I'm sorry about using anonymous functions mom, please forgive me.
	
		// stop the html 5 videos
		$("video").each(function() {
			try {
				$(this).get(0).pause();
			} catch(err) {
				// no pause on video tag (IE8 and below)
			}
		});
		
		// stop the flash videos
		$(".video-item embed, .video-item object").each(function() {
			try {
				$(this).get(0).pauseMedia();
			} catch(err) {
				// Flash Error
			}
		});
	},
	
	cancelRequest : function() {
		site.cancelSearch();
	
		if(site.xhrJSON) {
			site.xhrJSON.abort();
		}
	}
	
}

$(document).ready(site.init);
