/* Define Brookings namespace BROOK */
if( typeof BROOK === "undefined" || !BROOK ) { var BROOK = {}; }

BROOK.namespace = function() {
	var a=arguments, o=null, i, j, d;
	for (i=0; i<a.length; i=i+1) {
		if( typeof(a[i]) != 'string' ) { continue; }
		d=a[i].split(".");
		o=window;
		for (j=0; j<d.length; j=j+1) {
			o[d[j]]=o[d[j]] || {};
			o=o[d[j]];
		}
	}
	return o;
};

BROOK.define = function( a ) {
	return BROOK.namespace( "BROOK." + a );
};



/* Placeholder Helper */
BROOK.define( 'Placeholder' );
BROOK.Placeholder = function() {
	
	var self = this;
	
	var hasPlaceholder = self.testPlaceholder();
	if( hasPlaceholder ) {
		return;
	} else {
		/* This doesn't address the issue with password field being unable to show
		   placeholder text as a readable word. It will show up as **** per usual.
		*/
		$( 'input[placeholder], textarea[placeholder]' ).each( function() {
			var elValue = $(this).val();
			var placeholder = $(this).attr( 'placeholder' );
			if( elValue !== placeholder ) {
				$(this).val( placeholder );
				elValue = $(this).val();
			}
			
			$(this).focus( function() {
				if( elValue == placeholder ) {
					$(this).val( '' );
				}
				elValue = $(this).val();
			});
			
			$(this).blur( function() {
				elValue = $(this).val();
				if( elValue == placeholder || elValue == '' ) {
					$(this).val( placeholder );
				} else {
					$(this).val( elValue );
				}
				elValue = $(this).val();
			});
		});
	}
};

BROOK.Placeholder.prototype = {
	
	testPlaceholder: function() {
		var i = document.createElement( 'input' );
		return 'placeholder' in i;
	}
	
};



/* Reset the Scrollbar to the top of the viewport */
BROOK.define( 'scrollReset' );
BROOK.scrollReset = function() {
	$( 'html, body' ).animate( { scrollTop: $( 'html' ).offset().top }, 10 );
};



/* New Image */
BROOK.define( 'newImage' );
BROOK.newImage = function( id, file ) {
	$( '#' + id ).attr( 'src', '/images/' + file );
};


/* New Window */
BROOK.define( 'newWindow' );
BROOK.newWindow = function( url, name, left, top, width, height, menubar ) {

	var config = {
		'url': url || '',
		'name': name || 'popup',
		'left': left || 10,
		'top': top || 10,
		'width': width || 884,
		'height': height || 640,
		'menubar': menubar || 0
	};
	
	var nw = window.open( url, title, 'left=' + config.left + ', top=' + config.top + ', width=' + config.width + ', height=' + height + ', menubar=' + menubar +', location=no, resizable=1, status=no, scrollbars=1' );
	if( window.focus ) {
		nw.focus();
	}
	return false;

};



/* image rollovers */
BROOK.define( 'initRollovers' );
BROOK.initRollovers = function( el, imgClass ) {
	
	var aImages = $( el + ' img.' + imgClass );
	
	$( aImages ).each( function( i ) {
		var src = $( aImages[i] ).attr( 'src' );
		var ftype = src.substring( src.lastIndexOf( '.' ), src.length );
		var hsrc = src.replace( ftype, '_on' + ftype );
		
		$( aImages[i] ).hover(
			function() {
				$(this).attr( 'src', hsrc );
			},
			function() {
				$(this).attr( 'src', src );
			}
		);
	});
};



/* Create and Read Cookies */
BROOK.define( 'createCookie' );
BROOK.createCookie = function(name,value,days) {
	var expires;
	if( days ) {
		var date = new Date();
		date.setTime( date.getTime() + ( days*24*60*60*1000 ) );
		expires = "; expires="+date.toGMTString();
	}
	else {
		expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
};

BROOK.define( 'readCookie' );
BROOK.readCookie = function( name ) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for( var i=0; i < ca.length; i++ ) {
		var c = ca[i];
		while( c.charAt(0)==' ' ) {
			c = c.substring(1,c.length);
		}
		if( c.indexOf(nameEQ) == 0 ) {
			return c.substring( nameEQ.length, c.length );
		}
	}
	return null;
};



/* Setting font size stylesheets */
BROOK.define( 'fontsizer' );
BROOK.Fontsizer = function() {
	
	config = {
		'controls': $( '.reading-tools span' ),
		'stylesheet': BROOK.readCookie( 'BrookingsTextSize' ) || 'S'
	};
	
	var self = this;
	self.setActiveStylesheet( config, config.stylesheet );
	self.init( config );
	
};

