// set up namespace
if (Object.isUndefined(com))
{
	var com = {};
}
if (Object.isUndefined(com.atmospherebbdo))
{
	com.atmospherebbdo = {};
}
if (Object.isUndefined(com.atmospherebbdo.widgets))
{
	com.atmospherebbdo.widgets = {};
}

com.atmospherebbdo.Config = {
	Search: {defaultText: "Type your question here"},
    Flash: {
        minVersion: 9
    },
    TopNav: {
        "who-we-are": {},
        "innovation": {},
        "products-and-services": {},
        "news-and-events": {},
        "financial-information": {},
        "global-citizenship": {},
        "careers": {}
    },
    PreloaderSettings: {
        images: ["/common/images/global-navigation/global-navigation-thumbs.jpg", "/common/images/local-navigation/bg-light-blue.png", "/common/images/local-navigation/arrow-white-up.gif", "/common/images/local-navigation/arrow-white-down.gif", "/common/images/local-navigation/arrow-white-right.gif", "/common/images/global-navigation/blank.gif", "/common/images/global-navigation/menu-item-arrow.gif", "/common/images/global-navigation/top-level.gif"]
    },

    SifrSettings: {
        swfs: {
            gothamThin: {
                src: '/common/swf/sifrLatinThin.swf'
            },
            gothamBook: {
                src: '/common/swf/sifrLatinBook.swf'
            }
        },
        configs: [{
            atmo: {
                font: 'gothamThin'
            }, /* Namespace our added params here, to avoid conflict with sifr internal params */
            selector: '.copy-holder .inner h2',
            css: {
                '.sIFR-root': {
                    'color': '#FFFFFF'
                }
            },
            wmode: 'transparent'
        }, {
            atmo: {
                font: 'gothamThin'
            },
            selector: '.tabs h2',
            css: {
                '.sIFR-root': {
                    'color': '#4A0080'
                }
            },
            wmode: 'transparent'
        }, {
            atmo: {
                font: 'gothamThin'
            },
            selector: 'h2',
            css: {
                '.sIFR-root': {
                    'color': '#4A0080',
                    'kerning': true,
                    'letter-spacing': -3
                }
            },
            wmode: 'opaque'
        }, {
            atmo: {
                font: 'gothamBook'
            },
            selector: 'div.also-interested-in h4',
            css: {
                '.sIFR-root': {
                    'color': '#4A0080'
                }
            },
            wmode: 'transparent'
        }, {
            atmo: {
                font: 'gothamBook'
            },
            selector: '#recruiting-locations h4',
            css: {
                '.sIFR-root': {
                    'color': '#4A0080'
                }
            },
            wmode: 'transparent'
        }, {
            atmo: {
                font: 'gothamThin'
            },
            selector: '#content h4',
            css: {
                '.sIFR-root': {
                    'color': '#4A0080'
                }
            },
            wmode: 'transparent'
        }, {
            atmo: {
                font: 'gothamThin'
            },
            selector: '#sidebar h4',
            css: {
                '.sIFR-root': {
                    'color': '#4A0080'
                }
            },
            wmode: 'transparent'
        }, {
            atmo: {
                font: 'gothamThin'
            },
            selector: 'li.level-1 a',
            css: {
                '.sIFR-root': {
                    'color': '#FFFFFF',
                    'cursor': 'pointer'
                },
                'a': {
                    'text-decoration': 'none',
                    'color': '#FFFFFF'
                },
                'a:hover': {
                    'text-decoration': 'none',
                    'color': '#FFFFFF'
                }
            },
            wmode: 'transparent'
        }, {
            atmo: {
                font: 'gothamThin'
            },
            selector: '.search-box .category a',
            css: {
                '.sIFR-root': {
                    'color': '#FFFFFF',
                    'cursor': 'pointer'
                },
                'a': {
                    'text-decoration': 'none',
                    'color': '#FFFFFF'
                },
                'a:hover': {
                    'text-decoration': 'none',
                    'color': '#FFFFFF'
                }
            },
            wmode: 'transparent'
        }, {

            atmo: {
                font: 'gothamThin'
            },
            selector: '.inner .use-sifr',
            css: {
                '.sIFR-root': {
                    'color': '#FFFFFF'
                }
            },
            wmode: 'transparent'
        }]
    }
};

com.atmospherebbdo.Dev = {
  linkInvalid: function()
{
    alert("This link is not active on the testing site.");
  }
};

