var settings = {
  restoreOpacity: true
};
var lockNav = false;
var shouldClose = false;

$(document).ready(function() {
  
  //expanding div for main navigation
  $("li.feature").mouseenter(function() {
    shouldClose = false;
    $("#navigationContainer").stop().animate({height: '180px'}, 500);
  });
  $("li.sub").mouseenter(function() {
    shouldClose = false;
    $("#navigationContainer").stop().animate({height: '65px'}, 300);
  });
  $("li.none").mouseenter(function() {
    shouldClose = false;
    $("#navigationContainer").stop().animate({height: '40px'}, 200);
  });
  $("#navigationContainer").mouseleave(function() {
    if(lockNav) { shouldClose = true; return; }
    $(this).stop().animate({height: '40px'}, 500);
    shouldClose = false;
  });

  //primary navigation content tabs  
  $("ul#primaryNavigation").tabs("#primaryNavigationExpanded > div", { event: 'mouseover' });

  //animated navigation hovers
	$('ul#primaryNavigation a:not(.currentSec)').css('background-position', '0px -5px');
	$('ul#primaryNavigation a.currentSec').css('background-position', '0px 0px');
	$('ul#primaryNavigation a:not(.currentSec)').mouseenter(function() {
		$(this).stop().animate({backgroundPosition: '0px 0px'}, 200);
	});
	$('ul#primaryNavigation a:not(.currentSec)').mouseleave(function() {
		$(this).stop().animate({backgroundPosition: '0px -5px'}, 200);
	});
	$("input[name=q]").focusin(function() {
	  lockNav = true;
	});
	$("input[name=q]").focusout(function() {
	  lockNav = false;
	  if(shouldClose) $("#navigationContainer").mouseleave();
	});
	  
  //animated footer legal on click
  $('#nond').css({height: '0px'});
  
  $('#legal').toggle(function() {
    $('#nond').animate({height: "100px"}, 500);
      }, function() {
    $('#nond').animate({height: "0px"}, 500);
  });
    
  //animated footer sitemap on hover
  $('#sitemap').hover(function() {
    $(this).stop().animate({height: '200px'}, 500);
  }, function(){
    $(this).stop().animate({height: '20px'}, 500);
  });
		
	
  //show/hide all page content except image and logo
	$('p#show').hide();
	$("#cleaner").click(function () {
	  var ccheight = $('#contentContainer').css('height');
	  $('#contentContainer').css({height: ccheight})
	  $('#mainLeftContainer').animate({ "opacity": "toggle" }, 750);
	  $('#mainRightContainer').animate({ "opacity": "toggle" }, 750);
	  $('#mainFullContainer').animate({ "opacity": "toggle" }, 750);
	  $('#homeContent').animate({ "opacity": "toggle" }, 750);
		$('#secondaryContainer').animate({ "opacity": "toggle" }, 750);
		$('#tertiaryContainer').animate({ "opacity": "toggle" }, 750);
		$('#relatedContainer').animate({ "opacity": "toggle" }, 750);
		$('#footer').animate({ "opacity": "toggle" }, 750);
		$('#primaryNavigation').animate({ "opacity": "toggle" }, 750);	
		$('p#hide').toggle();
		$('p#show').toggle();
	});
	
	//show/hide main_left copy on hub pages
  if($(".expandedCopy").contents("p").length && $(".expandedCopy").contents("p").text()) {
    $("#featureCopy:not(.noArrow)").css('background-image', 'url(/_public/images/common/more-hint.png)');
    $(".contentHide").hover(function() {
      $(".contentHide").stop().animate({width: '635'}, 500);
    } , function(){
      $(".contentHide").stop().animate({width: '200'}, 500);
    });
  }
  	
  //project scrollable using flowplayer <= THIS MAY BE DEPRICATED
  if($("#secondaryContainer .scrollable .items").length > 4)
    $("#secondaryContainer")
      .scrollable({ circular: true })
      .autoscroll({ steps: 1, interval: 3000, autoplay: true, autopause: true });

	//when a new image is clicked load it, crossfade and reset
	function loadImage(path) {
	  var heroLibrary = "/_public/images/heroLibrary/";
	  var imageRequest = path;
  	$('#imageContainerLower').css('background-image', 'url(' + heroLibrary + imageRequest + ')');
  	$('#imageContainerUpper').animate({ opacity: 0 }, 1000, function () {
  			$('#imageContainerUpper').css('background-image', 'url(' + heroLibrary + imageRequest + ')');
  			if(settings.restoreOpacity) $('#imageContainerUpper').css('opacity', 1 );	
  	});
	}

	//when the page completes, load the first image as the default
	$("#topimage").append($("<div id=\"imageContainerLower\"></div>"));
	$("#topimage").append($("<div id=\"imageContainerUpper\"></div>"));
	loadImage($('.imageLoad:first').attr('id'));
  
  //if the hero images are visible, allow the user to click them to rotate the image
  var imageLoad = $('.imageLoad');
	$('.imageLoad').click(function(event) {
		event.preventDefault();	
		loadImage($(this).attr("id"));
	});
	
	//rotate the other hero images if more than one is available
	if(imageLoad.length > 1) {
	  var currentImage = 0;
	  var imageRotator = setInterval(function() {
	    currentImage = currentImage + 1;
	    loadImage($(imageLoad[currentImage % imageLoad.length]).attr("id"));
	  }, 6000);
	  $('.imageLoad, .videoLoad').click(function(event) {
	    clearInterval(imageRotator);
	  });
	}

  // adjust the thumbnail based on its size
  
  // locations map interaction
	$('#usmap > ul > li').hover(function(){
		var dot = $(this);
		var toppos = dot.attr("data-y");
		var leftpos = dot.attr("data-x");
		var opensize = '140px'
		var offset = '-=130' //this is opensize minus 10 pixels to account for margin
		var opendir = dot.attr("data-open-direction");
		dot.stop().css({'width': '7px', 'height': '7px', 'top': dot.attr("data-y")+'px', 'left': dot.attr("data-x")+'px' });
		// increase the z-index to move it above he other squares
		$(this).css('z-index', 1799);
		
		// determine the direction the li should open and move accordingly
		if(opendir == "DR" || (opendir == "" && toppos < 310 && leftpos < 570) ) {
			$(this).stop().animate({'width': opensize, 'height': opensize}, 300);		// down right
		} else if( opendir == "DL" || (opendir == "" && toppos < 310 && leftpos > 569) ) {
			$(this).stop().animate({'width': opensize, 'height': opensize, 'left': offset }, 300); 	// down left	
		} else if( opendir == "UR" || (opendir == "" && toppos > 309 && leftpos < 569) ) {
			$(this).stop().animate({'width': opensize, 'height': opensize, 'top': offset }, 300); 	// up right
		} else {
			$(this).stop().animate({'width': opensize, 'height': opensize, 'top': offset, 'left': offset }, 300); 	// up left
		}
		
		// close the li and move back to its original position on mouse out
		}, function() {
		  var dot = $(this);
			$(this).stop().animate({'width': '7px', 'height': '7px', 'top': dot.attr("data-y")+'px', 'left': dot.attr("data-x")+'px' }, 300);
			$(this).css('z-index', 1700); //reset the z-index
	});
	
	//video content
	function supports_video() {
    return !!document.createElement('video').canPlayType;
  }
  
  function supports_h264_baseline_video() {
    if (!supports_video()) { return false; }
    var v = document.createElement("video");
    return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
  }
  
  function supports_ogg_theora_video() {
    if (!supports_video()) { return false; }
    var v = document.createElement("video");
    return v.canPlayType('video/ogg; codecs="theora, vorbis"');
  }
  
	$('a.videoLoad').click(function(event) {
	  event.preventDefault();
	  $('div#videoContent').css('display', 'block');
	  var baseVideoPath = "/_public/images/heroLibrary/";
	  
	  if(supports_h264_baseline_video()) {
	    var vid = $('<video src="'+baseVideoPath+$(this).attr("data-mp4")+'" controls>');
	    $("#video")
	      .html("")
	      .append(vid);
	    vid[0].load();
	    vid[0].play();
	  } else {
	    var vid = $('<a style="display:block;width:640px;height:360px;" href="'+baseVideoPath+$(this).attr("data-flv")+'" id="flv"></a>');
	    $("#video")
	      .html("")
	      .append(vid);
	    $("#video a").flowplayer("/_public/video/flowplayer-3.2.4.swf", { clip: { autoPlay: true } });
	  }
	  $('#topimage').children().css('filter', 'inherit');
	  $('div#topimage, #topimage > *').animate({ opacity: 0.2}, 500);
	  $('div#detailCopy').css('display', 'none');
//	  .animate({ opacity: 0.2}, 500);
	});
	
	$('a#videoClose').click(function(event) {
	  event.preventDefault();
	  
	  $("#video").html("");
	  $('div#videoContent').css('display', 'none');
	  $('div#topimage, #topimage > *').animate({ opacity: 1.0}, 500);
	  $('div#detailCopy, #detailCopy *').css('display', 'block');
//	  .animate({ opacity: 1.0}, 500);
	})
	
	// first paragraph style (REMOVED AT CLIENT REQUEST)
//	$('.expandedCopy p:first').addClass('bodyFirst');
	
	// temp: switching the logos
	$('#switchlogo').click(function(){
	  $('#Kimley-Horn').attr('src', '/_public/images/kimley-horn-logo-b.jpg');
	});
	
});

