$(document).ready(function() {

	jQuery.fx.interval = 20;
	
	/* Variables for scripts */
	var body = $("body"),
	    htmlElement = $("html"),
	    utilityNav = $("nav.utilitynav");
	var windowWidth;
	
	/* Check for HTML5 form capability, see if we need the polyfill */	
	function h5formSetup() {
		if ($(".h5form").length > 0) {
			H5F.setup($('.h5form'), {
			    validClass: "valid",
			    invalidClass: "invalid",
			    requiredClass: "required",
			    placeholderClass: "placeholder"
			});
		}
	}
	Modernizr.load([
	  {
	    test : Modernizr.inputtypes.email && Modernizr.input.required && Modernizr.input.placeholder,
	    nope : '/js/h5f.min.js',
	    callback : function () {
	      $("body").addClass("h5fneeded");
				h5formSetup();
	    }
	  }
	]);

	/* Main nav dropdowns */
	$("ul.sf-menu").superfish({
		animation: {height:'show'},
		speed:"fast",
		autoArrows:false,
		dropShadows:true
	});
	
	/* Subnav animations */
	var subSubNav = $(".subnav li.here ul").add(".subnav li.parent-here ul");
	$(subSubNav).slideDown('fast', 'linear');
		
	/* Form submission/validation */
	$("form#contactform input.formbutton").click(function(event) {  
		event.preventDefault(); 
		
		$(this).parents("form").addClass("validated");
		
		var formIsValid = true; //default assumption that we'll prove false if needed
			
		/* Do some extra checking for Safari/Chrome just in case, */
		/* since they will still submit a form with invalid values (!!) */
		if (!$("body").hasClass("h5fneeded")) {
			if ($("form#contactform :invalid").length > 0) {
				formIsValid = false;
			};
		} else {
			formIsValid = document.getElementById("contactform").checkValidity();//$("form#contactform").checkValidity();
		};
		
		/* Passed all the tests, ready to go! */
		if (formIsValid == true) {
			//javascript:alert('success!');
			$("form#contactform").submit();
		} else {
			//alert("Not valid!");
		};

	});
	
	
	/* Utility nav animations */
	
	function collapseUtil(utilitylistitem) {
	  if ((!$(body).hasClass("narrowwindow")) && (!$(utilitylistitem).hasClass("utilityactive"))) {	  
		  $(utilitylistitem).stop().animate({
				left: '0'
			}, 200)
		}
	};
	
	function expandUtil(utilitylistitem, offset) {
	  if ((!$(body).hasClass("narrowwindow")) && (!$(utilitylistitem).hasClass("utilityactive"))) {
		  $(utilitylistitem).stop().animate({
				left: offset
			}, 200)
	  }	  
	};
	
	/* Left offsets when expanded:
	  Normal: -4.75em
	  Search: -20em
	  Search on homepage: -15.25em */
	
	if (!$(body).hasClass("home")) {
		$(".utilitynav li:not('#nav-search')").hover(function() {
			expandUtil(this, '-4.75em');		
		}, function() {
			collapseUtil(this);
		})
		$(".utilitynav li#nav-search").hover(function() {
			expandUtil(this, '-20em');
		}, function() {
			collapseUtil(this);
		})
	} else {
	  $(".utilitynav li#nav-search").hover(function() {
			expandUtil(this, '-15.25em');
		}, function() {
			collapseUtil(this);
		})
	};
	
	/* Search field active */
	$("#search #searchfield")
	  .focus(function() {  
	    var listParent = $(this).parents("li");
	    if ($(listParent).css("left") == "0px") {
	      if (!$(body).hasClass("home")) {
	        expandUtil(listParent, '-20em');	        
	      } else {
	        expandUtil(listParent, '-15.25em');
	      }
	    }
	    $(this).parents("li").addClass("utilityactive");
	  })
	  .blur(function() {
	    var listParent = $(this).parents("li");
	    listParent.removeClass("utilityactive");
	    if ($(listParent).css("left") != "0px") {
	      collapseUtil(listParent);
	    }	    
	  });
	  
	$(".utilitynav li#nav-home a, .utilitynav li#nav-login a")
	  .focus(function() {
	    var listParent = $(this).parent("li");
	    if ($(listParent).css("left") == "0px") {
	      if (!$(body).hasClass("home")) {
	        expandUtil(listParent, '-4.75em');	        
	      }
	    }
	  })
	  .blur(function() {
	    var listParent = $(this).parent("li");
	    if ($(listParent).css("left") != "0px") {
	      if (!$(body).hasClass("home")) {
	        collapseUtil(listParent);	        
	      }
	    }
	  });
	  
  $(".utilitynav li#nav-search a")
	  .focus(function() {
	    $("#searchfield").focus();
	  });
	
	/* Search text hint */
	if ($("#search label").length > 0) {
		$("#search label").inFieldLabels();
	}
	
	/* Slideshow */	
	var featureslideshow = $("div.slideshow");
	if ($(featureslideshow).length > 0) {
		$(featureslideshow).after("<div id=\"slideshownav\"><ul></ul></div>").cycle({
			timeout: 6000,
			pause: true,
			cleartype: true,
			pager: '#slideshownav ul',
			// callback fn that creates a thumbnail to use as pager anchor 
		pagerAnchorBuilder: function(idx, slide) { 
				return '<li><a href="#">' + (idx+1) + '</a></li>'; 
			}
		});
		
		//If they click or focus on the slide nav, the slideshow stops auto-rotating
		$("div#slideshownav ul li a").click(function() {
			$(featureslideshow).cycle("pause");
		});
		$("div#slideshownav ul li a").focus(function() {
			$(featureslideshow).cycle("pause");
		})
		
	};
	
	/* Hide/reveal links */
	var reveallinks = $("div.revealwrapper a.revealmore");
	var hidelinks = $("div.revealwrapper a.hidemore");
		
	$(reveallinks).click(function() {	
		var revealblock = $(this).parents("div.revealwrapper");
		var reveallong = $(revealblock).children("div.longcontent");
		var revealshort = $(revealblock).children("div.shortcontent");
		
		var shortheight = revealblock.innerHeight();
		var longheight = reveallong.innerHeight();

		revealblock.css("height", shortheight)
			.addClass("revealed")
			.animate({
				height: longheight
			});			

		return false;
	});
	
	$(hidelinks).click(function() {
		var revealblock = $(this).parents("div.revealwrapper");
		var reveallong = $(revealblock).children("div.longcontent");
		var revealshort = $(revealblock).children("div.shortcontent");
		
		var shortheight = revealshort.innerHeight();
		var longheight = revealblock.innerHeight();

		revealblock.css("height", longheight)
			.animate({
				height: shortheight
			}, function() {
				$(this).removeClass("revealed");
			});
					
		return false;
	});
	
	/* Tabs */
	$(".tabs").tabs();
	
	/* Check height of vertical tabs vs. tab content */
	if ($("div.verticaltabs").length > 0) {
	  var verticalTabNav = $("div.verticaltabs ul.tabnav");
	  var verticalTabNavHeight = verticalTabNav.height();
	  var verticalTabContentPanels = $("div.verticaltabs > section");
	  if (verticalTabNavHeight > 343) {
	    verticalTabContentPanels.css("min-height", (verticalTabNavHeight-38));
	  }  
	}
	
	/* Table styling */
	$("table > tbody > tr:last-child").addClass("last");
	$("table > tbody > tr > td:last-child").addClass("last");
	$("table > thead > tr > th:last-child").addClass("last");
	$("table > thead > tr > th:first-child").addClass("first");
	$("table > tbody > tr > td:first-child").addClass("first");
	$("table > tbody > tr:odd").addClass("even");
	
	/* Vertical centering height adjustment for IE7 */
	var isIE7 = $.browser.msie && $.browser.version=="7.0";	
	if (isIE7) {
		$(".contentintro .quotewrapper").append('<span class="heightadjuster"></span>');
	}
	
	function isWindowNarrow() {
		windowWidth = $(window).width();
		if (windowWidth < 1041) {
			body.addClass("narrowwindow");
		};
	};
	
	isWindowNarrow();
	
	/* Test for nth-child and do odd/even striping via jQuery if not */
	
	// selectorSupported lovingly lifted from the mad italian genius, diego perini
  // http://javascript.nwbox.com/CSSSupport/
  function selectorSupported(selector){
    var support, link, sheet, doc = document,
        root = doc.documentElement,
        head = root.getElementsByTagName('head')[0],
        impl = doc.implementation || {
          hasFeature: function() {
            return false;
          }
        },

    link = doc.createElement("style");
    link.type = 'text/css';
    (head || root).insertBefore(link, (head || root).firstChild);
    sheet = link.sheet || link.styleSheet;
    if (!(sheet && selector)) return false;
    support = impl.hasFeature('CSS2', '') ?
      function(selector) {
        try {
          sheet.insertRule(selector + '{ }', 0);
          sheet.deleteRule(sheet.cssRules.length - 1);
        } catch (e) {
          return false;
        }
        return true;
      } : function(selector) {
        sheet.cssText = selector + ' { }';
        return sheet.cssText.length !== 0 && !(/unknown/i).test(sheet.cssText) && sheet.cssText.indexOf(selector) === 0;
      };
    return support(selector);
  };

  Modernizr.addTest('nthchild',function(){
    return selectorSupported(':nth-child(2n+1)');
  })
  
	if (htmlElement.hasClass("no-nthchild")) {
	  var oddRows = $("ul.eventlist li").filter(":even");
	  if (oddRows.length > 0) {
	    oddRows.addClass("oddrow");
	  }
	};
	
	/* Login modal window (lightbox) */
	
	// Set up the modal structure 
  $('body').append('<div id="modal-login" class="jqmWindowLogin"><div class="jqmWindowInner"><div id="jqmWindowTarget"></div></div><a href="#" class="jqmClose">Close Window</a></div>');
  
  // Set up modal window triggering
	$('#modal-login').jqm({       
		modal: false,
		ajax: '@href',
		target: '#jqmWindowTarget',
		toTop: true,
		overlay: 40,
		trigger: 'a.openlogin'
	});
  
	/* Carousel/image gallery modal scripts */
	if ($("div.carouselwrap").length > 0) {
	  $('div.carousel ul').jcarousel({
	    scroll: 1
	  });
	}
	
	/* Gallery modal windows (lightboxes) */
	if ($("div.carouselgallery").length > 0) {
	  
	  /* Set up the modal structure */
	  $('body').append('<div id="modal-gallery" class="jqmWindow"><div class="jqmWindowBody"><img src="/images/blank.gif" id="galleryimage" alt="" /></div><div class="jqmWindowFooter"><span id="thisitemnumber">1</span>/<span id="totalitemsnumber">1</span>&nbsp;&nbsp;&nbsp;<span id="thisitemtitle"></span></div><a href="#" id="gallery-previous" class="gallerynav">Previous image</a><a href="#" id="gallery-next" class="gallerynav">Next image</a><a href="#" class="jqmClose">Close Window</a></div>');
	  
	  /* Declare modal variables */
	  var carouselListItems = $("div.carouselgallery ul:first-child li");
	  var carouselLinks = $("div.carouselgallery a");
	  var totalItemsNumber = carouselListItems.length;
	  
	  var thisItemNumber;
	  var thisItemTitleText;
	  var thisItemGalleryImage;
	  
	  var totalItemsTarget = $("div#modal-gallery span#totalitemsnumber");
	  var thisItemNumberTarget = $("div#modal-gallery span#thisitemnumber");
	  var galleryImageTarget = $("div#modal-gallery img#galleryimage");
	  var thisItemTitleTarget = $("div#modal-gallery span#thisitemtitle");
	  var galleryPrevLink = $("div#modal-gallery a#gallery-previous");
	  var galleryNextLink = $("div#modal-gallery a#gallery-next");
	  	  	
  	/* Set some initial values */
  	$(totalItemsTarget).text(totalItemsNumber);
  	
  	/* Function to get values from a specified link */
  	function carouselModalSetup(gallerylink) {
  	  var thisListItem = gallerylink.parent("li");
  	  
  	  /* Get values from link */
  	  thisItemNumber = $(carouselListItems).index(thisListItem) + 1;
  	  thisItemTitleText = gallerylink.find("span").text();
  	  thisItemGalleryImage = gallerylink.attr("href");
  	  
  	  /* Put values into modal */
  	  thisItemNumberTarget.text(thisItemNumber);
  	  thisItemTitleTarget.text(thisItemTitleText);
  	  galleryImageTarget.attr("src", thisItemGalleryImage);
  	  
  	  /* Hide prev/next arrows if needed */
  	  if (thisItemNumber == 1) {
  	    galleryPrevLink.hide();
  	    $(galleryNextLink).show();
  	  }	else if (thisItemNumber == totalItemsNumber) {
  	    $(galleryPrevLink).show();
  	    galleryNextLink.hide();
  	  } else {
  	    $(galleryPrevLink).show();
    	  $(galleryNextLink).show();
  	  }
  	}
  	
  	function carouselModalReset() {  	  
  	  $(galleryImageTarget).attr("src", "/images/blank.gif");
  	}
  	
  	/* Set up modal window triggering */
  	$('#modal-gallery').jqm({       
  		modal: false, 
  		toTop: true,
  		overlay: 40,
  		trigger: 'a.openmodal',
  		onShow: function(hash) {
  			carouselModalSetup($(hash.t));
  			hash.w.show();
  		},
  		onHide: function(hash) {
  	    hash.w.hide();
  	    hash.o.remove();
  		  carouselModalReset();	  
  		}
  	});
  	
  	/* Set up forward/next buttons */
  	$(galleryPrevLink).click(function() {
  	  var previousItem = carouselListItems.get(parseFloat(thisItemNumber) - 2);
  	  var previousItemLink = $(previousItem).find("a"); 
  	  carouselModalSetup(previousItemLink);
  	  return false;
  	});
  	
  	$(galleryNextLink).click(function() {
  	  var nextItem = carouselListItems.get(parseFloat(thisItemNumber));
  	  var nextItemLink = $(nextItem).find("a"); 
  	  carouselModalSetup(nextItemLink);
  	  return false;
  	});
  	
	};
	
	/* Testimonials and Case Studies Filters */
	if ($(".filtered").length > 0) {
		
		var allFilteredItems = $(".filtered");
		var allFilterTagLinks = $("a.filtertag");
		var filterDropdown = $("select#filterby");

		function filterItems(cssClass) {
			allFilteredItems.hide();
			
			// Can't use fading if it's IE 7/8
			if ($.browser.msie  && ((parseInt($.browser.version) == 7) || (parseInt($.browser.version) == 8))) {
			   if (cssClass == "Show All") {
					allFilteredItems.show().addClass("iefix").removeClass("iefix");
				} else {
					$("div."+cssClass).show().addClass("iefix").removeClass("iefix");
				}
			} else {
			  if (cssClass == "Show All") {
					allFilteredItems.fadeIn().addClass("iefix").removeClass("iefix");
				} else {
					$("div."+cssClass).fadeIn().addClass("iefix").removeClass("iefix");
				}
			}
		}

		$(filterDropdown).change(function() {	
			var cssClass = $(this).find("option:selected").val();
			filterItems(cssClass);
		});

		$(allFilterTagLinks).click(function() {
			var classList = $(this).attr('class').split(/\s+/);
			var targetClass;
			$.each( classList, function(index, item){
				if (item.indexOf("tag-") == 0) {
					targetClass = item.replace("tag-", "");
				}
			});
			//alert(targetClass);
			filterItems(targetClass);
			return false;
		});
	
	};

	/* Do on resize */
	$(window).smartresize(function(event) {
		body.removeClass("narrowwindow");
		isWindowNarrow();
	});
	
})

