//Global JavaScript Document

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

	Notes:
		+ I rely on JQuery v1.2.6

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

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

// Fix JS flash of unstyled content by hiding all descendents of HTML until DOM is loaded.
// Check for class of "no-position-fix" on HTML element. If present, we don't run this.
if(!jQuery('html.no-position-fix').length) {
	jQuery('html').addClass('js');
}


// Global variable assignment
var brizo = {
	setGlobals: function() {
		brizo.contentBody = jQuery('div#content-body');
		
		// Store left position of #content-body (if not for a pop up)
		if (jQuery('.popup-content, .elearning-popup').length > 0) {
			brizo.contentBodyLeft = 0;
		} else {
			brizo.contentBodyLeft = jQuery('div#content-body').position().left;
		}
		brizo.backLinkHTML = '<a href="#" rel="back" class="back-link">back</a>';
		brizo.easing = 'easeOutQuad';
		brizo.areaPhoto = jQuery('div#area-photo');
		brizo.scrollerTitles = jQuery('div#area-title, div#function-title, div#collection-title');
		brizo.thumbWrapper = jQuery('div#thumb-wrapper');
		brizo.sideNav = jQuery('div#sidenav-box');
		brizo.backLink = jQuery('a.back-link').length ? jQuery('a.back-link') : null;
		brizo.loadingIconBlack = '<img src="/images/gui/icons/loading-white-on-black.gif" class="loading-icon" />';
		brizo.loadingIconWhite = '<img src="/images/gui/icons/loading-black-on-white.gif" class="loading-icon" />';
		brizo.siteSearchDefault = jQuery('form#search-form input#search-text').val();
		if(jQuery('ul#sidenav ul.subnav').length) {
			if (jQuery('body').attr('id') == 'home') {
				brizo.sideLis = jQuery('li#li-customer-service, li#li-company, li#li-showroom-locator, li#li-professionals');
				brizo.subnavs = jQuery('li#li-customer-service ul.subnav, li#li-company ul.subnav, li#li-showroom-locator ul.subnav, li#li-professionals ul.subnav');
			} else {
				brizo.sideLis = jQuery('ul#sidenav > li');
				brizo.subnavs = jQuery('ul.subnav');
			}
		}
	},
	
	// List of body IDs which will not use default content animation
	animationExceptions: [
		'home'
		, 'kitchen'
		, 'bath'
		, 'product-detail-page'
		, 'kitchen-collection'
		, 'green-home'
		, 'green-beauty'
		, 'calendar'
		, 'email-a-friend'
		, 'faq-form'
		, 'wheretobuy-map'
	],
	
	// List of body IDs which will not auto-load side nav
	sidenavExceptions: [
		'home'
		, 'green-home'
	],
	
	listSlider: function(hidingElms, triggerElm, showFirst, callBack) {
		var cb = (typeof callBack == 'undefined') ? '' : callBack;
		if (typeof showFirst == 'undefined' || showFirst === '') {
			hidingElms.hide();
		} else {
			triggerElm.eq(0).toggleClass('expanded');
			hidingElms.slice(1).hide();
		}	
		triggerElm.each(function(){
			jQuery(this).css({ cursor: 'pointer' }).click(function(){
				if (jQuery(this).hasClass('expanded')) {
					jQuery(this).next().slideUp('fast', cb);
					jQuery(this).toggleClass('expanded');
				} else {
					jQuery(this).next().slideDown('fast', cb);
					jQuery(this).toggleClass('expanded');
				}
				console.log(this);
				newHead = '#' + this.id;
				return newHead;				
			});
		});
	},
	
	// Load thumb scroller
	showThumbScroller: function() {
		swfobject.embedSWF( "/flash/thumb_scroller.swf", "thumb_scroller", "640", "120", "9.0.0", "flash/expressinstall.swf", flashvars, params, attributes);
	},
	
	// Update XML and reload thumb scroller
	switchXml: function(newXml) {
		flashvars.xml_path = newXml;
		brizo.showThumbScroller();
	},
	

	catchSideNav: function() {
		jQuery('ul#sidenav a').not('a#emailLink').not('a#link-custom-showers').bind('click', function(){
			var newHref = jQuery(this).attr('href').replace('.html', '.xml');
			jQuery(this).parents('ul').find('a').removeClass('active');
			jQuery(this).addClass('active');
			brizo.switchXml(newHref);
			return false;
		});
	},
	
	// open external links in a new window
	externalLinks: function() {
		jQuery('a[href^="http"]').not('.thickbox, #link-spanish').unbind().click(function(){
			window.open(this.href);
			return false;
		});
	},
	
	// open PDFs links in a new window
	pdfLinks: function() {
		jQuery('a[href$=".pdf"], area[href$=".pdf"]').unbind().click(function(){
			window.open(this.href);
			return false;
		});
	},
	
	// open Downloadable files in a new window
	fileLinks: function() {
		jQuery('a[href$=".xls"], a[href$=".ppt"], a[href$=".doc"], a[href$=".zip"], a[href$=".csv"]').unbind().click(function(){
			window.open(this.href);
			return false;
		});
	},
	
	// open logo image format links in a new window
	logoLinks: function() {
		if(jQuery('body#logos').length) {
			jQuery('body#logos div#content-body a').unbind().click(function(){
				window.open(this.href);
				return false;
			});
		}
	},
	
	// open Event Gallery download links in new window
	eventGalleryLinks: function() {
		if(jQuery('body#event-gallery').length) {
			console.log('viewing event gallery...');
			jQuery('body#event-gallery div#content-body a').not('a.thickbox').unbind().click(function(){
				window.open(this.href);
				return false;
			});
		}
	},
	
	// add classes to form inputs for css use
	addFormClasses: function() {
		if(jQuery('input').length) {
			jQuery('input').each(function(){
				jQuery(this).addClass(this.type);
			});
		}
	},
	
	hideScroller: function() {
		if(jQuery('#related-title').length) {
			jQuery('#related-title').animate({ opacity: 0 }, 125, brizo.easing);
		}
		if(jQuery('#thumb_scroller').length) {
			jQuery('#thumb_scroller').css({ right: '-2000px' });
			jQuery('#wrapper').css({ overflow: 'hidden' });
		}
	},
	
	showScroller: function() {
		if(jQuery('#related-title').length) {
			jQuery('#related-title').animate({ opacity: 1 }, 125, brizo.easing);
		}
		if(jQuery('#thumb_scroller').length) {
			jQuery('#thumb_scroller').css({ right: '34px' });
			jQuery('#wrapper').css({ overflow: 'auto' });
		}
	},
	
	// Preload images when activated
	// - accepts array as input
	preloadImages: function(imageArray) {
		jQuery.each(imageArray,function(e) {
			jQuery(new Image()).attr('src',this);
		});
	},
	
	fadeMe: function(fadeThis) {
			jQuery(fadeThis).css({ opacity: 0.25 });
	},
	
	unFadeMe: function(unFadeThis) {
		jQuery(unFadeThis).css({ opacity: 1 });
	},
	
	// Image swap with fade transition
	// - accepts image object and new image path as args
	changePhoto: function(image, newSrc, matteColor) {
		image.animate({ opacity: 0 }, 50, function(){
			var imgPar = image.parent();
			// var loadingIcon = matteColor === 'white' ? brizo.loadingIconWhite : brizo.loadingIconBlack;
			// var loadTimer = setTimeout(function(){
			// 	imgPar.append(loadingIcon);
			// }, 150);
			image.attr('src', newSrc);
			image.animate({ opacity: 1 }, 500);
			// setTimeout(function(){
			// 	clearTimeout(loadTimer);
			// 	imgPar.find('img.loading-icon').remove();
			// 	image.animate({ opacity: 1 }, 150);
			// }, 100);
			// console.log('calling image load...');

			// var x = 0;
			// image.load(function(){
			// 	console.log('x: ', x);
			// 	clearTimeout(loadTimer);
			// 	imgPar.find('img.loading-icon').remove();
			// 	image.animate({ opacity: 1 }, 150);
			// 	x++;
			// });
		});
	},
	
	slideOut: function(elm) {
		jQuery(elm).animate({ left: '-475px', opacity: 0 });
	},
	
	
	hideContentBody: function(hideType) {
		var ht = (typeof hideType === 'undefined') ? 'fade' : hideType;
		if(ht === 'fade') {
			brizo.contentBody.animate({ opacity: 0 }, 100, brizo.easing);
		} else if(ht === 'slide') {
			brizo.contentBody.animate({ left: '-525px', opacity: 0 }, 500, function(){
				brizo.contentBody.css({ left: '-788px' });
			});
		}	else if(ht === 'none') {
			brizo.contentBody.hide();
		}
	},
	
	showContentBody: function(showType) {
		var st = (typeof showType === 'undefined') ? 'fade' : showType;
		if(st === 'fade') {
			brizo.contentBody.animate({ opacity: 1 }, 100, brizo.easing, function() {
				if ( $.browser.msie ) { // removes text aliasing introduced by opacity effects in IE
					this.style.removeAttribute('filter');
				}
			});
		} else if(st === 'slide') {
			brizo.contentBody.css({ left: '-525px' }).animate({ left: brizo.contentBodyLeft, opacity: 1 }, 500);
		}	else if(st === 'none') {
			brizo.contentBody.show();
		}
	},
	
	showBackLink: function() {
		brizo.backLink = jQuery('a.back-link').length ? jQuery('a.back-link') : null;
		if(brizo.backLink != null) {
			brizo.backLink.css({ left: 0, opacity: 0, cursor: 'pointer' }).animate({ opacity: 1 }, 500);
		}
	},
	
	hideBackLink: function() {
		backLink.animate({ opacity: 0 }, 250, '',
			// Shift out of viewport to prevent accidental discovery/clicks
			function(){ backLink.css({ left: '-200px' });
		}); 
	},
		
	initPage: function() {
		jQuery('#search-submit').css({ opacity:'0' });
		// Hide subnav items
		jQuery('#main-nav > li > ul').hide();


		jQuery('#search-text').focus(function(){
			jQuery(this).css({ color:'#333', textAlign:'left' });
			jQuery('#search-submit').animate({ opacity: 1 }, 300);
			jQuery('#search-text').animate({ opacity: 1 }, 300);
			if(jQuery(this).val() === brizo.siteSearchDefault) {
				jQuery(this).val('');
			}
		}).blur(function(){
			jQuery('#search-submit').animate({ opacity: 0 }, 300);
			jQuery('#search-text').animate({ opacity: 0.5 }, 300, function(){
				if(jQuery(this).val() === '') {
					jQuery(this).val(brizo.siteSearchDefault);
				}
			});
			
		});
	},
	
	initMenus: function() {
		if(!jQuery('body#site-home').length) {
			var hideDelay = null;
			var showDelay = null;

			// When mousing over top nav point, open subnav items
			jQuery('#main-nav > li').bind('mouseover', function(){
				var actingUl = jQuery(this).find('ul');
				var actingLis = jQuery(this).find('ul').find('li');

				if(hideDelay){
					clearTimeout(hideDelay);
				}
					var sibs = jQuery(this).siblings().find('ul');
					sibs.each(function(){
						jQuery(this).fadeOut('fast');
						jQuery(this).parent('li').removeClass('expanded');
					});
					actingUl.slideDown();
					if(!jQuery(this).hasClass('expanded')){
						actingLis.css({ opacity: 0, position:'relative', top:'-7px' });
						actingLis.each(function(i){
							showDelay = (i+1) * 50;
							var thisLi = jQuery(this);
							setTimeout(function(){
								thisLi.animate({ opacity: 1, top: 0 }, 150);
							}, showDelay);
						});
						jQuery(this).addClass('expanded');
					}				
			});

			jQuery('#main-nav > li').bind('mouseout', function(){				
				hideDelay = setTimeout(function(){
					jQuery('#main-nav > li').removeClass('expanded');
					jQuery('#main-nav > li > ul').fadeOut('fast');
				}, 500);			
			});	
		}
	},
	
	hideSubnavs: function() {
		// Only run if there are subnav items
		if(jQuery('ul#sidenav ul.subnav').length) {			
			brizo.subnavs.hide();
		}
	},
	
	// Accordion-esque expand/collapse for the side nav
	setSidenav: function() {
		// Only run if there are subnav items
		if(jQuery('ul#sidenav ul.subnav').length) {			
			var timer = null;
			
			brizo.sideLis.hoverIntent(
				function(){
					clearTimeout(timer);
					if(!jQuery(this).hasClass('expanding')) {
						brizo.sideLis.not(this).removeClass('expanding').animate({ marginTop: 0 }, 250);
						brizo.subnavs.not(this).slideUp();
						jQuery(this).addClass('expanding');
						jQuery(this).find('ul.subnav').slideDown();
						return false;
					}
				},
				function(){
					clearTimeout(timer);
					var actingLi = jQuery(this);
					var thisLi = jQuery(this).find('ul.subnav');
					timer = setTimeout(function(){
						thisLi.slideUp('normal', function(){
							actingLi.removeClass('expanding');
						});
						actingLi.animate({ marginTop: 0 }, 250);
					}, 1000);
					return false;
				}
			);
		}	
	},
	
	// Conditionally add wmode parameter to SWFObject calls if browser is not FF2
	addWMode: function() {
		if(typeof params !== 'undefined') {
			// Get browser version number
			var browserVersion = jQuery.browser.version;
			// Trim version number to X.X (major version for FF)
			var parsedBrowserVersion = Number(browserVersion.split('.').slice(0,2).join('.'));
			// If browser is NOT FireFox 2, add wmode param
			if(!(jQuery.browser.mozilla && parsedBrowserVersion < 1.9)) {
				params.wmode = "transparent";
			};
		}		
	},
	
	setToolTips: function() {
		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('.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" />'
			});
		});
	},
	
	linkFileTypes: function() {
		var $a = jQuery('.download 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');
				}
			}			
		});
	},
	
	advancedSearch: function() {
		if(!jQuery('body').hasClass('no-adv-search')){
			if(jQuery('div#search-adv').length){
				jQuery('div#search-adv').dialog({
					autoOpen: false, 
					autoResize: false, 
					closeOnEscape: false, 
					closeText: 'close (x)', 
					hide: 'slide',
					show: 'slide',
					position: [$("a#search-adv-open").offset().left - 193, $("a#search-adv-open").offset().top + 20],
					width: 320,
					height: 325,
					minWidth: 320,
					minHeight: 325, 
					draggable: false,
					resizable: false,
					zIndex: 5
				});
				
				jQuery('a#search-adv-open').click(
					function(){
						if(jQuery(this).hasClass('showdialogbox')) {
							jQuery('div#search-adv').dialog('close');
							jQuery(this).removeClass('showdialogbox');
							return false;
						} else {
							jQuery('div#search-adv').dialog('open');
							jQuery(this).addClass('showdialogbox');
							return false;
						}					
		    	}
				);
			}			
		}		
	},
	
	oneLink: function(sHostname){
		document.location.href = document.location.protocol + "//" + sHostname + document.location.pathname + document.location.search;
	},

	applyOneLink: function(){
		jQuery('#link-spanish').click(function(){
			brizo.oneLink('es.brizo.com');
			return false;
		});
	}
};

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


// Initialize JS functions
jQuery(document).ready(function(){
	jQuery('html').removeClass('js');
	brizo.addWMode();
	brizo.setGlobals();	
	//brizo.autoBackLink();
	brizo.externalLinks();
	brizo.pdfLinks();
	brizo.fileLinks();
	brizo.logoLinks();
	brizo.eventGalleryLinks();
	brizo.addFormClasses();
	brizo.initPage();	
	brizo.initMenus();
	brizo.hideSubnavs();	
	brizo.setSidenav();
	brizo.setToolTips();
	if(typeof sIFR != 'undefined') {
		sIFR.initialize();
	}
	brizo.linkFileTypes();
	brizo.advancedSearch();
});