//Global JavaScript Document

/********************************

	Notes:
		+ I rely on JQuery v1.2.6
		+ use "jQuery" instead of $ for noConflict() use with other JS libs.

********************************/

// Prevent console commands from throwing errors in IE
try { console.log('init console... done'); } catch(e) { console = { log: function() {} }; }

// Global variables
var menuSpeed = 150; //menu animation speed in milliseconds
var hideDelay = 500; //delay to hide menus in milliseconds	


function activateMainNav() {
	//
	// Code for main navigation dropdown menus
	//
	hideDelay = 250; //delay to hide menus in milliseconds

	jQuery('#mainNav > li').each(function(i) {

		if( (jQuery('ul', this).length) > 0 ) {

			var hideDelayTimer = null;
			var beingShown = false;
			var shown = false;
			var trigger = jQuery('>a', this);
			var menu = jQuery('>ul', this);			

			jQuery([trigger.get(0), menu.get(0)]).hover(
				function() {

					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					if (beingShown || shown) {
						// don't trigger the animation again
						return;
					} else {
						// reset position of info box
						beingShown = true;

						trigger.addClass('over');
						menu.slideDown(menuSpeed, function() {
							beingShown = false;
							shown = true;							
						});
					}

					return false;
				},
				function(){

					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					hideDelayTimer = setTimeout(function () {
						hideDelayTimer = null;
						menu.slideUp( menuSpeed, function () {
							shown = false;
							trigger.removeClass('over');							
						});

						}, hideDelay);

						return false;
					}
				);
			}
		});

		jQuery('#mainSearchButton').click(function(){
			jQuery('#searchBox').submit();
		});

		jQuery('#header h1').click(function(){
			window.location = jQuery('a', this).attr('href');								 

		});
	}

// Hide form selects on nav mouseover in IE6
function hideSelects() {
	// Use feature checking to recognize IE6
	if (typeof document.body.style.maxHeight === "undefined") {
		// Collect dropdown nav items
		var menus = jQuery('#mainNavKitchen, #mainNavBath, #mainNavSupport, #mainNavPro');
		// Collect selects with a class of hideMe or selects within #pageHeader
		var selects = jQuery('form select.hideMe, #pageHeader select');		
		
		// Hide and show the selects on hover/mouseout of dropdowns
		menus.hover(function(){
			selects.css({
				visibility: 'hidden'
			});			
		}, function(){
			selects.css({
				visibility: 'visible'
			});			
		});
	}	
}


/* Switch between Compact and Detail views */
function switchViews() {
	if (jQuery('div#productsWrapper').length) {
		// Make sure we're not on the Comparison page
		if(!jQuery('div.comparison').length) {		
			// Assign links to vars
			var compact = jQuery('li#topViewCompact a');
			var detailed = jQuery('li#topViewDetail a');

			// Compact view link
			compact.bind('click', function(){
				jQuery('div#productsWrapper').addClass('compact');
				compact.addClass('active');
				detailed.removeClass();
				return false;
			});

			// Detailed view link
			detailed.bind('click', function(){
				jQuery('div#productsWrapper').removeClass('compact');
				detailed.addClass('active');
				compact.removeClass();
				return false;
			});
		}
	}
}


/* Reorder products */
function initReorder() {
	if(jQuery(".sortable-products").length) {
		jQuery(".sortable-products").sortable( {
			placeholder: "ui-selected",
			accept: "myItem",
			revert: "true",
			tolerance: "pointer",			
			update: function(){
				serial = jQuery('.sortable-products').sortable('serialize');
				jQuery(".History").append(serial+"<br>");
			}
		 });
	}
}



/* Calls to SWFObject */
function loadFlash(movie, elementId, width, height, site) {
	if(document.getElementById(elementId)) {
		swfobject.embedSWF(movie, elementId, width, height, '8.0.0', 'expressInstall.swf', {fparam: site}, {'wmode': 'transparent'});
	}
}

function myDeltaFilterSubmit() {
	if(jQuery('#myDeltaFilterForm').length) {
		jQuery('#myDeltaFilterForm').bind('submit', function(){
			applyPreferences();
			return false;
		});
	}
}

// Check to see if any favorites exist for the currently viewed category
function checkForFavorites() {
	if(jQuery('label.myFavorite :input:checked').length == 0) {
		if(jQuery('input#chkOnlyShowFavorites:checked').length) {
			jQuery('input#chkOnlyShowFavorites').attr('checked', '');
			jQuery('form#myDeltaFilterForm').submit();
		}
		jQuery('div.onlyFavorites').hide();
	} else {
		jQuery('div.onlyFavorites').show();
	}
}

// Function to apply sifr with class and font parameters
function applySifr(sifrClass, sifrFont) {
	sIFR.replaceElement(named({
				sSelector:".sifr-" + sifrClass,
				sFlashSrc:"/js/sifr/"+ sifrFont +".swf",
				sColor:"#ffffff",
				sWmode: "transparent"
			}));
}

