/* ##########################################################################
#############################################################################
		
Version 2.0
Author			- o2
Release Date	- 10/22/10
		
#############################################################################
########################################################################## */


/*  Toyota ESQ - Common Scripts
 *--------------------------------------------------------------------------*/
 
// Set up variables
// ######################################################################
// ######################################################################

// Array of filter IDs
var filtersArray = new Array;
var selectedFilters = new Array;

// Array of divs to rotate on the splash page
var featuredArticles = new Array('splashFeatureImg1', 'splashFeatureImg2', 'splashFeatureImg3', 'splashFeatureImg4', 'splashFeatureImg5');
//
var numOfArticles

// The starting index in the featuredArticles array
var currentArticle = 0;
var previousArticle = null;

// Booleans that do not allow hover functions to fire until mouse-out functions have completed
/*
var isCollapsed = true;
var isExpanded = false;
*/
var envDropDownTracker = new Object;
envDropDownTracker.isCollapsed = true;
envDropDownTracker.isExpanded = false;

var safetyDropDownTracker = new Object;
safetyDropDownTracker.isCollapsed = true;
safetyDropDownTracker.isExpanded = false;

var qualityDropDownTracker = new Object;
qualityDropDownTracker.isCollapsed = true;
qualityDropDownTracker.isExpanded = false;

var tagPreviewTracker = new Object;
tagPreviewTracker.isCollapsed = true;
tagPreviewTracker.isExpanded = false;

// for tool tip
var isVisible = false;
var isHidden = true;

// Load our print & filters cookies
var printCookie = readCookie("style");
var filterCookie = readCookie("filtered");

