var FrontPage = {

	activeSlide: 0,
	loopCheck: 0,
	maxLoops: 251,		// 250 * 3.6 seconds = 900 seconds = 15 minutes + 1 to end on the first frame
	SLIDESHOWDURATION: 4000,

	makeDots: function(){
		var thisParent = this;
		slideShowElement = jQuery.map( slideshow.slice(0,8), function( theImg ) {
			var i = jQuery( '<img src="' + theImg.imgUrl + '" />')
			if ( theImg.linkUrl )
				i.wrap( '<a href="' + theImg.linkUrl + '"/>');
			return i;
		});

		this.topImage = new ImageSwap('.topimg img');
		jQuery('.topimg').eq(0).hide().css('visibility', 'visible').fadeIn(1000);

		// add a link to the top image if there isn't one already
		this.topLink = jQuery('.topimg a');
		if ( this.topLink.length < 1 )
			this.topLink = this.topImage.img.wrap( '<a href="' + slideshow[0].linkUrl + '"/>').parent()

		jQuery(slideShowElement).each( function( slideShowIndex, slideShowItem ) {
			var dotBox = jQuery('<div class="dot_off">').fadeTo(0,0).appendTo('#dotdiv');

			// attach relevant element, image and link info for later on
			dotBox.data('img',slideShowElement[ slideShowIndex ] );
			dotBox.data('imgUrl', slideshow[ slideShowIndex ].imgUrl );
			dotBox.data('linkUrl', slideshow[ slideShowIndex ].linkUrl );

			dotBox.hover(function() { thisParent.dotOn(dotBox); }, function() { thisParent.dotsOff(); });
			dotBox.click(function() { thisParent.loopCheck = 0; thisParent.dotClicked( dotBox ); }); // reset loopCheck on click)

			(function() { dotBox.animate( { opacity: 0}, {duration: 1500 - 150 * slideShowIndex} ).animate( { opacity: 0.5}, 1000)}) ();

		})

		this.playSlideshow()
	},


	dotsOff: function(onDot){	// removes the hover state and fades all dots out if not .dot_on
		if (!onDot); onDot = jQuery('.dot_hover');
		jQuery('.dot_hover').not('.dot_on').stop(true).removeClass('dot_hover').animate( {opacity: 0.5 }, {queue: false, duration: 270} );
	},

	dotOn: function(onDot){ // fades a dot up
		onDot.addClass('dot_hover');
		onDot.stop().animate( { opacity: 1 }, { queue: false, duration: 150 });
	},

	dotClicked: function(clickDot){
		// jQuery('#dotdiv div.dot_on').removeClass('dot_on').addClass('dot_off');
		clickDot.siblings('.dot_on').removeClass('dot_on').addClass('dot_off');
		clickDot.addClass('dot_on').removeClass('dot_off'); // sets the dot to the clicked-state, red background
		this.dotsOff()
		this.dotOn(clickDot);

		if ( clickDot.parent().is('#dotdiv')) {
			this.playSlideshow();
			this.topLink.attr('href', clickDot.data('linkUrl') );
			this.topImage.swap( clickDot.data('imgUrl') );
		} else if ( clickDot.parent().is('.navlinks')) {
			this.newsScroll(clickDot.data( 'showNews' ));
		}
	},

	playSlideshow: function(){
		var thisParent = this;
		window.clearTimeout( this.slideshowPlaying );
		this.slideshowPlaying = window.setTimeout( function(){ thisParent.advanceSlideshow() }, thisParent.SLIDESHOWDURATION );
	},

	advanceSlideshow: function(){
		var clickMe, dotdiv = jQuery('#dotdiv');
		clickMe = jQuery('div.dot_on', dotdiv).next();
		if ( this.loopCheck++ < this.maxLoops ) {
			if ( clickMe.length > 0 ) {
				this.dotClicked( clickMe );
			} else {
				this.dotClicked( jQuery('div.dot_off', dotdiv).eq(0) );
			}
		}
	},

	makeTopNavLinks: function(){
		var bg, ie6Fix, topnav = jQuery('#topwide .nav');

		bg = jQuery('<div/>').addClass( 'navfader' ).css({'width': topnav.width(), 'height': topnav.height() }).insertBefore( topnav ).fadeTo(0, 0);

		topnav.hover(	function(){bg.animate( { opacity: 0.5 },  { queue:false, duration:333 }) },
						function(){bg.animate( { opacity: 0 },	{ queue:false, duration:667 }) } );

		jQuery('#topwide .nav ul').css({top: -25});

		ie6Fix = (jQuery('#topwide .nav ul').position().top == -25) ? 0 : -25;

		jQuery('#topwide .nav ul li').css( { marginTop: 0 + ie6Fix }).each( function(i){
				theLink = jQuery(this);
				( function() { theLink.animate({ marginTop: 0 + ie6Fix }, 1000 + 200 * ( i + 1 ) ).animate( { marginTop: 30 + ie6Fix },	{  duration: 500 }, 'linear') }) ();
		} );
	},

	newsScrollInit: function() {
		// insert buttons
		// add hover state which clears and restarts the timeout
		// call the setTimeout to trigger the animation

		var thisParent = this;
		jQuery('#bottomWideCenter').append('<div class="navlinks"></div>');
		jQuery('.homenews').each(function(i) {

					var dotBox = jQuery('<div class="dot_off">').fadeTo(0,0).appendTo('#bottomWideCenter .navlinks');

					dotBox.data('showNews', i );
					dotBox.hover( function() { thisParent.dotOn(dotBox); }, function() { thisParent.dotsOff( ); });
					dotBox.click( function() { thisParent.dotClicked( dotBox ); });
			})

		jQuery('#bottomWideCenter').hover(  function(){
				thisParent.doNews = false;
				window.clearTimeout( thisParent.newsScrolling );
			}, function() {
				thisParent.newsAdvance();
				thisParent.doNews = true;
			})
		this.newsScrollStart();

	},

	newsScrollStart: function() {
		var thisParent = this,
			clickThis = jQuery('#bottomWideCenter .navlinks .dot_on');

		if (clickThis.length < 1)
				clickThis = jQuery('#bottomWideCenter .navlinks .dot_off:last');

		jQuery('#bottomWideCenter .navlinks .dot_off').animate( {opacity: 0.5}, 1000 ).eq(0).animate( {opacity: 0.5}, 0, function() {
					thisParent.dotClicked( clickThis );
				})

		this.newsAdvance();
		thisParent.doNews = true;
	},

	newsAdvance: function() {
		var thisParent = this,
			clickMe = jQuery('#bottomWideCenter .navlinks .dot_on').prev();

		if ( thisParent.doNews && this.loopCheck < this.maxLoops ) {

			if ( clickMe.length > 0 ) {
				this.dotClicked( clickMe );
			} else {
				this.dotClicked( jQuery('.navlinks .dot_off').eq( jQuery('.navlinks .dot_off').length - 1 ) );
			}
		}
		window.clearTimeout(thisParent.newsScrolling);
		thisParent.newsScrolling = window.setTimeout( function(){ thisParent.newsAdvance() }, thisParent.SLIDESHOWDURATION * 2);
	},

	newsScroll: function(i) {
		var thisParent = this;

		var newsWidth = jQuery('#bottomWideCenter').innerWidth(),
			newScrollLeft; // = Math.ceil( jQuery('#newsscroller').parent().scrollLeft()/newsWidth + 6 ) % 5 * newsWidth; // 6 is number of news items + 1

		newScrollLeft = (4-i) * newsWidth * -1; // reversed since the items appear float: left
		jQuery('#newsscroller').animate( {marginLeft: newScrollLeft}, {queue: false, duration: 1250})
	}
}



