
var startTime = new Date();
var isOldIE = /MSIE [1-6]\b/.test(navigator.userAgent);
var isBeforeIE8 = /MSIE [1-7]\b/.test(navigator.userAgent);
var isBeforeIE9 = /MSIE [1-8]\b/.test(navigator.userAgent);
	
//Supports autofocus attribute
if(jQuery('<input autofocus="autofocus" />')[0].autofocus !== true){
	jQuery(function($){
		$(':input[autofocus]').focus();
	});
}


jQuery(function($){
	$(document.documentElement).addClass('dom-loaded');
	
	//Add Google Analytics (without blocking DOM load)
	//var gaScript = document.createElement('script');
	//gaScript.onload = gaScript.onreadystatechange = function(e){
	//	if(window._gat && !window.pageTracker){
	//		try {
	//			window.pageTracker = _gat._getTracker("UA-5986100-3");
	//			window.pageTracker._trackPageview();
	//		} catch(err) {}
	//	}
	//};
	//gaScript.src = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.") + 'google-analytics.com/ga.js';
	//gaScript.type = 'text/javascript';
	//document.getElementsByTagName('body')[0].appendChild(gaScript);
	
	if($(document.documentElement).hasClass('no-border-radius')){
		//$('a.button').curve({
		//	radius:10
		//});
	}
	
	//Don't let tel and fax links be clickable; auto-select their contents
	$('a[href^="fax:"], a[href^="tel:"]').click(function(e){
		try { //For IE
			if(document.body.createTextRange) {
				var range = document.body.createTextRange();
				range.moveToElementText(this);
				range.select();
			}
			e.preventDefault();
		}
		catch(e){}
	}).mousedown(function(e){
		try {
			//For non-IE
			if(window.getSelection){
				var range = document.createRange();
				range.selectNodeContents(this);
				var sel = window.getSelection();
				sel.removeAllRanges();
				sel.addRange(range);
				e.preventDefault();
			}
			//For IE
			else if(document.body.createTextRange) {
				var range = document.body.createTextRange();
				range.moveToElementText(this);
				range.select();
				e.preventDefault();
			}
		}
		catch(e){}
	});

	
	//Animate the banner tag line in
	//$('#banners h3:first').animate(
	//	{
	//		textIndent:40
	//	},{
	//		duration:slideTransition/2,
	//		complete:function(){
	//			//window.setTimeout(function(){
	//			//	var props = {};
	//			//	if(isBeforeIE9)
	//			//		props.left = 950;
	//			//	else {
	//			//		props.opacity = 0.0;
	//			//		props.textIndent = 950
	//			//	}
	//			//	$('#banners h3').animate(props, {duration:slideTransition/2});
	//			//}, slideDuration-slideTransition/2)
	//		}
	//	}
	//);
	
	
	
	//Animate menus
	$("#navigation > ul > li").mouseenter(function(){
		$(this).addClass('hover')
			   .find('> ul')
			   .stop(true, true)
			   .slideDown('fast');
	});
	$("#navigation > ul > li").mouseleave(function(){
		var $ul = $(this).find('> ul');
		if($ul.length){
			$ul.slideUp('fast', function(){
			   $(this).parent().removeClass('hover');
			});
		}
		else {
			$(this).removeClass('hover');
		}
	});
	
	//Don't select the text of links if double clicking on them
	$("#navigation a:not([href])").each(function(){
		this.onselectstart = function(){return false}
	});
	
	//Hacks for old browsers
	$('#searchform input')
		.focus(function(){ $(this).addClass('focus') })
		.blur(function(){ $(this).removeClass('focus') });
	
	
	//Make sure that the tertiary navigation does not overlap the #content in browsers (IE<=7) that have it absolutely positioned
	var $nav3 = $('.tertiary-navigation:first');
	if($nav3.length ||/**/ $nav3.css('position') == 'absolute'){
		var $content = $('#content:first');
		$content.css('minHeight', $nav3.height() + parseInt($content.css('borderBottomWidth'), 10));
		if(isOldIE)
			$content.css('height', $nav3.height() + parseInt($content.css('borderBottomWidth'), 10));
		
		
		//console.info()
	}
	
	
	//Initialize contact form
	if($('#harmer_contact_form').length){
		$('#harmer_contact_form :input').change(function(){
			$('#harmer_contact_form_populated').val('1');
		});
		//if(!$('#contact_form_populated').val())
		//	$('#harmer_contact_industry')[0].selectedIndex = -1;
	}
	
	//Implement :first-word pseudo class
	//var h2 = $('#content:not(".catalog-category") h2:first')[0];
	//if(h2){
	//	$(h2.childNodes).each(function(){
	//		//NOTE: This is not right since it should recurse into children, but anyways
	//		if(this.nodeType == 1/*Element*/ && $(this).is(':visible')){
	//			data = this.firstChild.data;
	//			throw Error('Not implemented');
	//		}
	//		else if(this.nodeType == 3/*Text*/){
	//			var span = document.createElement('span');
	//			span.className = 'first-word';
	//			var matches = this.data.match(/^(\s*\w+)(.*)/);
	//			span.appendChild(document.createTextNode(matches[1]));
	//			this.parentNode.replaceChild(span, this);
	//			span.parentNode.insertBefore(document.createTextNode(matches[2]), span.nextSibling);
	//		}
	//	});
	//}
	
	//if(isOldIE){
	//	$('body.home #introduction p:first-child').addClass('first-child');
	//	var hoverSelectors = [
	//		'#navigation li li',
	//		'body.interior #navigation li.primary',
	//		'#faq dt',
	//		'#faq dd'
	//	];
	//	//Add hover class names
	//	$products.add(hoverSelectors.join(',')).hover(
	//		function(){$(this).addClass('hover')},
	//		function(){$(this).removeClass('hover')}
	//	);
	//	$('#navigation > ul').hover(
	//		function(){ $('body').addClass('hide-selects'); },
	//		function(){ $('body').removeClass('hide-selects'); }
	//	)
	//	
	//	$('form :input').each(function(){
	//		if(this.getAttribute('required'))
	//			$(this).addClass('required');
	//	});
	//}
	//$('#faq-toc a').click(function(){
	//	$('#faq dt').removeClass('target');
	//	$(this.href.replace(/.+(?=#)/, '')).addClass('target');
	//});
	//
	//$('#faq dd:last-child').addClass('last-child');
	
	
	////Preload images
	//setTimeout(function(){
	//	preloadImagsFromStylesheets();
	//}, 1000);
	
	if($('body').hasClass('home')){
		$('#banners img:first-child').load(initializeBannerSlideshow);
	}
	
	if(isBeforeIE8)
		$('img').removeAttr('alt'); //remove tooltip
	
	var $floatingContents = $("#content > .floating-contents");
	if($floatingContents.length && $floatingContents.css('position') == 'relative'){
		$floatingContents
			.css('top', ($floatingContents.parent().outerHeight(true)-$floatingContents.outerHeight(true))/2)
			.addClass('positioned'); //make visible after having been positioned
	}
	//var $firstBanner = $('#banners img:first-child');
	//if($firstBanner.length)
	//	$firstBanner[0].onload = initializeBannerSlideshow;
	
	//Focus on the search box
	$('a[href="#s"]').click(function(e){
		$(this.href.substr(this.href.indexOf('#'))).focus();
		e.preventDefault();
	});
});