function uiFunctions () {
	
	// Prototype
	// ######################################################################
	// ######################################################################
	
	// Extend Prototype to check IE Version (only checks for IE by default)
	Prototype.Browser.IE6=(Prototype.Browser.IE && (navigator.appVersion.indexOf("MSIE 6") >- 1));	
	

	// PNG Fix for IE6 Users
	// ######################################################################
	// ######################################################################
	
	if (Prototype.Browser.IE6) {
		$$("img[src$=.png]").each(pngfix);	
	}
	
	function pngfix(png){
		png.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + png.src + "', sizingMethod='scale')";
		png.src = "/esq/assets/ui/blank.gif";
	}

	// Navigation
	// ######################################################################
	// ######################################################################
	
	// Primary (Top) Navigation
	// //////////////////////////////////////////////////////////////////////
	
	$$('#topNav li a img').each(function (image) {
	    	Event.observe(image, 'mouseover', opacityDown.bind(image));  
	    	Event.observe(image, 'mouseout', opacityUp.bind(image));
	  	});
	  	
	// Top Search Bar Submit 
	$$('#topSearchSubmit').each(function (searchIcon) {
	    	Event.observe(searchIcon, 'mouseover', opacityDown.bind(searchIcon));  
	    	Event.observe(searchIcon, 'mouseout', opacityUp.bind(searchIcon));
	  	});
	
	// Splash Page Navigation
	// //////////////////////////////////////////////////////////////////////
	
	// Splash Page - Automatically rotate through featured articles
	var autoRotate = setInterval(function () {
		featuredArticleRotate('auto');
		}, 5000);
		
	// Get Number of Featured Articles
	numOfArticles = $$("#splashFeatureNav a").length
	// Splash Page - Featured Articles Images
	$$('#splashFeature a img').each(function (e) {
	    	//Event.observe(e, 'click', fireTag.bind(e,'2120.4', {'<article_type>':'Article','<article_title>':e.alt}));
	  	});
		  	
	// Splash Page - Featured Articles Navigation
	$$('#splashFeatureNav a img').each(function (e) {
	    	Event.observe(e, 'mouseover', swapOver.bind(e));  
	    	Event.observe(e, 'mouseout', swapOut.bind(e));
	    	Event.observe(e, 'click', featuredArticleNavClicked.bind(e));
	    	//Event.observe(e, 'click', fireTag.bind(e,'2120.6'));
	  	});
	  	
	// Splash Page - Filters Navigation
	$$('#splashContent .splashFilter').each(function (e) {
			// Populate the filtersArray
			// example of className -> "splashFilter quality On"
			// name: filter name, also 2nd item in class name  (example value -> quality)
			// isOn: if the filter is on or off (example value ->  true)
			filtersArray.push({'name': e.className.split(" ")[1], 'isOn': e.className.search("On")});

			// Event handlers
	    	/*
	    	Event.observe(e, 'click', filterContent.bind(e));
	    	Event.observe(e, 'click', buildArticleList.bind(e));
			*/
	});
		
	// Interior Page Navigation
	// //////////////////////////////////////////////////////////////////////
	 
	// Interior Page - Filters Navigation
	$$('#tertiaryNav .interiorFilter').each(function (e) {
			// Populate the filtersArray
			// example of className -> "splashFilter quality On"
			// name: filter name, also 2nd item in class name  (example value -> quality)
			// isOn: if the filter is on or off (example value ->  true)
			filtersArray.push({'name': e.className.split(" ")[1], 'isOn': e.className.search("On")});
			
			// Event handlers
	    	// Event.observe(e, 'click', filterContent.bind(e));
	});
	
	// //////////////////////////////////////////////////////////////////////
	// //////////////////////////////////////////////////////////////////////
	
	// Interior Page - Category Navigation Drop Downs
	// //////////////////////////////////////////////////////////////////////
	
	// ENVIRONMENT
	// /////////////////////////////////////////////////
	if($('envDropDown') != undefined) {
   		$$('#envButton').each(function (elmt) {
			Event.observe(elmt, 'mouseover', function () {
				slideDown('envDropDown', envDropDownTracker);
			});
			
			Event.observe(elmt, 'mouseout', function () {
				var target = $('envDropDown');
		     	var mouse_over_element; 
		     
		     	// Check to see what the mouse is now over, and assign it to mouse_over_element...
		     	if (event.toElement) {
		        	mouse_over_element = event.toElement;
		     	} else if (event.relatedTarget) {
		       		mouse_over_element = event.relatedTarget;
		     	}
		     	
		     	// In the event that the mouse is over something outside the DOM (like an alert window)...
		     	if (mouse_over_element == null) {
		        	return;
		     	}
		     	
		     	// Positive result event !!!
		     	if(!mouse_over_element.descendantOf(target) && target != mouse_over_element) {
		        	slideUpDelayed('envDropDown', envDropDownTracker);
		     	}
			});
		});
		
		$('envDropDown').observe('mouseout', function(event) {
	     	var target = $('envDropDown');
	     	var mouse_over_element; 
	     
	     	// Check to see what the mouse is now over, and assign it to mouse_over_element...
	     	if (event.toElement) {
	        	mouse_over_element = event.toElement;
	     	} else if (event.relatedTarget) {
	       		mouse_over_element = event.relatedTarget;
	     	}
	     	
	     	// In the event that the mouse is over something outside the DOM (like an alert window)...
	     	if (mouse_over_element == null) {
	        	return;
	     	}
	     	
	     	// Positive result event !!!
	     	if(!mouse_over_element.descendantOf(target) && target != mouse_over_element) {
	        	slideUpDelayed('envDropDown', envDropDownTracker);
	     	}
	   	});
	}
   	
	// SAFETY
	// /////////////////////////////////////////////////
	if($('safetyDropDown') != undefined) {
		$$('#safetyButton').each(function (elmt) {
			Event.observe(elmt, 'mouseover', function () {
				slideDown('safetyDropDown', safetyDropDownTracker);
			});
			
			Event.observe(elmt, 'mouseout', function () {
				var target = $('safetyDropDown');
		     	var mouse_over_element; 
		     
		     	// Check to see what the mouse is now over, and assign it to mouse_over_element...
		     	if (event.toElement) {
		        	mouse_over_element = event.toElement;
		     	} else if (event.relatedTarget) {
		       		mouse_over_element = event.relatedTarget;
		     	}
		     	
		     	// In the event that the mouse is over something outside the DOM (like an alert window)...
		     	if (mouse_over_element == null) {
		        	return;
		     	}
		     	
		     	// Positive result event !!!
		     	if(!mouse_over_element.descendantOf(target) && target != mouse_over_element) {
		        	slideUpDelayed('safetyDropDown', safetyDropDownTracker);
		     	}
			});
		});
		
		$('safetyDropDown').observe('mouseout', function(event) {
	     	var target = $('safetyDropDown');
	     	var mouse_over_element; 
	     
	     	// Check to see what the mouse is now over, and assign it to mouse_over_element...
	     	if (event.toElement) {
	        	mouse_over_element = event.toElement;
	     	} else if (event.relatedTarget) {
	       		mouse_over_element = event.relatedTarget;
	     	}
	     	
	     	// In the event that the mouse is over something outside the DOM (like an alert window)...
	     	if (mouse_over_element == null) {
	        	return;
	     	}
	     	
	     	// Positive result event !!!
	     	if(!mouse_over_element.descendantOf(target) && target != mouse_over_element) {
	        	slideUpDelayed('safetyDropDown', safetyDropDownTracker);
	     	}
	   	});
   	}
   	
   	// QUALITY
   	// /////////////////////////////////////////////////
	if($('qualityDropDown') != undefined) { 
	   	$$('#qualityButton').each(function (elmt) {
			Event.observe(elmt, 'mouseover', function () {
				slideDown('qualityDropDown', qualityDropDownTracker);
			});
			
			Event.observe(elmt, 'mouseout', function () {
				var target = $('qualityDropDown');
		     	var mouse_over_element; 
		     
		     	// Check to see what the mouse is now over, and assign it to mouse_over_element...
		     	if (event.toElement) {
		        	mouse_over_element = event.toElement;
		     	} else if (event.relatedTarget) {
		       		mouse_over_element = event.relatedTarget;
		     	}
		     	
		     	// In the event that the mouse is over something outside the DOM (like an alert window)...
		     	if (mouse_over_element == null) {
		        	return;
		     	}
		     	
		     	// Positive result event !!!
		     	if(!mouse_over_element.descendantOf(target) && target != mouse_over_element) {
		        	slideUpDelayed('qualityDropDown', qualityDropDownTracker);
		     	}
			});
		});
		
		$('qualityDropDown').observe('mouseout', function(event) {
	     	var target = $('qualityDropDown');
	     	var mouse_over_element; 
	     
	     	// Check to see what the mouse is now over, and assign it to mouse_over_element...
	     	if (event.toElement) {
	        	mouse_over_element = event.toElement;
	     	} else if (event.relatedTarget) {
	       		mouse_over_element = event.relatedTarget;
	     	}
	     	
	     	// In the event that the mouse is over something outside the DOM (like an alert window)...
	     	if (mouse_over_element == null) {
	        	return;
	     	}
	     	
	     	// Positive result event !!!
	     	if(!mouse_over_element.descendantOf(target) && target != mouse_over_element) {
	        	slideUpDelayed('qualityDropDown', qualityDropDownTracker);
	     	}
	   	});
	}
	
	// //////////////////////////////////////////////////////////////////////
	// //////////////////////////////////////////////////////////////////////
	  	
	// Interior Page - Tags thumbnail
	$$('.splashTag a').each(function (tagsThumb) { 
			// Let Lightview know we have selected a non-gallery item  
			// so it can adjust the lightbox accordingly
			Event.observe(tagsThumb, 'click', function () {
				isGallery = false;
				noResize = false;
				hideButtons();
				setBackground();
				adjustMargins();
			});
		});
	
	$$('#tags .button').each(function (tagsThumb) {
			Event.observe(tagsThumb, 'mouseover', function () {
				slideDown('tagPreview', tagPreviewTracker);
			});
			
			// Let Lightview know we have selected a non-gallery item  
			// so it can adjust the lightbox accordingly
			Event.observe(tagsThumb, 'click', function () {
				isGallery = false;
				noResize = false;
				hideButtons();
				setBackground();
				adjustMargins();
			});
		});
	
	$$('#tagPreview a').each(function (tagsPreview) {
			Event.observe(tagsPreview, 'mouseout', function () {
				slideUpDelayed('tagPreview', tagPreviewTracker);
			});
			
			// Let Lightview know we have selected a non-gallery item  
			// so it can adjust the lightbox accordingly
			Event.observe(tagsPreview, 'click', function () {
				//Give the lightbox time to popup
				clearTimeout(autoCollapse);
				autoCollapse = setTimeout (function () {
				slideUp('tagPreview', tagPreviewTracker); }, 
				3000
				);

				isGallery = false;
				noResize = false;
				hideButtons();
				setBackground();
				adjustMargins();
			});
		});
	  	
	// Interior Page - Media Navigation (simple feedback on mouse-over)
	$$('#articleMedia .lightview img').each(function (mediaThumb) {
		Event.observe(mediaThumb, 'mouseover', opacityDown.bind(mediaThumb));
		Event.observe(mediaThumb, 'mouseout', opacityUp.bind(mediaThumb));
		// Let Lightview know we have selected a gallery item so 
		// it can adjust the lightbox accordingly
		Event.observe(mediaThumb, 'click', function (mediaThumb) {
			isGallery = true;
			hideButtons();
			setBackground();
			adjustMargins();
		});
	});
	
	$$('#aboutMedia .lightview img').each(function (mediaThumb) {
		Event.observe(mediaThumb, 'mouseover', opacityDown.bind(mediaThumb));
		Event.observe(mediaThumb, 'mouseout', opacityUp.bind(mediaThumb));
		// Let Lightview know we have selected a gallery item so 
		// it can adjust the lightbox accordingly
		Event.observe(mediaThumb, 'click', function (mediaThumb) {
			isGallery = true;
			hideButtons();
			setBackground();
			adjustMargins();
		});
	});
	
	// Interior Page - CAPTCHA Navigation
	
	$$('.captchaImage').each(function(icon) {
			Event.observe(icon, 'mouseover', opacityDown.bind(icon));
			Event.observe(icon, 'mouseout', opacityUp.bind(icon));
		
		});
	  	
	// Global - Footer Navigation 
	// //////////////////////////////////////////////////////////////////////
	 	
	$$('#footer ul li a').each(function (e) {
	    	Event.observe(e, 'mouseover', opacityDown.bind(e));  
	    	Event.observe(e, 'mouseout', opacityUp.bind(e));
	  	});
	  	
	$$('#toyotaLogo').each(function (e) {
	    	Event.observe(e, 'mouseover', opacityDown.bind(e));  
	    	Event.observe(e, 'mouseout', opacityUp.bind(e));
	  	});
	  	
	// Social Bookmark Roll-overs
	$$('#subNav .colA a img').each(function (icon) {
			Event.observe(icon, 'mouseover', opacityDown);
			Event.observe(icon, 'mouseout', opacityUp);
		});
	  	
	
	// "Help" Cues
	// ######################################################################
	// ######################################################################
	
	// Additional Search/Blog Results Help
	$$('#altSearchResultsHelp').each(function (helpIcon) {
			Event.observe(helpIcon, 'mouseover', showSearchToolTip);
			Event.observe(helpIcon, 'mouseout', hideSearchToolTip);  
		});
		
	$$('#altBlogResultsHelp').each(function (helpIcon) {
			Event.observe(helpIcon, 'mouseover', showBlogToolTip);
			Event.observe(helpIcon, 'mouseout', hideBlogToolTip);  
		});
		
	// Printing Event Listeners
	// ######################################################################
	// ######################################################################	
	// Select stylesheets
	$$('#subNav .colD form ol li input').each(function (checkbox) {
			Event.observe(checkbox, 'click', function () {
				setActiveStyleSheet(checkbox.getAttribute('name'));
			});
		});
		
	// Print
	$$('#subNav #printButton').each(function (printButton) {
			Event.observe(printButton, 'click', function () {
				window.print();
			});
		});
		
	// Events Functions
	// ######################################################################
	// ######################################################################
	
	// Global 
	// //////////////////////////////////////////////////////////////////////
	
	// Fade in/out on hover
	function opacityDown () {
	  		new Effect.Opacity(this, { from: 1.0, to: 0.6, duration: 0.1 });
	}
	  		
	function opacityUp () {
	  		new Effect.Opacity(this, { from: 0.6, to: 1.0, duration: 0.1, queue: 'end', limit: 2 });  		
	}
	  		
	// Splash Page
	// //////////////////////////////////////////////////////////////////////
	
	// Splash Navigation: swap image in/out on hover	
	function swapOver () {
			currentSource = this.src;
			var newSource = currentSource.replace("off", "over");
			this.src = newSource;
			}
			
	function swapOut () {
			currentSource = this.src;
			var newSource = currentSource.replace("over", "off");
			this.src = newSource;
			}
	
	// Splash Page: Image slideshow 
	// "Auto" = Automatically rotate through featured articles
	// "Manual" = Slideshow can be interrupted by user interaction	
	
	function featuredArticleRotate (type) {
		// Crossfade the current featured article image
		switch (type){
			case 'manual':
			// Do nothing, because we already established the current/previous articles in the click handler
			break;
			case 'auto':
				// Add 1 to the currentArticle, because we want to go to the next article
				previousArticle = currentArticle;
				currentArticle++;
			break;
		}
		// Fade out the previously selected article
		var effect = Effect.Fade(featuredArticles[previousArticle], { duration:.4 });
		
		if (effect) {
			// For IE6: target  style.filter, because we have moved the image source to the Alpha filter as part of the png fix
			if(Prototype.Browser.IE6){
				$$('#featureNav'+(previousArticle+1))[0].style.filter = $$('#featureNav'+(previousArticle+1))[0].style.filter.replace("_on", "_off");
			} else {
				$$('#featureNav'+(previousArticle+1))[0].src = $$('#featureNav'+(previousArticle+1))[0].src.replace("_on", "_off");
			}
		
			// Fade in the new article
			if (currentArticle >= numOfArticles) currentArticle = 0;
			Effect.Appear(featuredArticles[currentArticle], { duration:.4 });
		
			// switch the highlighted number
			if(Prototype.Browser.IE6){
				$$('#featureNav'+(currentArticle+1))[0].style.filter = $$('#featureNav'+(currentArticle+1))[0].style.filter.replace("_off", "_on");
				$$('#featureNav'+(currentArticle+1))[0].style.filter = $$('#featureNav'+(currentArticle+1))[0].style.filter.replace("_over", "_on");
			} else {
				$$('#featureNav'+(currentArticle+1))[0].src = $$('#featureNav'+(currentArticle+1))[0].src.replace("_off", "_on");
				$$('#featureNav'+(currentArticle+1))[0].src = $$('#featureNav'+(currentArticle+1))[0].src.replace("_over", "_on");
			}
		}
	}
	
	function featuredArticleNavClicked () {
			var articleIndex = parseInt(this.id.substr(this.id.length-1,1));
			// Do nothing if this is already selected
			if((articleIndex-1) != currentArticle) {
				// restart the interval from the time the user switched the article
				clearInterval(autoRotate);
				autoRotate = setInterval(function () {
					featuredArticleRotate('auto');
					}, 5000);
				
				//update the main image (crossfade)
				previousArticle = currentArticle;
				currentArticle = articleIndex-1;
				featuredArticleRotate('manual');
			}		
	}
	
	function buildArticleList() {		
		var ulElement = $("environmentSafetyQuality");
		// remove current list
		if (ulElement) {
			if ( ulElement.hasChildNodes() ) {
				while ( ulElement.childNodes.length >= 1 ) {
					ulElement.removeChild( ulElement.firstChild );       
				} 
			}
			var i = 0;
			var j = 0;
			var len = numOfArticles
			while (i < len && featuredArticlesJson[j]) {
				var article = featuredArticlesJson[j++];
				//if (appendToList(article.filters)) {
					var liElement = document.createElement("li");
					var linkElement = document.createElement("a");
					linkElement.href = article.url;
					Event.observe(linkElement, 'click', fireTag.bind(linkElement,'2120.3', {'<article_type>':'FeaturedArticle','<article_title>':article.title}));
					linkElement.appendChild(document.createTextNode(article.title));
					liElement.appendChild(linkElement);
					ulElement.appendChild(liElement);
					i++;
				//}
			}
		}
	}
	
	function appendToList(filters) {
		for (var i = 0; i < selectedFilters.length; i++) {
			if (filters.indexOf(selectedFilters[i]) != -1) return true;
		}
		return false;
	}
			
					
	// Tags Navigation (Interior Pages): slide thumbnail in/out on hover
	// //////////////////////////////////////////////////////////////////////
	
	// Slide the thumbnail down, and set both "isExpanded" and "isCollapsed"
	// to false since we are in between the two states
	function slideDown (target, tracker) {
		if (tracker.isCollapsed) {
	  		Effect.SlideDown(target, { duration: 0.5, afterFinish: function () {
	  			switchExpanded(target, tracker);
	  		}});
	  		tracker.isExpanded = false;
	  		tracker.isCollapsed = false;
		}
	 }
	 
	 // Slide the thumbnail up & hide it
	 function slideUp (target, tracker) {
		if (tracker.isExpanded){
			// Cancel the timeout before it automatically fires this function again
			clearTimeout(autoCollapse);
			Effect.SlideUp(target, { duration: 0.5, afterFinish: function () {
				switchCollapsed(target, tracker);
			}});
			tracker.isCollapsed = false;
			tracker.isExpanded = false;
	  	}
	 }

	 //Delayed slideUp to help deal with displaying the tag cloud
	 function slideUpDelayed (target, tracker) {
		if (tracker.isExpanded){
				// Cancel the timeout before it automatically fires this function again
				clearTimeout(autoCollapse);
				autoCollapse = setTimeout (function () {
					slideUp(target, tracker); }, 
				500
				);
	  		} 
	  	}

	// Switch the thumbnail's state to "isExpanded" and start a 4-sec timeout
	// (in case a user moves to another part of the page w/o mouse-ing out of the thumbnail)	  		
	function switchExpanded (target, tracker) {
		tracker.isExpanded = true;
		// Collapse if user doesn't interact w/ tag thumbnail within 3 seconds
		autoCollapse = setTimeout (function () {
			slideUp(target, true); }, 
			3000 
		);
	}
	
	// Switch the thumbnail's state to "isCollapsed"
	function switchCollapsed (target, tracker) {
		tracker.isCollapsed = true;
	}
		
	// Search / Blog Page: Fade tool tips in / out
	// //////////////////////////////////////////////////////////////////////
	
	// Fade tool tip in
	function showSearchToolTip () {
		if (isHidden) {
			new Effect.Appear('altSearchResultsTip', { duration: 0.4, afterFinish: setVisible });
			isVisible = false;
			isHidden = false;
		}
	}
	
	function showBlogToolTip () {
		if (isHidden) {
			new Effect.Appear('altBlogResultsTip', { duration: 0.4, afterFinish: setVisible });
			isVisible = false;
			isHidden = false;
		}
	}
	
	// Fade tool tip out
	function hideSearchToolTip () {
		if (isVisible) {
			clearTimeout(autoFade);
			new Effect.Fade('altSearchResultsTip', { duration: 0.4, afterFinish: setHidden });
			isVisible = false;
			isHidden = false;
		}
	}
	
	function hideBlogToolTip () {
		if (isVisible) {
			clearTimeout(autoFade);
			new Effect.Fade('altBlogResultsTip', { duration: 0.4, afterFinish: setHidden });
			isVisible = false;
			isHidden = false;
		}
	}
	
	// Switch tool tip state to "isVisible"
	function setVisible () {
		isVisible = true;
		// Collapse if user doesn't interact w/ tag thumbnail within 20 seconds
		autoFade = setTimeout (function () {
			hideToolTip(); }, 
			15000
			);
	}
	
	// Switch tool tip state to "isHidden"
	function setHidden () {
		isHidden = true;
	}
	
	// Filters Functions & Logic
	// //////////////////////////////////////////////////////////////////////
	var filter_tag_fired = false;
	function filterContent () {
		// Set up variables
		var selectedFilter = null;
		var active_count = 0;
		
		//Parse out the selected filter name
		var selectedFilterName = this.className.split(" ")[1];

		// Get the selected filter & number of active filters
		for (var i=0; i<filtersArray.length; i++){		
			if (selectedFilterName == filtersArray[i].name){
				selectedFilter = filtersArray[i];
			}
			if (filtersArray[i].isOn){
				active_count++;
			}
		}
		
		// Activate/Deactivate filters based on how many are currently active
		switch (active_count){
			case 5:
				// Deactivate other filters, keep selected filter active
				for (var i=0; i<filtersArray.length; i++)
					if (filtersArray[i] != selectedFilter)			
						setFilterState(filtersArray[i].name, false);
				break;

			case 4:
				// Deactivate other filters, keep selected filter active
				for (var i=0; i<filtersArray.length; i++)
					if (filtersArray[i] != selectedFilter)			
						setFilterState(filtersArray[i].name, false);
				break;
			case 3:
				// Deactivate other filters, keep selected filter active
				for (var i=0; i<filtersArray.length; i++)
					if (filtersArray[i] != selectedFilter)			
						setFilterState(filtersArray[i].name, false);
				break;
			case 2:
				if (selectedFilter.isOn)
					setFilterState(selectedFilterName, false);
				else 
					setFilterState(selectedFilterName, true);
				break;				
			case 1:
				if (!selectedFilter.isOn)
					setFilterState(selectedFilterName, true);
				break;				
		}
		// Set the selectedFilters array
		selectedFilters = [];
		for (var j=0; j<filtersArray.length; j++){		
			if (filtersArray[j].isOn){
				selectedFilters.push(filtersArray[j].name);
			}
		}
		// TagCloud Initialize from tags.js
		var filters = selectedFilters.join(',');
		initializeTagCloud(filters);
		this.href = this.href + filters;;
		if (!filter_tag_fired) {
			fireTag(omn_filter_tag_id);
			filter_tag_fired = true;
		}
		$$('#topNav li a').each(function (e) {
			resetFilterString(e);
	  	});
		$$('#articleMeta p a').each(function (e) {
			resetFilterString(e);
	  	});
	}
	
	//Will update the the state and display of the
	//specified filter (filterName) to specified state (isOn)
	function setFilterState(filterName, isOn)
	{
		var newState = isOn ? "On" : "Off";
		var oldState = isOn ? "Off" : "On";
		
		//update the filter state in the filter array
		for (var i=0; i<filtersArray.length; i++)		
			if (filterName == filtersArray[i].name)
			{			
				filtersArray[i].isOn = isOn;
				break;
			}

		//SPLASH PAGE-----
		//update the splash filter class with "On" or "Off"
		$$('#splashFilter_'+filterName).each(function (e) {
	    	e.removeClassName(oldState);
	    	e.addClassName(newState);
	  	});

		//update the filter title image
		$$('#splashFilter_'+filterName + " " + ".filterTitle").each(function (e) {
			e.setAttribute("src", "/esq/assets/ui/splash_filters_"+filterName+"_"+newState.toLowerCase()+".gif");
	  	});

		//update the filter indicator image
		$$('#splashFilter_'+filterName + " " + ".indicator").each(function (e) {
			e.setAttribute("src", "/esq/assets/ui/splash_filters_"+newState.toLowerCase()+".gif");
			e.setAttribute("alt", newState);
	  	});

		//update the filter copy image
		$$('#splashFilter_'+filterName + " " + ".filterDescription").each(function (e) {
			e.setAttribute("src", "/esq/assets/ui/splash_filters_"+filterName+"_copy_"+newState.toLowerCase()+".gif");
	  	});
	  	
	  	
	  	//INTERIOR PAGE-----
	  	//update the indicator filter copy image
	  	/*
		$$('.interiorFilter.'+filterName).each(function (e) {
			e.removeClassName(oldState);
	    	e.addClassName(newState);
	  	});

	  	//update the filter copy image
		$$('.interiorFilter.'+filterName + " " + ".interiorIndicator").each(function (e) {
			e.setAttribute("src", "/esq/assets/ui/filter_dot_"+newState.toLowerCase()+".gif");
	  	});
	  	*/
	}
	
	// Client-side Cookie Functions
	// //////////////////////////////////////////////////////////////////////
	
	// Filter handling-------------------------------------------------------/
	
	// Load the filters cookie, or set the default filters if no cookie exists
	var activated = filterCookie ? filterCookie : getDefaultFilters();
	if (activated.split) activated = activated.split(',');
	loadActiveFilters(activated);
	selectedFilters = activated;
	
	// TagCloud Initialize from tags.js
	if (typeof initializeTagCloud != 'undefined') initializeTagCloud(selectedFilters.join(','));
	buildArticleList();
	$$('#topNav li a').each(function (e) {
		resetFilterString(e);
  	});
	$$('#articleMeta p a').each(function (e) {
		resetFilterString(e);
  	});
	
	//email a friend support
	var emailfriend = $('emailafrienda');
	if (emailfriend) {
		emailfriend.href = emailfriend.href + '?link=' + document.URL;
		emailfriend.href = emailfriend.href + '&articleTitleField=' + (article_title !== undefined && article_title !== null ? escape(article_title) : escape("unknown title"));
		emailfriend.href = emailfriend.href + '&articleTypeField=' + (article_type !== undefined && article_type !== null ? escape(article_type) : escape("unknown type"));
	}
	
	// Default: All filters on
	function getDefaultFilters(){
		for (var i=0; i<filtersArray.length; i++) {
			selectedFilters.push(filtersArray[i].name);
		}
		return selectedFilters;
	}	
	
	// Set active filters
	function loadActiveFilters(activated){
		for (var i=0; i < filtersArray.length; i++){
			var isActive = false;
			for (var j=0; j < activated.length; j++){
				//alert(filtersArray[i].name + " = " + activated[j]);
				if(filtersArray[i].name == activated[j]){
					isActive = true;
				}
			}	
					
			if (isActive){
				setFilterState(filtersArray[i].name, true );
			} else {
				setFilterState(filtersArray[i].name, false );
			}
		}
	}
			
	
		
	
	// Print handling--------------------------------------------------------/
	
	// establish the title of our print stylesheet
	var title = printCookie ? printCookie : getPreferredStyleSheet();
	loadActiveStyleSheet(title);
	// For print: Load full-res images if the user wants to include them
	if (title.indexOf('Image')){
			loadFullResImages();
	}

	// On load, set the default stylesheet
	function loadActiveStyleSheet(title) {
			var i, a, main;
			if (title == "Print " || title == "null") {
				title = "Print Text,Images";
				} 
			for(i=0; (a = $$('link')[i]); i++) {
		  		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
		    		a.disabled = true;
		      		if(a.getAttribute("title") == title) a.disabled = false;
		    		}
		  		}
		  		// Select any applicable checkboxes on refresh (via cookie)
		  		// so the user doesn't lose their selection
		  		$$('#subNav .colD form ol li input').each(function (checkbox) {
		  				var checkboxName = checkbox.getAttribute('name');
		  				if(title.indexOf(checkbox.getAttribute('name')) > -1){
		  					checkbox.checked = true;
		  					}
		  				});
		  	
			}
	// Switch to new stylesheets after default stylesheet is loaded	
	function setActiveStyleSheet() {
			// Check to see which checkboxes are selected.
			// Add selected checkboxes' names to the selected array
			var selected = new Array();
			var title = new String;
			var i, a, main;
			
			$$('#subNav .colD form ol li input').each(function (checkbox) {
					if(checkbox.checked){
						selected.push(checkbox.getAttribute('name'));
						}
			});
			// Set the style sheet based on selected checkboxes 
			title = "Print " + selected.toString();
			if (title == "Print ") title = "Print Text,Images";
			
			for(i=0; (a = $$('link')[i]); i++) {
		  		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
		    		a.disabled = true;
		      		if(a.getAttribute("title") == title) a.disabled = false;
		    		}
		  		}
			}
	
	function getPreferredStyleSheet() {
	  		var i, a;
	  		for(i=0; (a = $$('link')[i]); i++) {
	    		if(a.getAttribute("rel").indexOf("style") != -1
	       			&& a.getAttribute("rel").indexOf("alt") == -1
	       			&& a.getAttribute("title")
	       			) return a.getAttribute("title");
	  			}
	  		return null;
			}
			
	// We need to insert full resimages into the document if the user has selected to 
	// print images... just hide them in the common CSS and show them in the print CSS
	
	// ###############################################################################
	// IMPORTANT! We will also need to remove the server-side pagination of the text 
	// so the entire article copy prints out
	
	function loadFullResImages() {
			$$('#articleMedia a').each(function (thumbnail) {
				var fullResImg = new Element ('img', {	'class':'printImg', 
														'src':	thumbnail.getAttribute('href') });
				// Omit videos
				if (thumbnail.getAttribute('href').indexOf('youtube') < 1){
					$('articleCopy').insert(fullResImg);
				}
				
				});
			
			}
	
	//Omniture fireTag
	if (typeof fireTag != 'undefined') fireTag(omn_onload_tag_id, onloadParams);
};

