jQuery.fn.oTimeline = function(settings) {
    settings = jQuery.extend({
        easeFunc: 'easeOutQuad',
        easeTime: 1000,
        toolTip: false,
        timelineControlSelector: 'ul.dates',
        timelinePanelsSelector: 'div.date'
    }, settings);
    
    function GetHash(str)
    {
        if (str.indexOf('#') > -1)
        {
            var segments = str.split('#');
            if (segments.length > 1)
            {
                return segments[1];
            }
            return segments[0];
        }
        return '';
    }
    
	return this.each(function() {
		var container = jQuery(this);
		var origControls = container.find(settings.timelineControlSelector);
		var origPanels = container.find(settings.timelinePanelsSelector);
		
		if (origPanels.length > 0)
		{
		    //Add a class so we can figure out in css if this element has been changed via this script
		    container.addClass('oTimeline');
		    
		    //Get the timeline panels and some basic info
		    var panelWidth = jQuery(origPanels[0]).outerWidth(true);
		    var panelHeight = jQuery(origPanels[0]).outerHeight(true);
		    var panelCount = origPanels.length;
		    var totalPanelWidth = panelWidth*panelCount;
    		
    		//Set up our panel area
		    var panels = origPanels.clone();
		    panels.each(function(){
		        $(this).find('p.toTop').remove();
		    });
    		var panelViewPort = jQuery('<div class="panelViewPort"></div>').css('width', panelWidth).css('height', panelHeight);    		    		
		    var panelsContainer = jQuery('<div class="panelsContainer"></div>').css('width', totalPanelWidth).css('height', panelHeight).append(panels);
		    origPanels.remove();		    
		    panelViewPort.append(panelsContainer);
		    container.prepend(panelViewPort);
		    
		    //Set up the timeline controls
		    var controls = origControls.clone();
		    controls.find('li:first a').addClass('selected');		    
		    controls.find('li a').each(function(){
		        var controlLink = jQuery(this);
		        controlLink.click(function(){
		            return MoveTimeline($(this));
		        });
		    });
		    var totalControlsWidth = 0;
		    origControls.find('li').each(function(){
		        totalControlsWidth += jQuery(this).outerWidth(true);
		    });
		    var controlsWidth = panelWidth;
		    var controlsHeight = origControls.outerHeight(true);
    		var controlsViewPort = jQuery('<div class="controlsViewPort"></div>').css('width', controlsWidth).css('height', controlsHeight);
		    controls.css('width', totalControlsWidth).css('height', controlsHeight);
		    origControls.remove();		    
		    controlsViewPort.append(controls);
		    container.append(controlsViewPort);
		    
		    //Add some next and previous controls
		    var prevControl = jQuery('<div class="timelinePrev"><a href="#"><img src="/resources/images/history/timeline/timeline-left.gif" alt="Move the timeline to the previous entry" /></a></div>');
		    prevControl.find('a').click(function(){
		        var controlLinks = controls.find('a');
                var currentIndex = controlLinks.index(controls.find('a.selected'));
                if (currentIndex > 0)
                {
                    var prevLink = jQuery(controlLinks[currentIndex - 1]);
		            return MoveTimeline(prevLink);
                }
                return false;
		    });
		    container.append(prevControl);
		    
		    var nextControl = jQuery('<div class="timelineNext"><a href="#"><img src="/resources/images/history/timeline/timeline-right.gif" alt="Move the timeline to the next entry" /></a></div>');
		    nextControl.find('a').click(function(){
		        var controlLinks = controls.find('a');
                var currentIndex = controlLinks.index(controls.find('a.selected'));
                if (currentIndex < panelCount - 1)
                {
                    var nextLink = jQuery(controlLinks[currentIndex + 1]);
		            return MoveTimeline(nextLink);
                }
                return false;
		    });
		    container.append(nextControl);
    
            //Call this to move the timeline around
            function MoveTimeline(selectedLink)
            {
                //See if the selected link has a hash (it should!)
                var hash = GetHash(selectedLink.attr('href'));
                if (hash.length > 0)
                {
                    //Find the corresponding panel
                    var panelIndex = panels.index(jQuery('#' + hash));
                    if (panelIndex > -1)
                    {
                        //Move the panel container to the appropriate panel
                        var leftPos = -(panelWidth*panelIndex);
                        panelsContainer.stop();
                        panelsContainer.animate({ left: leftPos}, settings.easeTime, settings.easeFunc);
                    }
                        
                    //Move the controls as well
                    var controlItems = controls.find('li');
                    var controlIndex = controlItems.index(selectedLink.parent());
                    if (controlIndex > -1)
                    {              
                        var controlItem = jQuery(controlItems[controlIndex]);  
                        var pos = controlItem.position();      
                        var controlsCenter = controlsWidth/2;
                        var controlItemCenterPos = pos.left + (controlItem.outerWidth(true)/2);
                        var maxLeft = -totalControlsWidth + controlsWidth;
                                              
                        var leftPos = 0;
                        //If the selected control item is past the centre point of the viewport, scroll it
                        if (controlItemCenterPos > controlsCenter)
                        {
                            leftPos = controlsCenter - controlItemCenterPos;            
                        }
                        //If the left position will move the controls past the right hand edge of the viewport, don't scroll
                        if (leftPos < maxLeft)
                        {
                            leftPos = maxLeft;
                        }
                        controls.stop();
                        controls.animate({ left: leftPos}, settings.easeTime, settings.easeFunc);
                    }
                        
                    //Set the css class so we know which has been selected
                    controls.find('a.selected').removeClass('selected');
                    selectedLink.addClass('selected');
                        
                    //We may need to hide either prev or next depending on where we are in the timeline
                    SetPrevNextControls();
                    
                    //Set the location so users can bookmark their point in the timeline
                    location.hash = 'timeline-' + hash;
                }
                return false;
            }
            
            function CheckLocation()
            {
                if (location.hash)
                {
                    var locHash = location.hash;
                    if (locHash.indexOf('timeline-') > -1)
                    {
                        locHash = locHash.replace('timeline-', '');
                    }
                    var link = controls.find('a[href=' + locHash + ']');
                    if (link.length > 0)
                    {
                        MoveTimeline(link);
                    }
                }
            }
            
            function SetPrevNextControls()
            {                
		        var controlLinks = controls.find('a');
                var currentIndex = controlLinks.index(controls.find('a.selected'));
                
                var prev = container.find('div.timelinePrev');
                prev.show();
                if (currentIndex == 0)
                {
                    prev.hide();
                }  
                
                var next = container.find('div.timelineNext');
                next.show();              
                if (currentIndex == panelCount - 1)
                {
                    next.hide();
                }
            }
		    
		    CheckLocation();
		    
		    SetPrevNextControls();
		}
    });
};
