// ======================================================================================================================
// BEGIN: jQuery Cookie Plugin
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
 
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
 
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
// END: jQuery Cookie Plugin


// ======================================================================================================================
// Javascript Functions

jQuery.preloadImages = function(){
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}

jQuery().ready(function(){
	
// Adds a 'scriptOn' class to the body, for controlling JS-disabled styles
$("body").addClass("scriptOn");	


/* ********** UTILITY NAV ********** */
	// Diplays top set of links in the utility navigation
	$("ul#utilityNav > li").hoverIntent(
		function(){
			$(this).children("div").show();
			$(this).children("a").css({
				background: "#fff",
				color: "#000"
			});
		},
		function(){
			$(this).children("div").hide();
			$(this).children("a").css({
				background: "#000",
				color: "#fff"
			});			
		}
	);

/* ////////// END UTILITY NAV ********** */
	
	
/* ********** MAIN NAV ********** */

function getFlashMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function callToActionscript(flash, isPlay) {
   getFlashMovie(flash).IMPlayPause(isPlay);
}

	// Diplays main set of links in the main navigation (and resets them, if there was a flyout in place)
	$("ul#mainNav > li").hoverIntent(
		function(){
			$(this).children("div").fadeIn(100);
		},
		function(){
			$(this).children("div").fadeOut(100, 
				function(){
					$(this).css({width: "546px"});
					$("div.activeFlyout").remove();
				}
			);
		}
	);
	
//$("body#homePage ul#mainNav").hoverIntent(
//		function(){
//			//$("div#content").fadeTo(300, 0.33);
//			
//			//Pause the Flash Movie
//			callToActionscript('imwall', false)
//		},
//		function(){
//			//$("div#content").fadeTo(300, 1.0);
//			
//			//Resume the Flash Movie
//			callToActionscript('imwall', true)
//		}			
//	);

	// Function to animate and populate contents of flyout in main navigation
	function flyOut(){
		// Adds a class to an existing flyout, if there is one
		$("div.activeFlyout").addClass("oldFlyout");
	
		// Gets the screen position of the hovered link, for use later
		var notchOffset = $(this).position();
		notchOffset = "right " + (notchOffset.top - 5) + "px";
		
		// Gets the height of the main div, for use later
		var parentHeight = $("ul#mainNav > li > div").height();
		
		// Finds the index of the column in which the hovered link appears...
		var linkCol = $(this).parent().parent().prevAll("ul").length + 1;
		// ...and the index of the column where the existing flyout is located...
		var flyoutOrder = 4 - $("div.oldFlyout").nextAll().length;
		
		/* ...and compares the two, to see if the current hovered link is in the same
		 * set as the last one. If so, there's no need to animate the flyouts, and the
		 * contents can just be switched out instead
		 */
		if (flyoutOrder == linkCol) {
			$("div.oldFlyout").html($(this).next().html())
			.css({"background-position": notchOffset})
			.children().fadeIn("fast")
			;
		}
		
		// If there is no old flyout or it's in a different column, we have to:
		else {
			$(this).next()													// 1. grab the new flyout content div
			.clone()														// 2. make a copy of it
			.addClass("activeFlyout")										// 3. add the flyout class
			.insertBefore($(this).parent().parent())						// 4. Insert it into the correct place in the DOM
			.css({															
				"height": parentHeight,										// 5. Match its height to the main div (so the background color extends to the bottom)
				"background-position": notchOffset							// 6. Set the position of the 'notch' background image
			})
			.show();														// 7. Display the flyout (which is still at 0px width)
			
			$(this).parent().parent().parent().animate({width: "686px"});	// 8. Animate the width of the main div
			
			$("div.oldFlyout").children().hide();							// 9. Hide the children of the old flyout, if there was one
			$("div.oldFlyout").animate({width: "0"},function(){				// 10. Reduce the width of the old flyout back to 0px
				$(this).remove();											// 11. Remove the old flyout from the DOM
			});
			$("div.activeFlyout").animate({width: "140px"},function(){		// 12. Animate the width of the new flyout to 140px
				$(this).children().fadeIn("fast");							// 13. Finally, fade in the content of the new flyout
			});					
													
		}
	}
	function flyIn(){} // hoverIntent needs an "out" function, and since we won't use it, we just define an empty one
	
	/* This is the configuration object for hoverIntent. We're storing it in the data 
	 * object of the mainNav to keep it out of global scope.
	 */
	$("#mainNav").data("hInt", {config: {
	     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
	     interval: 100, // number = milliseconds for onMouseOver polling interval    
	     over: flyOut, // function = onMouseOver callback (REQUIRED)    
	     timeout: 500, // number = milliseconds delay before onMouseOut    
	     out: flyIn // function = onMouseOut callback (REQUIRED)    
		}
	});
	
	// Initializes hoverIntent on the nav links, passing the configuration object
	$("#mainNav li ul li a").hoverIntent($("#mainNav").data("hInt").config);

/* ////////// END MAIN NAV ********** */


/* ********** SUB NAV ********** */
	// Accordion function for the sub navigation, starts with event binding on the <a>s
//	$("ul#subNav > li > a").bind("click",
//		function(){
//			// Checks to see if the nav item being clicked is expanded. If so...
//			if ($(this).hasClass("active")) {							
//				$(this).next().slideUp(200);							// 1. Collapses the nav item set
//				$(this).removeClass("active");							// 2. Removes the 'active' class
//			}
//			// Otherwise...
//			else {
//				$("ul#subNav li a.active").removeClass("active")		// 1. Removes any 'active' class that may be present
//				.next().slideUp(400);									// 2. Collapses any open nav set
//				$(this).next().slideDown(400);							// 3. Expands the nav set that was clicked on
//				$(this).addClass("active");								// 4. Adds the 'active' class to the clicked item
//			}
//			return false;												// Prevents standard link behavior
//		}
//	);
/* ////////// END SUB NAV ********** */	



/* ********** FOOTER TABS OUTS ********** */
	// Shows the footer tabs on hover
	$("ul#marketingModules > li.hasTab h3").hoverIntent(
		function(){
			$(this).children("div.footerTab")
				.show()
				.css({
					zIndex: "100"
				});
				
			$(this).css({
				color: "#000",
				"border-bottom": "2px solid #2477b2"
			})
			.parent("li").css({
				background: "#fff"
			})										
			.siblings()
			.css("opacity", "0.33");
		},
		function(){
			
			$(this).children("div.footerTab").hide();
			$(this).css({
				color: "#fff",
				"border-bottom": "2px solid #000"
			})
			.parent("li").css({
			background: "transparent url(/custom/img/bg/bg_marketingDivider.gif) no-repeat scroll 0 10px"
			})									
			.siblings()
			.css("opacity", "1");
		}
	);
/* ////////// END FOOTER TAB OUTS ********** */



/* ********** MAIN ACCORDION ********** */
	// Wraps the contents of each accordion module in a div (keeping the nonsemantic div out of the markup)
	jQuery.each($("ul#accordion > li > h4"),
		function(){
			$(this).siblings().wrapAll("<div class='dynWrap'></div>");
		}
	);
	// Accordion function, starts with event binding on the <h4>s
	$("ul#accordion > li > h4").bind("click",
		function(){
			// Checks to see if the accordion header being clicked is closed. If so...
			if ($(this).hasClass("closed")) {							
				$(this).next().slideDown(400);							// 1. Expands the accordion module that was clicked on
				$(this).removeClass("closed");							// 2. Removes the 'closed' class from the clicked h4
			}
			// Otherwise...
			else {
				$(this).next().slideUp(500);							// 1. Collapses the accordion module
				$(this).addClass("closed");								// 2. Adds the 'closed' class
			}
		}
	);
	// Auto collapses the accordion modules (unless they have the class, 'staysOpen')
	setTimeout(function(){
		$("ul#accordion > li:not(.staysOpen) > h4:not(.closed)").click();
		}, 
		5000
	);		
/* ////////// END MAIN ACCORDION ********** */	


/* ********** SUPPORT PHONE DIRECTORY ACCORDION ********** */
	// Hide any accordion module that doesn't have class 'active' applied
	$("ul#supportAccord > li > h4:not(.active) + div").hide();
	
	// Accordion function, starts with event binding on the <h4>s
	$("ul#supportAccord > li > h4").bind("click",
		function(){
			// Checks to see if the accordion module being clicked is expanded. If so...
			if ($(this).hasClass("active")) {							
				$(this).next().slideUp(400);							// 1. Collapses the accordion module
				$(this).removeClass("active");							// 2. Removes the 'active' class
			}
			// Otherwise...
			else {
				$("ul#supportAccord > li > h4").removeClass("active")	// 1. Removes any 'active' class that may be present
				.next().slideUp(400);									// 2. Collapses any open nav set
				$(this).next().slideDown(400);							// 3. Expands the nav set that was clicked on
				$(this).addClass("active");								// 4. Adds the 'active' class to the clicked item
			}
		}
	);
/* ////////// END SUPPORT PHONE DIRECTORY ACCORDION ********** */



/* ********** GLOSSARY TABS ********** */
	if ($('.glossaryTabs').length > 0) {
		$('.glossaryTabs').accessibleTabs({
		    // Classname to apply to the div that is wrapped around
		    // the original Markup
		    wrapperClass: 'glossaryContent',
		    // Classname to apply to the LI of the selected Tab
		    currentClass: 'current',
		    // Tag or valid Query Selector of the Elements to Transform the
		    // Tabs-Navigation from (originals are removed)
		    tabhead: 'h6',
		    // Tag or valid Query Selector of the Elements to be treated as
		    // the Tab Body
		    tabbody: '.tabbody',
		    // can be 'fadeIn', 'slideDown', 'show'
		    fx:'fadeIn',
		    // speed (String|Number): 'slow', 'normal', or 'fast') or the number of
		    // milliseconds to run the animation
		    fxspeed: 'normal',
		    // text to indicate for screenreaders which tab is the current one
			currentInfoText: 'current tab: ',
			// Definition where to insert the Info Text.
			// Can be either 'prepend' or 'append'
			currentInfoPosition: 'prepend',
			// Class to apply to the span wrapping the CurrentInfoText
			currentInfoClass: 'current-info' 
		});
	}
	
	if ($('.genericTabs').length > 0) {
		$('.genericTabs').accessibleTabs({
		    // Classname to apply to the div that is wrapped around
		    // the original Markup
		    wrapperClass: 'genericContent',
		    // Classname to apply to the LI of the selected Tab
		    currentClass: 'current',
		    // Tag or valid Query Selector of the Elements to Transform the
		    // Tabs-Navigation from (originals are removed)
		    tabhead: 'h6',
		    // Tag or valid Query Selector of the Elements to be treated as
		    // the Tab Body
		    tabbody: '.tabbody',
		    // can be 'fadeIn', 'slideDown', 'show'
		    fx:'fadeIn',
		    // speed (String|Number): 'slow', 'normal', or 'fast') or the number of
		    // milliseconds to run the animation
		    fxspeed: 'normal',
		    // text to indicate for screenreaders which tab is the current one
			currentInfoText: 'current tab: ',
			// Definition where to insert the Info Text.
			// Can be either 'prepend' or 'append'
			currentInfoPosition: 'prepend',
			// Class to apply to the span wrapping the CurrentInfoText
			currentInfoClass: 'current-info',
			saveState:true
			/*autoAnchor:true*/
		});
	}
/* ////////// END GLOSSARY TABS ********** */



/* ********** IRON MOUNTAIN ASSIST ********** */
	if ($('#assistTool').length > 0) {
		$("#assistBtn").click(function(){
			
			//Slide down the Assist form.
			//Add the bottom border
//			$(this).css("opacity", "0").siblings("form").slideDown("normal", function(){
			$(this).css("opacity", "0").siblings("div").slideDown("normal", function(){
				if ($("body:not(.landingPage)").length > 0) {			//Check to see if we are not on the landing page.
					$(this).css("border-bottom", "2px solid #000");
				}
			});		
			
			return false;												//Prevent the default a element action
		});
		
		$(".closeBtn").click(function(){								//When the closed button is clicked then slide the form up.
//			$(this).parent("form").css("border-bottom", "2px solid #FBFBFB").slideUp("normal", 
			$(this).parent("div").css("border-bottom", "2px solid #FBFBFB").slideUp("normal", function(){
				$("#assistBtn").animate({opacity: 1.0}, 300);
			});		
		});
	}

/* ////////// END IRON MOUNTAIN ASSIST ********** */


//		alert("next stop LANDING PAGE NAVIGATION "+ $(".landingPage").length);

/* ********** LANDING PAGE NAVIGATION ********** */
	if ($(".landingPage").length > 0) {
		// Get a string of all the image src attributes (separated by commas and spaces)...	
		var allImgSrc = "";
		jQuery.each($("ul#subNav > li > div > img"),
			function(){
				allImgSrc = allImgSrc + "'" + $(this).attr("src") + "', ";
			}
		);	
		// ...and pass it to the image preloader (chopping off the last comma and space)		
		$.preloadImages(allImgSrc.substring(0, allImgSrc.length - 2));		
		
		// Function to swap contents of the landing page hero
		function landingSwap(){
			var navClicked = this;	
			//Use Collection Instead
			var anchorId = $(this).attr("id");
			var imgOffset = anchorId.substring(1,anchorId.length);
			var newIndex = "div#m"+imgOffset+" > img";
												
			//var newImg = $(navClicked).next().children("img:first");	// 1. Get the new image
			var newContent = $(newIndex).nextAll().clone();				// 2. Copy the new content
			$("div#hero > img").fadeTo(400, 0,							// 3. Fade the existing image out
				function(){													// and then afterwards...
					var newSrc = $(newIndex).attr("src");						// 4. Get the src of the new image
					var newAlt = $(newIndex).attr("alt");						// 5. Get the alt of the new image
					$("div#hero > img").attr("src", newSrc);
					//$(this).attr("src", newSrc);							// 6. Set the existing image src to new image src
					$("div#hero > img").attr("alt", newAlt)

					//$(this).attr("alt", newAlt);							// 7. Set the existing image alt to the new image alt
					$("div#hero > img").fadeTo(400, 1);
					//$(this).fadeTo(400, 1);									// 8. Fade the new image in
				}
			);
			$("div#hero > div").html(newContent);						// 9. Replace the existing content with the copy of the new content
		}
		function funcPH(){} // hoverIntent needs an "out" function, and since we won't use it, we just define an empty one
		
		/* This is the configuration object for hoverIntent. We're storing it in the data 
		 * object of the subNav to keep it out of global scope.
		 */
		if ($("ul#subNav").length > 0) {
			$("ul#subNav").data("hInt", {
				config: {
					sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
					interval: 200, // number = milliseconds for onMouseOver polling interval    
					over: landingSwap, // function = onMouseOver callback (REQUIRED)    
					timeout: 500, // number = milliseconds delay before onMouseOut    
					out: funcPH // function = onMouseOut callback (REQUIRED)    
				}
			});
			// Initializes hoverIntent on the nav links, passing the configuration object
			$(".landingPage ul#subNav > li > a").unbind().hoverIntent($("ul#subNav").data("hInt").config);	
		}
	}
/* ////////// END LANDING PAGE NAVIGATION ********** */


/* ********** Hero Carousel ********** */
	if ($("#scroller").length > 0) {
		
		//Move the Image Carousel forward one image
		$(".next").click(function(){
			$("#scroller ul li:first")
			.appendTo("#scroller ul")
		});
		
		//Move the Image Carousel backward one image
		$(".prev").click(function(){
			$("#scroller ul li:last")
			.prependTo("#scroller ul")
		});
		
		//Extract the contents of the image scroller li and place it into the hero div on click
		//$("#scroller ul").live("click", function(event){ - $("#scroller ul").live is not a function 
		$("#scroller ul li").click(function(event){
			
			//Get the target of the click event.
			e = event.target;
			
			//Check to see the element that is clicked on is an Image
			if($(e).is("img")){
				
				newHeroSrc = $(e).next().children(".hero").attr("src");			//The src attribute of the new hero image
				newHeroAlt = $(e).next().children(".hero").attr("alt");			//The alt attribute of the new hero image
				
//				newContents = $(e).next().children().filter(":not(.hero)");		//The entire contents of the li class except for elements with a .hero class
// Change this to the four elements that should be present as for some reason the clone()->prependTo inverts the order of elements

                newh3 = $(e).next().children("h3").html();
                newspan = $(e).next().children("span").html();
                newp = $(e).next().children("p").html();
                newa = $(e).next().children("a").html();
	
//	            alert($(newContents).value);			
				
				$("#hero > img").fadeTo(400, 0, function(){						//Fade out the old hero image
					$(this).attr("src", newHeroSrc);
					$(this).attr("alt", newHeroAlt);
					$(this).fadeTo(400, 1);										//Fade in the new hero image
				});
								
				$(".carouselTarget > :not(#scrollerWrapper)").fadeTo(400, 0, function(){		//Fade out the carouselTarget
					$("div.carouselTarget > h3").html(newh3).attr("style","opacity: 1;");
					$("div.carouselTarget > a").html(newa).attr("style","opacity: 1;");
					$("div.carouselTarget > p").html(newp).attr("style","opacity: 1;");
					$("div.carouselTarget > span").html(newspan).attr("style","opacity: 1;");
					$(".carouselTarget").fadeTo(400, 1);
				});
				
			}
		});
	}
 
/* ////////// END Hero Carousel ********** */



/* ********** Modal Window ********** */
	
	//Uses the JQModal plugin to activate the Modal Dialog box.
	
	if ($(".modal").length > 0) {				//First Check to see if a modal window exists on the page.
		$(".modal").jqm({
			trigger: '.openModal',				//The css selector for opening the modal window
			overlay: 70,						//The opacity of the overaly behind the modal window 0-100
			closeClass: 'closeModal',			//The css class name of the close button
			ajax: '@href'						//Fill the Modal via an ajax call from the triggers href attribute
		});
	}
/* ////////// END Modal Window ********** */



/* ********** superPopups ********** */
	
	//Place the class "print" on any <a> tag that you wish to cause a popup to fire.  
	//Create your own version to customize however you need. See the superPopu.js for all config options
	
	$(".print").click(function(){
			
			href = $(this).attr("href");
			
			superPopup({
				height: 100,
				width: 200,
				url: href
			});
		
		return false;
	});
/* ////////// END superPopups ********** */




	// ---------------------------------------------------------------------------------------
	// BEGIN: Ellipsis - after max character | slice points
	/* Keep HTML tags */
	function useEllipsis(maxChars, className) {
		var slicePoint = maxChars;
		$(className).each(function() {
			var allText = $(this).html();

			if (allText.length > slicePoint) {
				// This cuts off after maxChars characters but up to the word
				var startText = allText.slice(0, slicePoint).replace(/\w+$/, '');

				// Add ellipsis
				startText = startText + "...";
				$(this).html(startText);
				$(this).attr('title',allText);
			}
		});
	}

	//Initialize Ellipsis
	useEllipsis (75, "#BIN_Accordion a");
	// END: Ellipsis
	
	
	// ---------------------------------------------------------------------------------------
	// BEGIN: IE6 - hide dropdown
	if ($.browser.msie && $.browser.version<"7") {
		if ($('#categoryFilterDropdown').length) {
			$("#mainNav li").hover(function(){
				$("#categoryFilterDropdown select").hide();
			},function(){
				$("#categoryFilterDropdown select").show();
			});
		}
	}
	// END: IE6 - hide dropdown



});