function setSelectedFilters() {
	var activeFilters = new Array();
	for (var i=0; i<filters.length; i++)
		if (filters[i].isOn)			
			activeFilters.push(filters[i].name);
	return activeFilters.join(',');
}

function searchOnSubmit() {
	document.forms[0].filters.value = selectedFilters.join(',');
	return true;
}

function resetFilterString(elem) {
	if (elem && elem.href) {
		var url = elem.href;
		if (url.indexOf("?") != -1) {
			if (url.indexOf("&filters=") != -1) {
				url = url.substring(0,url.indexOf("&filters="));
			}
			elem.href = url + "&filters=" + selectedFilters.join(',');
		}
	}
}

Event.observe(window, 'load', uiFunctions);

Event.observe(window, 'unload', function(e) {
		// If user hasn't activated a new "selectedFilters" set by the time they
		// leave the page, create one now
		if(selectedFilters == ""){
			for (var i=0; i < filtersArray.length; i++){
				if (filtersArray[i].isOn){
					selectedFilters.push(filtersArray[i].name);
				}
			}
		}
		// Currently activated filters
		var activated = selectedFilters;
		
		// Current print stylesheet
		var title = getActiveStyleSheet();
		
  		createCookie("style", title, 365);	
  		createCookie("filtered", activated, 365);
		});
		