com.atmospherebbdo.Util = {
	debug: true,

	log: function()
	{
		if ( !Util.debug ) return;

		if (!window.atmo) {
			window.atmo = {};
			window.atmo.log = [];
		}

		// Determine what to do based on params
		if (arguments[0])
		{
			switch(arguments[0].constructor)
			{
				// Util.log(/pattern/) - filter log and output it
				case RegExp:
				dump(arguments[0]);
				break;

				// Util.log("some string") - add "some string" to the log
				case String:
				write(arguments[0]);
				break;

				default:
				throw new Error("Util.log called with invalid argument.")
				return;
			}
		}
		else
		{
			// Util.log() - no params, output the log
			dump();
		}

		function write(str){
			try {
				var d = new Date();
				window.atmo.log.push('(' + d.getTime() + ') ' + d.toString() + ": " + str);
			}
			catch (err1) {

			}
		}

		function dump()
		{
			var log;
			if (arguments[0])
			{
				var regexp = arguments[0];
				log = window.atmo.log.filter(function(str) { return regexp.test(str); });
			}
			else
			{
				log = window.atmo.log;
			}


			try {
				console.log(log.join("\n"));
			}
			catch (err)
			{
				try
        {
          var logWindow = window.open("about:blank", "logWindow", "toolbar=no,width=500,height=500,resizable=yes,scrollbars=yes");
          logWindow.document.write(
              '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >'
            + '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + window.atmo.log.join('<br />') + '</body></html>'
          );
        }
        catch (err2)
        {
          alert(window.atmo.log.join("\n"));
        }
			}
		}
	},

	isMetaData: function( element )
	{
		if ( !!element.hasClassName( 'meta' ) )
			return true;

		var ancestors = element.ancestors();

		for ( var i=0, l=ancestors.length; i<l; i++ )
		{
			if ( ancestors[i].hasClassName( 'meta' ) )
				return true;
		}

		return false;
	},

	isBackupContent: function ( element )
	{
		return com.atmospherebbdo.Session.flashTargets.elements().include(element);
	},

	/*
	 * Use busy waiting to execute code after a condition is filled
	 */
	waitFor: function( params )
	{
	      var condition  = params.condition;
	      var interval   = params.interval || 300;
	      var maxTries   = params.maxTries || 10;
	      var currentTry = params._currentTry || 0; // private

		// If condition passes, run the code
	      if ( condition() === true )
			return params.callback();

	      // Limit the # of attempts
	      if ( currentTry < maxTries )
	      {
	          // Increment the attempt #
	          params._currentTry = currentTry+1;

		// Create the recursive call
		var f = function() { return Util.waitFor( params ); }

	          // Wait for one interval and execute
	          setTimeout( f, interval );
	      }
	      else
	      {
	          // alert( 'Maximum tries used for waitFor()...quitting' );
	      }
	  },

	// Queue the function, fire it when the named event occurs
	runAfterEvent: function(name, f)
	{
		Util.log("inside Util.runAfterEvent() - " + name);
		window.atmo.eventQueue.subscribe(name, f);
	},

	// Trigger any functions waiting on the named event
	eventNotify: function(name)
	{
		Util.log("--" + name + "--");
		window.atmo.eventQueue.notify(name);
	},

	preloadImages: function()
	{
	  var images = com.atmospherebbdo.Config.PreloaderSettings.images;
	  for (var i=0, l=images.length; i<l; i++)
	  {
	    var head = document.getElementsByTagName('head')[0];
	    var node = document.createElement('img');
	    head.appendChild(node);
	    node.setAttribute('src', images[i]);
	  }
	},

	// Return true if sifr has done tag replacements for all the matched elements
	sifrLoaded: function( selector )
	{
		Util.log("Util.sifrLoaded("+selector+")");
		var elements = $$( selector );

		// empty? then this selector is done
		if( !elements.length )
		{
			Util.log("Util.sifrLoaded("+selector+") - no elements");
			return true;
		}

		// remove empty elements and flash backup content
		var elements = elements.filter( function (element)
		{
			return !element.empty() && !Util.isBackupContent(element);
		});

		// empty now? then is selector is done
		if (!elements.length)
		{
			Util.log("Util.sifrLoaded("+selector+") - elements are all empty");
			return true;
		}

		var sifrCompleteElements = elements.filter( function (element)
		{
			if ( Util.isMetaData(element) || element.select('object').length )
			{
				return true;
			}
		});

		if (sifrCompleteElements.length == elements.length)
		{
			Util.log("All sifr ready for selector: " + selector);
			return true;
		}
		else
		{
			Util.log("sifr not complete for selector: " + selector);
			return false;
		}

		return true;
		//return window.atmo.eventQueue.hasFired("sifr-replace-selector(" + selector + ")-completed");
	},

	allSifrLoaded: function()
	{
		var configs = com.atmospherebbdo.Config.SifrSettings.configs;

		var sifrCompletes = configs.filter( function (config)
		{
			return Util.sifrLoaded(config.selector);
		});

		if (sifrCompletes.length == configs.length)
		{
			return true;
		}
		else
		{
			return false;
		}
	},

	homepageFlashLoaded: function ()
	{
		// if Flash is not present, act like it was loaded
		if (!Util.minimumFlashVersionMet())
		{
			return true;
		}
		var flashReady = $$('#news-items #experience-flash').length;
		if (flashReady && flashReady > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	},

	minimumFlashVersionMet: function ()
	{
		return (deconcept.SWFObjectUtil.getPlayerVersion().major >= com.atmospherebbdo.Config.Flash.minVersion);
	}

	/**
	*
	*  URL encode / decode
	*  http://www.webtoolkit.info/
	*


	Url: {
		// public method for url encoding
		encode: function(string)
		{
			return escape(this._utf8_encode(string));
		},

		// public method for url decoding
		decode: function(string)
		{
			return this._utf8_decode(unescape(string));
		},

		// private method for UTF-8 encoding
		_utf8_encode: function(string)
		{
			string = string.replace(/\r\n/g, "\n");
			var utftext = "";

			for (var n = 0; n < string.length; n++)
			{

				var c = string.charCodeAt(n);

				if (c < 128)
				{
					utftext += String.fromCharCode(c);
				}
				else
					if ((c > 127) && (c < 2048))
					{
						utftext += String.fromCharCode((c >> 6) | 192);
						utftext += String.fromCharCode((c & 63) | 128);
					}
					else
					{
						utftext += String.fromCharCode((c >> 12) | 224);
						utftext += String.fromCharCode(((c >> 6) & 63) | 128);
						utftext += String.fromCharCode((c & 63) | 128);
					}

			}

			return utftext;
		},

		// private method for UTF-8 decoding
		_utf8_decode: function(utftext)
		{
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;

			while (i < utftext.length)
			{

				c = utftext.charCodeAt(i);

				if (c < 128)
				{
					string += String.fromCharCode(c);
					i++;
				}
				else
					if ((c > 191) && (c < 224))
					{
						c2 = utftext.charCodeAt(i + 1);
						string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
						i += 2;
					}
					else
					{
						c2 = utftext.charCodeAt(i + 1);
						c3 = utftext.charCodeAt(i + 2);
						string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
						i += 3;
					}

			}

			return string;
		}
	}
    **/

};

// Shorthand, until we are ready to replace all other references
var Util = com.atmospherebbdo.Util;

// Required for sifr replacements
var parseSelector = $$;

com.atmospherebbdo.Sifr = {

	// Start busy waiters to notify us when Sifr replacements are done
	addListeners: function()
	  {
	  	var atmo = com.atmospherebbdo;
		var configs = atmo.Sifr.validConfigs();

		for (var i=0, l=configs.length; i<l; i++)
		{
			atmo.Sifr.listenForReplacement(configs[i].selector);
		}
	  },

	  activate: function()
	  {
	  	var fonts = $H(com.atmospherebbdo.Config.SifrSettings.swfs);

        for (var i = 0, l = fonts.keys().length; i < l; i++)
        {
            sIFR.activate( fonts.get( fonts.keys()[i] ) );
        }
	  },

	doReplacements: function()
	{
		Util.log("entering doReplacements()");

		var atmo = com.atmospherebbdo;
		var settings = atmo.Config.SifrSettings;

		// Fire completed event if sifr is disabled
		if (!atmo.Session.sifrEnabled)
		{
			atmo.Sifr.complete();
			return;
		}
	    // Only load the fonts needed
	    //var fonts = atmo.Sifr.validFonts();
	    var validConfigs = atmo.Sifr.validConfigs();

	    if (validConfigs.length < 1)
	    {
	        atmo.Sifr.complete();
	    }

	    // Enable fonts
        atmo.Sifr.activate();

		// Only try to replace selectors which match something
	    validConfigs.map(function(config)
	    {
	        Util.log('calling sIFR.replace() for selector ' + config.selector);
	        sIFR.replace(settings.swfs[config.atmo.font], config);
	    });

	    settings.configs = validConfigs;

	    Util.log("leaving doReplacements()");
	},

	// Show items that need to be hidden until sifr is loaded
	showHiddenElements: function()
	{
		Util.log('entering showHiddenElements()');

		var items = $$('.sifr-image', '#local-navigation', 'h2');
		if (items)
		{
		  for (var i=0, l=items.length; i<l; i++)
		  {
		    items[i].setStyle({'visibility': 'visible'});
		  }
		}

		Util.log('leaving showHiddenElements()');
	},

	// Adds a polling timer that fires an event when a single sifr replacement is completed
	listenForReplacement: function(selector, completedSelectors)
	{
		var configs = com.atmospherebbdo.Sifr.validConfigs(),
			completedSelectors = com.atmospherebbdo.Session.sifrSelectorsReplaced;

        var condition = function(){
	            var done = Util.sifrLoaded(selector);
	            Util.log("checking if sifr selector "+selector+" has been replaced: " + done);
	            return done;
        	},
			callback = function(){
	            Util.eventNotify("sifr-replace-selector(" + selector + ")-completed");

	            // Track which ones are finished
	            completedSelectors.push(selector);
	        };

		// After the "started" event for this selector fires, poll until it's done,
		//   then fire the "completed" event
        Util.runAfterEvent("sifr-replace-selector(" + selector + ")-started", function(){
            Util.log("calling Util.waitFor for sifr selector " + selector);
            Util.waitFor({
                condition: condition,
                callback: callback
            });
        });
	},

	fireIfCompleted: function()
	{
		if (com.atmospherebbdo.Sifr.allReplacementsCompleted())
		{
			com.atmospherebbdo.Sifr.complete();
		}
	},

	complete: function()
	{
		Util.eventNotify("sifr-all-replacements-completed");
	},

	// Return true if sifr-replace-selector events have completed
	allReplacementsCompleted: function()
	{
		var q = window.atmo.eventQueue;

		// If there's one param, it's a selector; check if it's been completed
		if (arguments[0])
		{
			return q.hasFired("sifr-replace-selector(" + arguments[0] + ")-completed");
		}
		var configs = com.atmospherebbdo.Sifr.validConfigs();

		// See if all selectors have been completed
		for (var i=0, l=configs.length; i<l; i++)
		{
			if (!q.hasFired("sifr-replace-selector(" + configs[i].selector + ")-completed"))
			{
				return false;
			}
		}
		return true;
	},
	validConfigs: function()
	{
		Util.log("entering Sifr.validConfigs()");

		// Return selectors with nonempty sets of nonempty elements
		var configs = com.atmospherebbdo.Config.SifrSettings.configs.filter( function (config)
		{
			Util.log("Checking selector: "+config.selector + " (" + $$(config.selector).length + " elements)");
			var elements = $$( config.selector ).filter(function(el) {
				return (!$(el).empty()
		                && !Util.isMetaData(el)
		                && !el.select('object').length);
			});
			return elements.length;
		});

	    Util.log("Sifr valid configs: "+configs.map(function(el) {return el.selector;}).join(",") );
		Util.log("leaving Sifr.validConfigs()");

        return configs;
	},
	validFonts: function()
	{
		var fonts = [];

		com.atmospherebbdo.Sifr.validConfigs().each( function (config) {
	        if (!fonts.include(config.atmo.font))
	        {
	          fonts.push(config.atmo.font);
	        }
		});
		return fonts;
	}
};

com.atmospherebbdo.SwfLoader = Class.create(
{
	initialize: function( options )
	{
		Util.log("SwfLoader.init()");

		// Inline arguments override those in config
		if ( arguments[1] ) Object.extend( options, arguments[1] );

		this.swf = options.swf;
		this.name = options.name;
		this.target = options.target;
		this.width = options.width;
		this.height = options.height;
		this.version = options.version || "9";
		this.bgColor = options.bgColor || "#1b0044";
		this.flashvars = options.flashvars || {};
		this.params = options.params || {"allowScriptAccess": "always", "wmode": "opaque"};

		this.flashvars = $H(this.flashvars);
		this.params = $H(this.params);

		// Ensure unique, non-empty ID for the <OBJECT>/<EMBED> tag
		if ( !this.name || this.name == this.target )
		{
			this.name = this.target + '-flash';
		}

		// if we can show the flash, we want to hide the backup content so
		// sifr won't sifr-ize it
		if (Util.minimumFlashVersionMet())		{
			$(this.target).hide();
		} else {
			return;
		}

		Util.log("exiting SwfLoader.init()");
	},



	write: function()
	{
		Util.log("entering SwfLoader.write()");
		$(this.target).show();

		// This must happen here, since Session.isLatinBasedLanguage won't exist until after dom:loaded
		//this.flashvars.set("isLatinBasedLanguage", com.atmospherebbdo.Session.isLatinBasedLanguage);

		this.so = new SWFObject(this.swf, this.name, this.width, this.height, this.version, this.bgColor);

		for (var i=0, keys=this.params.keys(), l=keys.length; i<l; i++)
		{
			this.so.addParam( keys[i], this.params.get( keys[i] ) );
		}
		for (var i=0, keys=this.flashvars.keys(), l=keys.length; i<l; i++)
		{
			this.so.addVariable( keys[i], this.flashvars.get( keys[i] ) );
		}

		this.so.write(this.target);
		Util.log("leaving SwfLoader.write()");
	}
});

Object.extend(
	com.atmospherebbdo.SwfLoader,
	{
		instances: [],

		embed: function( options )
		{
			if (
				// Don't embed flash movie for old versions of flash plugin
				!Util.minimumFlashVersionMet()
			) { return; }

			Util.log("entering SwfLoader.embed()");
			var instance = new com.atmospherebbdo.SwfLoader( options );

			this.instances.push( instance );

            var callback = function(){
				Util.log("SwfLoader.embed() callback");
                this.write();
            }.bind(instance);

			// If options.immediate is set, don't wait on sIFR
			if ( options.immediate ) { return callback(); }

			Util.runAfterEvent("sifr-all-replacements-completed", callback);
		},

		addTarget: function(id)
		{
			var targets = com.atmospherebbdo.Session.flashTargets;
			if (!targets.include(id))
			{
				targets.push(id);
			}
		},

		emptyBackupContent: function()
		{
		  Util.log("entering emptyBackupContent()");

			if (!com.atmospherebbdo.SwfLoader.instances.length
				|| $('h1')
				|| !Util.minimumFlashVersionMet())
			{
				Util.log("...not emptying anything.")
				return;
			}

			var instances = com.atmospherebbdo.SwfLoader.instances;
			for (var i = 0, l = instances.length; i < l; i++)
			{
				var sl = instances[i];
				// Don't wipe out the content for swfs that are already loading (e.g., homepage)
				if (!sl.immediate) {
					Util.log("...emptying target div: " + sl.target);
					$(sl.target).update('');
				}
			}

		  Util.log("leaving emptyBackupContent()");
		},

		// Wrapper functions to be called inline in the HTML

		// this is a teaser to an experience -- click it and go there
		writeAccordionExperience: function(divCSSSelector, experienceSWFURL, linkURL)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   divCSSSelector,
				swf:      experienceSWFURL,
				name:     divCSSSelector,
				width:    "196",
				height:   "148",
				bgColor:  "#FFFFFF",             // optional
				flashvars: 
				{
					"linkURL": linkURL,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				},   // optional
				params:    {"allowScriptAccess": "always", "wmode": "opaque"}   // optional
			});
		},

		writeVideoPlayer196x146: function(divCSSSelector, videoURL, thumbnailURL)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   divCSSSelector,
				swf:      "/common/swf/video-player-196x146.swf",  // TODO - path into config
				name:     divCSSSelector,
				width:    "196",
				height:   "146",
				bgColor:  "#FFFFFF",             // optional
				flashvars: 
				{
					"vidURL": videoURL, 
					"thumbnailURL": thumbnailURL,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});
		},

		writeVideoPlayer320x240: function(divCSSSelector, videoURL, thumbnailURL)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   divCSSSelector,
				swf:      "/common/swf/video-player-320x240.swf",  // TODO - path into config
				name:     divCSSSelector,
				width:    "320",
				height:   "267",
				bgColor:  "#FFFFFF",             // optional
				flashvars: 
				{
					"vidURL": videoURL, 
					"thumbnailURL": thumbnailURL,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});

		},

		writeVideoPlayer478x360: function(divCSSSelector, videoURL, thumbnailURL)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   divCSSSelector,
				swf:      "/common/swf/video-player-478x360.swf",  // TODO - path into config
				name:     divCSSSelector,
				width:    "478",
				height:   "398",
				bgColor:  "#FFFFFF",             // optional
				flashvars: 
				{
					"vidURL": videoURL, 
					"thumbnailURL": thumbnailURL,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});

		},

		// simply here as an example
		writeE1Experience: function(experienceSWFURL, assetsPath)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   "experience",
				swf:      experienceSWFURL,
				name:     "experience-flash",
				width:    "938",
				height:   "580",
				bgColor:  "#1b0044",             // optional
				flashvars: 
				{
					"assetsPath": assetsPath,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});

		},

		writeCareersExperience: function(experienceSWFURL, assetsPath)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   "experience",
				swf:      experienceSWFURL,
				name:     "experience-flash",
				width:    "713",
				height:   "350",
				bgColor:  "#1b0044",             // optional
				flashvars: 
				{
					"assetsPath": assetsPath, 
					pathURL: assetsPath,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});

		},

		writeSuccessStoriesExperience: function(experienceSWFURL, assetsPath)
		{
			if (!Util.minimumFlashVersionMet()) { return; }

			if (!$('experience'))
			{
				return;
			}
			Util.log("entering SwfLoader.writeSuccessStoriesExperience()");

			// Save the container's id
			var SwfLoader = com.atmospherebbdo.SwfLoader;
			SwfLoader.addTarget($('experience'));

			// Move stories off screen so sifr can replace headers silently
			$$('div.story').each(function(el) {
		        el.setStyle({position: 'absolute', left: '-100000px'}) ;
		        Util.log("hid story content for el: " + el.getAttribute('id'));
		        Util.log("el's width: " + $(el).getWidth());
		      });



			// read the DOM and build up XML in data
			var data =
			"<success-stories>" +
			/* TT 6/26 $$('#content > div.story').map( function(story) */
				$$('#content div.story').map( function(story)
				{

					// skip the default story
					if (story.id == "default")
					{
						return "";
					}

					var storyType;
					story.id.match( /-slideshow$/ ) ? storyType = "slideshow" : storyType = "video";

					var parseMetaBlock = function( meta )
					{
						// Get gallery images
						if ( meta.hasClassName( 'images' ) )
						{
							var images = meta.select( 'div.image' );

							return meta.immediateDescendants().map( function( el )
								{
									switch( el.tagName )
									{
										case "H2":
											return "<slideshow-title>" + el.innerHTML + "</slideshow-title>";
										case "H5":
											return "<related-title>" + el.innerHTML + "</related-title>";
										case "UL":
											return el.immediateDescendants().map( function( li )
													{
														var a = li.down();

														return "<related-item>"
														+ "<item-title>" + a.innerHTML + "</item-title>"
														+ "<item-url>" + a.readAttribute( 'href' ) + "</item-url>"
														+ "</related-item>"
													} ).join( '' );
									}
								}).join( '' ) + images.map( function( img )
									{
										if ( img == images.first() )
											return "<poster-image-url>" + img.innerHTML + "</poster-image-url>";
										return "<gallery-image-url>" + img.innerHTML + "</gallery-image-url>";
									} ).join( '' );
						}

						// Get video metadata
						if ( meta.hasClassName( 'video' ) )
						{
							return meta.immediateDescendants().map( function( el )
								{
									switch( el.tagName )
									{
										case "DIV":
											var node = "";
											if (el.hasClassName('image'))
											{
												node = "<poster-image-url>" + el.innerHTML + "</poster-image-url>";
											}
											return node;
											break;

										case "A":
											return "<connection>" + el.readAttribute( 'href' ) + "</connection>"
													+ "<flv>" + el.readAttribute( 'rel' ) + "</flv>";

										case "H2":
											return "<video-title>" + el.innerHTML + "</video-title>";

										case "P":
											return "<paragraph>" + el.innerHTML + "</paragraph>";

										case "H5":
											return "<related-title>" + el.innerHTML + "</related-title>";

										case "UL":
											return el.immediateDescendants().map( function( li )
											{
												var a = li.down();

												return "<related-item>"
												+ "<item-title>" + a.innerHTML + "</item-title>"
												+ "<item-url>" + a.readAttribute( 'href' ) + "</item-url>"
												+ "</related-item>"
											} ).join( '' );
									}
								}).join( '' );
						}
					};

					// Return the XML
					return "<story id='" + story.id + "'>"

					// H2
					+ "<story-title>" + story.select( 'h2.title' ).first().innerHTML + "</story-title>"

					// Type of story (video story, slideshow)
					+ "<" + storyType + ">"

					+ story.select( 'div.meta' ).map ( parseMetaBlock ).join( '' )

					+ "</" + storyType + ">"

					+ "</story>";

				} ).join('') +
			"</success-stories>";
			var escaped = encodeURIComponent(data);

			Util.log("...before call to SwfLoader.embed()");
			Util.log("...escaped data: " + escaped);

			com.atmospherebbdo.SwfLoader.embed(
			{
				target:   "experience",
				swf:      experienceSWFURL,
				name:     "experience-flash",
				width:    "938",
				height:   "461",
				bgColor:  "1b0044",
				flashvars:
				{
					'dataXML': escaped,
					pathURL: assetsPath,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});



		},

		writeSmartServicesExperience: function(experienceSWFURL, assetsPath)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   "experience",
				swf:      experienceSWFURL,
				name:     "experience-flash",
				width:    "939",
				height:   "461",
				bgColor:  "#1b0044",
				flashvars: 
				{
					assetsPath: assetsPath,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});
		},

		writeHarmonyExperience: function(experienceSWFURL, pathURL)
		{

			com.atmospherebbdo.SwfLoader.embed({
				target:   "experience",
				swf:      experienceSWFURL,
				name:     "experience-flash",
				width:    "938",
				height:   "560",
				bgColor:  "#1b0044",
				flashvars: 
				{
					assetsPath: pathURL, 
					pathURL: pathURL,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});

		},

		writeInnovationExperience: function(innovationSWFURL, pathURL)
		{
			com.atmospherebbdo.SwfLoader.embed({
				target:   "experience",
				swf:      innovationSWFURL,
				name:     "experience-flash",
				width:    "938",
				height:   "560",
				bgColor:  "#1b0044",
				flashvars: 
				{
					"pathURL": pathURL,
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});
		},

		writeFlashHeader: function(divCSSSelector, headerSWFURL, width, height)
		{
			com.atmospherebbdo.SwfLoader.embed({
					target:   divCSSSelector,
					swf:      headerSWFURL,
					name:     divCSSSelector,
					width:    width, //"470",
					height:   height, //"97",
					bgColor:  "#e4f4fd"
			});
		},
		
		isLatinBased: function ()
		{
			return $$('body')[0].hasClassName('is-latin-true');
		},

		writeHomepageFlash: function (homepageSWFURL)
		{
			if (!Util.minimumFlashVersionMet()) { return; }

			if (!$('news-items'))
			{
				return;
			}

			var listItemParser = function (li)
			{
				var priority = li.select('.priority').first().innerHTML ;
				var heading = li.select('h3').first().innerHTML ;
				var subheading = li.select('h4').first().innerHTML ;
				var imageURL = li.select('div.image').first().innerHTML;
				// optional thumbnail image
				var thumbnailURL = imageURL;
				try
				{
					thumbnailURL = li.select('div.thumbnail').first().innerHTML;
				}
				catch(e)
				{
					// wasn't there, use the default image
				}

				var snippet = li.select('h5').first().innerHTML;
				var cta = li.select('a').first().innerHTML ;//textContent;
				var link = li.select('a').first().readAttribute('href');

				var data = "<box priority='" + priority +"'>" +
					'<heading>' + heading + '</heading>' +
					'<subHeading>' + subheading + '</subHeading>' +
					'<imageURL>' + imageURL + '</imageURL>' +
					'<thumbnailURL>' + thumbnailURL + '</thumbnailURL>' +
					'<snippet>' + snippet + '</snippet>' +
					'<cta>' + cta + '</cta>' +
					'<link>' + link + '</link>' +
				'</box>';
				return data;
			};

			// read the DOM and build up XML in data
			var data =
			"<homepage>" +
				"<intro>" +
					$$('.meta.intro h2').map( function(line)
					{
						return "<line>" + line.firstChild.nodeValue + "</line>";
					}).join('') +
				"</intro>" +
				"<question>" +
					$('interested-in').firstChild.nodeValue +
				"</question>" +
				$$('#news-items > ul').map( function(ul)
				{
					var data = "<identifier id='" + ul.className + "'>" +
						ul.childElements().map( listItemParser ).join('');
					return data + '</identifier>';
				} ).join('') +
			"</homepage>";

			var escaped = encodeURIComponent(data);

			// and write the SWFObject

			//com.atmospherebbdo.Config.SwfSettings.homepage.flashvars = {'dataXML': escaped};
			com.atmospherebbdo.SwfLoader.embed({
				immediate: true,
				target:   "news-items",
				swf:      homepageSWFURL,
				name:     "experience-flash",
				width:    "744",
				height:   "510",
				bgColor:  "#FFFFFF",
				flashvars: 
				{
					'dataXML': escaped, 
					'dataPath': '/common/swf/homepage_main.swf',
					'isLatinBasedLanguage': com.atmospherebbdo.SwfLoader.isLatinBased()
				}
			});
		}
	}
);