BROOK.Fontsizer.prototype = {

	init: function( config ) {
		var self=this;
		
		$( config.controls ).click( function(e) {
			e.preventDefault();
			
			if( $(this).hasClass( 'txt-med' ) ) {
				self.setActiveStylesheet( config, 'M' );
			}
			else if( $(this).hasClass( 'txt-lrg' ) ) {
				self.setActiveStylesheet( config, 'L' );
			}
			else {
				self.setActiveStylesheet( config, 'S' );
			}
			
			$(this).blur();
		});
		
	},
	
	setActiveStylesheet: function( config, title ) {
		var self=this;
		config.stylesheet = title;
		self.setSize( config );
		
		$( 'body' ).removeClass( 'txtsz-s txtsz-m txtsz-l' );
		$( 'body' ).addClass( 'txtsz-' + config.stylesheet.toLowerCase() );
	},
	
	setSize: function( config ) {
		var stylesheet = config.stylesheet;
		BROOK.createCookie('BrookingsTextSize', stylesheet, 365);
	}

};



/* DIV switcher for rotating feature elements */
BROOK.define( 'SwitchDivs' );
BROOK.SwitchDivs = function( el, oldnum, newnum ) {
	var objOld = el + oldnum;
	var objNew = el + newnum;
	
	if( $(objOld).css( 'display' ) != 'none' ) {
		$(objOld).css( 'display', 'none' );
	}
	
	$( objNew ).css( 'display', 'block' );
};



/* Flavor bar hover */
BROOK.define( 'Flavors' );
BROOK.Flavors = function() {
    
    var $isIE = $.browser.msie;
    if( $isIE ) {
        var $whichIE = $.browser.version;
    }
    
    if( $isIE && $whichIE < '7' ) {
        $( '.content-tools > ul.onsite > li:first-child' ).addClass( 'first-item' );
    }
    
    // if is IE8 or less, create an iframe shim
    if( $isIE && $whichIE <= 9 ) {
        $('.content-tools > ul > li').hover(
            function() {
                var dropdown = $(this).children('div.dropdown');
                // if has a dropdown
                if( dropdown.length > 0 ) {
                    
                    var frameHeight = $(dropdown).height();
                    var frameWidth = $(dropdown).width() + 4;
                    var iframeShim = '<iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="0" src="#" class="iframeshim" style="width:' + frameWidth + 'px; height:' + frameHeight + 'px"></iframe>';
                    $( iframeShim ).appendTo( $(this) );
                    
                    $(this).addClass('hover');
                    if( $(this).hasClass( 'share' ) ) {
                        $(this).addClass('share-hover');
                    }
                }
            },
            function() {
                $(this).removeClass('hover');
                if( $(this).hasClass('share') ) {
                    $(this).removeClass('share-hover');
                }
                $( 'iframe.iframeshim' ).remove();
            }
        );
	}
    
    this.init();
};

BROOK.Flavors.prototype = {
    
    init: function() {
        var self=this;
        
        /* Facebook to Google Analytics */
        $( '.facebook a' ).click( function(e) {
            _gaq.push(['_trackSocial', 'facebook', 'send']);
        });
        
        /* Twitter to Google Analytics */
        twttr.events.bind('tweet', function(event) {
            if (event) {
                _gaq.push(['_trackSocial', 'twitter', 'tweet']);
            }
        });
        
        /* StumbleUpon to Google Analytics */
        $( '.stumble a' ).click( function(e) {
            _gaq.push(['_trackSocial', 'stumbleupon', 'share']);
        });
        
    }
};

function LinkedInShare() {
    _gaq.push(['_trackSocial', 'LinkedIn', 'Share']);
}



/* My Portfolio Personalization Palette */

/* The Personalization Tabs: Personalizer */
BROOK.define( 'Personalizer' );
BROOK.Personalizer = function( config ) {
	
	config = {
		't': config.t || $( 'personalized' ),
		'tabs': config.tabs || $( '#' + config.t + ' .tabs li' ),
		'tabContent': config.tabContent || $( '#' + config.t + ' div.thetab' )
	};
	
	var self = this;
	
	this.init( config );
};

BROOK.Personalizer.prototype = {
	
	init: function( config ) {
		var self = this;
		
		$( config.tabs ).each( function() {
			
			$(this).removeClass( 'off' );
			
			var tabId = $( this ).children( 'a' ).attr( 'href' ).split( '#' )[1];
			
			$( this ).click( function(e) {
				e.preventDefault();
				
				self.chooseTab( config, tabId );
				
				$(this).siblings( 'li' ).removeClass( 'on' );
				$(this).addClass( 'on' );
			});
			
			if( $( this ).hasClass( 'on' ) ) {
				$( '#' + tabId ).removeClass( 'tabclose' ).addClass( 'tabopen' );
			}
			else {
				$( '#' + tabId ).removeClass( 'tabopen' ).addClass( 'tabclose' );
			}
			
		});
		
		
		$( '#mync button' ).hover(
			function() {
				$(this).addClass( 'hover' );
			},
			function() {
				$(this).removeClass( 'hover' );
			}
		);
		
	},
	
	chooseTab: function( config, tab ) {
		
		$( config.tabContent ).each( function(i) {
			if( $(this).attr('id') == tab ) {
				$( '#' + tab ).removeClass( 'tabclose' ).addClass( 'tabopen' ).children( 'a' ).click( function(e) {
					e.preventDefault();
				});
			}
			else {
				$( this ).removeClass( 'tabopen' ).addClass( 'tabclose' );
			}
		
		});
		
		BROOK.createCookie( 'opentab', tab );
		
	}
	
};