function getActiveStyleSheet() {
	  		var i, a;
	  		for(i=0; (a = $$('link')[i]); i++) {
	    		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
	  			}
	  		return null;
			}

function createCookie(name,value,days) {
  		if (days) {
    		var date = new Date();
    		date.setTime(date.getTime()+(days*24*60*60*1000));
    		var expires = "; expires="+date.toGMTString();
  			}
  			else expires = "";
  			if (value.join) value = value.join(',');
  			document.cookie = name+"="+value+expires+"; path=/";
		}
			
function readCookie(name) {
	  		var nameEQ = name + "=";
	  		var ca = document.cookie.split(';');
	  		for(var i=0;i < ca.length;i++) {
	    		var c = ca[i];
	    		while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	  			}
	  		return null;
			}
	
// sIFR 3
// ######################################################################
// ######################################################################

var museosans100 = {
	src: '/esq/assets/ui/museosans100.swf'
};

var museosans300 = {
	src: '/esq/assets/ui/museosans300.swf'
};

var museosans900 = {
	src: '/esq/assets/ui/museosans900.swf'
};

sIFR.forceWidth = true;

sIFR.activate(museosans100, museosans300, museosans900);

sIFR.replace(museosans100, {
	selector: 'h1'
	,wmode: 'transparent'
	,css: {
    	'.sIFR-root': { 'color': '#1b2935', 'background-color': '#fdfcfc','width': '650px'  }
,
    	'a': { 'text-decoration': 'none' },
		'a:link': { 'color': '#1b2935' },
		'a:hover': { 'color': '#286071' }    }
});