com.atmospherebbdo.widgets.Accordion = Class.create(
{
	// takes a list of AccordionToggles and an index to open at start
	initialize: function ( toggleList, start )
	{
		this.openIndex = undefined;
		this.animationDuration = 0.4;
		this.toggleList = toggleList;

		this._associateEventWithToggles();
		if (Object.isUndefined(start))
		{
			this.closeAll(true);
		}
		else
		{ // null argument to allow activate() to handle events as first argument
			this.activate(null, start, true);
		}
	},

	_associateEventWithToggles: function ()
	{
		var toggleIndex = 0;
		this.toggleList.each( function (obj)
		{
			if (!obj.toggle)
			{
				return;
			}
			obj.toggle.observe('click', this.activate.bindAsEventListener( this, toggleIndex ));
			obj.toggle.onclick = function () { return false; };
			toggleIndex++;
		}, this);
	},

	_closeSection: function (obj, skipAnimation)
	{
		if (obj.toggle)
		{
			obj.toggle.up().removeClassName('active');
		}
		if (obj.blocks)
		{
			obj.blocks.each( function (block)
			{
				block.removeClassName('open');
				if (skipAnimation)
				{
					block.hide();
				}
				else
				{
					// fancy animation here
					//block.hide();
						new Effect.BlindUp(block, {duration:this.animationDuration});
  				}
			}.bind(this));
		}
	},

	_openSection: function (obj, skipAnimation)
	{
		if (obj.toggle)
		{
			obj.toggle.up().addClassName('active');
		}
		if (obj.blocks)
		{
			obj.blocks.each( function (block)
			{
				block.addClassName('open');
				if (skipAnimation)
				{
					block.show();
				}
				else
				{
					// fancy animation here
					//block.show();
						new Effect.BlindDown(block,{duration:this.animationDuration});
  				}
			}.bind(this));
		}
	},

	activate: function (e, i, skipAnimation )
	{

		var newOpenSections = this.toggleList[i];
		var oldOpenSections = this.toggleList[this.openIndex];

		if (newOpenSections == oldOpenSections)
		{
			return;
		}
		else if (oldOpenSections)
		{
			this._closeSection(oldOpenSections, skipAnimation);
		}
		else
		{
			this.closeAll(true);
		}

		this._openSection( newOpenSections, skipAnimation );
		this.openIndex = i;
	},

	closeAll: function ( skipAnimation )
	{
		this.toggleList.each( function (obj)
		{
			this._closeSection(obj, skipAnimation);
		}, this);
	}
});