/* The My Portfolio Sections */
BROOK.define( 'MypSections' );
BROOK.MypSections = function( config ) {
	
	var config = {
		t: config.t || 'myp',
		sections: config.sections || $( '#' + config.t + ' ul > li' ),
		sectionLnks: config.sectionLnks || $( '#' + config.t + ' a.group' ),
		sectionContent: config.sectionContent || $( '#' + config.t + ' div.body' )
	};
	
	var self = this;
	self.init( config );
};

BROOK.MypSections.prototype = {

	init: function( config ) {
		var self = this;
		
		$( config.sectionLnks ).click( function(e) {
			e.preventDefault();
			
			var sId = $(this).attr( 'href' ).split( '#' )[1];
			self.chooseSection( config, sId );
		});
	},
	
	chooseSection: function( config, sId ) {
		var self = this;
		
		$( config.sections ).each( function() {
			if( $(this).attr('id') == sId ) {
				if( $(this).hasClass( 'closed' ) ) {
					$( this ).removeClass( 'closed' ).addClass( 'open' );
				}
				else {
					$( this ).removeClass( 'open' ).addClass( 'closed' );
				}
			}
			else {
				$( this ).removeClass( 'open' ).addClass( 'closed' );
			}
		
		});
		
		BROOK.createCookie( 'opensection', sId );
		
	}
	
};



/* Spotlight */
BROOK.define( 'spotlight' );
BROOK.spotlight = function() {

	config = {
		'spotlightLength': parseInt(config.spotlightLength) || 0,
		'lower': parseInt(config.lower) || 0,
		'upper': parseInt(config.upper) || 3,
		'spotlightId': config.spotlightId || 'spotlightItems',
		'backId': config.backId || 'backward',
		'forwId': config.forwId || 'forward',
		'backImg': config.backImg || '/i/buttons/spotlight_back.gif',
		'forwImg': config.forwImg || '/i/buttons/spotlight_forw.gif'
	};
	
	var self = this;
	
	if( config.spotlightLength > 4 ) {
		self.startSpotlight( config );
	}

};

BROOK.spotlight.prototype = {

	startSpotlight: function( config ) {
		var self=this;
		var i = config.spotlightLength;
		while( i > 3 ) {
			$( '#spot_' + i ).css( 'display', 'none' );
			i--;
		}
		
		if( config.spotlightLength > 3 ) {
			self.buildNav( config );
		}
	},
	
	buildNav: function( config ) {
		var self=this;
		var spotlightNav = $( '.spotlight #spotNav' );
		var navItems = '<li id="' + config.backId + '"></li><li id="' + config.forwId + '"></li>';
		$( spotlightNav ).append( navItems );
		
		self.showButtons( config );
	},
	
	showButtons: function( config ) {
		var self=this;

		// nav items
		var backBtn = $( '#' + config.backId ).html('').unbind( 'click' );
		var forwBtn = $( '#' + config.forwId ).html('').unbind( 'click' );
		
		// nav back buttons
		var backBtnOff = '<span title="Go back">Go back</span>';
		var backBtnOn = '<a href="#">Go back</a>';
		
		// nav forward buttons
		var forwBtnOff = '<span title="Go forward">Go forward</span>';
		var forwBtnOn = '<a href="#">Go forward</a>';
		
		if( config.lower != 0 ) {
			// add class to image for hovering and set click event
			$( backBtn ).append( backBtnOn ).click( function() {
				self.spotlightUpdate( config, -1 );
				return false;
			});
		}
		else {
			$( backBtn ).append( backBtnOff );
		}
		
		
		if( config.upper != (config.spotlightLength - 1) ) {
			// add class to image for hovering and set click event
			$( forwBtn ).append( forwBtnOn ).click( function() {
				self.spotlightUpdate( config, 1 );
				return false;
			});
		}
		else {
			$( forwBtn ).append( forwBtnOff );
		}
		
	},
	
	spotlightUpdate: function( config, offset ) {
		var self=this;
		config.lower = config.lower + offset;
		config.upper = config.lower + 3;
		
		if( config.upper < config.spotlightLength - 1 ) {
			if( config.lower < 0 ) {
				config.lower = 0;
				config.upper = 3;
			}
		}
		else {
			config.upper = config.spotlightLength - 1 ;
			config.lower = config.upper - 3;
		}
		
		// change spotlights and update nav
		self.switchSpots( config );
		self.showButtons( config );
	},
	
	switchSpots: function( config ) {
		$( '#' + config.spotlightId + ' .spot' ).css( 'display', 'none' );
		for( var i = config.lower; i <= config.upper; i++ ) {
			$( '#spot_' + i ).css( 'display', 'block' );
		}
	}
	
};