sIFR.replace(museosans300, {
	selector: 'h2'
	,wmode: 'transparent'
	,css: {
    	'.sIFR-root': { 'color': '#286071', 'background-color': '#fdfcfc', 'letter-spacing': 1.0, 'text-transform': 'uppercase' },
    	'a': { 'text-decoration': 'none' },
		'a:link': { 'color': '#286071' },
		'a:hover': { 'color': '#1b2935' }
    }
});

sIFR.replace(museosans300, {
	selector: 'h3'
	,wmode: 'transparent'
	,css: {
    	'.sIFR-root': { 'color': '#a2b9c4', 'background-color': '#1e2834', 'letter-spacing': 1.0, 'text-transform': 'uppercase' },
    	'a': { 'text-decoration': 'none' },
		'a:link': { 'color': '#a2b9c4' },
		'a:hover': { 'color': '#fdfcfc' }
    },
	onRelease: function(){fireTag(2130.2);}
});


// Lightview
// ######################################################################
// ######################################################################
    var prev_width = 0;
	var prev_height = 0;
	var viewer_width;
	var viewer_height;
	var controller;
	var controller_width;
	var interiorController_width;
	var controller_marginLeft;
	var isGallery = false;
	var noResize = false;
	
// Lightview: On Load
// //////////////////////////////////////////////////////////////////////
document.observe('lightview:loaded', function() {
	hideButtons();
});