var nav = {

	setupNavRollovers: function() {
		this.navDuration = 180;
		var theDur = this.navDuration,
			thisParent = this;

		jQuery('#nav ul li img').animate({opacity:1}, 0).parent().parent().not('.current_page_item').hover( function(){
			jQuery(this).find('img').css({visibility: 'visible'}).animate({opacity:0}, { duration: 100, queue: false });
		}, function(){
			jQuery(this).find('img').animate({opacity:1}, { duration: 500, queue: false });
		}).click(function() {
			jQuery(this).unbind('mouseenter mouseleave');
		})
	},
	
	setupAccordion: function() {
		var thisParent = this;
		jQuery('#subnav > ul > li > ul, #subnav > ul > li > ol').each(function(){
			jQuery(this).parent().children('a:first').addClass('nestHeader');
		})

		jQuery.ui.accordion.animations.slowSlide = function(options) {
			this.slide(options, {duration: 350});
		};

		jQuery('#subnav_ul').accordion({ 
				active: false,
				autoHeight: false,
				collapsible: true,
				navigation: true,
				animated: 'slowSlide',
				header: '.nestHeader',
				changestart: function(event, ui) {
					ui.oldContent.animate({opacity:0}, 400)
					ui.newContent.animate({opacity:1}, 400)
				},
				change: function() {
					thisParent.drawNavLines();
				}
		});
		this.drawNavLines()
	},
	
	navLinesDimensions: function() {
		var subnavBox, navBox,
			lineDims = {};
			
		subnavBox = jQuery('#subnav_ul');
		if (subnavBox.find('.current_page_item').length) {
			subnavBox = subnavBox.find('.current_page_item');
			if (subnavBox.parent().css('display') == 'none')
				subnavBox = jQuery('#subnav_ul').find('.current_page_parent');
		}
			
		navBox = jQuery('#nav');
		if (navBox.find('.current_page_item').length)
			navBox = navBox.find('.current_page_item');
		
		lineDims.top = subnavBox.position().top + subnavBox.height()/2;
		lineDims.height = navBox.offset().top - subnavBox.offset().top + navBox.height()/2 - subnavBox.height()/2;
		lineDims.left = jQuery('#nav').width();

		return lineDims;
	},

	drawNavLines: function() {
		var navLines = jQuery('#navlines'),
			coords = this.navLinesDimensions();
			
		if (!navLines.length) { // navLines doesn't exist yet, create it and set the intial dimensions immediately
			navLines = jQuery('<div id="navlines" style="left:' + jQuery('#nav').width() + 'px"></div>').insertAfter('#nav');
			navLines.css(this.navLinesDimensions())
		}
		navLines.animate(coords, 50);
	},


	contactMapPopUps: function() {
		jQuery('#contactMap #prg_locations div a').qtip({
				position: {corner: {target: 'center', tooltip: 'topLeft'}},
				style: {
					background: '#fff',
					padding: '0 1.5em 2em 1.5em',
					width: 200,
					border: {width: 2, color: '#f00'},
					title: {background: '#fff', padding: '0 1em 0.5em 1em'},
					tip: {corner:'topLeft', size: {x: 8, y:8}}
				},
				tip: { size: { x: 12, y: 18 } },
				content: {title: { text: true, button: false}},
				show: {delay: 0, solo: true},
				hide: {delay: 500, fixed: true, effect:{length:333}},
				api:{
					onRender: function(){
						var self=this;
						this.updateTitle( this.elements.content.html().split('|')[0] );
						this.updateContent( this.elements.content.html().split('|')[1]  + '<br />Click for more <a href="' + this.elements.target.attr('href') + '">about this office</a>.');
						this.elements.tip.click(function(){window.location = self.elements.target.attr('href')})
					}
				}
		});
	},


	frameImages: function() {
		/*
		   TODO This can be removed, but it will require checking all existing content for "align=right" attributes...
		*/
		jQuery('#bigbox img[align=right]').addClass('frameImageRight');
		jQuery('#bigbox img[align=left]').addClass('frameImageLeft');
	},


	insertSWFObject: function(container, videoFile){

		var w = jQuery('#'+container).width(),
			h = jQuery('#'+container).height(),
		
			flashvars = {	file: videoFile, 
							overstretch: false,
							bufferlength: 10,
							autostart: true,
							usefullscreen: false,
							displayheight: h
						},
			params = {	allowfullscreen: false,
						allowscriptaccess: true
					 }
					
		if(videoFile.toLowerCase().substring(videoFile.length-3) == 'flv')
			videoFile = "/swf/flvplayer.swf";	// specify the flvplayer if there's an FLV file
							
		swfobject.embedSWF(videoFile, container, w, h, '9.0.0', '/swf/expressInstall.swf', flashvars, params, {});
	},


	resizeLocationSidebar: function(){
		var bbperson = jQuery('#bigbox .person'),
			blockHeight = 180;
		if (jQuery.support.boxModel) blockHeight += 10; // fudge the size a bit to prevent bad wraps in IE
		if (bbperson){
			jQuery('#locationSidebar').height( Math.ceil(jQuery('#locationSidebar').height() / bbperson.height() ) * 180 )
		}
	},

	toggleSection: function() {
		jQuery('.toggleSection .toggleThis').hide()
		jQuery('.toggleSection .toggleTrigger').toggle(
			function(){console.log('clicked on'); jQuery(this).parent().find('.toggleThis').slideDown('slow');},
			function(){console.log('clicked off'); jQuery(this).parent().find('.toggleThis').slideUp('slow');})
	},


	formatProductListings: function(){
		var products = jQuery('#resource-links img, #productpartners img');
		if ( products.length > 0 ) {
		products.removeClass('frameImageLeft').css('float', 'none').removeAttr('align');
		products.each( function() {
				if ( jQuery(this).width() > 180 || jQuery(this).height() > 180 ) {
					if ( jQuery(this).width() / jQuery(this).height() > 1 ) {
						jQuery(this).css( 'width', 180 );
					} else {
						jQuery(this).css( 'height', 180 );
					}
				}
			})
		jQuery('#resource-links p, #productpartners p').append('<br style="clear: both" />')
		products.wrap('<div class="thumb"/>');
		}
	},


	protectEmailLinks: function(){
		var d = document.links;
		for(i=0;i<d.length;i++){
			if(d[i].protocol == 'mailto:'){
				d[i].href = d[i].href.replace(/^(mailto:[^+]+)\+([^+]+)(?:\+|\.)?([^+?]+)?/,'$1@$2.$3').replace(/\.$/,'')
				if (d[i].childNodes.length==0) // add email address to no-text links
					d[i].appendChild(document.createTextNode(d[i].href.substring(7)));
			}
		};
	},

	initialize: function(){
		jQuery('.js').removeClass('js'); // remove the js class now that we're loaded		
		if ( jQuery('#subnav').length ) this.setupAccordion();

		this.setupNavRollovers();

		if ( jQuery('#topwide').length ) {
			FrontPage.makeTopNavLinks();
			FrontPage.makeDots();
		}

		this.protectEmailLinks();

		if ( jQuery('#bigbox').length ) this.frameImages();
		if (jQuery('#contactMap').length) this.contactMapPopUps();

		this.formatProductListings();
		
		if ( jQuery('.homenews').length ) {
			FrontPage.newsScrollInit()
		}
		if (jQuery('.toggleSection').length ){
			this.toggleSection();
		}
	}
},

