var lastKeywordSearch = "";
var strategy = 0;
var creative = 0;
var mediaVar = 0;
var analytics = 0;
var twitterURL = 'http://twitter.com/#!/AREA203Digital';
var searching;
var initial = 0;
var blogServer = "http://area2oh3.com/203api";
//var blogServer = "http://area203blog.local/203api";
var animatedSlidersYet = false;
var scrollPoint = 225;
var isMobile = null;
var changingInputs = false;
var keypressTimeout = null;
var slider;
var justLoadedHorizList = false;
var interruptHash = false;
var hashKeys = new Array();
var hashValues = new Array();
var hashToBe;
var hashed = true;
var modalOpen = false;
var detailsOpen = false;
var backButton = false;

function clearChangingInputs() {
	changingInputs = false;
}

jQuery.noConflict();
(function($) {

	$('a[href^="http:"]:not(a[href^="http://' + document.location.hostname + '"])').click(function () {
		try {
			s.linkTrackVars = 'prop1';
			s.linkTrackEvents = 'None';
			s.prop1 = 'Exit: '+$(this).attr('href');
			s.tl(this, 'e');
			
		} catch (e) {}
	});
	
	if (window.location.hash && window.location.hash != '#') {
		animatedSlidersYet = true;
		parseHash(window.location.hash);
	} else {
		hashed = false;
		parseHash('type=slider');
	}
	
	$(window).hashchange(function() {
		parseHash(window.location.hash);
	});
	
	var deviceAgent = navigator.userAgent.toLowerCase();
	isMobile = deviceAgent.match(/(iphone|ipod|ipad|android)/);
	
	searching = $('#searching');

	$(function() {
		// Contact form validation
		$('#contact-form, .contact-form').validate({
			rules: {
				from_name: "required",
				from_email: {
					required: true,
					email: true
				},
				message: "required"
			},
			messages: {
				from_name: 'Required',
				from_email: {
					required: 'Required',
					email: 'Invalid Address'
				},
				message: "Required"
			},
			submitHandler: function() {
				$.get(contactScript, {
					from_name: $('#from_name').val(),
					from_email: $('#from_email').val(),
					message: $('#message').val()
				}, function(data) {
					alert(data);
					$('#from_name, #from_email, #message').val('');
				});
			}
		});
		
		// Contact form ajax
		var contactScript = $('#contact-form').attr('action');
		$('#contact-form').removeAttr('action');

		// Strategy Slider
		$("#strategy").slider({
			value: (hashed && !isNaN(hashValues[1])) ? hashValues[1] : 0,
			min: 0,
			max: 10,
			step: 1,
			slide: function(event, ui) {
				activate();
				interruptHash = false;
				$("#strategySlider").val(ui.value);
			},
			start: function() { changingInputs = true; },
			stop: function() { changingInputs = false; }
		});
		$("#strategySlider").val($("#strategy").slider("value"));
		strategy = $("#strategy").slider("value");
		
		// Creative Slider
		$("#creative").slider({
			value: (hashed && !isNaN(hashValues[2])) ? hashValues[2] : 0,
			min: 0,
			max: 10,
			step: 1,
			slide: function(event, ui) {
				activate();
				interruptHash = false;
				$("#creativeSlider").val(ui.value);
			},
			start: function() { changingInputs = true; },
			stop: function() { changingInputs = false; }
		});
		$("#creativeSlider").val($("#creative").slider("value"));
		creative = $("#creative").slider("value");

		// Media Slider
		$("#media").slider({
			value: (hashed && !isNaN(hashValues[3])) ? hashValues[3] : 0,
			min: 0,
			max: 10,
			step: 1,
			slide: function(event, ui) {
				activate();
				interruptHash = false;
				$("#mediaSlider").val(ui.value);
			},
			start: function() { changingInputs = true; },
			stop: function() { changingInputs = false; }
		});
		$("#mediaSlider").val($("#media").slider("value"));
		mediaVar = $("#media").slider("value");

		// Analytics Slider
		$("#analytics").slider({
			value: (hashed && !isNaN(hashValues[4])) ? hashValues[4] : 0,
			min: 0,
			max: 10,
			step: 1,
			slide: function(event, ui) {
				activate();
				interruptHash = false;
				$("#analyticsSlider").val(ui.value);
			},
			start: function() { changingInputs = true; },
			stop: function() { changingInputs = false; }
		});
		$("#analyticsSlider").val($("#analytics").slider("value"));
		analytics = $("#analytics").slider("value");
		
		// Unbind keys
		$('#strategy .ui-slider-handle, #creative .ui-slider-handle, #media .ui-slider-handle, #analytics .ui-slider-handle').unbind('keydown');
		
		$("#keyword").keypress(function() {
			changingInputs = true;
			clearTimeout(keypressTimeout);
			keypressTimeout = setTimeout("clearChangingInputs()", 1000);
		});
		galleryCheck();
		
		// Nav to populate search
		$('.filter').click(function() {
			interruptHash = false;
			$('#keyword').val($(this).text());
		});
		
		// view-positions
		$('#view-positions').click(function() {
			$('#keyword').val('jobs');
		});
		
		// Logo to reset
		$('#site-logo').click(function() {
			resetLocation = window.location.href;
			resetLocation = resetLocation.split('#');
			window.location.href = resetLocation[0];
		});
	
		/*
		$('#horizList').jcarousel({
			initCallback: carousel_initCallback,
			scroll: 6,
	        buttonNextHTML: null,
	        buttonPrevHTML: null
		});
		*/
		
		// Setup map iframe if we're not mobile
		if (!isMobile)
		{
			$("#map").html('<iframe width="316" height="218" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=1516+Riverside+Drive,+Chattanooga,+TN,+37406&amp;aq=t&amp;sll=37.0625,-95.677068&amp;sspn=56.899383,114.433594&amp;ie=UTF8&amp;hq=&amp;hnear=1516+Riverside+Dr,+Chattanooga,+Tennessee+37406&amp;ll=35.054592,-85.280857&amp;spn=0.015317,0.027037&amp;z=14&amp;output=embed"></iframe>');
		}
		
		// Start after a delay to let the sliders animate the first time round
		setTimeout(function() {
//			check(true, '');
			setInterval(function() { check(false, ''); }, 1000);
			setInterval(function() { checkSearching(); }, 3000);
		}, 2250);

		if ($('#keyword').val() && $('#keyword').val() != '') {
			interruptHash = true;
			animatedSlidersYet = true;
			keywordSearch(true);
		}

/*
		if (searchParam != "") {
			$('#keyword').val(searchParam);
		} else if (personParam != "") {
			getDetails("departments/" + personParam, true);
		} else if (caseParam != "") {
			getDetails("disciplines/" + caseParam, true);
		} else {
			check(true, false);
		}
*/
		
//		setInterval(function() { check(false, ''); }, 1000);
//		setInterval(function() { checkSearching(); }, 3000);

		$('.privacy-policy').click(function() {
			$('#privacy-policy').modal({
				onOpen: function(dialog) {
					if (isMobile) {
						dialog.overlay.show();
						dialog.container.show();
						dialog.data.show();
					} else {
						dialog.overlay.fadeIn('fast', function() {
							dialog.data.show();
							dialog.container.fadeIn('slow');
						});
					}
				},
				onClose: function(dialog) {
					if (isMobile) {
						dialog.overlay.hide();
						dialog.container.hide();
						dialog.data.hide();
						$.modal.close();
					} else {
						dialog.container.fadeOut('slow', function() {
							dialog.data.hide();
							dialog.overlay.fadeOut('fast', function() {
								$.modal.close();
							});
						});
					}
				},
				containerCss: {
					backgroundColor:"#d3d2d2",
					width:960,
					minHeight:605,
					padding: '40px 20px 20px'
				},
				opacity: 80
			});
		});
		
	});
	
	function animateSliders() {
		animatedSlidersYet = true;
		if (isMobile)
		{
			return;
		}
			
		slideDelay = 200;
		slideCount = $('a.ui-slider-handle').length;
		for (i=0; i<slideCount; i++) {
			$('a.ui-slider-handle').eq(i).delay(slideDelay).animate({left:'100%'}, 750, function() {
				$(this).animate({left:'0%'}, 750);
			});
			slideDelay = slideDelay + 200;
		}
	}
	/*
	function carousel_initCallback(carousel) {
	    $('#horizList-next').bind('click', function() {
	        carousel.next();
	        return false;
	    });
	
	    $('#horizList-prev').bind('click', function() {
	        carousel.prev();
	        return false;
	    });
	}
	*/
	
	function loadingFade() {
		var currentDisplayStatus = $("#searching").css('display');

		if (currentDisplayStatus=='block') {
			if (isMobile) {
				$("#searching").hide();
			} else {
				$("#searching").fadeOut();
			}
		} else {
			if (isMobile) {
				$("#searching").show();
			} else {
				$("#searching").fadeIn();
			}
		}
	}
	function activate() {
		$('#filters').removeClass('inactive');
		$('#keyword').val('');
		lastKeywordSearch = "";
	}
	function deactivate(type) {
		$('#filters').addClass('inactive');
		$("#strategy").slider("value", 0);
		$("#creative").slider("value", 0);
		$("#media").slider("value", 0);
		$("#analytics").slider("value", 0);
		$("#strategySlider").val(0);
		$("#creativeSlider").val(0);
		$("#mediaSlider").val(0);
		$("#analyticsSlider").val(0);
		creative = 0;
		strategy = 0;
		mediaVar = 0;
		analytics = 0;
		if (type) {
			activate();
			check(true, '');
		}
	}
	function resetDetails() {
		
		var currentDisplayStatus = $("#details").css('display');
		if (isMobile)
		{
			if (currentDisplayStatus=='block') {
				$('#results').show();
			}
			$('#details, #contact-details').hide();
			$('#horizListContainer').hide();
		}
		else
		{
			if (currentDisplayStatus=='block') {
				$('#results').css({opacity:0}).slideDown('fast', function() {
					$(this).animate({opacity:1}, 'slow');
				});
			}
	
			if (personParam=='') {
				$('#details, #contact-details').animate({opacity:0}, 'slow', function() {
					$(this).slideUp();
				});
				$('#horizListContainer').animate({opacity:0}, 'slow', function() {
					$(this).slideUp();
				});
			}
		}

		detailsOpen = false;
	}
	
	function check(force, type) {
		if (changingInputs)
			return;
				
/* hash change
		if ($('#keyword').val()) {
			keywordSearch(force);
		} else if (interruptHash == false) {
			hashToBe =	'type=slider';
			hashToBe +=	'&strategy=' + $("#strategy").slider('value');
			hashToBe +=	'&creative=' + $("#creative").slider('value');
			hashToBe +=	'&media=' + $("#media").slider('value');
			hashToBe +=	'&analytics=' + $("#analytics").slider('value');
			window.location.hash = hashToBe;
		} else {
			sliderSearch(force);
		}
*/
		
		$('#keyword').val(jQuery.trim($('#keyword').val()));
		if (interruptHash == false) {
			if ($('#keyword').val()) {
				hashToBe =	'type=keyword';
				hashToBe +=	'&keyword=' + $('#keyword').val();
			} else {
				hashToBe =	'type=slider';
				hashToBe +=	'&strategy=' + $("#strategy").slider('value');
				hashToBe +=	'&creative=' + $("#creative").slider('value');
				hashToBe +=	'&media=' + $("#media").slider('value');
				hashToBe +=	'&analytics=' + $("#analytics").slider('value');
			}
			window.location.hash = hashToBe;
		} else if ($('#keyword').val() && $('#keyword').val() != lastKeywordSearch) {
			hashToBe =	'type=keyword';
			hashToBe +=	'&keyword=' + $('#keyword').val();
			window.location.hash = hashToBe;
			keywordSearch(force);
		} else {
			sliderSearch(force);
		} 
	}
	function checkSearching() {
		var currentStatus = $(searching).css('display');
		if (currentStatus=='block') {
			$(searching).fadeOut();
		}
	}

	function sliderSearch(force)
	{
		
/* hash changes
		if (force ||
			$("#creativeSlider").val() != creative ||
			$("#strategySlider").val() != strategy ||
			$("#mediaSlider").val() != media ||
			$("#analyticsSlider").val() != analytics)
		{
*/
		if (force ||
			$("#strategy").slider("value") != strategy ||
			$("#creative").slider("value") != creative ||
			$("#media").slider("value") != mediaVar ||
			$("#analytics").slider("value") != analytics)		
		{
		
/* hash changes
			strategy = $("#strategySlider").val();
			creative = $("#creativeSlider").val();
			media = $("#mediaSlider").val();
			analytics = $("#analyticsSlider").val();
*/
						
			activate();
			interruptHash = true;
			
			clearAllItems($("#results"));
	
			// Don't want to close if we're first in here
			if (personParam == "" || caseParam == "") {
				resetDetails();
			}
	
			if (initial==1) {
				loadingFade();
			}
		
			strategy = $("#strategy").slider("value");
			creative = $("#creative").slider("value");
			mediaVar = $("#media").slider("value");
			analytics = $("#analytics").slider("value");
			
			s.linkTrackVars = 'prop1, prop2, prop3, prop4';
			s.linkTrackEvents = 'None';
			s.prop1 = 'Creative: '+creative;
			s.prop2 = 'Strategy: '+strategy;
			s.prop3 = 'Media: '+mediaVar;
			s.prop4 = 'Analytics: '+analytics;
			s.tl(this, 'o');
			
			$.getJSON(blogServer + "?jsoncallback=?",
				{
					req: "slidersearch",
					creative: creative,
					strategy: strategy,
					media: mediaVar,
					analytics: analytics
				},
				function(data) { gotResults(data); }
			);
			initial = 1;
		}
	}
	
	function keywordSearch(force)
	{
		if (force || $("#keyword").val() != lastKeywordSearch)
		{
			if ($("#keyword").val().toLowerCase()=='contact') {
				getDetails('contact-us', '', true);
			} else {
			
				clearAllItems($("#results"));
				resetDetails();
				
				deactivate();
				
				if (initial==1)
				{
					loadingFade();
				}
		
				s.linkTrackVars = 'prop1';
				s.linkTrackEvents = 'None';
				s.prop1 = 'Keyword: '+$("#keyword").val();
				s.tl(this, 'o');
			
				$.getJSON(blogServer + "?jsoncallback=?",
					{
						req: "livesearch",
						keyword: $("#keyword").val()
					},
					function(data) { gotResults(data); }
				);
			}
			lastKeywordSearch = $("#keyword").val();
		}
		initial = 1;
	}
	
	function gotResults(data)
	{	
		createGrid(data);
		createHorizScroller(data);

		if (!animatedSlidersYet)
		{
			animateSliders();
		}
	}
	
	// 1 - 145 x 120
	// 2 - 308 x 120
	// 3 - 471 x 120
	// 4 - 308 x 260
	// 5 - 471 x 260
	// 6 - 634 x 260
	
	//var thumbWidths = [0, 145, 290, 435, 290, 435, 580];
	//var thumbHeights = [0, 120, 120, 120, 240, 240, 240];
	var thumbWidths = [0, 145, 308, 471, 308, 471, 634];
	var thumbHeights = [0, 120, 120, 120, 260, 260, 260];
	
	function createHorizScroller(data)
	{
		var h = "";
		var newHtml = "";
		indexCount = 0;
		for (index in data)
		{
			var result = data[index];
			
			if (result.filler == "1") {
				break;
			}
				
			var author = '';
			var excerpt = '';
			var read_more = '';
/* 			var link = result.post_type+'/'+result.post_name; */
			var link =	'#type=details&name='+escape(result.post_name);
			var filler = (result.filler == "1") ? " filler-item " : "";
			var linkTarget = '';
			
			/* excerpt trimming */
			if (result.excerpt&&thumbHeights[result.thumbId]==120) {
				result.excerpt = trimByWord(result.excerpt, 10);
			} else if (result.excerpt&&thumbHeights[result.thumbId]>=260) {
				result.excerpt = trimByWord(result.excerpt, 20);
			}
				
			if (result.excerpt) {
				result.excerpt = trimShortcode(result.excerpt);
			}
				
			/* title trimming */
			if (result.post_type=='post'&&result.post_title.length>60) {
				result.post_title = trimByWord(result.post_title, 8);
			}
				
			/* change link for case studies */
			if (result.post_type=='case_studies') {
/* 				link = 'disciplines/'+result.post_name; */
				link =	'#type=details&name='+escape(result.post_name);
				link +=	'&related=disciplines';
			}
				
			/* change link for disciplines */
			if (result.post_type=='disciplines' || result.post_type=='people') {
/* 				link = 'departments/'+result.post_name; */
				link =	'#type=details&name='+escape(result.post_name);
				link +=	'&related=departments';
			}
			
			if (result.post_name == 'work') {
				link =	'#type=keyword&keyword='+escape(result.post_name);
			}

			/* change link for people */
			if (result.post_name == 'people') {
				link =	'#type=keyword&keyword=people'
			}
			
			/* Tweets target _blank */
			if (result.post_type=='tweets')
				linkTarget = 'target="_blank"';
				
				
			primary_cat = '';
			switch (result.post_type) {
				case 'post':
					author = "<p class='author'>Posted by " + result.display_name + " on " + dateFormat(mysqlTimeStampToDate(result.pdate), "mmmm dS, yyyy") + "</p>";
					excerpt = "<div class='excerpt'>" + result.excerpt + "</div>";
					read_more = "<div class='read-more'>Read More</div>";
					a_class = 'interceptHoriz';
					if (result.primary_cat) {
						primary_cat = result.primary_cat;
					}
					break;
				case 'tweets':
					link = twitterURL;
					a_class = '';
					break;
				default:
					a_class = 'interceptHoriz';
			}
			
			var thumbId = 1;
			if (result.thumb_1 != null) { thumbId = 1; }
			else if (result.thumb_2 != null) { thumbId = 2; }
			else if (result.thumb_3 != null) { thumbId = 3; }
			
			if (result["thumb_" + thumbId] != null)
			{
				h = "<div class='item " + result.post_type + " " + primary_cat + " " + filler + "'><a class='interceptHoriz' href='" + link + "'><img src='" + result["thumb_" + thumbId] + "' width='" + thumbWidths[thumbId] + "' height='" + thumbHeights[thumbId] + "' alt='" + result.post_title + "'/></a></div>";
			} else {
				h = "<div class='item " + result.post_type + " " + primary_cat + " size_" + thumbWidths[thumbId] + "x" + thumbHeights[thumbId] + " " + filler + "' style='width:" + thumbWidths[thumbId] + "px; height:" + thumbHeights[thumbId] + "px;'><a class='"+a_class+"' href='" + link + "' "+linkTarget+"><div class='padding'><h2>" + result.post_title + "</h2>" + author + excerpt + read_more + "</div></a></div>";
			}
			
			if (result.post_type) {
				newHtml += "<li style='width:" + (thumbWidths[thumbId]+18) + "px;'>" + h + "</li>";
			}
				
//			$("#horizList").jcarousel("add", indexCount, h);
			indexCount++;
		}

//		$("#horizList").jcarousel("size", indexCount);
		justLoadedHorizList = true;
		$('#horizList').html(newHtml);
		if (indexCount > 0) 
		{
			slider = $('#horizList').bxSlider({
				displaySlideQty: 6,
				moveSlideQty: 6,
				infiniteLoop: false,
				controls: false
			});
			$('#horizList-next').click(function() {
				slider.goToNextSlide();
				return false;
			});
	
			$('#horizList-prev').click(function() {
				slider.goToPreviousSlide();
				return false;
			});
		}
		
		interceptHorizLinks();
	}
	
	function createGrid(data)
	{
		var h = [];

		for (index in data)
		{
			var result = data[index];
			result.thumbId = getNearestThumbId(result);
			result.iw = thumbWidths[result.thumbId];
			result.ih = thumbHeights[result.thumbId];
			result.html = getThumbItem(result);
			h.push(result);
		}
		
		positionItems($("#results"), h, $);

		loadingFade();
		interceptLinks();
		galleryCheck();
	}
	
	function getNearestThumbId(result)
	{
		var thumbitems = [];
		if (result.thumb_1 != null) { thumbitems.push(1); }
		if (result.thumb_2 != null) { thumbitems.push(2); }
		if (result.thumb_3 != null) { thumbitems.push(3); }
		if (result.thumb_4 != null) { thumbitems.push(4); }
		if (result.thumb_5 != null) { thumbitems.push(5); }
		if (result.thumb_6 != null) { thumbitems.push(6); }
		
		if (thumbitems.length == 0)
		{
			thumbitems.push(1);
			if (result.filler == 0)
			{
				if (result.post_type=='post') {
					thumbitems.push(2);
					thumbitems.push(4);
					/*thumbitems.push(5);*/
				} else if (result.post_type=='tweets') {
					thumbitems.push(1);
				} else if (result.post_type=='job_postings') {
					thumbitems.push(1);
					thumbitems.push(2);
					thumbitems.push(3);
				} else {
					thumbitems.push(1);
					thumbitems.push(2);
					thumbitems.push(3);
					thumbitems.push(4);
					thumbitems.push(5);
					thumbitems.push(6);
				}
			}
		}
			
		var smallest = thumbitems[0];
		var largest = thumbitems[thumbitems.length-1];
		var newWeight = (result.weight/10)*6;
		
		var nearestThumbId = -1;
		var nearestDelta = 100000;
		var i = 0;
		for (i = 0; i < thumbitems.length; ++i)
		{
			var delta = (thumbitems[i] > newWeight) ? thumbitems[i] - newWeight : newWeight - thumbitems[i];
			if (delta < nearestDelta)
			{
				nearestThumbId = thumbitems[i];
				nearestDelta = delta;
			}
		}
		
		return nearestThumbId;
	}
	
	function getThumbItem(result)
	{
		var author = '';
		var excerpt = '';
		var read_more = '';
/* 		var link = result.post_type+'/'+result.post_name; */
		var link =	'#type=details&name='+escape(result.post_name);
		var filler = (result.filler == "1") ? " filler-item " : "";
		var linkTarget = '';
		
		/* excerpt trimming */
		if (result.excerpt&&thumbHeights[result.thumbId]==120) {
			result.excerpt = trimByWord(result.excerpt, 10);
		} else if (result.excerpt&&thumbHeights[result.thumbId]>=260) {
			result.excerpt = trimByWord(result.excerpt, 20);
		}
			
		if (result.excerpt) {
			result.excerpt = trimShortcode(result.excerpt);
		}
			
		/* title trimming */
		if (result.post_type=='post'&&result.post_title.length>60) {
			result.post_title = trimByWord(result.post_title, 6);
		}
			
		/* change link for case studies */
		if (result.post_type=='case_studies') {
/* 			link = 'disciplines/'+result.post_name; */
			link =	'#type=details&name='+escape(result.post_name);
			link +=	'&related=disciplines';
		}

		/* change link for disciplines */
		if (result.post_type=='disciplines' || result.post_type=='people') {
/* 			link = 'departments/'+result.post_name; */
			link =	'#type=details&name='+escape(result.post_name);
			link +=	'&related=departments';
		}
		
		if (result.post_name == 'work') {
			link =	'#type=keyword&keyword='+escape(result.post_name);
		}

		/* change link for people */
		if (result.post_name == 'people') {
			link =	'#type=keyword&keyword=people'
		}
		
		if (result.post_type=='tweets')
			linkTarget = 'target="_blank"';
			
			
		primary_cat = '';
		switch (result.post_type) {
			case 'post':
				author = "<p class='author'>Posted by " + result.display_name + " on " + dateFormat(mysqlTimeStampToDate(result.pdate), "mmmm dS, yyyy") + "</p>";
				excerpt = "<div class='excerpt'>" + result.excerpt + "</div>";
				read_more = "<div class='read-more'>Continue to blog</div>";
				a_class = 'intercept';
				if (result.primary_cat) {
					primary_cat = result.primary_cat;
				}
				break;
			case 'tweets':
				link = twitterURL;
				a_class = '';
				break;
			default:
				a_class = 'intercept';
		}
		
		if (result.post_title != null)
		{
			if (result.post_type != "post" && result["thumb_" + result.thumbId] != null)
			{
				return /*$(*/"<div class='isotope-item  " + result.post_type + " " + primary_cat + " " + filler + "'><a class='intercept' href='" + link + "' "+linkTarget+"><img src='" + result["thumb_" + result.thumbId] + "' width='" + thumbWidths[result.thumbId] + "' height='" + thumbHeights[result.thumbId] + "' alt='" + result.post_title + "'/></a></div>"/*)*/;
			} else {
				return /*$(*/"<div class='isotope-item " + result.post_type + " " + primary_cat + " size_" + thumbWidths[result.thumbId] + "x" + thumbHeights[result.thumbId] + " " + filler + "' style='width:" + thumbWidths[result.thumbId] + "px; height:" + thumbHeights[result.thumbId] + "px;'><a class='"+a_class+"' href='" + link + "' "+linkTarget+"><div class='padding'><h2>" + result.post_title + "</h2>" + author + excerpt + read_more + "</div></a></div>"/*)*/;
			}
		}
	}
	
	function interceptLinks() {
/*
		$('a.intercept').click(function(e) {
			e.preventDefault();
			getDetails($(this).attr('href'), true);
			return false;
		});
*/
	}
	
	function interceptHorizLinks() {
/*
		$('a.interceptHoriz').click(function(e) {
			e.preventDefault();
			getDetails($(this).attr('href'), false);
			return false;
		});
*/
	}

	function galleryCheck() {
		// Thumbnails
		$('.thumbnails a').lightBox({
			imageLoading:	'/ui-images/lightbox-ico-loading.gif',
			imageBtnPrev:	'/ui-images/lightbox-btn-prev.png',
			imageBtnNext:	'/ui-images/lightbox-btn-next.png',
			imageBtnClose:	'/ui-images/lightbox-btn-close.png',
			imageBlank:		'/ui-images/lightbox-blank.gif',
			containerBorderSize:	25,
			fixedNavigation:	true
		});
	}
	
/* 	function getDetails(ref, animateOpening) { */
	function getDetails(name, related, animateOpening) {
/*
		ref = ref.split('/');
		relType = ref[0];
		postID = ref[1];
*/
		relType = related;
		postID = name;
				
		if (postID == 6655)
		{
			$('#keyword').val("people");
		}
		else if (postID == 6667 || postID == 'work')
		{
			$('#keyword').val("work");
		}
		else if (postID == 'people')
		{
			$('#keyword').val("people");
		}
		else if (postID == 'privacy-policy')
		{
			$('#privacy-policy').modal({
				onOpen: function(dialog) {
					if (isMobile) {
						dialog.overlay.show();
						dialog.container.show();
						dialog.data.show();
					} else {
						dialog.overlay.fadeIn('fast', function() {
							dialog.data.show();
							dialog.container.fadeIn('slow');
						});
					}
					modalOpen = true;
				},
				onClose: function(dialog) {
					if (isMobile) {
						dialog.overlay.hide();
						dialog.container.hide();
						dialog.data.hide();
						$.modal.close();
					} else {
						dialog.container.fadeOut('slow', function() {
							dialog.data.hide();
							dialog.overlay.fadeOut('fast', function() {
								$.modal.close();
							});
						});
					}
					modalOpen = false;
					if (backButton == false) {
						interruptHash = true;
						history.go(-1);
					}
					backButton = false;
					$('#horizListContainer').hide();
				},
				containerCss: {
					backgroundColor:"#d3d2d2",
					width:960,
					minHeight:605,
					padding: '40px 20px 20px'
				},
				opacity: 80
			});
			//$('#horizListContainer').hide();
		}
		else
		{
			$.getJSON(blogServer + "?jsoncallback=?",
				{
					req: "itemdetails",
					id: postID,
					types: relType
				},
				function(data) {
					if (data.details.post_title == null)
						$('#keyword').val(postID);
					else
						gotDetails(data, animateOpening);
				}
			);
			
			if (postID==6683||postID=='contact-us'||postID=='contact') {
				$('#contact-details').css({opacity:0}).slideDown('fast', function() {
					$(this).animate({opacity:1}, 'slow');
				});
				$('#horizListContainer').css({opacity:0}).slideDown('fast', function() {
					$(this).animate({opacity:1}, 'slow');
				});
				$('#results').animate({opacity:0}, 'slow', function() {
					$(this).slideUp();
				});
				
			}
		}
	}
	
	function gotDetails(data, animateOpening) {
		
		personParam = "";	// Clear that we did this search
		caseParam = "";	

		// Check - if no data returned, don't try and show details page
		if (typeof data.details.post_type == 'undefined' || data.details.post_type == null)
		{
			resetDetails();
			return;
		}
		else
		{
			$('#searching').fadeOut();
		}
		
		if (data.details.post_name != 'contact-us') {
			$('#contact-details').animate({opacity:0}, 'slow', function() {
				$(this).slideUp();
			});
		}
			
		var postType = data.details.post_type;
		var postTitle = data.details.post_title;
		var postContent = data.details.post_content;
		var postDate = data.details.post_date;
		var displayName = data.details.display_name;
		var postImage = '<img src="'+data.details.blog_3+'" />';
		var authorUrl = data.details.author_url;
		var commentCount = data.details.comment_count;
		var postLink = data.details.permalink;
		var authorP = data.meta.thumbnail_P;
		var personTitle = data.meta.title;
		var caseHeader = data.meta.thumbnail_H;
		if (data.relations.departments)
			var personDept = data.relations.departments[0].post_title;
			
		if (postLink == null) {
			var permLink = data.details.id;
		}
		else {
			var permLink = postLink.substr(postLink.indexOf("/", 8)+1);
		}
		
		primary_cat = '';
		if (postType=='post') {
			postContent = trimByWord(data.details.excerpt, 55); // trimming the excerpt
			primary_cat = data.details.primary_cat;
		}
		
		/* tweaking the department */
		if (personDept) {
			personDept = personDept.toLowerCase().replace(/[ |\t]/gi, '-');
		}
		
		var classes = 'detail';
		classes += ' '+postType;
		classes += ' '+primary_cat;
		if (personDept) {
			classes += ' '+personDept;
		}
		if (postType=='departments')
			classes += ' '+postTitle.toLowerCase().replace(/[ |\t]/gi, '-');
			
		if (postType=='disciplines' && typeof data.relations.departments != 'undefined')
			classes += ' '+data.relations.departments[0].post_title.toLowerCase().replace(/[ |\t]/gi, '-');
		
		
		var name = postTitle;
		var jobTitle = personTitle;
		if (postType=='job_postings') {
			name = postTitle;
		}
		var currentTime = new Date();
		if (!postImage) {
			postImage = name;
		}

		// To print
		var details = '<div class="'+classes+'">';
		details += '<div class="padding">';
		if (postType=='people'&&authorP) {
			details += '<div class="portfolio-image"><img src="'+authorP+'" width="471" height"471" /></div>';
			details += '<div class="portfolio-adj">';
		}
		if (postType=='post') {
			details += '<div class="blog-header"><div class="blog-logo">2OH!3</div><div class="clear"></div><a class="simplemodal-close" href="">CLOSE</a></div>';
		}
		details += '<div class="header">';
		details += '<div class="name">'+name+'</div>';
		if (postType=='people') {
			details += '<div class="title">'+jobTitle+'</div>';
		}
//		if (postType=='people'||postType=='departments'||postType=='disciplines')
//			details +=					'<div class="badge">Badge</div>';

		if (postType != 'post') {
			details += '<div class="closebtn"><a class="close" href="#">Close</a></div>';
		}

		if (postType=='case_studies') {
			details +=					'<div class="disciplines">';
			if (data.relations.disciplines) {
				var i = 0;
				while (i < data.relations.disciplines.length) {
					details += data.relations.disciplines[i].post_title;
					if (i < (data.relations.disciplines.length-1)) {
						details += ' &bull; ';
					}
					i++;
				}
			}
			details += '</div>';			
			if (caseHeader) {
				details += '<div class="case-header"><img src="'+caseHeader+'" /></div>';
			}
			details += '<div class="clear"></div>';
		}
		details += '</div>';
		if (postType=='post') {
			details += '<div class="post-meta"><div class="post-author">'+dateFormat(mysqlTimeStampToDate(postDate), "mmmm dS, yyyy")+' by <a href="'+authorUrl+'" target="_blank">'+displayName+'</a></div><div class="post-comments">('+commentCount+') <a href="'+postLink+'#disqus_thread" target="_blank">Comments</a></div><div class="clear"></div></div>';
		}
		details += '<div class="content">';
		if (postType=='post') {
			details += '<div class="post-image">'+postImage+'</div>';
		}
		details += trimShortcode(postContent);
		
		// adding in the social media links
		if (postType=='people') {
			details += '<ul class="social">';
			if (data.meta.facebook)
				details += '<li><a class="facebook" href="' + data.meta.facebook + '" target="_blank">Facebook</a></li>';
			if (data.meta.twitter)
				details += '<li><a class="twitter" href="' + data.meta.twitter + '" target="_blank">Twitter</a></li>';
			if (data.meta.linkedin)
				details += '<li><a class="linkedin" href="' + data.meta.linkedin + '" target="_blank">LinkedIn</a></li>';
			if (data.meta.dribble)
				details += '<li><a class="dribble" href="' + data.meta.dribble + '" target="_blank">Dribble</a></li>';
/*
			if (data.meta.email_address)
				details += '<li><a class="email" href="mailto:' + data.meta.email_address + '">Email</a></li>'
*/
			details += '</ul>';
		}
		
		// adding "launch project" and "back to results"
		if (postType=='case_studies') {
			details += '<div class="clear"></div>';
			details += '<ul class="case-study-nav">';
			details += '<li><a class="close back-to-results" href="#">Back to Results</a></li>';
			if (data.meta.link)
				details += '<li><a class="launch-project" href="' + data.meta.link + '" target="_blank">Launch Project</a></li>';
			details += '</ul>';
		}
				
		if (postType=='post') {
			details += '<a class="read-more" href="'+postLink+'" target="_blank">Read more</a>';
		}
		details += '<div class="clear"></div></div>';
		if (postType=='people'&&authorP) {
			details += '</div>';
		}
		details += '</div>';
		details += '<div class="clear"></div></div>';
		
		details += "<script language='javascript'> _gaq.push(['_setAccount', 'UA-1043292-3']); _gaq.push(['_trackPageview', '" + permLink + "']); _gaq.push(['_setAccount', 'UA-22279618-2']); _gaq.push(['_trackPageview', '" + permLink + "']); </script>";
		
		// Omniture
/*
		s.linkTrackVars = 'prop1';
		s.linkTrackEvents = 'None';
		s.prop1 = permLink;
		s.tl(this, 'o');
*/
		
		s.pageName = permLink;
		var s_code = s.t();
		if (s_code) document.write(s_code);
		
		if (postType=='post') {
			$('#blog-details').html(details).modal({
				onOpen: function(dialog) {
					if (isMobile) {
						dialog.overlay.show();
						dialog.container.show();
						dialog.data.show();
					} else {
						dialog.overlay.fadeIn('fast', function() {
							dialog.data.show();
							dialog.container.fadeIn('slow');
						});
					}
					modalOpen = true;
				},
				onClose: function(dialog) {
					if (isMobile) {
						dialog.overlay.hide();
						dialog.container.hide();
						dialog.data.hide();
						$.modal.close();
					} else {
						dialog.container.fadeOut('slow', function() {
							dialog.data.hide();
							dialog.overlay.fadeOut('fast', function() {
								$.modal.close();
							});
						});
					}
					modalOpen = false;
					if (backButton == false) {
						interruptHash = true;
						history.go(-1);
					}
					backButton = false;
					$('#horizListContainer').hide();
				},
				containerCss: {
					backgroundColor:"#d3d2d2",
					width:960,
					minHeight:605,
					padding: '40px 20px 20px'
				},
				opacity: 80
			});
			resetDetails();
		} else {
			
			if (isMobile)
			{
				if (animateOpening) {
					scroll(0, scrollPoint);
					$('#details').html(details).show();
					$('#horizListContainer').show();
					$('#results').hide();
					
				} else {
					$('#details').html(details);
				}
			} 
			else 
			{
				$('html, body').animate({scrollTop:scrollPoint}, 'slow');
				//scroll(0,0);
				if (animateOpening) {
					$('#details').html(details).css({opacity:0}).slideDown('fast', function() {
						$(this).animate({opacity:1}, 'slow');
					});
					$('#horizListContainer').css({opacity:0}).slideDown('fast', function() {
						$(this).animate({opacity:1}, 'slow');
					});
					$('#results').animate({opacity:0}, 'slow', function() {
						$(this).slideUp();
					});
				} else {
					$('#details').html(details);
				}
			}
		}
		
		galleryCheck();

		$('a.close').click(function(e) {
			e.preventDefault();
			//resetDetails();
			interruptHash = true;
			history.go(-1);
			return false;
		});
		
		if (justLoadedHorizList)
		{
			justLoadedHorizList = false;
			slider.goToSlide(0);
		}
		
		detailsOpen = true;
	}
	
	/* Date format */
	function mysqlTimeStampToDate(timestamp) {
		//function parses mysql datetime string and returns javascript Date object
		//input has to be in this format: 2007-06-05 15:26:02
		var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
		var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
		return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
	}
	var dateFormat = function () {
		var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
			timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
			timezoneClip = /[^-+\dA-Z]/g,
			pad = function (val, len) {
				val = String(val);
				len = len || 2;
				while (val.length < len) { val = "0" + val; }
				return val;
			};
	
		// Regexes and supporting functions are cached through closure
		return function (date, mask, utc) {
			var dF = dateFormat;
	
			// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
			if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
				mask = date;
				date = undefined;
			}
	
			// Passing date through Date applies Date.parse, if necessary
			date = date ? new Date(date) : new Date();
			if (isNaN(date)) { throw SyntaxError("invalid date"); }
	
			mask = String(dF.masks[mask] || mask || dF.masks["default"]);
	
			// Allow setting the utc argument via the mask
			if (mask.slice(0, 4) == "UTC:") {
				mask = mask.slice(4);
				utc = true;
			}
	
			var	_ = utc ? "getUTC" : "get",
				d = date[_ + "Date"](),
				D = date[_ + "Day"](),
				m = date[_ + "Month"](),
				y = date[_ + "FullYear"](),
				H = date[_ + "Hours"](),
				M = date[_ + "Minutes"](),
				s = date[_ + "Seconds"](),
				L = date[_ + "Milliseconds"](),
				o = utc ? 0 : date.getTimezoneOffset(),
				flags = {
					d:    d,
					dd:   pad(d),
					ddd:  dF.i18n.dayNames[D],
					dddd: dF.i18n.dayNames[D + 7],
					m:    m + 1,
					mm:   pad(m + 1),
					mmm:  dF.i18n.monthNames[m],
					mmmm: dF.i18n.monthNames[m + 12],
					yy:   String(y).slice(2),
					yyyy: y,
					h:    H % 12 || 12,
					hh:   pad(H % 12 || 12),
					H:    H,
					HH:   pad(H),
					M:    M,
					MM:   pad(M),
					s:    s,
					ss:   pad(s),
					l:    pad(L, 3),
					L:    pad(L > 99 ? Math.round(L / 10) : L),
					t:    H < 12 ? "a"  : "p",
					tt:   H < 12 ? "am" : "pm",
					T:    H < 12 ? "A"  : "P",
					TT:   H < 12 ? "AM" : "PM",
					Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
					o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
					S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
				};
	
			return mask.replace(token, function ($0) {
				return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
			});
		};
	}();
	
	// Some common format strings
	dateFormat.masks = {
		"default":      "ddd mmm dd yyyy HH:MM:ss",
		shortDate:      "m/d/yy",
		mediumDate:     "mmm d, yyyy",
		longDate:       "mmmm d, yyyy",
		fullDate:       "dddd, mmmm d, yyyy",
		shortTime:      "h:MM TT",
		mediumTime:     "h:MM:ss TT",
		longTime:       "h:MM:ss TT Z",
		isoDate:        "yyyy-mm-dd",
		isoTime:        "HH:MM:ss",
		isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
		isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
	};
	
	// Internationalization strings
	dateFormat.i18n = {
		dayNames: [
			"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
			"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
		],
		monthNames: [
			"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
			"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
		]
	};
	
	// For convenience...
	Date.prototype.format = function (mask, utc) {
		return dateFormat(this, mask, utc);
	};
	
	// Excerpt trim
	function trimByWord(sentence, len) {
		var result = sentence;
		var resultArray = result.split(" ");
		if(resultArray.length > len){
			resultArray = resultArray.slice(0, len);
			result = resultArray.join(" ") + "&hellip;";
		}
		
		return result;
	}
	// remove shortcodes from excerpts
	function trimShortcode(str) {
		str = str.replace(/(\[[\w\d\s="',-\/]*[\]]?)/gi, '');
		return str;
	}
	
	function parseHash(hash) {
		hash = hash.replace(/#/,''); // remove the preceeding #
		resetHashArrays();
		assignHashArrays(hash);
		
		$('#jquery-overlay,#jquery-lightbox').click();
		
		if	(detailsOpen == true && hashKeys[0] == 'type' && hashValues[0] != 'details') {
			resetDetails();
		}
		
		if (modalOpen == true) {
			backButton = true;
			$.modal.close();
		}
		
		if (hashKeys[0] == 'type') {
			interruptHash = true;
			switch(hashValues[0]) {
				case 'keyword':
					if (hashKeys[1] == 'keyword') {
						$('#keyword').val(unescape(hashValues[1]));
					}
					break;
				case 'slider':
					$("#strategy").slider({ value: (hashValues[1]) ? hashValues[1] : 0, min: 0, max: 10, step: 1, slide: function(event, ui) {
						activate(); interruptHash = false; $("#strategySlider").val(ui.value);
					}, start: function() { changingInputs = true; }, stop: function() { changingInputs = false; } });
					
					$("#creative").slider({ value: (hashValues[2]) ? hashValues[2] : 0, min: 0, max: 10, step: 1, slide: function(event, ui) {
						activate(); interruptHash = false; $("#creativeSlider").val(ui.value);
					}, start: function() { changingInputs = true; }, stop: function() { changingInputs = false; } });
					
					$("#media").slider({ value: (hashValues[3]) ? hashValues[3] : 0, min: 0, max: 10, step: 1, slide: function(event, ui) {
						activate(); interruptHash = false; $("#mediaSlider").val(ui.value);
					}, start: function() { changingInputs = true; }, stop: function() { changingInputs = false; } });
					
					$("#analytics").slider({ value: (hashValues[4]) ? hashValues[4] : 0, min: 0, max: 10, step: 1, slide: function(event, ui) {
						activate(); interruptHash = false; $("#analyticsSlider").val(ui.value);
					}, start: function() { changingInputs = true; }, stop: function() { changingInputs = false; } });
					
					if (initial == 0) {
						sliderSearch(true);
					}
					break;
				case 'details':
					if (initial == 0) {
						$.getJSON(blogServer + "?jsoncallback=?",
							{
								req: "slidersearch",
								creative: creative,
								strategy: strategy,
								media: mediaVar,
								analytics: analytics
							},
							function(data) { gotResults(data); }
						);
						initial = 1;
					}
					interruptHash = true;
					$('#keyword').val('');
					
					n = hashValues[1];
					r = (hashValues[2]) ? hashValues[2] : '';
					getDetails(n, r, true);
					break;
			}
		} else if (hashKeys[0] == 'lbclose') {
			interruptHash = true;
			history.go(-1);
		} else {
			activate();
			$('#keyword').val('');
			$("#strategy").slider('value', 0);
			$("#creative").slider({ value: 0 });
			$("#media").slider({ value: 0 });
			$("#analytics").slider({ value: 0 });
			sliderSearch(true);
		}
	}
	function resetHashArrays() {
		hashKeys = [];
		hashValues = [];
	}
	function assignHashArrays(hash) {
		hash = hash.split('&');
		for (i = 0; i < hash.length; i++) {
			hashKeyVal = hash[i].split('=');
			for (j = 0; j < hashKeyVal.length; j++) {
				hashKeys[i] = hashKeyVal[0];
				hashValues[i] = hashKeyVal[1];
			}
		}
	}
})(jQuery);