// Lightview: On image/video open or change
// //////////////////////////////////////////////////////////////////////
document.observe('lightview:opened', function(event) {

	//This allows the back button to close the lightbox
	reqHistory.setValue(0, "1");
	lightboxIsVisible = true;
	
	//Fire Omniture Tag on display of any image
	if (isGallery) {
		var capitalType = article_type.substring(0,1).toUpperCase() + article_type.substring(1,article_type.length);
		var img_title = event.target.firstChild.alt;
		if(event.target.href.toUpperCase().lastIndexOf('JPG') != -1)
		{
			fireTag('2144.1', {'<image_title>':img_title,'<article_type>':capitalType,'<article_title>':article_title});
		}
		else
		{
			fireTag('2145.1', {'<video_title>':img_title,'<article_type>':capitalType,'<article_title>':article_title});
		}
	} else {
		fireTag('2136.1');
	}
	
	// Set our position and dimension variables every time we change assets/videos
	$$('.lv_contentTop').each(function (viewer) {
			// Get the width & height of the image/video we are viewing
	    	viewer_width = parseFloat(viewer.style.width);
	    	viewer_height = parseFloat(viewer.style.height);

			// If the image gallery does not need to be resized, don't resize it!
	    	if(isGallery && prev_width == viewer_width && prev_height == viewer_height){
	    		isGallery = true;
	    		noResize = true;
	    	} else if(isGallery) {
	    		isGallery = true;
	    		noResize = false;
	    	} else {
	    		isGallery = false;
	    		noResize = false;
	    	}
	    	
	    	prev_width = viewer_width;
	    	prev_height = viewer_height;
	    	
	    	
	    	// Find the controller (this is what navigates through sets)
	    	controller = $('lightviewController');
	    	
	    	// Controller width should be the width of the image/video + borders + button width
	    	controller_width = viewer_width + 130;
	    	// Interior divs need to be a few px thinner to accommodate margins
	    	interiorController_width = controller_width - 12;
	    	
	    	// Calculate our margin values while we're at it
	    	controller_marginLeft = -0.5*(controller_width);
	    	closeButton_marginTop = -(viewer_height) + 22;
	    	
	    	// Add padding if we are using a caption
	    	if(isGallery && !noResize){
	    		viewer.style.paddingBottom = "10px";
	    	} else if(isGallery){
	    		viewer.style.paddingBottom = "10px";
	    	} else { 
	    		viewer.style.paddingBottom = "0px"; 
	    	}
	    	
	});
	
	// Push the captions below the image content, w/ a break in between
	$$('.lv_Center').each(function (content) {
	    var startHeight = parseFloat(content.style.height);
	    var newHeight = startHeight + 10;
	 
	    if (isGallery && !noResize) {
	    	content.style.height = newHeight + "px";
	    } else { content.style.height = startHeight + "px"; }
	    	
	});
	    	
	// Make controller's parent divs wider so we can float our buttons to the right & left of the image/video
	$$('.lv_controllerCenter').each(function (center) {
		center.style.width = interiorController_width + "px";
	});
	
	$$('.lv_controllerTop').each(function (middle) {
		middle.style.width = interiorController_width + "px";
	});
	
	$$('.lv_controllerMiddle').each(function (middle) {
		middle.style.width = interiorController_width + "px";
	});
	
	$$('.lv_controllerBottom').each(function (middle) {
		middle.style.width = interiorController_width + "px";
	});
	
	$$('.lv_topcloseButtonImage').each(function (topButton) {
		topButton.style.marginTop = "0px";
		topButton.style.paddingRight = "0px";
	});
	
	
	// Set styles for our controller
	controller.style.width = controller_width + "px";
	controller.style.marginLeft = controller_marginLeft + "px";
	controller.style.marginTop = "-50px";
	controller.style.zIndex = 4999; 
	controller.style.top = "50%";
	
	// Make prev/next parent divs' width 0 so we can mouse over our buttons
	$$('.lv_PrevSide').each(function (parentDiv) {
		parentDiv.style.width = 0;
	});
	
	$$('.lv_NextSide').each(function (parentDiv) {
		parentDiv.style.width = 0;
	});
	
	
	// Fade in nav elements
	$$('.lv_controllerPrev .lv_Button').each(function (prevButton) { 
		new Effect.Appear(prevButton, { duration: 0.4 });
	});
	
	$$('.lv_controllerNext .lv_Button').each(function (nextButton) { 
		new Effect.Appear(nextButton, { duration: 0.4 });
	});
	
	$$('.lv_topcloseButtonImage .lv_Button').each(function (topButton) {
		new Effect.Appear(topButton, { duration: 0.4 });
		topButton.style.width = "61px";
		// IE Fix (icon gets cut off)
		if (Prototype.Browser.IE) {
			topButton.style.marginLeft = "0px";
			}
		if (Prototype.Browser.IE6) {
			topButton.style.marginLeft = "0";
			}
	});
	
	// Set event handlers for our prev/next buttons 
	$$('.lv_Button').each(function (button) {
	    Event.observe(button, 'mouseover', lv_opacityDown.bind(button));  
	    Event.observe(button, 'mouseout', lv_opacityUp.bind(button));
	    Event.observe(button, 'click', fadeOut.bind(button));
	});
	
	$$('.lv_captionDesc a').each(function (event) {
	    Event.observe(event, 'click', function (event) {
	    	var data = event.target.firstChild.data;
	    	var img_title = event.target.rel;
	    	if (data && data.indexOf('Resolution') != -1) { //image download
	    		fireTag('2144.2', {'<resolution>':data,'<image_title>':img_title,'<article_type>':article_type,'<article_title>':article_title});
	    	} else { // video download
	    		fireTag('2145.2', {'<video_format>':data,'<video_title>':img_title,'<article_type>':article_type,'<article_title>':article_title});
	    	}
		});
	});
	
	//alert('You opened ' + event.target.href);
});