com.atmospherebbdo.widgets.Tabs = Class.create(
{
	initialize: function ( tabList )
	{
		this.currentTabIndex = undefined;

		this.tabList = tabList;
		this._associateEventWithTabs();
		this.activate(0);
	},

	_associateEventWithTabs: function ()
	{
		var tabIndex = 0;
		this.tabList.each( function (obj)
		{
			obj.tab.observe('click', this.activate.bind( this, tabIndex));
			obj.tab.onclick = function () { return false; };
			tabIndex++;
		}, this);
	},

	_closeTab: function (obj)
	{
		obj.tab.removeClassName('current');
		obj.block.removeClassName('open');
		obj.block.hide();
	},

	_openTab: function (obj)
	{
		obj.tab.addClassName('current');
		obj.block.addClassName('open');
		obj.block.show();
	},

	activate: function (i)
	{
		var newCurrentTab = this.tabList[i];
		var oldCurrentTab = this.tabList[this.currentTabIndex];

		if (newCurrentTab == oldCurrentTab)
		{
			return;
		}
		else if (oldCurrentTab)
		{
			// there's a shown tab, hide it
			this._closeTab(oldCurrentTab);
		}
		else
		{
			// no tabs selected
			this.tabList.each( function (obj) {
				this._closeTab(obj);
			}, this);
		}

		this._openTab( newCurrentTab );

		this.currentTabIndex = i;
	}
});