function initializeBannerSlideshow(){
	if($('#banners').hasClass('initialized') || $('#banners').hasClass('banner-count-1'))
		return;
	
	if(isOldIE){
		$('#banners').addClass('initialized');
	}
	else {
		//Add a curtain to cover the loading banners; and then animate it away once
		// the first image is loaded?
		var $curtain = $(document.createElement('div')).attr('id', 'banner-curtain');
		$('#banners').append($curtain);
		$('#banners').addClass('initialized');
		$curtain.animate({
			opacity:0.0
		}, {
			duration:1000,
			complete:function(){
				$('#banners').addClass('initialized');
				$(this).remove();
			}
		});
	}
}

jQuery(window).load(function(){
	//Detect if images are enabled
	var $firstImg = jQuery('#header img');
	if($firstImg[0].height != parseInt($firstImg.css('height'), 10)){
		jQuery(document.documentElement)
			.removeClass('images-enabled')
			.removeClass('graphical-nav');
	}
	
	//Animate banner images
	var $bannerImgs = $('#banners img');
	if($bannerImgs.length > 1){
		initializeBannerSlideshow();
			
		//Animate the banners
		if(!isOldIE) {
			var initialSlideDuration = 8000;
			var slideDuration = 6000;
			var slideTransition = 2000;
			
			var nowTime = new Date();
			//var initialSlideDuration = Math.max(slideDuration - (nowTime.valueOf() - startTime.valueOf()), 0);
			
			var $banners = $('#banners');
			var lastBannerPos = 0;
				
			var animationIntervalID;
			var cyclesThrough = 0;
			var animateBanners = function(){
				
				i = lastBannerPos+1;
				if(!$bannerImgs[i]){
					//Now we need to pause and hold the animation for awhile
					i = 0;
					cyclesThrough++;
					//if(cyclesThrough == 1){
					//	slideDuration = slideDuration*3;
					//}
					//if(isOkToPause){
					//	//console.info('Pause')
					//	isPaused = true;
					//	isOkToPause = false;
					//	window.setTimeout(function(){
					//		//console.info('UnPause')
					//		isPaused = false;
					//	}, 40000);
					//}
				}
				//if(isPaused)
				//	return;
				var $bannerImg = $($bannerImgs[i]);
				
				//Now we need to move thisBannerPos to the beginning of the list and then animate it to full opacity
				$bannerImg.css({opacity:0.0});
				$banners[0].insertBefore($bannerImg[0], $banners[0].firstChild);
				
				//For IE and WebKit, CSS :first-child rules need to be applied via changing parent className
				$banners.toggleClass('temp');
				
				$bannerImg.stop();
				$bannerImg.animate({opacity:1.0}, {duration:slideTransition});
				
				lastBannerPos = i;
				window.setTimeout(animateBanners, slideDuration);
			}
			window.setTimeout(animateBanners, initialSlideDuration);
		}
	}
	
	
	//Animate category landing pages
	var $thumbImgs = $('#thumbnail-gallery img');
	if($thumbImgs.length > 1){
		
		if(!isOldIE) {
			var slideDuration = 3000;
			var slideTransition = 500;
			
			var nowTime = new Date();
			var initialSlideDuration = Math.max(slideDuration - (nowTime.valueOf() - startTime.valueOf()), 0);
			
			var $thumbnailGallery = $('#thumbnail-gallery');
			var lastBannerPos = 0;
				
			var animationIntervalID;
			var animateBanners = function(){
				
				i = lastBannerPos+1;
				if(!$thumbImgs[i])
					i = 0;
				var $thumbImg = $($thumbImgs[i]);
				
				//Now we need to move thisBannerPos to the beginning of the list and then animate it to full opacity
				$thumbImg.css({opacity:0.0});
				$thumbnailGallery[0].insertBefore($thumbImg[0], $thumbnailGallery[0].firstChild);
				
				//For IE and WebKit, CSS :first-child rules need to be applied via changing parent className
				$thumbnailGallery.toggleClass('temp');
				
				$thumbImg.stop();
				$thumbImg.animate({opacity:1.0}, {duration:slideTransition});
				
				lastBannerPos = i;
				window.setTimeout(animateBanners, slideDuration);
			}
			window.setTimeout(animateBanners, initialSlideDuration);
		}
	}
	
});

/**
 * Load all external resources specified in the CSS stylesheets (pre-fetching)
 */
function preloadImagsFromStylesheets(){
	var loadedImages = {};
	jQuery(document.styleSheets).each(function(){
		if(!this.href)
			return;
		//var baseURL = this.href.replace(/[^\/]+$/, '');
		var baseURL = '';
		jQuery(this.cssRules ? this.cssRules : this.rules).each(function(){
			var url = this.style.backgroundImage;
			if(url && (url != 'none') && (url != 'initial')){
				url = baseURL + url.replace(/^\s*url\(['"]?/i, '').replace(/['"]?\)\s*$/, '');
				if(/^data:/.test(url))
					return;
				if(loadedImages[url])
					return;
				console.info(url)
				loadedImages[url] = true;
				var img = new Image();
				img.src = url;
			}
		});
	});
	loadedImages = null;
}