// Lightview: On hide/close
// //////////////////////////////////////////////////////////////////////
document.observe('lightview:hidden', function() {
	if(lightboxIsVisible)
	{			
	
		history.back(-1); 
			
		lightboxIsVisible=false;
		// Reset the "prev_width" and "prev_height" vars
		prev_width = 0;
		prev_height = 0;
	}
	
});


// Lightview: Related functions
// //////////////////////////////////////////////////////////////////////

// Display Options: Add formatting to acommodate caption box for media galleries

//Hide all navigation elements until image/video is loaded
function hideButtons () {
	$$('.lv_Button').each(function (buttons) {
		buttons.style.display = "none";
	});
}	

// Add background to galleries & sets to give the illusion of 'breaking' the border at the bottom
function setBackground () {
	$$('.lv_WrapDown').each(function (wrapDown) {
		if (isGallery) {
			wrapDown.style.backgroundImage = "url('/esq/assets/lightview/wrapDown_bground.gif')";
		} else { wrapDown.style.backgroundImage = "none"; }	
	});
}

// Re-position the lightbox vertically if no caption is being used
function adjustMargins() {
	$$('.lv_Container').each(function (container) {
		if (!isGallery) {
			container.style.marginTop = "0px";
		} else { 
				container.style.marginTop = "40px";
				// IE Fixes
				if (Prototype.Browser.IE){
					container.style.marginTop = "30px"; 
				}
				
				if (Prototype.Browser.IE6) {
					container.style.marginTop = "70px";
				} 
			}
	});
}

	
// Hover functions
function lv_opacityDown () {
  		new Effect.Opacity(this, { from: 1.0, to: 0.6, duration: 0.2 });
  		}
  		