// Function to look for sifr-replaced elements and run applySifr() as needed
function addSifr() {
	// Look for sifr-classed h2s
	if(jQuery('body').find('h2[class^="sifr-"')) {
		// Run applySifr() for each class
		if(jQuery('.sifr-semibold').length) { applySifr('semibold', 'itc-stone-sans-std-semibold'); }
		if(jQuery('.sifr-medium').length) { applySifr('medium', 'itc-stone-sans-std-medium'); }
	}
}

//Set up tooltips and footnotes
function addTooltips() {	
	jQuery('.toolTip').each(function(){
		jQuery(this).cluetip({ 
			arrows: true, 
			dropShadow: false,
			hoverIntent: true,
			sticky: true,
			mouseOutClose: true,
			closePosition: 'title',
			showTitle: true,
			closeText: '<img src="/images/cluetip/close.gif" alt="close" />'
		});
	});
	
	jQuery('.toolTip-touch').each(function(){
		jQuery(this).cluetip({ 
			arrows: true, 
			dropShadow: false,
			hoverIntent: true,
			sticky: true,
			mouseOutClose: true,
			closePosition: 'title',
			showTitle: true,
			closeText: '<img src="/images/cluetip-touch/close.gif" alt="close" />'
		});
	});
	
	jQuery('.toolTipInline').each(function(){		
		jQuery(this).cluetip({ 
			arrows: true, 
			dropShadow: false,
			hoverIntent: true,
			splitTitle: '|',
			sticky: true,
			mouseOutClose: true,
			closePosition: 'title',
			showTitle: true,
			closeText: '<img src="/images/cluetip/close.gif" alt="close" />'
		});
	});
	
	//Finish titles
	//jQuery('.finishOption img').each(function(){
	//	jQuery(this).cluetip({
	//		showTitle: false,
	//		cluetipClass: 'tooltip',
	//		splitTitle: '|',
	//		tracking: true,
	//		width: 100,
	//		mouseOutClose: true
	//	}).click(function(){
	//		jQuery('#cluetip').css({ display:'none' })
	//	});
	//});
	
	//Set up footnote cluetips 
	jQuery('.footnote').each(function(){
		jQuery(this).cluetip({
			arrows: true,
			local:true,
			hideLocal:false,
			showTitle:false,
			cursor: 'pointer'
		});
	});
	
}


// Swap content
// - Use classes .swap1 and .swap2 for swap containers
// - Swap containers must be adjacent
// - Use class .swapSwitch for trigger element
function swapContent() {
	if(jQuery('.swap2').length) {
		jQuery('.swap2').hide();

		jQuery('.swapSwitch').bind('click', function(){
			if(jQuery(this).parents('.swap1').length) {
				jQuery(this).parents('.swap1').hide();
				jQuery(this).parents('.swap1').siblings('.swap2').show();
				if (jQuery(this).parents('.swap1').siblings('.swap2').find('input[type=text]')) {
					jQuery(this).parents('.swap1').siblings('.swap2').find('input[type=text]').eq(0).focus();					
				}
			} else if(jQuery(this).parents('.swap2').length) {
				jQuery(this).parents('.swap2').hide();
				jQuery(this).parents('.swap2').siblings('.swap1').show();
			}
			return false;
		});
	}
}

// Add classes to form inputs for css use
function addFormClasses() {
	if(jQuery('input').length) {
		jQuery('input').each(function(){
			jQuery(this).addClass(this.type);
		});
	}
}

// Show/hide list items
// Parameters:
// - hidingElms = Required - jQuery object containing elements to be hidden
// - triggerElm = Required - jQuery object containing elements which act as triggers for showing/hiding
// - showFirst = Optional - Flag indicating whether first item should remain visible at page load
function listSlider(hidingElms, triggerElm, showFirst) {	
	if (typeof showFirst == 'undefined') {
		hidingElms.hide();
	} else {
		triggerElm.eq(0).toggleClass('expanded');
		hidingElms.slice(1).hide();
	}	
	triggerElm.each(function(){
		jQuery(this).click(function(){
			if (jQuery(this).hasClass('expanded')) {
				jQuery(this).next().slideUp('fast');
				jQuery(this).toggleClass('expanded');
			} else {
				jQuery(this).next().slideDown('fast');
				jQuery(this).toggleClass('expanded');
			}
		});
	});
}

// Showing/hiding of search results
function collapseSearchResults() {
	if (jQuery('body.resultsAllCategories .searchSectionResults').length) {
		listSlider(jQuery('.searchSectionResults'), jQuery('.searchSectionHeader'), 1);	
	}
}

// Showing/hiding of FAQ
function collapseFaq() {
	if (jQuery('ul#faq').length) {
		listSlider(jQuery('ul#faq .faqAnswer'), jQuery('ul#faq li h3'));
	}
}