/* Slideshow Control */
BROOK.define( 'Slideshow' );
BROOK.Slideshow = function( config ) {
	
	var config = {
		'slideshowLength': parseInt( config.slideshowLength ) || 0,
		'current': parseInt( config.current ) || 0,
		'title': config.title || '',
		'slideId': config.slideId || '#slide',
		'controls': config.controls || '#controls',
		'index': config.index || '#slides_index',
		'nextLnk': config.nextLnk || '#slide-next',
		'prevLnk': config.prevLnk || '#slide-prev'
	};
	
	var self=this;
	self.init( config );
	self.setControls( config );
};

BROOK.Slideshow.prototype = {

	init: function( config ) {
		$( config.index ).html( "1 of " + config.slideshowLength );
		$( config.controls ).css( 'display', 'block' );
	},
	
	setControls: function( config ) {
		var self=this;
		$( config.prevLnk ).click( function(e) {
			e.preventDefault();
			self.changeSlide( config, -1 );
		});
		
		$( config.nextLnk ).click( function(e) {
			e.preventDefault();
			self.changeSlide( config, 1 );
		});
	},
	
	changeSlide: function( config, offset ) {
		var self=this;
		
		var oldSlide = config.current;
		config.current = config.current + offset;
		
		if( config.current != oldSlide ) { // current and previous don't match
		
			// if current is equal to or greater than no. billboards, reset to zero
			if( config.current >= config.slideshowLength ) {
				config.current = 0;
			}
			
			// if current is less than zero, reset to no. billboards minus 1
			else if( config.current < 0 ) {
				config.current = config.slideshowLength - 1;
			}
			
			// otherwise, keep current as is and rotate.
			BROOK.SwitchDivs( config.slideId, oldSlide, config.current );
			document.title = self.updateTitle( config );
		}
	},
	
	updateTitle: function( config ) {
		var currentItem = config.current + 1;
		
		$( config.index ).html( currentItem + ' of ' + config.slideshowLength );
		var docTitle = config.title + ' - Slide ' + currentItem;
		return docTitle;
	}

};



/* Rotating Facts */
BROOK.define( 'RotatingFacts' );
BROOK.RotatingFacts = function() {
	
	config = {
		'factsLength': parseInt(config.factsLength) || 0,
		'fCurrent': parseInt(config.fCurrent) || 0,
		'fTid': parseInt(config.fTid) || 0,
		'fPaused': parseInt(config.fPaused) || 0,
		'fTimer': parseInt(config.fTimer) || 2000,
		'slideId': config.slideId || '#slide_'
	};
	
	this.pauseOnHover( config );
	this.autoRotate( config );
};

BROOK.RotatingFacts.prototype = {
	
	rotateFacts: function( config, offset ) {
		var self=this;
		
		clearTimeout( config.fTid );
		var index = config.fCurrent + offset;
		var old_fCurrent = config.fCurrent;
		if (index != config.fCurrent) {
			if (index < config.factsLength) {
				if (index < 0) {
					config.fCurrent = parseInt( config.factsLength ) - 1;
				} else {
					config.fCurrent = index;
				}
			} else {
				config.fCurrent = 0;
			}
			// rotate Facts
			BROOK.SwitchDivs( config.slideId, old_fCurrent, config.fCurrent );
		}
		self.autoRotate( config );
	},
	
	rotateFactsPause: function( config ) {
		clearTimeout( config.fTid );
	},
	
	rotateFactsResume: function( config ) {
		var self=this;
		//config.fTid = setTimeout( 'this.rotateFacts( config, 1)', config.fTimer );
		config.fTid = setTimeout( function() { self.rotateFacts( config, 1 ); }, config.fTimer, self);
	},
	
	autoRotate: function( config ) {
		var self=this;
		//config.fTid = setTimeout( 'BROOK.rotatingFacts.prototype.rotateFacts(config, 1)', config.fTimer );
		config.fTid = setTimeout( function() { self.rotateFacts( config, 1 ); }, config.fTimer, self);
	},
	
	pauseOnHover: function( config ) {
		var self=this;
		var fSlide = '';
		
		$( config.factsLength ).each( function(i) {
			fSlide = $( config.slideId + i );
			if( fSlide != '' ) {
				fSlide.hover(
					function() {
						self.rotateFactsPause( config );
					},
					function() {
						if( config.fPaused != 1 ) {
							self.rotateFactsResume( config );
						}
					}
				);
			}
		});
	}

};



/* Rotating Feature */
BROOK.define( 'RotateFeature' );
BROOK.RotateFeature = function() {
	
	config = {
		'billboardLength': parseInt(config.billboardLength) || 0,
		'current': parseInt(config.current) || 0,
		'tid': parseInt(config.tid) || 0,
		'featureNav': config.featureNav || 'featureNav',
		'paused': parseInt(config.paused) || 0,
		'fTimer': parseInt(config.fTimer) || 8000,
		'slideId': config.slideId || '#story_'
	}
	
	var self = this;
	
	self.init( config );
};