ImageSwap = function(imgElement, options){
	this.img = jQuery(imgElement);
	this.wrapper = ( this.img.parent().is('a') ) ? this.img.parent() : this.img;
	this.wrapper = this.wrapper.wrap('<div style="position: relative;" />');
	if ( this.wrapper.is('img') ) this.wrapper = this.wrapper.parent();	// if it's an image return the parent, if it's whatever is containing the img, leave it
	this.options = { duration: 1500 };	// default options
	jQuery.extend( this.options, options ); // overwrite default options with input options

	this.swap = function(newImageUrl) {
		var thisParent = this,
		newImage = this.img.clone(true);

		newImage.css({'top': 0, 'left': 0, 'position': 'absolute', 'display': 'none' });	// float the replacement over the top of the old image;

		newImage.hide().load( function() {
									thisParent.wrapper.append(newImage);
									newImage.fadeIn(thisParent.options.duration, function() {
												/*
												thisParent.img.attr( 'src', newImage.attr('src') );
												newImage.remove();
												*/
												newImage.prev().remove();
											});
									});
		newImage.attr('src', ( ( typeof( newImageUrl ) == 'string') ? newImageUrl : newImageUrl.src ) );	// check replacement for element or string, match src attribute
	}
}


jQuery(function(){nav.initialize()})