/*
 * Page - namespace for html-related methods
 */
com.atmospherebbdo.Page = {
	applyGlobalNavigationStyles: function()
	{
		var hoverableListItems = $$('#global-navigation li');
		var globalNav = $( 'global-navigation' );
		var topLevelElements = $$('#global-navigation > li');
		var topLevelDescendants = [];

		rewriteGlobalNav();

		topLevelElements.each( function( li )
		{
			topLevelDescendants.push( li );
			topLevelDescendants = topLevelDescendants.concat( li.descendants() );
		});

		if ( Prototype.Browser.IE6 && hoverableListItems.length )
		{
			addGlobalNavHoversIE6();
		}
		else
		{
			addGlobalNavHovers();
		}

		tweakGlobalNavImages();

		function rewriteGlobalNav()
		{
			Util.log("entering rewriteGlobalNav()");
			var images = $$('#global-navigation li.menu-item div.image-holder > img');
			for (var i=0, l=images.length; i<l; i++)
			{
				Element.replace(images[i], '<div class="thumb"></div>');
			}
			Util.log("leaving rewriteGlobalNav()");
		}

		function addGlobalNavHovers()
		{
			if (hoverableListItems.length)
			{
				hoverableListItems.each( function (li)
				{
					var over = addHover.bind( li );
					var out  = removeHover.bind( li );
					li.observe('mouseover', over);
					li.observe('mouseout', out);
				});
			}
		}

		function addGlobalNavHoversIE6()
		{
			var iframe = new IframeShim();

			hoverableListItems.each( function (li)
			{
				var over = function( e )
				{
					addHover.call( li, e );
					iframe.positionUnder( li );
				};

				var out = function( e )
				{
					if ( !topLevelDescendants.include(e.toElement) )
					{
						iframe.hide();
					}
					removeHover.call( li, e );
				}

				li.observe('mouseover', over);
				li.observe('mouseout', out);
			});
		}

		function tweakGlobalNavImages()
		{
			// Apply right-side drop shadows & item arrows
			$$('#global-navigation > li').each( function( listItem )
			{
				var menu = listItem.down('.menu-items');
				var children = menu.childElements();
				var numChildren = children.length;
				var rightShadow = new Element('img', {src: '/common/images/global-navigation/dropdown-shadow-right.png'});
				var rightShadowContainer = new Element('div');
				var lastItem = children[ numChildren - 2 ];

				// Insert the arrows
				for ( var i=0; i<numChildren-1; i++ )
				{
					var arrow = new Element('img', {src: '/common/images/global-navigation/menu-item-arrow.gif', "class": 'arrow'});
					children[i].select('.image-holder').first().insert(arrow);
				}

				// Add bottom border to last item
				lastItem.setStyle({ borderBottom: '1px solid #d3d3d3' });
				rightShadowContainer.addClassName( 'right-shadow' );
				rightShadowContainer.update( rightShadow );
				listItem.appendChild( rightShadowContainer );

				// Calculate dimensions
				var menuHeight = menu.getHeight();
				var menuLeft = parseInt(menu.getStyle('left').replace(/px/, ''));
				var menuItemWidth = 208;
				var rightShadowHeight = 294;
				var rightShadowWidth = 24;
				var bottomShadowHeight = 24;
				var bottomShadowWidth = 234;
				var clipHeight = (menuHeight-bottomShadowHeight-1);

				// Add right-side shadow and position it
				rightShadowContainer.makeClipping().setStyle(
				{
					width: rightShadowWidth+'px',
					height: clipHeight+'px',
					left: menuItemWidth + menuLeft + 'px',
					top: listItem.getHeight() + 'px'

				});
				rightShadow.setStyle(
				{
					top: (-rightShadowHeight + menuHeight) + 'px'
				});
			});
		}
	},
	applyGeneralListStyles: function()
	{
	  Util.log("entering applyGeneralListStyles()");
		// style first and last li elements where needed
		$$(
			'#breadcrumb li:first-child',
			'#accordion-panels li:first-child',
			'#large-image-links li:first-child',
			'#mid-size-image-links li:first-child',
			'#video-links li:first-child',
			'div.also-interested-in li:first-child').each( function (li)
		{
			li.addClassName('first');
		});
		$$(
			'#breadcrumb li:last-child',
			'#accordion-panels li:last-child',
			'#large-image-links li:last-child',
			'#mid-size-image-links li:last-child',
			'#video-links li:last-child').each( function (li)
		{
			li.addClassName('last');
		});

		// hide any <ul> tags without list elements within them
		// this is needed on the SR1 page.
		$$('ul').each( function (ul)
		{
			if (ul.childElements().length == 0)
			{
				ul.hide();
			}
		});
	  Util.log("leaving applyGeneralListStyles()");
	},

	/**
	 * Adds mouseover/mouseout events that apply a ".hover" class
	 *
	 */
	applyHoverStyles: function ()
	{
	  Util.log("entering applyHoverStyles()");
		var hoverables = $$(
			'#body div.search input.search-button',
			'ul.single-link > li',
			'ul.multiple-link > li',
			'#t1 table td',
			'#e2 ul#mid-size-image-links li'
		);

		hoverables.each( function (fragment)
		{
			fragment.observe('mouseover', function ()
			{
				this.addClassName('hover');
			});
			fragment.observe('mouseout', function ()
			{
				this.removeClassName('hover');
			});
		});

		// special hovers
		$$('.bottom a', '.top a').each( function (link)
		{
			var div = link.next('.copy-holder');
			link.observe('mouseover', function ()
			{
				div.addClassName('hover');
			});
			link.observe('mouseout', function ()
			{
				div.removeClassName('hover');
	        });
	    });
	    
	    // left nav hovers
	    $$('#local-navigation ul li').each( function (li)
	    {
	        li.observe('mouseover', function ()
	        {
	            if (li.hasClassName('level-1'))
	            {
	                if (li.hasClassName('arrow-purple-up'))
	                {
	                    li.removeClassName('arrow-purple-up');
	                    li.addClassName('arrow-white-up');
	                    li.addClassName('change-arrow-on-hover');
	                }
	            }
	            else if (li.hasClassName('level-2'))
	            {
	                if (li.hasClassName('purple-text'))
	                {
	                    li.removeClassName('purple-text');
	                    li.addClassName('orange-text');
	                    li.addClassName('change-text-on-hover');
	                }
	                    
	                if (li.hasClassName('arrow-purple-up'))
	                {
	                    li.removeClassName('arrow-purple-up');
	                    li.addClassName('arrow-orange-up');
	                    li.addClassName('change-arrow-on-hover');
	                }
	                else if (li.hasClassName('arrow-purple-right'))
	                {
	                    li.removeClassName('arrow-purple-right');
	                    li.addClassName('arrow-orange-right');
	                    li.addClassName('change-arrow-on-hover');
	                }
	            }
	            else if (li.hasClassName('level-3'))
	            {
	                if (li.hasClassName('purple-text'))
	                {
	                    li.removeClassName('purple-text');
	                    li.addClassName('orange-text');
	                    li.addClassName('bold');
	                    li.addClassName('change-text-on-hover');
	                }
	                
	                if (li.hasClassName('arrow-purple-up'))
	                {
	                    li.removeClassName('arrow-purple-up');
	                    li.addClassName('arrow-orange-up');
	                    li.addClassName('change-arrow-on-hover');
	                }
	                else if (li.hasClassName('arrow-purple-right'))
	                {
	                    li.removeClassName('arrow-purple-right');
	                    li.addClassName('arrow-orange-right');
	                    li.addClassName('change-arrow-on-hover');
	                }
	            }
	            else if (li.hasClassName('level-4'))
	            {
	                if (li.hasClassName('purple-text'))
	                {
	                    li.removeClassName('purple-text');
	                    li.addClassName('orange-text');
	                    li.addClassName('bold');
	                    li.addClassName('change-text-on-hover');
	                }
	            }
	        });
	        li.observe('mouseout', function ()
	        {
	            if (li.hasClassName('level-1'))
	            {
	                if (li.hasClassName('change-arrow-on-hover'))
	                {
	                    if (li.hasClassName('arrow-white-up'))
	                    {
	                        li.removeClassName('arrow-white-up');
	                        li.addClassName('arrow-purple-up');
	                    }
	                    li.removeClassName('change-arrow-on-hover');
	                }
	                
	            }
	            else if (li.hasClassName('level-2'))
	            {
	                if (li.hasClassName('change-text-on-hover'))
	                {
	                    if (li.hasClassName('orange-text'))
	                    {
	                        li.removeClassName('orange-text');
	                        li.addClassName('purple-text');
	                    }
	                    li.removeClassName('change-text-on-hover');
	                }
	                
	                if (li.hasClassName('change-arrow-on-hover'))
	                {
	                    if (li.hasClassName('arrow-orange-up'))
	                    {
	                        li.removeClassName('arrow-orange-up');
	                        li.addClassName('arrow-purple-up');
	                    }
	                    else if (li.hasClassName('arrow-orange-right'))
	                    {
	                        li.removeClassName('arrow-orange-right');
	                        li.addClassName('arrow-purple-right');
	                    }
	                    li.removeClassName('change-arrow-on-hover');
	                }
	            }
	            else if (li.hasClassName('level-3'))
	            {
	                if (li.hasClassName('change-text-on-hover'))
	                {
	                    if (li.hasClassName('orange-text'))
	                    {
	                        li.removeClassName('orange-text');
	                        li.removeClassName('bold');
	                        li.addClassName('purple-text');
	                    }
	                    li.removeClassName('change-text-on-hover');
	                }
	                
	                if (li.hasClassName('change-arrow-on-hover'))
	                {
	                    if (li.hasClassName('arrow-orange-up'))
	                    {
	                        li.removeClassName('arrow-orange-up');
	                        li.addClassName('arrow-purple-up');
	                    }
	                    else if (li.hasClassName('arrow-orange-right'))
	                    {
	                        li.removeClassName('arrow-orange-right');
	                        li.addClassName('arrow-purple-right');
	                    }
	                }
	            }
	            else if (li.hasClassName('level-4'))
	            {
	                if (li.hasClassName('change-text-on-hover'))
	                {
	                    if (li.hasClassName('orange-text'))
	                    {
	                        li.removeClassName('orange-text');
	                        li.removeClassName('bold');
	                        li.addClassName('purple-text')
	                    }
	                    li.removeClassName('change-text-on-hover');
	                }
	            }
			});
		});

	  Util.log("leaving applyHoverStyles()");
	},

	applyPrintOnlyStyles: function()
	{
		if (com.atmospherebbdo.Page.mediaType() !== "print") { return; }

		// Inject <IMG> tag, since background images won't display on print stylesheet
		$$("#header h1.logo").first().update(new Element('img', {src: '/common/images/pr_print_logo.gif', width: '150', height: '32'}));
	},


	// Return "print" if header is hidden
	mediaType: function()
	{
		if ( $$('#header h1.logo a').first().getStyle("display") === "none" )
		{
			return "print";
		}

		return "screen";
	},

	applySelectAllBehavior: function()
	{
		var selectAllLink = $$('.select-all-link a').first();

		if (selectAllLink)
		{
			var boxes = $$('#show-options input');
			if (boxes)
			{

				// disable href
				selectAllLink.writeAttribute('href', 'javascript:;');
				selectAllLink.observe('click', function ()
				{
					boxes.each( function (box)
					{
						box.checked = true;
					});
				});
			}
		}
	},

	applyTableStyles: function()
	{
		if (!$$('table').length) { return; }

		$$('table.calendar tbody > tr:nth-child(even)').each( function (row)
		{
			row.addClassName('alternate');
		});

		$$('table.calendar td').each( function (cell)
		{
			if(cell.cleanWhitespace().childElements().length == 0)
			{
				cell.addClassName('empty');
			}
		});
	},

	rewriteLocalNav: function()
	{
	  Util.log("entering rewriteLocalNav()");

	 if (!$$('#local-navigation').length)
	 {
	   Util.log("...no local nav, firing early");
	   LocalNavDesc.notifyCompleted();
	 }

		var nav = new LocalNavDesc( '#local-navigation' );
		if (nav && nav.top) {
			nav.write();
		}
		else {
			LocalNavDesc.notifyCompleted();
		}
	  Util.log("leaving rewriteLocalNav()");
	},

	stylePaginationAndSiteTools: function()
	{
		var pagination = $$('div.pagination').first();
		var siteTools = $('site-tools');

		if (pagination && siteTools)
		{
			var parent = pagination.up();
			var container = new Element('div');
			parent.insert(container);
			container.insert(siteTools);
			var clear = new Element('div', {'class': 'clear'});
			container.insert(clear);
			container.insert(pagination);

			clear.addClassName('line');
			pagination.addClassName('moved');
			siteTools.addClassName('moved');
		}

	},

	setupTabs: function() {
		// Don't hide tabs until sifr does its thing
		var tabs = $$('.tabs');
		if (!tabs.length) return;

		tabs.each(function(fragment){
			var tabsList = [];
			var tabButtons = fragment.select('.buttons>li');
			var tabContents = fragment.select('.contents>div');
			for (var i = 0; i < tabButtons.length; i++) {
				tabsList.push({
					tab: tabButtons[i],
					block: tabContents[i]
				});
			}
			var tabs = new com.atmospherebbdo.widgets.Tabs(tabsList);
		});
	},

	setSearchText: function()
	{
/*
	  Util.log("entering setSearchText()");

		var text,
			atmo        = com.atmospherebbdo,
			topInput    = $('global-search-field'),
			sideInput   = $('searchfield'),
			defaultText = atmo.Config.Search.defaultText,
			query       = atmo.Session.queryString;

		if ( !topInput && !sideInput ) { return; }



        // Order of priority: first take value searched for, then html value, then default
		topInput.setValue(query.iqname || topInput.getValue() || defaultText);
		sideInput.setValue(query.iqname || sideInput.getValue() || defaultText);


		var f = function()
		{
			if (input.getValue() === "")
			{
				input.setValue(text);
			}
		};

		f();

		input.observe( 'focus', function ()
		{
			input.setValue( '' );
		});
		input.observe( 'blur', f );

	  Util.log("leaving setSearchText()");
*/
	}

};

