var scrollbar;
var redirect = '';

var switchpics = function()
{
	$$('.switch-pics').each( function(el) {
		el.observe('click', function(e) { 
			var pos = (parseInt( e.findElement('a').id.replace('switch-', '') ) * -157) + 'px';
			$$('.polaroid img').each( function( p ) {
				p.style.backgroundPosition = pos + " top";
			} );
			
			e.stop();
		}, false);
	} );	
}
	
var polaroidWidth;
var polaroidLinks;
var polaroidSurround;
var polaroidElem = false;
var personInfoBlock = false;
var polaroidPos = false;
var curpos;

var polaroids = function()
{
	if($('polaroids_content') && $('polaroids_track'))
	{
		scrollbar = new Control.ScrollBar('polaroids_content','polaroids_track', { slider_options: { axis: 'horizontal' } });

		polaroidLinks = $$('div.polaroid').length;
		polaroidSurround = scrollbar.container.down('div');
		polaroidWidth = $$('div.polaroid').first().getWidth();
		
		if($('polaroids_track'))
		{
			var left_img = new Element('img', { src : '/staticfiles/img/arrow-left.gif', alt : 'Left Handle', 'class' : 'scroll-handle', id : 'left-scroll-handle'});
			var right_img = new Element('img', { src : '/staticfiles/img/arrow-right.gif', alt : 'Right Handle', 'class' : 'scroll-handle', id : 'right-scroll-handle'});

			left_img.observe('click', function( el ) { scrollbar.scrollBy(-25); } );
			right_img.observe('click', function( el ) { scrollbar.scrollBy(25); } );

			$('polaroids_track').insert( { before : left_img } );
			$('polaroids_track').insert( { after : right_img });		
			show_arrows(scrollbar);
		}
		
		scrollbar.container.style.width = scrollbar.container.getWidth() + 1 + 'px';
		scrollbar.recalculateLayout();
				
		document.observe('personLink:click', personLink, false);
		$$('.person-link').each( function(el) {
			el.observe('click', function(e) {
				polaroidElem = e.findElement('a');
				var id = 'person-' + polaroidElem.id.split('-').last();
				polaroidElem = $(id);
				document.fire('personLink:click');
				e.stop();
			}, false);
		} );
		
		if($$('.plugPanel-subbox').length > 0)
		{
			polaroidElem = $('person-0');
			document.fire('personLink:click');
		}
	}
}

var show_arrows = function(scrollbar)
{
	$$('.scroll-handle').each(function(el)
	{
		if(scrollbar.container.getWidth() >= polaroidSurround.getWidth())
		{
			el.hide();
		}
		else
		{
			el.show();
		}
	});	
}
var personLink = function( e )
{
	// stop observing the clicks
	document.stopObserving('personLink:click');

	// if there is a personInfoBlock, close it
	document.observe('personInfoBlock:closed', personInfoBlock_closed, false);
	closeInfoBlock();
}

var personInfoBlock_closed = function( e )
{
	// get the position number of the previous polaroid
	prev = (typeof(e.memo.previous) == 'string') ? parseInt(e.memo.previous) : -1;

	// get the position number of the new polaroid
	pos = parseInt(polaroidElem.id.split('-').last());
	
	// reset the image position
	$$('div.polaroid a img').each( function( im ) { im.style.backgroundPosition = '0 0'; } );
	
	// if the new polaroid is different, open the new one
	if(prev != pos)
	{
		// create a new block of content and give it zero width
		personInfoBlock = new Element('div', { 'class': 'dbl-polaroid', 'id': 'person-info-block-'+pos } ).update( '<div>' + $("person-info-"+pos).innerHTML + '</div>');
		personInfoBlock.style.width = 0;
	
		// if in the info can display to the right, do that
		var cp = (pos * polaroidWidth);
		var n = (polaroidLinks * polaroidWidth);
		var t = ( (n-cp) > scrollbar.container.getWidth() );
		
		if(t || pos < 3)
		{
			curpos = (pos * polaroidWidth);
			polaroidElem.up('div.polaroid').insert( { after: personInfoBlock } );
		}
		else // otherwise display to the left
		{
			curpos = ((pos - 2) * polaroidWidth);
			polaroidElem.up('div.polaroid').insert( { before: personInfoBlock } );
		}

		// observe the infoblock opened event, and animate the opening
		document.observe('personInfoBlock:opened', personInfoBlock_opened, false);
		openInfoBlock();		
	}
	else // otherwise just leave it closed
	{
		// reset the click link action
		document.observe('personLink:click', personLink, false);
	}
}

var personInfoBlock_opened = function()
{
	// set the position of the polaroid bg-image
	polaroidElem.down('img').style.backgroundPosition = '0 -157px';
	
	// scroll to ensure polaroid is showing
	scrollbar.scrollTo( curpos, true );
	
	// set up the close event
	personInfoBlock.down('a.person-info-close').observe( 'click', function(ev) {
		closeInfoBlock();
	} );
	
	// reset the click link action
	document.observe('personLink:click', personLink, false);
}