BROOK.RotateFeature.prototype = {
	
	init: function( config ) {
		var self=this;
		
		$( '.rotate-feature a.prev' ).click( function(e) {
			e.preventDefault();
			self.rotateBillboard( config, -1 );
		});
		
		$( '.rotate-feature a.next' ).click( function(e) {
			e.preventDefault();
			self.rotateBillboard( config, 1 );
		});
		
		$( '#' + config.featureNav + ' li[id^=c]' ).each( function() {
			$(this).click( function(e) {
				e.preventDefault();
				var item = parseInt( $(this).text() );
				self.rotateBillboardJump( config, item );
			});
		});
		
		self.pause( config );
		self.autoRotate( config );
		self.pauseRestart( config, "pause" );
		
	},
	
	rotateBillboard: function( config, offset ) {
		var self = this;
		clearTimeout( config.tid );
		
		var old_current = config.current; // current billboard showing
		config.current = config.current + offset; // new billboard to show
		
		if( config.current != old_current ) { // current and previous don't match
		
			// if current is equal to or greater than no. billboards, reset to zero
			if( config.current >= config.billboardLength ) {
				config.current = 0;
			}
			
			// if current is less than zero, reset to no. billboards minus 1
			else if( config.current < 0 ) {
				config.current = parseInt(config.billboardLength) - 1;
			}
			
			// otherwise, keep current as is and rotate.
			BROOK.SwitchDivs( config.slideId, old_current, config.current );
			self.switchCircles( config );
		}
		
		self.autoRotate( config );
	},
	
	rotateBillboardJump: function( config, item ) {
		var self = this;
		var old_current = config.current;
		config.current = item;
		
		BROOK.SwitchDivs( config.slideId, old_current, config.current );
		self.switchCircles( config );
	},
	
	rotateBillboardPause: function( config ) {
		clearTimeout( config.tid );
	},
	
	rotateBillboardResume: function( config ) {
		var self=this;
		config.tid = setTimeout( function() { self.rotateBillboard( config, 1 ); }, config.fTimer, self);
	},
	
	switchCircles: function( config ) {
		clearTimeout( config.tid );
		
		$( '.rotate-feature #' + config.featureNav + ' li' ).each( function(i) {
			var $elem = $(this);
			var lid = $elem.attr( 'id' );
			if( lid ) {
				if( lid == 'c' + config.current ) {
					$elem.addClass( 'on' );
				}
				else {
					$elem.removeClass( 'on' );
				}
			}
		});
	},
	
	pauseRestart: function( config, id ) {
		var self = this;
		
		$( '#' + id + ' a' ).addClass( 'running' ).click( function(e) {
			e.preventDefault();
			
			if( $(this).hasClass( 'running' ) ) {
				$(this).addClass( 'paused' ).removeClass( 'running' );
				self.rotateBillboardPause( config );
				config.paused = 1;
			}
			else {
				$(this).removeClass( 'paused' ).addClass( 'running' );
				self.rotateBillboardResume( config );
				config.paused = 0;
			}
		});
		
	},
	
	autoRotate: function( config ) {
		var self=this;
		config.tid = setTimeout( function() { self.rotateBillboard( config, 1 ); }, config.fTimer, self);
	},
	
	pause: function( config ) {
		var self = this;
		
		$( '.rotate-feature' ).hover(
			function() {
				self.rotateBillboardPause( config );
				$( '#pause > a' ).removeClass( 'running' ).addClass( 'paused' );
			},
			function() {
				if( config.paused !=1 ) {
					self.rotateBillboardResume( config );
					$( '#pause > a' ).removeClass( 'paused' ).addClass( 'running' );
				}
			}
		);
		
	}
	
};



/* Rotate Galleries */
BROOK.define( 'RotateGallery' );
BROOK.RotateGallery = function() {
	
	config = {
		'galleryNav': config.galleryNav || 'galleryNav',
		'galleryName': config.galleryName || 'gallery',
		'galleryLength': parseInt(config.galleryLength) || 0,
		'current': parseInt(config.current) || 0,
		'btnDir': config.btnDir || '/i/buttons/',
		'dotSrcOff': config.dotSrcOff || 'feature_dot.gif',
		'dotSrcOn': config.dotSrcOn || 'feature_dot_on.gif',
		'arrowLeft': config.arrowLeft || 'feature_arrow_l.gif',
		'arrowRight': config.arrowRight || 'feature_arrow_r.gif',
		'slideId': config.slideId || '#gallery'
	};
	
	var self=this;
	
	if( config.galleryLength > 1 ) {
		self.setUpGallery( config );
		self.createGalleryNav( config );
	}
	else {
		return;
	}
};