/*
 * Session - for storing data pertaining to this page load
 */
com.atmospherebbdo.Session = {

	// Gather information about page layout, locale
	getPageInfo: function()
	{
		var body    = document.body,
			atmo    = com.atmospherebbdo,
			session = atmo.Session,
			page    = atmo.Page;

		// If it's foreign language content, set it into session.language

		session.bodyId      = body.id;
		session.bodyEl      = $(body);
		session.isLatinBasedLanguage = !session.bodyEl.hasClassName("is-latin-false");
		session.sifrEnabled = (session.isLatinBasedLanguage
								&& page.mediaType() === "screen"
								&& Util.minimumFlashVersionMet());
/*
		session.queryString = (function()
		{
		  var uri = location.href.split("?");
		  if (uri.length < 2) { return {};}

		  var s = uri[1].replace(/\#$/, ''),
		  	  query = {};

		  s.replace(/\b([^&=]*)=([^&=]*)\b/g, function (m, a, d) {

		    if (typeof query[a] != 'undefined') {
		      query[a] += ',' + atmo.Util.Url.decode(d).replace(/\+/g, ' ');
		    } else {
		      query[a] = atmo.Util.Url.decode(d).replace(/\+/g, ' ');
		    }
		  });

		  return query;
		})();
*/
	},
	sifrSelectorsReplaced: [],
	flashTargets: (function(){
	  // private, static
	  var _targets  = [];
	  var _elements = [];

	  return {
	  	include: function(el)
		{
			return _targets.include(el);
		},
		push: function(el)
		{
			_targets.push(el);
			$(el).descendants().each(function(child) {
				_elements.push(child);
			});
		},
		targets: function() { return _targets; },
		elements: function() { return _elements; }
	  };
	})()
};