// Disable search results-per-page select if "All" categories is selected
function setResultsSelect() {
	function switchMe() {
		if (jQuery('select#collection').length) {
			if (jQuery('select#collection').val() == "DLT_all") {
				jQuery('select#num').attr('disabled', 'disabled');
			} else {
				jQuery('select#num').attr('disabled', '');
			}
		}
	}
	// Run function on page load
	switchMe();
	// Attach function to select
	jQuery('select#collection').bind('change', function() {switchMe();});
}

// function setDiagram() {
// 	if (jQuery('div#diagram').length) {
// 		jQuery('img#diagram2').hide();
// 
// 		jQuery('div#diagram').append('<p><a href="#" id="diagramSwitcher">Expand Diagram</a></p>');
// 
// 		var img1 = jQuery('img#diagram1').attr('src');
// 		var img2 = jQuery('img#diagram2').attr('src');
// 
// 		jQuery('a#diagramSwitcher').bind('click', function(){				
// 			if (jQuery(this).hasClass('clicked')) {					
// 				jQuery('img#diagram1').attr('src', img1);
// 				jQuery(this).text('Expand Diagram');
// 				jQuery(this).toggleClass('clicked');
// 			} else {
// 				jQuery('img#diagram1').attr('src', img2);
// 				jQuery(this).text('Collapse Diagram');
// 				jQuery(this).toggleClass('clicked');
// 			}				
// 			return false;
// 		})
// 	}	
// }


// shows confirmation message on add/remove stuff to mydelta
function showConfirmation (data) {

	if (data.isAnonymousWithItems) {
		jQuery("#mydeltaAnonWarning").show() ;
	} else {
		jQuery("#mydeltaAnonWarning").hide() ;
	}
}

// Open downloadable files in new browser window
function setDownloadLinks() {
	jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".xls"], a[href$=".ppt"], a[href$=".csv"]').unbind().bind('click', function(){
		window.open(this.href);
		return false;
	});
}

// Open external links in new browser window
function setExternalLinks() {
	jQuery('a[rel*="external"], a[href^="http"]').not('a[id*="_dart_"]').not('.thickbox').unbind().bind('click', function(){
		window.open(this.href);
		return false;
	});
}

function closeThickBox () {
	if ('function' == typeof tb_remove) {
		tb_remove();
	}	
}

function invokeOnCloseThickBox (functionObj) {	
	jQuery ("#TB_window").unload (functionObj) ;
}

// Recover hidden Flash objects
function recoverFlash(){
	jQuery('object.hidden').removeClass('hidden');	
}

function initPrint(){
	jQuery('#printButton').bind('click', function(){
		window.print();
		return false;
	});
}

function checkProCookie() {
	if(jQuery.cookie('proUser') !== '1') {
		//jQuery('#mainNavPro').remove();
	}
}

function linkFileTypes() {
	var $a = jQuery('.download a, #findDeltaRep a, .download-xls a');
	
	$a.each(function(x){
		var $this = jQuery(this);
		var $fileType = $this.attr('href').split('.').reverse()[0].toLowerCase();
		if($this.find('img').length != 0) {
			return;
		} else {
			if($fileType === 'pdf') {
				$this.addClass('pdf');
			} else if($fileType === 'xls') {
				$this.addClass('xls');
			} else if($fileType === 'ppt') {
				$this.addClass('ppt');
			} else if($fileType === 'doc') {
				$this.addClass('doc');
			} else if($fileType === 'csv') {
				$this.addClass('csv');
			}	else if($fileType === 'zip') {
				$this.addClass('zip');
			}
		}			
	});
}

// Auto-hide default input text
// add class of "default" to inputs to activate
function inputDefault() {
	jQuery('input[type="text"].default').each(function(){
		var $this = jQuery(this);
		var $def = $this.val();
		// hide default text on focus
		$this.focus(function(){
			if($this.val() === $def) {
				$this.val('');
			}
		})
		// show default text if empty on blur
		.blur(function(){
			if($this.val() === '') {
				$this.val($def);
			}
		});
	});
};

// Open logo links in new window
function logoNewWindow() {
	jQuery('div.logoGroupWrapper a').unbind().click(function(){
		window.open(this.href);
		return false;
	});
}

// Open links with rel="window" in new window
function classNewWindows() {
	jQuery('a[rel="window"]').unbind().click(function(){
		window.open(this.href);
		return false;
	});
}

/* Initialization of functions created above */
jQuery(document).ready(function() {
	activateMainNav();
	myDeltaFilterSubmit();
	switchViews();
	initReorder();
	loadFlash();
	//addSifr();
	addTooltips();
	swapContent();
	addFormClasses();
	collapseSearchResults();
	collapseFaq();
//	setResultsSelect();
	//setDiagram();
	setExternalLinks();
	hideSelects();
	initPrint();
	checkProCookie();
	linkFileTypes();
	setDownloadLinks();
	inputDefault();
	logoNewWindow();
	classNewWindows();
});