BROOK.RotateGallery.prototype = {
	
	setUpGallery: function( config ) {
		$( '#' + config.galleryName + ' div[id^=' + config.galleryName + ']' ).each( function() {
			if( $(this).attr( 'id' ) != (config.galleryName + config.current ) ) {
				$(this).css( 'display', 'none' );
			}
			else {
				$(this).css( 'display', 'block' );
			}
		});
	},
	
	createGalleryNav: function( config ) {
		var self=this;
		var gall = $( '#' + config.galleryName );
		
		var navDiv = $( '<div id="' + config.galleryNav + '" class="gallery-nav"></div>' );
		
		var prevLnk = $( '<a href="#" class="prev">Previous</a>' );
		$( prevLnk ).click( function(e) {
			e.preventDefault();
			self.rotateGalleryUpdate( config, -1 );
			$(this).blur();
		});
		
		var dotSrc;
		var theDots = '';
		for(var i=0; i < config.galleryLength; i++) {
			var theDot;
			if( i==0 ) {
				theDot = '<span class="dot dot-on" rel="c' + i + '">Item ' + (i+1) + '</span>';
			}
			else {
				theDot = '<span class="dot" rel="c' + i + '">Item ' + (i+1) + '</span>';
			}
			
			theDots += theDot;
		}
		
		var nextLnk = $( '<a href="#" class="next">Next</a>' );
		$( nextLnk ).click( function(e) {
			e.preventDefault();
			self.rotateGalleryUpdate( config, 1 );
			$(this).blur();
		});
		
		$( navDiv ).append( prevLnk );
		$( navDiv ).append( theDots );
		$( navDiv ).append( nextLnk );
		$( gall ).append( navDiv );
	},

	rotateGalleryUpdate: function( config, offset ) {
		var self=this;
		var index = config.current + offset;
		var old_current = config.current;
		if (index != config.current) {
			if (index < config.galleryLength) {
				if (index < 0) {
					config.current = config.galleryLength - 1;
				} else {
					config.current = index;
				}
			} else {
				config.current = 0;
			}
			
			// rotate Billboard
			BROOK.SwitchDivs( config.slideId, old_current, config.current );
			self.switchCircles( config );
		}
	},
	
	switchCircles: function( config ) {
		$( '#' + config.galleryNav + ' span[rel]' ).each( function(i) {
			if( $(this).attr( 'rel' ) == ( 'c'+config.current ) ) {
				$(this).addClass( 'dot-on' );
			}
			else {
				$(this).removeClass( 'dot-on' );
			}
		});
	}
	
};



/* Hub Pages */
/* All Brookings Hub */
BROOK.define( 'hub' );
BROOK.hub = function( config ) {
	
	var config = {
		'blurbs': config.blurbs || $( 'div.hub-blurb' ),
		'blurbsLen': config.blurbsLen || 0,
		'tabBase': config.tabBase || 'ul.hub-tabs',
		'tabGroup': config.tabGroup || $( config.tabBase ),
		'tabs': config.tabs || $( config.tabBase + ' li' )
	};
	
	config.tabGroup = $( config.tabBase );
	config.tabs = $( config.tabBase + ' li' );
	config.blurbsLen = $( config.blurbs ).length;
	
	BROOK.hub.prototype.init( config );

};

BROOK.hub.prototype = {

	init: function( config ) {
		var self=this;
		
		$( config.tabGroup[0] ).css( 'display', 'block' );
		
		var bon = Math.floor( Math.random() * config.blurbsLen );
		$( config.blurbs ).each( function(idx) {
			
			if( idx != bon ) {
				$( config.blurbs[idx] ).removeClass( 'active-blurb' );
				$( config.tabs[idx] ).removeClass( 'on' );
			}
			else {
				$( config.blurbs[idx] ).addClass( 'active-blurb' );
				$( config.tabs[idx] ).addClass( 'on' );
			}
			
		});
		
		self.switchTabs( config );
		
	},
	
	switchTabs: function( config ) {
		var self=this;
		
		var $tabs = config.tabs;
		$tabs.each( function( idx ) {
			$tab = $(this);
			$tab.click( function(e) {
				e.preventDefault();
				var $elem = $(this);
				
				var $lnk = $elem.find( 'a' ).eq(0);
				var lnkId = $lnk.attr('href');
				
				if( lnkId != null ) {
					// turn off all tabs and blurbs
					$( config.tabs ).removeClass( 'on' );
					$( config.blurbs ).removeClass( 'active-blurb' );
					
					// turn on clicked tab and associated blurb
					$elem.addClass( 'on' );
					$( lnkId ).addClass( 'active-blurb' );
				}
			});
		});
		
	}

};