/*
 * Events - classes and methods for custom page events
 */
com.atmospherebbdo.Events = {};

/*
 * @class  Subscriber
 * @author Mike Cavaliere
 *
 * Represents code that must fire after a specified named event
 *
 */
com.atmospherebbdo.Events.Subscriber = function(name, fn)
{
	this._className = "Subscriber";
	this._fn = fn;
	this._name = name;
};

com.atmospherebbdo.Events.Subscriber.prototype = {
    is: function(criterion)
    {
        switch (typeof criterion)
        {
            case "object":
                return criterion === this;
            case "function":
                return criterion === this._fn;
                break;
            case "string":
                return criterion === this._name;
                break;
        }

        return false;
    },
    fire: function()
    {
        return this._fn();
    }
};

/**
 * Handles subscribing/notification of code for custom events
 *
 * @classDescription Handles subscribing/notification of code for custom events
 * @return Returns a new OrderedEventQueue
 * @author Mike Cavaliere
 *
 */
com.atmospherebbdo.Events.OrderedEventQueue = function()
{
  this._className = "OrderedEventQueue";
  this._log   = [];
  this._subscribers = []; 			// Queued code waiting for events
  this._notifications = [];		// Expired events
};

com.atmospherebbdo.Events.OrderedEventQueue.prototype = {

    // Push fn into queue; set it to fire on the indicated event
    subscribe: function()
    {
        var oe = arguments[0];

        if (arguments.length > 1)
        {
            oe = new com.atmospherebbdo.Events.Subscriber(arguments[0], arguments[1]);
        }

        // If the event already occurred, execute now
        if (this.hasFired(oe._name))
        {
            this._subscribers.push(oe);
            oe.fire();
            return;
        }

        this._subscribers.push(oe);


    },

    remove: function()
    {

    },

    // Run all queued code waiting on a given event
    notify: function(eventName)
    {
        var list = this.subscribersTo(eventName);

        this._log.push("firing event: " + eventName);
        this._notifications.push(eventName);

        for (var i = 0, l = list.length; i < l; i++)
        {
            list[i].fire();
        }
    },

    hasFired: function(event)
    {
        for (var i = 0, l = this._notifications.length; i < l; i++)
        {
            if (this._notifications[i] == event)
            {
                return true;
            }
        }

        return false;

    },

    // Return true if code in the queue is waiting on the event
    contains: function(eventName)
    {
        return !!this.subscribersTo(eventName);
    },

    // Return index of first occurrence of this event
    subscribersTo: function(eventName)
    {
        var matches = [];

        for (var i = 0, l = this._subscribers.length; i < l; i++)
        {
            if (this._subscribers[i].is(eventName))
            {
                matches.push(this._subscribers[i]);
            }
        }

        return matches;
    },

    // Return log
    log: function()
    {
        return this._log;
    }
};

function addHover(event)
{
	if (mouseOverCheck(event, this))
		this.addClassName('hover');
}

function removeHover(event)
{
	if (mouseOverCheck(event, this))
		this.removeClassName('hover');
}

// Avoid overlapping mouseover/mouseout events
function mouseOverCheck(e, handler){
	if (!['mouseout', 'mouseover'].include(e.type))
		return false;

	var relatedTarget;

	// Which element we're going to or coming from
	if (e.relatedTarget)
		relatedTarget = e.relatedTarget;
	else

	// IE versions of relatedTarget
	if (e.type == 'mouseout')
		relatedTarget = e.toElement;
	else
		relatedTarget = e.fromElement;

	// Traverse up until we find the target element, or the root
	while (relatedTarget && relatedTarget != handler)
		relatedTarget = relatedTarget.parentNode;

	// Return true if we're not moving onto a child of the original element
	return (relatedTarget != handler);
}

function positionGlobalNavThumbs()
{
	Util.log("entering positionGlobalNavThumbs()");

	// Calculate background positions
	var col = 0;
	for (key in com.atmospherebbdo.Config.TopNav)
	{
		var containers = $$("#" + key + " div.thumb");
		var row, el, left, top;

		for ( row = 0, l = containers.length; row < l; row++ )
		{

			el   = containers[ row ];
			left = 0 - (col * 55);
			top  = 0 - (row * 54);
			el.setStyle({
				"backgroundPosition": left+"px " + top + "px"
			});
		}

		++col;
	}
	Util.log("leaving positionGlobalNavThumbs()");
}

// These sections break some of the styling rules
var SPECIAL_NAVIGATION_SECTIONS = ['News and Events', 'Financial Information', 'Careers'];

/*
 * LocalNavLink
 *
 * @text		       Text of the link
 * @hasSubPages        True if this link has subpages in the sitemap tree
 * @isCurrent          True if this link correlates to the current page
 * @childLinks         Array of LocalNavLinks reflecting child pages of the current link
 * @level              Level of this link's page in site tree/depth of the link in the list (1 for top-level)
 * @section            Text for top-level section this link belongs to
 * @showingAllChildren True if all of this link's child pages are visible
 * @specialSection     True if this link belongs to one of the weird sections
 * @isLastChild        True this is the last child link for its depth
 * @isOnlyChild   	   True if this link has no siblings (in the nav)
 * @top				   Reference to the root element in the tree (level 1)
 * @tree			   Reference to the parent LocalNavDesc
 *
 */
