var AJAX_CACHE={};

$(document).ready(function() {


// GENERAL
	/* For bilingual styling */
	$('body[lang=fr]').addClass('french');
	
	/* Makes targeting form elements easier in IE6	*/
	$('input').each(function() {
		var inputType = $(this).attr('type');
		$(this).addClass(inputType);
	});
  
 
// NAVIGATION	
	$('ul#nav ul.sub.current').show();
	
	$('ul#nav li a').live('click', function() {				
		$('ul#nav li').children('ul.sub').hide();
		$(this).siblings('ul.sub').show();
		
		if ( ($(this).attr('href') != '#') && ($(this).parents('ul').attr('class') == 'sub current') ) {
			$('ul.sub.current').show();
		} else if ( $(this).parents('li[class^=nav_]').children('a').attr('href') == '#' ) {
			$(this).parent().parent().show();
		}
		
		$(this).parent().siblings().children('ul.sub:visible').hide();
	});


// ACCORDION SECTIONS
	var dds=$('dl dd').filter(function(idx) {
		return $(this).prev("dt").hasClass("active")?0:1;
	}).hide();
		
	$('body#customer_support dl dt').live('click', function() {	
		if (!$(this).hasClass("noAccordian")) {
			if ( $(this).attr('class') == 'active' ) {
				$(this).removeClass('active').siblings('dd:visible').hide();
			} else {
				$(this).parent().find('dd:visible').hide();
				$(this).parent().find('dt').removeClass('active');
				$(this).toggleClass('active').next('dd').toggle();
			}
		}
	});
	

// SIDEBAR WIDGETS
	$('div.widget div.inner').hide();	
	
	/* Individual Widgets */
	$('div.widget h5').live('click', function() {
		if ( $(this).children('span').attr('class') == 'collapsed' ) {
			$(this).children('span').attr('class','expanded').parent().parent().children('div.inner').show();
		}
		else {
			$(this).children('span').attr('class','collapsed').parent().parent().children('div.inner').hide();
		}
	});
	
	/* All Widgets */
	$('a.show_widgets').live("click", function() {
		$(this).parent().find('h5').children('span').attr('class','expanded').parent().parent().children('div.inner').show();
		$(this).replaceWith('<a href="#" class="hide_widgets">Hide All</a>');
		$.cookie('show_widgets', 'true', { expires: 7 });
	});
	
	$('a.hide_widgets').live("click", function() {
		$(this).parent().find('h5').children('span').attr('class','collapsed');
		$(this).parent().find('div.inner').hide();
		$(this).replaceWith('<a href="#" class="show_widgets">Show All</a>');
		$.cookie('show_widgets', 'false', { expires: 7 });
	});
	
	/* Get or set Cookie */
	var show_widgets = $.cookie('show_widgets');
	function widgetCookie() {
		if ( show_widgets == 'true' ) {
			$('a.show_widgets:visible').hide();
			$('#customize').find('h5').children('span').attr('class','expanded');
			$('#customize div.inner').show();
			$('#customize').append('<a href="#" class="hide_widgets">Hide All</a>');
		}	else {
			$('#customize').find('h5').children('span').attr('class','collapsed');
			$('#customize div.inner').hide();
			$('#customize').append('<a href="#" class="show_widgets">Show All</a>');
		}
	};
	widgetCookie();
	
	
// TOOLTIPS
	/* Key Features */
	$('ul#key-features li').mouseenter(function() {
		var toolTipContent = $(this).children('div.popup').html();
		var featureWidth = $(this).outerWidth();
		
		$(this).append('<div class="tooltip">'+toolTipContent+'<span class="tick"></span></div>');
		$('div.tooltip').hide().fadeIn(350);
	});

	$('ul#key-features li').mouseleave(function() {
		$('div.tooltip').remove();
	});
		
	/* Glossary Items */
	$('ul#icons li').mouseenter(function() {

		var toolTipContent = $(this).find('img').attr('alt');
		
		$(this).append('<div class="tooltip"><p>'+toolTipContent+'</p><span class="tick"></span></div>');
		$('div.tooltip').hide().fadeIn(350);
	});

	$('ul#icons li').mouseleave(function() {
		$('div.tooltip').remove();
	});	
	
	/* Sidebar Widget Help */
	$('div.popup').hide();
		
	$('div.widget a.details_popup').click(function() {
		var toolTipContent = $(this).siblings('div.popup').html();
		var posBottom = $(this).parents('div.inner').offset().top - $(this).offset().top + $(this).parents('div.inner').outerHeight();
		var posLeft = 212;	//This is the width of the tooltip from screen.css
		var tooltipBottom = posBottom - $('div.tooltip').outerHeight() /2 -5;

		$(this).parent().append('<div class="tooltip">'+toolTipContent+'<span class="tick"></span></div>');
		
		var topPosition = $(this).parent('li').position().top;
		var tooltipHeight = $(this).siblings('.tooltip').outerHeight() /2 -10;

		$('div.tooltip').css({ 'top':'-'+tooltipHeight+'px' , 'left':'-'+posLeft+'px' }).hide().fadeIn(350);
		return false;
	});

	$('div.widget a.details_popup').mouseleave(function() {
		$('div.tooltip').remove();
	});	
	
	
// TABBED CONTENT
	$('div.tab_content').each(function() {
		$(this).attr('id', 'box_' + $("div.tab_content").index(this));

		if ( $(this).attr('id') == 'box_0' ) {
			$(this).show();
		} else {
			$(this).hide();
		}
	});

	$('ul#tabs li').each(function() {
		$(this).attr('id', 'tab_' + $("ul#tabs li").index(this));
	});
	
	$('ul#tabs li a').click(function() {
		var tabNumber = $(this).parent().attr('id').replace('tab_','box_');
		
		$('ul#tabs li a').attr('class','');
		$(this).addClass('active');
		$('div.tab_content[id='+tabNumber+']').show();
		$('div.tab_content[id!='+tabNumber+']').hide();
		return false;
	});
	
	
// COMPARE PRODUCT
	$('div.compare input[type=checkbox]').each(function() {
		$('div.compare input[type=checkbox]:checked').parents('li').addClass('compared');
	});
	
	$('div.compare input[type=checkbox]').live('change', function(e) {
		$(this).parent().parent().toggleClass('compared');
	});
	
	/* Remove column from comparison table */
	$('a.remove_product').click(function() {
		var colNumber = $(this).index('a.remove_product') +2;
		$(this).parents('table').find('td').filter(':nth-child('+colNumber+')').remove();
		$(this).parent().remove();
		numOfCols();
	});
	
	/* Only show 'Add Item' button if there are less than 4 columns */
	function numOfCols() {
		if ( $('table thead th[class != add_item]').size() >= 4 ) {
		  $('table th.add_item a').hide();
		} else {
		  $('table th.add_item a').show();
		}
	};
	numOfCols();
	
	
	/* Add a 'compare selected' link to all items being compared */
	$('div.compare input[type=checkbox]').live("change", function() {
		var $defaultItems = $('#product_listing ul.products li');
		var $comparedItems = $('#product_listing ul.products li.compared');
		var COMPARE_SELECTED=$('ul.products').attr("data-cstext");

		// If there is more than 1 product being compared
		if ($comparedItems.size() > 1) {		
			$defaultItems.each(function() {
				if (($(this).attr('class') == 'compared') && ($(this).find('a.compare-selected').length == 0)) {
					$(this).append('<a class="compare-selected" href="#">'+COMPARE_SELECTED+'</a>');
				} else if ($(this).attr('class') != 'compared') {
					$(this).find('a.compare-selected').remove();
				}
			});
		} else {
			$defaultItems.find('a.compare-selected').remove();
		}
	});
	
	
	/* Submit form when 'compare selected' link is clicked */
	$('a.compare-selected').live("click", function() {
		$('#comparisons form').find('input[type=submit]').trigger('click');
	});
	

// Fancybox configuration for product details
	/* Photo Gallery */
	$("#product_detail #showcase a[rel=gallery], a.popup").fancybox({
		'padding': 3,
		'overlayOpacity': 0.75,
		'overlayColor': '#000',
		'speedIn': 450,
		'speedOut': 300,
		'titleShow': false
	});

	$("#product_detail #showcase a.popuptext").fancybox({
		'padding': 10,
		'overlayOpacity': 0.75,
		'overlayColor': '#000',
		'speedIn': 450,
		'speedOut': 300,
		'titleShow': false
	});
	
	/* Video/Flash Content */
	$("#product_detail #showcase #thumbs ul li.video a").fancybox({
		'padding': 3,
		'overlayOpacity': 0.75,
		'overlayColor': '#000',
		'speedIn': 450,
		'speedOut': 300,
		'titleShow': false,
		'hideOnOverlayClick': false
	});	
	
	/* Configure Fancybox for SWF files */
	$('a.swf').fancybox({
		'padding': 0,
		'autoScale': false,
		'transitionIn': 'none',
		'transitionOut': 'none',
		'hideOnOverlayClick': false,
		'hideOnContentClick': false,
		'titleShow': false,
		'overlayOpacity': 0.5,
		'overlayColor': '#000'
	});
	
	/* Configure Fancybox for YouTube videos */
	$('a.youtube').click(function() {
		$.fancybox({
			'padding': 0,
			'autoScale': true,
			'transitionIn': 'none',
			'transitionOut': 'none',
			'title': this.title,
			'hideOnOverlayClick': false,
			'hideOnContentClick': false,
			'titleShow': false,
			'overlayOpacity': 0.5,
			'overlayColor': '#000',
			'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type': 'swf',
			'swf': {'wmode': 'transparent', 'allowfullscreen': 'true'}	
		});
		
		return false;
	});
	
	
	/* Configure Fancybox for Invodo videos */
	$('a.invodo').fancybox({
		'type': 'iframe',
		'padding': 0,
		'autoScale': false,
		'width': 495,
		'height': 285,
		'transitionIn': 'none',
		'transitionOut': 'none',
		'hideOnOverlayClick': false,
		'hideOnContentClick': false,
		'titleShow': false,
		'overlayOpacity': 0.5,
		'overlayColor': '#000',
		'scrolling': 'no'
	});
	
	
// SLIDESHOWS
	$('#home ul#featured').cycle({
		fx: 'fade',
		timeout: 7000,
		pager: '#showcase ul.controls',
		pagerAnchorBuilder: function(idx, slide) {
			var idNum = idx + 1;
			return '<li><a href="#">'+idNum+'</a></li>';
		}
	});
	
	$('#showcase ul.slides').cycle({
		timeout: 7000,
		pager: 'div.module ul.controls',
		pagerAnchorBuilder: function(idx, slide) {
			var idNum = idx + 1;
			return '<li><a href="#">'+idNum+'</a></li>';
		}
	});
	
	$('#product_listing #showcase ul#features').cycle({
		timeout: 7000,
		pager: '#showcase ul.controls',
		pagerAnchorBuilder: function(idx, slide) {
			var idNum = idx + 1;
			return '<li><a href="#">'+idNum+'</a></li>';
		}
	});
	
	
// GLOSSARY TERMS
	$('#content a.glossaryTerm').hover(function() {
		if ($(this).hasClass("dict")) {
			glossaryTermLoad(this,"d",$(this).attr("dict"));
		}
		else {
			glossaryTermLoad(this,"g",$(this).attr("gID"));
		}
	},function() {
		$('#glossaryDef').fadeOut(150).find('span.tick').remove();
	});
	
	/* AJAX call for product showcases */
	function glossaryTermLoad(obj,type,tag) {
	
		var onSuccess = function(text) {
			var offset=$(obj).offset();			
			$('#glossaryDef').hide().html(text).append('<span class="tick"></span>');
			$('#glossaryDef').css({top:(offset.top-$('#glossaryDef').outerHeight()-8)+'px',left:(offset.left-75)+'px'});
			$('#glossaryDef').fadeIn(150);
		}
		
		var url = '/ajax/ajax-glossaryterm.php?'+type+'='+tag;
		
		if (AJAX_CACHE[url]) onSuccess(AJAX_CACHE[url])
		else $.get(url, function(response,status,o) {
			AJAX_CACHE[url]=response;
			onSuccess(response);
		});
	}


// PRODUCT SHOWCASE
	/* Load previous/next buttons */
	$('#content .showcase.controls li.prev a').click(function(){
		cur_showcase=(cur_showcase<=1)?num_showcases:(cur_showcase-1);
		showcase_load(cur_showcase);
		return false;
	});
	
	$('#content .showcase.controls li.next a').click(function(){
		cur_showcase=(cur_showcase>=num_showcases)?1:(cur_showcase+1);
		showcase_load(cur_showcase);
		return false;
	});
	
	$('#product_listing #content #listings .sort_listing form#numPerPageForm select').change(function(){
		document.forms["numPerPageForm"].submit();
	});

	$('#product_listing #content #listings .sort_listing form#sortOptionsForm select').change(function(){
		document.forms["sortOptionsForm"].submit();
	});
	
	/* AJAX call for product showcases */
	function showcase_load(scNum) {
		var onSuccess = function(text) {
			$('#content #ajax_block').html(text).hide().fadeIn(850);
			$('#showcase ul.slides').cycle({
				timeout: 7000,
				pager: 'div.module ul.controls',
				pagerAnchorBuilder: function(idx, slide) { return '<li><a href="#">'+idx+'</a></li>'; }
			});
		}
		
		var url = '/ajax/ajax-showcase.php?id='+cur_pageID+'&n='+scNum;
		
		if (AJAX_CACHE[url]) onSuccess(AJAX_CACHE[url])
		else $.get(url, function(response,status,o) {
			AJAX_CACHE[url]=response;
			$('#content #ajax_block').html('<div id="ajax_loader"></div>');
			onSuccess(response);
		});
	}
	
	var os=$("form .formRow .input.date input");
	for (var i=0;i<os.length;i++) {
		o=os[i];
		$(o).datepicker({
			dateFormat:'yy-M-dd',
			gotoCurrent:true,
			minDate:$(o).attr('minDate'),
			maxDate:$(o).attr('maxDate'),
			changeMonth:true,
			changeYear:true,
			yearRange:'c-80:c+80'
			});
	}

	try {
		if ($("body").attr("id")=="product_detail") {
			product_loadOtherResults();
			product_handleFilters();
		}
		if ($("body").attr("id")=="product_listing") {
			list_preparePaginationLinks();
			list_prepareCompare();
		}
		if ($("body").attr("id")=="customer_support") {
			if ($("#step1").length>0) {
				publications_prepare();
				/* yellow fade behavior here */

			}
			else registration_prepare();
		}
		if ($("body").attr("id")=="locations") {
			wtb_prepare();
		}
		if ($("body").attr("id")=="heat_loss_calculator") {
			calc_prepare();
		}
		if ($("body").attr("id")=="flv_player") {
			flv_prepare();
		}
	}
	catch(e) {}

	// initialize the contact form if it's on the page...
	try { contactForm_prepare(); } catch(e) { }

	$("#news_listings #content #listings .sort_options select").change(function(e) {
		document.location=this.options[this.selectedIndex].value;
	});

	// Hide IE6 message if overlay is clicked
	$('#_l').live('click', function() {
		$(this).remove();
		$('#_d').remove();
	});
	
	
// Operating cost calculator
	$('#occ').flash('/flash/calculator_2010.swf');
	

// add background-image class to document search div 
	$('#customer_support .doc_type_options select').change(function(e){
	
		//$('#customer_support .docSearchForm #step1').addClass('step1-back');
	
	});


// Yellow fade out once time elapses after model search box is shown
	
	


});	// End of document ready

function flv_prepare(flv) {
	$("#thePlayer").flash({
		swf: '/flash/bds_player.swf',
		width:480,
		height:360,
		flashvars: {
			flvFile:'/'+flv
		}
	});
}