/* Tab Switching */
function setDetailTab( el ) {
	
	var tabSelected = document.getElementById( el );
	var tabsParent = tabSelected.parentNode;
	
	var tabs = tabsParent.getElementsByTagName( 'li' );
	var tabsLen = tabs.length;
	var t=0;
	while( t < tabsLen ) {
		var tabName = tabs[t].id.split( 'li' )[1];
		var filterIdFragment = 'div' + tabName;
		var listIdFragment = 'div' + tabName + 'List';
		var divFilter = $( 'div[id$="' + filterIdFragment + '"]' ).eq(0);
		var divList = $( 'div[id$="' + listIdFragment +'"]' ).eq(0);
		
		if( tabs[t] == tabSelected ) {
			tabs[t].className = 'active';
			$( divFilter ).css({
				'visibility': 'visible',
				'display': 'block'
			});
			$( divList ).css({
				'visibility': 'visible',
				'display': 'block'
			});
		}
		else {
			tabs[t].className = '';
			$( divFilter ).css({
				'visibility': 'hidden',
				'display': 'none'
			});
			$( divList ).css({
				'visibility': 'hidden',
				'display': 'none'
			});
		}
		
		t++;
	}
}



BROOK.SwitchTabs = function(tabs) {

	var $tabIds = $(tabs + ' a');
	if ($tabIds.length > 1) {
		$(tabs).each(function(i) {
			var $tab = $(this);
			var $tabId = $tab.find('a').attr('href').split('#')[1];

			$tab.click(function(e) {
				e.preventDefault();
				chooseTabs($tabId);
				$(this).siblings('li').removeClass('active');
				$(this).addClass('active');
			});

			if ($(this).hasClass('active')) {
				$('#' + $tabId).addClass('activetab');
			}
			else {
				$('#' + $tabId).removeClass('activetab');
			}
		});
	}
	else {
		$tabIds.eq(0).click(function(e) {
			e.preventDefault();
		});
	}

	function chooseTabs(tab) {
		$tabIds.each(function() {
			var theTab = $(this).attr('href').split('#')[1];
			$('#' + theTab).removeClass('activetab');
			if (tab == theTab) {
				$('#' + tab).addClass('activetab');
			}
		});
	}

}


BROOK.OtherMediaNav = function() {
	var $otherMediaItems = $( '.mm-othermedia .mm-tabcontent' );
	var $otherMediaItemsLen = $otherMediaItems.length;
	
	$otherMediaItems.each( function() {
		var $otherMediaItem = $(this);
		var $indivMediaItems = $otherMediaItem.find( 'div.mm-item' );
		if( $indivMediaItems.length > 3 ) {
			$indivMediaItems.each( function(i) {
				$(this).attr('id', 'mm-item-' + $otherMediaItem.attr('id') + '-' + i );
			});
			new BROOK.OtherMedia( config = {
				'otherMediaId': $otherMediaItem.attr('id'),
				'mediaItems': $indivMediaItems,
				'mediaLength': $indivMediaItems.length
			} );
		}
	});
	
};


/* Other Media Items Controls */
BROOK.OtherMedia = function( config ) {

	var config = {
		'otherMediaId': config.otherMediaId || null,
		'mediaItems': config.mediaItems || null,
		'mediaLength': config.mediaLength || 0,
		'lower': config.lower || 0,
		'upper': config.upper || 2,
		'prevId': config.prevId || 'mm-pager-prev-' + config.otherMediaId,
		'nextId': config.nextId || 'mm-pager-next-' + config.otherMediaId
	};
	
	var self = this;
	if( config.mediaLength > 3 ) {
		self.startOtherMedia( config );
	}

};

BROOK.OtherMedia.prototype = {

	startOtherMedia: function( config ) {
		var self=this;
		var i = config.mediaLength;
		while( i > 2 ) {
			$( '#mm-item-' + config.otherMediaId + '-' + i ).css( 'display', 'none' );
			i--;
		}
		
		if( config.mediaLength > 3 ) {
			self.buildPagers( config );
		}
	},
	
	buildPagers: function( config ) {
		var self=this;
		var navContainer = $( '.mm-othermedia #' + config.otherMediaId );
		var navItems = '<div class="mm-pager mm-pager-prev"><a href="#prev" title="Previous" id="' + config.prevId + '"><span>&lt;</span></a></div><div class="mm-pager mm-pager-next"><a href="#next" title="Next" id="' + config.nextId + '"><span>&gt;</span></a></div>';
		$( navContainer ).append( navItems );
		
		self.showButtons( config );
	},
	
	showButtons: function( config ) {
		var self=this;
		
		// nav items
		var $backBtn = $( '#' + config.prevId ).unbind( 'click' );
		var $forwBtn = $( '#' + config.nextId ).unbind( 'click' );
		
		$backBtn.click( function(e) {
			e.preventDefault();
			if( config.lower != 0 ) {
				self.otherMediaUpdate( config, -1 );
			}
		});
		
		$forwBtn.click( function(e) {
			e.preventDefault();
			if( config.upper != (config.mediaLength - 1) ) {
				self.otherMediaUpdate( config, 1 );
			}
		});
		
		// if we're at the beginning or end of the list, show/hide arrows as necessary
		config.lower === 0 ? $backBtn.hide() : $backBtn.show();
		config.upper === config.mediaLength - 1 ? $forwBtn.hide() : $forwBtn.show();
	},
	
	otherMediaUpdate: function( config, offset ) {
		var self=this;
		config.lower = config.lower + offset;
		config.upper = config.lower + 2;
		
		if( config.upper < config.mediaLength - 1 ) {
			if( config.lower < 0 ) {
				config.lower = 0;
				config.upper = 2;
			}
		}
		else {
			config.upper = config.mediaLength - 1 ;
			config.lower = config.upper - 2;
		}
		
		// change spotlights and update nav
		self.switchItems( config );
		self.showButtons( config );
	},
	
	switchItems: function( config ) {
		$( '#' + config.otherMediaId + ' .mm-item' ).css( 'display', 'none' );
		for( var i = config.lower; i <= config.upper; i++ ) {
			$( '#mm-item-' + config.otherMediaId + '-' + i ).css( 'display', 'block' );
		}
	}
	
};