LocalNavLink = Class.create(
{
	initialize: function ( )
	{
		var options = arguments[0] || {};

		//Util.log( 'LocalNavLink.initialize()' );

		this.anchor      = options.anchor;

		var potentialTextNode = options.anchor.firstChild;
		if (potentialTextNode)
		{
			this.text 		 = potentialTextNode.nodeValue;
		}
		else
		{
			this.text 	 = "";
		}
		this.url 		 = options.anchor.href;
		this.hasSubPages = options.hasSubPages || false;
		this.isCurrent 	 = options.isCurrent   || false;
		this.childLinks  = options.childLinks  || [];
		this.level 		 = options.level       || 1;
		this.section	 = options.section;
		this.specialSection = SPECIAL_NAVIGATION_SECTIONS.include(options.section);
		this.isLastChild = options.isLastChild || false;
		this.isOnlyChild = options.isOnlyChild || false;
		this.top		 = options.top || this;
		this.tree        = options.tree;
		this.ul          = this.getContainingList();

		if ( this.isCurrent )
			this.tree.currentPageLink = this;

		this.showingAllChildren = this.ul.hasClassName('all-sub-pages-visible');

		//Util.log( 'created LocalNavLink for '+this.text );

    	return this;
	},

	getContainingList: function ()
	{
		//Util.log( 'LocalNavLink.getContainingList()' );

		var el = this.anchor;
		var i = 0;
		while ( el.tagName != "UL" )
		{
			el = el.parentNode;
			if (++i >= 10) return;
		}
		return $(el);
	},

	// True if the link has links beneath it
	hasChildLinks: function ()
	{
		return this.childLinks.length > 0;
	},

	// True if a child or grandchild of this link is the current page
	descendantIsCurrent: function ()
	{
		if ( this.isCurrent ) return false;

		return (
			function( link )
			{
				if ( link.isCurrent ) {
					return true;
				}

				for ( var i=0, length=link.childLinks.length; i<length; i++ )
				{
					if ( arguments.callee( link.childLinks[i] ) ) return true;
				}
				return false;
			}
		)( this );
	},

	addChildLink: function ( link )
	{
		this.childLinks.push( link );
	},

	getArrowClasses: function ()
	{
		switch ( this.level )
		{
			case 1:
				/* TT 6/25	if ( this.isCurrent ) */
				if ( this.showingAllChildren || this.isCurrent )
				{
					this.normalClasses.push( 'arrow-white-down' );
					this.hoverClasses.push( 'arrow-white-down' );
				}
				else
				{
					this.normalClasses.push( 'arrow-purple-up' );
					this.hoverClasses.push( 'arrow-white-up' );
				}
				break;

			case 2:
				if ( this.hasChildLinks() )
				{
					if ( this.showingAllChildren )
					{
						this.normalClasses.push( 'arrow-orange-down' );
						this.hoverClasses.push( 'arrow-orange-down' );
					}
					else
					{
						this.normalClasses.push( 'arrow-purple-up' );
						this.hoverClasses.push( 'arrow-orange-up' );
					}
				}
				else
				{
					if (this.isOnlyChild)
					{
						this.normalClasses.push('arrow-orange-right');
						this.hoverClasses.push('arrow-orange-right');
					}
					else
					{
						if ( this.isCurrent )
						{
							this.normalClasses.push('arrow-orange-right');
							this.hoverClasses.push('arrow-orange-right');
						}
						else
						{
							if ( this.hasSubPages )
							{
								this.normalClasses.push('arrow-purple-right');
								this.hoverClasses.push('arrow-orange-right');
							}
						}


					}

				}
				break;

			case 3:
				// blue bg
				if ( this.hasChildLinks() )
				{
					if ( this.showingAllChildren )
					{
						this.normalClasses.push( 'arrow-orange-down' );
						this.hoverClasses.push( 'arrow-orange-down' );
					}
					else
					{
						this.normalClasses.push( 'arrow-purple-up' );
						this.hoverClasses.push( 'arrow-orange-up' );
					}
				}

				// gray bg
				else
				{
					if (this.isCurrent)
					{
						this.normalClasses.push('arrow-orange-right-large');
						this.hoverClasses.push('arrow-orange-right-large');
					}
					else if ( this.hasSubPages )
					{
						this.normalClasses.push('arrow-purple-right');
						this.hoverClasses.push('arrow-orange-right');
					}

				}
				break;

			case 4:
				if ( this.isCurrent )
				{
					this.normalClasses.push( 'arrow-orange-right-large' );
					this.hoverClasses.push( 'arrow-orange-right-large' );
				}
				break;

			default:
				return;
		}
	},

	getBaseClasses: function()
	{
		this.normalClasses.push( 'level-' + this.level );
		this.hoverClasses.push( 'level-' + this.level );
	},

	getBgClasses: function()
	{
		var klass;

		switch ( this.level ) {

			// Level 1 bg is in the css class

			case 2:
				klass = 'blue-bg';
				break;

			case 3:
				klass = ( this.isOnlyChild ? 'blue-bg' : 'gray-bg' );
				break;

			case 4:
				klass = 'gray-bg';
				break;

			default:
				return;
		}

		this.normalClasses.push( klass );
		this.hoverClasses.push( klass );
	},

	getBorderClasses: function()
	{
		var klass = 'bottom-border';

		switch ( this.level ) {

			// Level 1 bg is in the css class
			case 2:
				this.normalClasses.push( klass );
				this.hoverClasses.push( klass );
				break;

			case 3:
				if ( this.isOnlyChild || this.isLastChild )
				{
					this.normalClasses.push( klass );
					this.hoverClasses.push( klass );
				}
				break;

			case 4:
				if ( this.isLastChild )
				{
					this.normalClasses.push( klass );
					this.hoverClasses.push( klass );
				}
				break;

			default:
				return;
		}
	},

	getIndentClasses: function()
	{
		if (this.specialSection)
		{
			switch ( this.level )
			{
				case 1:
					klass = 'indent-1';
					break;

				case 2:
					klass = 'indent-2';
					break;

				case 3:
					klass = 'indent-3';
					break;

				// Note: there is no 4th level nav in the special sections
			}
		}
		else
		{
			switch ( this.level )
			{
				case 1:
					klass = 'indent-1';
					break;

				case 2:
					// Deeper indent for level 2 if we're on a top-level page
					/* TT 6/25 if ( this.tree.currentPageLink.level == 1 ) */
					if ( this.tree.currentPageLink && this.tree.currentPageLink.level == 1 )
					{
						klass = 'indent-2';
					}
					else
					{
						klass = 'indent-1';
					}
					break;

				case 3:
					klass = 'indent-2';
					break;

				case 4:
					klass = 'indent-3';
					break;
			}
		}
		this.normalClasses.push(klass);
		this.hoverClasses.push(klass);
	},

	getTextClasses: function( )
	{

		switch (this.level) {

			// Top-level is handled in css
			case 1:
				break;

			case 2:
				/* TT 6/25 if ( this.isCurrent || this.descendantIsCurrent() ) */
				if ( this.isCurrent || this.descendantIsCurrent() || this.hasChildLinks() )
				{
					this.normalClasses.push('orange-text');
					this.hoverClasses.push('orange-text');
				}
				else
				{
					this.normalClasses.push('purple-text');
					this.hoverClasses.push('orange-text');
				}

				this.normalClasses.push('bold');
				this.hoverClasses.push('bold');

				break;

			case 3:
				/* TT 6/25 if ( this.isCurrent || this.descendantIsCurrent() ) */
				if ( this.isCurrent || this.descendantIsCurrent() || this.hasChildLinks() )
				{
					this.normalClasses.push('orange-text', 'bold');
					this.hoverClasses.push('orange-text', 'bold');
				}
				else
				{
					this.normalClasses.push('purple-text');

					if ( this.hasSubPages )
					{
						this.hoverClasses.push('orange-text', 'bold');
					}
					else
					{
						/* TT 7/1 - Changed so the hover color is orange. */
						//this.hoverClasses.push('purple-text', 'bold');
						this.hoverClasses.push('orange-text', 'bold');
					}


				}
				break;

			case 4:
				if ( this.isCurrent || this.descendantIsCurrent() )
				{
					this.normalClasses.push('orange-text', 'bold');
				}
				else
				{
					this.normalClasses.push('purple-text');
				}
				this.hoverClasses.push('orange-text', 'bold');
				break;

			default:
				return;
		}

	},

	// Create the DOM node with classes attached
	create: function ( )
	{
		//Util.log( 'LocalNavLink.create('+this.text+')' );
		if ( !this.element )
		{
			this.normalClasses = [];
			this.hoverClasses  = [];

			this.getBaseClasses();
			this.getBgClasses();
			this.getBorderClasses();
			this.getIndentClasses();
			this.getArrowClasses();
			this.getTextClasses();

			var classDef = ( this.normalClasses.length < 1 ? null : this.normalClasses.join(' ') );

			var li   = document.createElement( "li" );
			var a    = document.createElement( "a" );
			var text = document.createTextNode( this.text );

			if ( classDef ) li.className = classDef;
			a.setAttribute( 'href', this.url );

			li.appendChild( a );
			a.appendChild( text );

			this.element = li;

			this.attachHover();
		}

		return this.element;
	},

	// Attach mouse events
	attachHover: function ( )
	{
		Util.log( 'LocalNavLink.attachHover()' );
		var normal = ( this.normalClasses.length < 1 ? null : this.normalClasses.join(' ') );
		var hover  = ( this.hoverClasses.length  < 1 ? null : this.hoverClasses.join(' ') );

		$(this.element).observe( 'mouseover', function( e )
		{
			this.element.className = hover;

		}.bind( this ) );

		$(this.element).observe( 'mouseout', function( e )
		{
			this.element.className = normal;

		}.bind( this ) );
	},

	// Recursively build the tree
	build: function ( )
	{
		Util.log( 'LocalNavLink.build('+this.text+')' );
		this.tree.listEl.appendChild( this.create() );

		for ( var i = 0, length = this.childLinks.length; i < length; i++ )
		{
			this.childLinks[i].build();
		}

		if ( this == this.tree.top )
		{
			this.tree.element.addClassName( 'completed' );
			LocalNavDesc.notifyCompleted();
		}

	}

});


Number.prototype.toText = function()
{
	if (this == 1) return "one";
	if (this == 2) return "two";
	if (this == 3) return "three";
	if (this == 4) return "four";
};