function lv_opacityUp () {
  		new Effect.Opacity(this, { from: 0.6, to: 1.0, duration: 0.2 });
  		
  		}
  		
 // Function to fade all nav elements out when a button is clicked
function fadeOut () {
	$$('.lv_Button').each(function (button) {
		new Effect.Fade(button, { duration: 0.4 });
	});
}

//Allows the lightbox to be closed by the back button
 var protoHistoryManager = new ProtoHistoryManager();
 var justLoaded = true;
 var lightboxIsVisible = false;
 var reqHistory = protoHistoryManager.register(
            'lb',
            [-1], // default, page 0
            function(values) {
            /*
                var index = this.links.indexOf(values[0]);
                if (index == 0 && this.justloaded) { 
                    $$('div.product').each(function(prod) {
                            prod.observe('mouseover', showgotoshopping);
                    }.bind(this));    

                    return; 
                }
                
                if (index != -1) {
                    this.justloaded = false;
                    this.linkClick(values[0], index);
                }
                */
				if(justLoaded)
					justLoaded = false;
				else if(lightboxIsVisible)
				{
					lightboxIsVisible = false;
					Lightview.hide();	

				}
				
            }.bind(this)
        );            
protoHistoryManager.start();



// Browser to CSS Class Function
// ######################################################################
// ######################################################################
/*
CSS Browser Selector v0.3.4 (Sep 29, 2009)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors

Modified (Jan 27, 2010) - o2 Creative Solutions, LLC
*/

function css_browser_selector(u){
	var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3_5':is('firefox/3.0')?g+' ff3':is('firefox/3.5')?g+' ff3_5':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