BROOK.MultimediaFind = function(c) {

	var $moreOptionsLnk = $(c + ' .more-options a');
	var $moreOptionsBox = $(c + ' .more-options-list');
	var $findSelects = $(c + ' select');

	$moreOptionsLnk.toggle(
		function() {
			$(this).addClass('open');
			$(this).text('Fewer Options');
			$moreOptionsBox.addClass('more-options-list-open');
		},
		function() {
			$(this).removeClass('open');
			$(this).text('More Options');
			$moreOptionsBox.removeClass('more-options-list-open');
		}
	);

	$moreOptionsBox.find('a').click(function(e) {
		e.preventDefault();
		var $optionBoxLnk = $(this);
		var url = $optionBoxLnk.attr('href').split('#')[1];
		if (url) {
			BROOK.openOverlay(url);
		}
	});

	$findSelects.bind('change', function(e) {
		e.preventDefault();
		var $select = $(this);
		var selectVal = $select.val();
		if (selectVal == 'all-topics') {
			BROOK.openOverlay(selectVal);
		}
		else if (selectVal != null && selectVal.length > 0) {
			document.location.href = selectVal;
		}
	});

};



BROOK.openOverlay = function(url) {

	if (url) {
		url = '#' + url;
		if ($(url).length != 0) {
			$('<div id="overlay"><div id="overlay-wrapper"><a href="#" class="overlay-close">Close</a></div></div><div id="mask"></div>').appendTo('body');
			var ol = $('#overlay .overlay-close');
			$('#overlay .overlay-close').click(function(e) {
				e.preventDefault();
				$('#overlay, #mask').remove();
				if( $.browser.msie && $.browser.version < 9 ) {
					BROOK.IframeShimRemove();
				}
				$('html, body').animate({ scrollTop: $('html').offset().top }, 100);
			});

			var overlayContent = $(url).html();
			var overlayWrapper = $(overlayContent).css('display', 'block');
			$(overlayWrapper).appendTo('#overlay-wrapper');
			
			var bodyHeight = $('body').height();
			var bodyWidth = $('body').width();
			var overlayHeight = $('#overlay-wrapper' ).height();
			var overlayWidth = $('#overlay-wrapper' ).width();
			var maskHeight = ( bodyHeight >= overlayHeight ) ? bodyHeight : overlayHeight;
			var maskWidth = ( bodyWidth >= overlayWidth ) ? bodyWidth : overlayWidth;
			$( "#mask" ).css({
				'height': maskHeight+123,
				'width': maskWidth
			});
			if( $.browser.msie && $.browser.version < 9 ) {
				BROOK.IframeShimAdd(maskHeight, maskWidth);
			}
			$('html, body').animate({ scrollTop: $('html').offset().top }, 10);
		}
	}

};



BROOK.IframeShimAdd = function(h, w) {
	// creating an iFrame shim for IE8 or less
	var frameHeight = h;
	var frameWidth = w;
	var iframeShim = '<iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="0" src="#" class="iframeshim" style="width:' + frameWidth + 'px; height:' + frameHeight + 'px"></iframe>';
	$( iframeShim ).insertBefore( '#mask' );
};

BROOK.IframeShimRemove = function() {
	$( 'iframe.iframeshim' ).remove();
};



$(document).ready(function() {
	
	$( 'body' ).addClass( 'has-js' );
	
	var placeholders = new BROOK.Placeholder();
	var fontsizer = new BROOK.Fontsizer();
	var flavors = new BROOK.Flavors();
	
	var personalized = new BROOK.Personalizer( config = { 't': 'personalized' } );
	var myp = new BROOK.MypSections( config = { 't': 'myp' } );
	
	if ($('.mm-find')) {
		BROOK.MultimediaFind('.mm-find');
	}

	if ($('.mm-othermedia .tabs li')) {
		BROOK.SwitchTabs('.mm-othermedia .tabs li');
		BROOK.OtherMediaNav();
	}	
	
});


