/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
	historyCurrentHash: undefined,
	
	historyCallback: undefined,
	
	historyInit: function(callback){
		jQuery.historyCallback = callback;
		var current_hash = location.hash;
		
		jQuery.historyCurrentHash = current_hash;
		if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash == '') {
			jQuery.historyCurrentHash = '#';
		}
		
			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			
			jQuery.isFirst = true;
		}
		jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
		if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
			
				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
				
			}
		} else if ($.browser.safari) {
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = location.hash;
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.historyCallback(document.URL.split('#')[1]);
					} else {
						var current_hash = location.hash;
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;
		
		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;
		
		if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});

$.fn.equalHeights = function(px) {
	$(this).each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
	});
	return this;
};

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({
		scope: 'body',
		reverse: false
	}, settings);
	
	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};			
	if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){		
			return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };
			
	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};

jQuery.preload = function() {
jQuery.each (arguments,function (e) {
	jQuery ('<img src="' + this + '" />');
});
};

function loadProducts(hash) {
	if(hash) {
		$("#product-list").empty().load('../../../en/embeds/product-thumbs/'+ hash +'/',function() {
			$('#product-list').equalHeights();
		});
	}
}
function loadState(hash) {
	if(hash) {
		$("#location-view").fadeOut(function() {
			$("#location-view").empty().load('../../en/embeds/sales-locator/'+ hash +'/', function() {
				$(this).fadeIn(function() {
					$("#show-map").css("visibility", "visible");
					$("#salesloc").slideUp();
				});
			});
		});
	}
}
function openWindow(url) {
	newwindow=window.open(url,'name','height=768,width=1024,location=0,status=1,scrollbars=1,resizable=1,menubar=0,toolbar=0');
	if (window.focus) {newwindow.focus()}
}
$(document).ready(function() {
	
	$("#sub-nav a[@href$=pdf]").attr('target', '_blank');
	$('#sitemap li:last').addClass('last');
	$('#product-list').equalHeights();

	$('.col1:last').addClass('last');
	$('.col2:last').addClass('last');
	$('.col2:first').addClass('top');

	$('#loading').ajaxStart(function() {
	 	$(this).fadeIn("fast");
	 }).ajaxStop(function() {
	 	$(this).hide();
	 });
		$.historyInit(loadProducts);
		$('.product-open ul li a:not(.location, .product)').click(function() {
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			$('.product-open').hide('');
			$('.product-dropdown h4').removeClass('show');
			$.historyLoad(hash);
			return false;
		});
	
	$('.product-open ul li').each(function(i) {
		if((i % 3) == 2) $(this).addClass('col3');
	});
	 
	$('.product-open').hide();
	var hide = false;
	$('.product-dropdown h4').hover(function() {
		if (hide) clearTimeout(hide);
		$('.product-open').fadeIn('fast');
		$('.product-dropdown h4').addClass('show');
  		}, function() {
			hide = setTimeout(function() {$('.product-open').fadeOut('fast'); $('.product-dropdown h4').removeClass('show');}, 250);
	  });
 	$('.product-open').hover(function() {
	    if (hide) clearTimeout(hide);
	}, function() {
	    hide = setTimeout(function() {$(".product-open").fadeOut("fast"); $('.product-dropdown h4').removeClass('show');}, 250);
	});
	
	var hidea = false;
	$('body#home .architectural h2').hover(function() {
		if (hidea) clearTimeout(hidea);
		$('body#home .architectural ul').slideDown(250);
		$('body#home .architectural .photo').animate({height: '170px'}, 250);
			$("<img>").attr("src",'/assets/images/homepage-education.jpg');
			$("<img>").attr("src",'/assets/images/homepage-entertainment.jpg');
			$("<img>").attr("src",'/assets/images/homepage-government.jpg');
			$("<img>").attr("src",'/assets/images/homepage-office.jpg');
	}, function() {
	    hidea = setTimeout(function() {$("body#home .architectural ul").slideUp(240); $('body#home .architectural .photo').animate({height: '299px'});}, 250);
	});
	$('body#home .architectural ul').hover(function() {
	    if (hidea) clearTimeout(hidea);
	}, function() {
	    hidea = setTimeout(function() {$("body#home .architectural ul").slideUp(240); $('body#home .architectural .photo').animate({height: '299px'});}, 250);
	});
	
	$('body#home .architectural ul li a').hover(function() {
		$('body#home .architectural .photo').css('background-image','url(/assets/images/homepage-'+ $(this).attr("id") +'.jpg)');
	}, function() {
		$('body#home .architectural .photo').css('background-image','url(/assets/images/homepage-arch.jpg)');
	});
	
	var hidet = false;
	$('body#home .transportation h2').hover(function() {
		if (hidet) clearTimeout(hidet);
		$('body#home .transportation ul').slideDown(250);
		$('body#home .transportation .photo').animate({height: '170px'}, 250);
				$("<img>").attr("src",'/assets/images/homepage-city-service-bus.jpg');
				$("<img>").attr("src",'/assets/images/homepage-demand-response.jpg');
				$("<img>").attr("src",'/assets/images/homepage-rail.jpg');
				$("<img>").attr("src",'/assets/images/homepage-motorcoach.jpg');
	}, function() {
	    hidet = setTimeout(function() {$("body#home .transportation ul").slideUp(240); $('body#home .transportation .photo').animate({height: '299px'});}, 250);
	});
	$('body#home .transportation ul').hover(function() {
	    if (hidet) clearTimeout(hidet);
	}, function() {
	    hidet = setTimeout(function() {$("body#home .transportation ul").slideUp(240); $('body#home .transportation .photo').animate({height: '299px'});}, 250);
	});
 	
	$('body#home .transportation ul li a').hover(function() {
		$('body#home .transportation .photo').css('background-image','url(/assets/images/homepage-'+ $(this).attr("id") +'.jpg)');
	}, function() {
		$('body#home .transportation .photo').css('background-image','url(/assets/images/homepage-trans.jpg)');
	});
	
	$('.installations .product-open li a').each(function(){
		var className = $(this).attr('class');
		var prevClassName = $(this).parent().prev().children('a').attr('class');
		
		if(className == prevClassName){
			var col = $(this).parent().attr('class');
		
			$(this).parent().remove();
		}
	});
	
	$('.installations .product-open li').each(function(){
		$(this).removeClass('col3');
	});
	
	$('.installations .product-open li:nth-child(3n)').each(function(){
		$(this).addClass('col3');
	});
	
	/*$('.tools .reverse-resources li').each(function(){
		var parentCat = $(this).parent().attr('id');
		var childCat = $(this).attr('class');
		
		$("li[class*='" + parentCat + "']").css('display','block');
	});*/
	
	/*$('.tools .reverse-resources').each(function(){
		var childCount = $(this).children().size();
		
		if(childCount == 0){
			var catName = $(this).prev().text();
			
			$(this).append('<li class="empty">This product currently has no ' + catName + '.</li>')
		}
	});*/
	
	var galleryCount = $('ul.gallery').children().size()
	
	$('a.gallery-nav').each(function(){
		if(galleryCount > 1){
			$(this).css('visibility','visible');
		}
	});
	
	$('a.external').click(function(){
		window.open(this.href);
		return false;
	});
});