(function($) {

function sameOrChild(n1, n2) {
	// http://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html
	return n1 === n2 || (typeof(n1.contains) !== 'undefined' ? n1.contains(n2) : !!(n1.compareDocumentPosition(n2) & 16));
}

function focusHandler(event) {
	event = $.event.fix(event || window.event), $this = $(this), isFocused = $this.data('focus.isFocused');
	if (!isFocused) {
		$this.data('focus.isFocused', true);
		event.type = 'focusin';
		return $.event.handle.apply(this, [event]);
	}	
}

function blurHandler(event) {
	var args = [].slice.call(arguments, 1), $this = $(this);
	event = $.event.fix(event || window.event);

	window.setTimeout(function() {
		if (!sameOrChild($this.get(0), document.activeElement)) {
			$this.data('focus.isFocused', false);
			event.type = 'focusout';
			return $.event.handle.apply($this.get(0), [event]);
		}
	}, 0);
}

function setupEvents(elem) {
	var $elem = $(elem), ref = $elem.data('focus.handlerReferences') || 0;
	if (ref == 0) {
		if (elem.addEventListener) {
			elem.addEventListener('focus', focusHandler, true);
			elem.addEventListener('blur', blurHandler, true);
		}
		else {
			elem.onfocusin  = focusHandler;
			elem.onfocusout = blurHandler;
		}
	}
	$elem.data('focus.handlerReferences', ref + 1)
	$elem.data('focus.isFocused', sameOrChild(elem, document.activeElement));
}

function teardownEvents(elem) {
	var $elem = $(elem), ref = $elem.data('focus.handlerReferences') || 0;
	if (ref == 1) {
		if (elem.removeEventListener) {
			elem.removeEventListener('focus', focusHandler, true);
			elem.removeEventListener('blur', blurHandler, true);
		}
		else {
			elem.onfocusin  = null;
			elem.onfocusout = null;
		}
		$elem.removeData('focus.handlerReferences')
		$elem.removeData('focus.isFocused');
	}
	else {
		$elem.data('focus.handlerReferences', ref - 1);
	}
}

$.each(['focusin', 'focusout'], function(i, x) {
	$.event.special[x] = {
		setup: function() { setupEvents(this); },
		teardown: function() { teardownEvents(this); }
	};
});

$.fn.extend({
	focusin: function(fn) {
		return fn ? this.bind('focusin', fn) : this.trigger('focusin');
	},
	focusout: function(fn) {
		return fn ? this.bind('focusout', fn) : this.trigger('focusout');
	}
});

})(jQuery);