// animate opening the info block
var openInfoBlock = function()
{
	var n = 20;
	var t = (polaroidWidth * 2) / n;
	var i = 0;

	new PeriodicalExecuter( function(pe) {
		polaroidSurround.style.width = ((polaroidLinks * polaroidWidth) + (i * n)) + 3 + 'px';
		scrollbar.recalculateLayout();
		
		show_arrows(scrollbar);

		personInfoBlock.style.width = (i * n) + 'px';

		i++;
		if(i == (t+1) )
		{
			document.fire('personInfoBlock:opened');
			document.stopObserving('personInfoBlock:opened');
			pe.stop();
		}
	}, 0.005 );
}

var closeInfoBlock = function()
{
	// if there is a personInfoBlock, close it
	if(personInfoBlock != false)
	{
		previous = personInfoBlock.id.split('-').last();

		var n = 20;
		var t = (polaroidWidth * 2) / n;
		var i = 0;

		new PeriodicalExecuter( function(pe) {
			var w = ((polaroidWidth * 2) - (i * n));
			
			personInfoBlock.style.width = w + 'px';

			polaroidSurround.style.width = ((polaroidLinks * polaroidWidth) + w) + 3 + 'px';
			scrollbar.recalculateLayout();
			
			show_arrows(scrollbar);
			
			i++;
			if(i == (t+1))
			{
				personInfoBlock.remove();
				personInfoBlock = false;
				
				document.fire('personInfoBlock:closed', { 'previous': previous } );
				document.stopObserving('personInfoBlock:closed');
				pe.stop();
			}
		}, 0.005 );
	}
	else
	{
		document.fire('personInfoBlock:closed');
		document.stopObserving('personInfoBlock:closed');
	}
}

var servicesmore = function()
{
	$$('.services-readmore').each( function(el) {
		el.observe('click', function(e) {
			var elem = e.findElement('a');
			elem.up('p').next('div.services-more').show();
			elem.up('p').hide();
			elem.up('p').next('div.services-more').down('a.services-readless').observe('click', function (ev) {
				var readless = ev.findElement('a');
				readless.up('div.services-more').hide();
				readless.up('div.services-more').previous('p').show();
			} );
			
			e.stop();
		});
	});
}

var bannersmore = function()
{
	$$('.banners-more').each( function(el) {
		el.observe('click', function (e) {
			var href = e.findElement('a').href.split('#').last();
			if($(href))
			{
				$$('.banner-copy-block').each( function(bcb) { bcb.hide(); } );
				$(href).show();
			}
		}, false);
	} );
}

var modal_window = function(){
	$$('a.download-popup').each( function(el) {
		el.stopObserving('click');
		el.observe('click', function( e ) {
			
			new Ajax.Request('/download_research/check_session', {
			  onSuccess: function(response) {

				if (response.responseText == '1') 
				{
					var link_arr = el.href.split('/');
					location.href = '/research/download/' + link_arr[link_arr.length - 1];
					return;
				}
				else
				{
					var cname = (el.className.indexOf('modallink-') != -1)?' '+get_classname(el, 'modallink-', 'modal-'):'';

					mod = window_factory( el, {iframe: true, className: 'modal'+cname} );
					mod.open();
					
				}
			  }
			});
			
			

			e.stop();
		}, false);
	});
}

var window_factory = function(container,options) {  
	
	var window_fade = $('control_overlay');
	
    var window_header = new Element('div',{  
        className: 'window_header'  
    });           
	window_header.update('<h3>A little information please</h3>');
    var window_close = new Element('div',{  
        className: 'window_close'  
    });                                    
    var window_contents = new Element('div',{  
        className: 'window_contents'  
    });	
	var window_loading = new Element('div',{
		className: 'window_loading'
	});
	
    var w = new Control.Modal(container,Object.extend({  
        className: 'modal',
  		fade: true,
		overlayOpacity: 0.75,
   		closeOnClick: window_fade,
        insertRemoteContentAt: window_contents,
  		afterClose: function() { 
			var id = this.container.id;
			this.destroy();
			$(id).remove();
			if(String(redirect).length > 0)
			{
				window.location = redirect;
			}
		},
		indicator: window_loading
    },options || {}));  
	w.container.insert(window_loading);
    window_header.down('h3').insert({top:window_close} ); 
    w.container.insert(window_header);   
                        
    w.container.insert(window_contents);
  	window_close.observe('click', function(e){
	    Control.Modal.close();
		e.stop();
	}, false);
    return w;  
};

function externalLinks() { $$('a').each( function(el) { if(el.getAttribute("href") && el.getAttribute("rel") == "external") { el.target="_blank"; } } ); }
function internalLinks() { $$('a').each( function(el) { if(el.getAttribute("href") && el.getAttribute("rel") == "internal") { el.target="_self"; } } ); }

document.observe('dom:loaded', bannersmore, false);
document.observe('dom:loaded', servicesmore, false);
document.observe('dom:loaded', switchpics, false);
document.observe('dom:loaded', polaroids, false);
document.observe('dom:loaded', externalLinks);
document.observe('dom:loaded', internalLinks);
document.observe('dom:loaded', modal_window);