
var iop = {
	init: function() {
		var thisParent = this;


		if (jQuery('.workset').length) { 
			this.insert_workset_controls();
			this.scrollToLinks();
			this.highlightLinksOnScroll();
			this.addWorkShim();
		}

		this.protectEmailLinks();

		jQuery(window).scroll(function(){ thisParent.highlightLinksOnScroll(); });

		if (jQuery('.slides').length) { 
			this.showNext(); 
			jQuery('html').keydown(function(e) {
				if (e.keyCode == '39') { // right arrow
					thisParent.showNext();
				}})
		}
		if (jQuery().columnize) { 
			jQuery('.columns').each(function(){
				var h = jQuery(this).height(),
					lh = parseInt(jQuery(this).css('line-height'), 10);
				jQuery(this).columnize({columns: 2, balance: true,  minHeight: (h / lh + 2.7) * lh, height: (h / lh + 4) * lh });
			});
		}

		jQuery('.target-blank, #news .firstcolumn a').attr('target', '_blank '); // bringing this into XHTML validity
	},

	insert_workset_controls: function(){
			var thisParent = this;
			// set up workset offsets:
			jQuery('.workset').each(function(){

				// resize containing boxes to fit contents
				var newWidth = jQuery(this).find('.item').length * jQuery(this).width();

				if (newWidth > jQuery(this).width() ) {
					jQuery(this).find('ul').addClass('count'+jQuery(this).find('.item').length).wrap("<div style='overflow:hidden'></div>");
					jQuery('<div class="prev"><div class="bg"></div><a href="" class="prev"></a></div>'+
						   '<div class="next"><div class="bg"></div><a href="" class="next"></a></div>')
						.appendTo(this);
					jQuery(this).hover(
						function(){thisParent.hide_buttons(jQuery(this).addClass('on'))},
						function(){thisParent.fade_workset_arrows(jQuery(this).removeClass('on'), 'hide');}
					);
					jQuery(this).after('<div class="worksetcontrols">'+
									   '<a href="#prev" class="prev" title="Previous">Previous</a>'+
									   '<a href="#next" class="next" title="Next">Next</a>'+
									   '<div class="status"><span class="active">1</span> / '+jQuery(this).find('.item').length+'</div>'+
									   '<div class="caption">'+jQuery(this).find('img').eq(0).attr('alt')+'</div>'+
									   '</div>');
					jQuery(this).parent().find('.worksetcontrols a.prev').css({'opacity': 0.5});
					jQuery(this).find('.bg').css({'opacity': 0}).next().css({'opacity': 0});
				}

				jQuery(this).data('index', 0);
			});

			jQuery('a.next, a.prev').click(function(){
				var x, scrollBox;
				if (jQuery(this).parent().is('.worksetcontrols')) {
					scrollBox = jQuery(this).parent().prev();
				} else{
					scrollBox = jQuery(this).parents('.workset');
				}
				x = scrollBox.data('index');
				x = (jQuery(this).hasClass('next')) ? x + 1 : x - 1;
				if ( x >= 0 && x < scrollBox.find('.item').length) {
					scrollBox.next().find('.status .active').text(x+1);
					scrollBox.next().find('.caption').fadeOut(75, function(){
						jQuery(this).text(scrollBox.find('img').eq(x).attr('alt'));
					}).delay(75).fadeIn(150);
					
					speedAdjuster = Math.abs( - x * scrollBox.width() - parseFloat(scrollBox.children().eq(0).css('margin-left'))) / scrollBox.width();
					scrollBox.children().eq(0).stop().animate({marginLeft: -x * scrollBox.width()}, {queue: false, duration: speedAdjuster * 600});
					scrollBox.data('index', x);
					thisParent.hide_buttons(scrollBox);
				}
				if (!jQuery.support.cssFloat) { this.blur(); }
				return false;
			});
			if ( typeof document['ontouchstart'] != 'undefined') {
					jQuery('.workset .next, .workset .prev').hide();
					jQuery('.workset li.item img').each(function(i,e){
						jQuery(e).detectFlicks({
							axis: 'x',
							threshold: 50,
							flickEvent: function(d) {
									if (d.direction == 'left2right') {
											jQuery(e).parents('.workset').find('.prev').click();
										} else {
											jQuery(e).parents('.workset').find('.next').click();
										}
									}
						});
				})
			}
	},

	hide_buttons : function(scrollBox){
		var containers = scrollBox.add(scrollBox.next());
		if (scrollBox.data('index') == scrollBox.find('.item').length -1) {
			this.fade_workset_arrows(jQuery(containers.find('.next')), 'hide');
			this.fade_workset_arrows(jQuery(containers.find('.prev')), 'show');
		} else if (scrollBox.data('index') === 0 ) {
			this.fade_workset_arrows(jQuery(containers.find('.prev')), 'hide');
			this.fade_workset_arrows(jQuery(containers.find('.next')), 'show');
		} else {
			this.fade_workset_arrows(jQuery(containers.find('.prev, .next')), 'show');
		}
	},

	fade_workset_arrows: function(items, action) {
		if (action == 'hide') {
			items.filter('.worksetcontrols a').animate({'opacity': 0.5});
			items.find('.bg').animate({'opacity': 0}).next().animate({'opacity': 0},function(){items.addClass('hidden');});
		} else {
			items.removeClass('hidden');
			items.filter('.worksetcontrols a').animate({'opacity': 1});
			if (items.parent().is('.on')){
				items.find('.bg').animate({'opacity': 0.4}).next().animate({'opacity': 1});
			}
		}
	},


	scrollToLinks: function() {
		var thisParent = this;
		jQuery('#subnav a[href^="#"]').click(function(){
			jQuery('html, body').animate({'scrollTop': jQuery(jQuery(this).attr('href')).offset().top});
			return false;
		});
	}, 

	makeLinksActive: function(item) {
		jQuery('#subnav li.active').removeClass('active');
		jQuery(item).parent().addClass('active');
	},
	
	keydownHandler: function(item) {
		jQuery('html').unbind('keydown').keydown(function(e){
			if (e.keyCode == 39) {
				jQuery(item).find('a.next').eq(0).click()
			} else if (e.keyCode == 37) {
				jQuery(item).find('a.prev').eq(0).click()
			}
		})
	},

	highlightLinksOnScroll: function() {
		var thisParent = this;
		jQuery('.block').each(function(){
			if (jQuery(this).attr('id') && jQuery(this).position().top + jQuery(this).height() - jQuery(window).scrollTop() >= 0) {
				thisParent.makeLinksActive(jQuery('#subnav a[href$='+jQuery(this).attr('id')+']'));
				thisParent.keydownHandler(this)
				return false;	// bail out of the loop
			}
		});
	},

	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:([^+]+)\+([^+]+)(?:\+|\.)?([^+?]+)?/,'mailto:$1@$2.$3').replace(/\.$/,'');
				if (!d[i].childNodes.length) { // add email address to no-text links
					d[i].appendChild(document.createTextNode(d[i].href.substring(7)));
				}
			}
		}
	},


	// home page slideshow properties and functions
	SLIDE_SHOW_DURATION: 5500,
	LOOP_COUNT: 0,
	RESET_LOOP_AFTER: 10 * 60 * 1000,  // 10 minutes * 60 seconds * 1000 milliseconds

	showNext: function() {
		if (++this.LOOP_COUNT * this.SLIDE_SHOW_DURATION > this.RESET_LOOP_AFTER ) {
			window.location = window.location;
		}

		var thisParent = this;
		nextSlide = jQuery('.slides.on').next('.slides');
		if (nextSlide.length === 0) {
			nextSlide = jQuery('.slides:first');
		}
		jQuery('.slides.on').removeClass('on').fadeOut(400);
		nextSlide.addClass('on').children('a, h1').animate({opacity:0},0);
		nextSlide.show();
		nextSlide.find('h1').delay(200).animate({opacity:1},{queue: true, duration: 500});
		nextSlide.find('a').delay(500).animate({opacity:1},{ duration: 1000});

		window.clearTimeout( this.slideshowPlaying );
		this.slideshowPlaying = window.setTimeout( function(){ thisParent.showNext(); }, thisParent.SLIDE_SHOW_DURATION );
	},

	addWorkShim: function(){
		var shimHeight = jQuery(window).height() -
			jQuery('#header').outerHeight() -
			jQuery('.block:last-child').outerHeight() -
			jQuery('#footer').outerHeight() -
			parseInt(jQuery('#footer').css('margin-top'), 10);
		if (shimHeight > 0){
			jQuery('#footer').css('margin-bottom', shimHeight);
		}
	}
};

jQuery(function(){ iop.init(); });
