function showElement(elementPassed)
{
	$(elementPassed).setStyle('display:inline');
}

function hideElement(elementPassed)
{
	$(elementPassed).setStyle('display:none');
}

function hideVisible(elementPassed)
{
	$(elementPassed).setStyle('visibility:hidden');
}

function showInvisible(elementPassed)
{
	$(elementPassed).setStyle('visibility:visible');
}

function styleTables(e) 
{
	var tables = $$('table');
	if (tables) {
		tables.each(function(e)
	  {
	    e.writeAttribute('border','0');
	  });
	};
	
  var evens = $$('table tbody tr:nth-child(odd)');
  if (evens) 
  {
    evens.each(function(tr) 
    {
      tr.addClassName('oddRow');
    });
  }
}

// // // // // // // //
//                   //
//     SCROLLER      //
//                   //
// // // // // // // //

var Scroller = Class.create(
{	
  initialize: function(scrollerWrapper)
	{
	  var scrollerWrapper = $(scrollerWrapper);
	  if (scrollerWrapper)
	  {
  	  this.scroller       = scrollerWrapper.down();
  	  var items           = this.scroller.childElements()
  	  this.itemCount      = items.length;
      this.step           = 0;
      this.startAnimation();
    }
    // var arrows          = scrollerWrapper.select('.arrow');
    /*
    arrows.each(function(arrow)
    {
      Element.observe(arrow, 'click', function(e)
      {
        var scroller;
        var direction;
        if (arrow.hasClassName('arrowLeft')) 
        {
          direction = 1;
        }
        else if (arrow.hasClassName('arrowRight')) 
        {
          direction = -1;
        }
        this.scroll(direction);
        Event.stop(e);
      }.bind(this))
    }.bind(this));*/
    
    
	},
	
	scroll: function(direction)
	{
	  var fadeDuration = 0.5;
    this.step += direction;
    
    if (this.step < 0) this.step = this.itemCount - 1;
    if (this.step == this.itemCount) this.step = 0;
    
    Effect.Fade(this.scroller, 
    {
      duration:     fadeDuration, 
      afterFinish:  function()
      {
        this.scroller.setStyle({ marginTop: (this.step * -127) + 'px' });
        Effect.Appear(this.scroller, { duration: fadeDuration });
      }.bind(this)
    })
	},
	
	startAnimation: function() 
	{
	  new PeriodicalExecuter(function(pe)
	  {
	    this.scroll(1);
	  }.bind(this), 6);
	}
});

// // // // // // // //
//                   //
//  EVENT SCROLLER   //
//                   //
// // // // // // // //

var EventScroller = Class.create(
{	
  initialize: function(eventScroller)
	{
	  var eventScroller = $(eventScroller);
	  if (eventScroller)
	  {
  	  this.scroller       = eventScroller.down();
  	  var items           = this.scroller.childElements()
  	  this.itemCount      = items.length;
      this.step           = 0;

      this.startAnimation();
    }
    
	},
	
	scroll: function(direction)
	{
	  var fadeDuration = 0.5;
    this.step += direction;
    
    if (this.step < 0) this.step = this.itemCount - 1;
    if (this.step == this.itemCount) this.step = 0;
    
    Effect.Fade(this.scroller, 
    {
      duration:     fadeDuration, 
      afterFinish:  function()
      {
        this.scroller.setStyle({ marginTop: (this.step * -205) + 'px' });
        Effect.Appear(this.scroller, { duration: fadeDuration });
      }.bind(this)
    })
	},
	
	startAnimation: function() 
	{
	  new PeriodicalExecuter(function(pe)
	  {
	    this.scroll(1);
	  }.bind(this), 6);
	}
});


// // // // // // // //
//                   //
//  SECONDARY MENU   //
//                   //
// // // // // // // //

var SubNavigation = Class.create(
{
	initialize: function(menu) 
	{ 
		var subMenus = $$('#' + menu.id + '>li>ul');
		var menuCount = 1;       
		subMenus.each(function(menu)
		{
			var parentItem = menu.previous();
			var listItem = parentItem.up();
			listItem.insert({top:"<div class='expandBtn'>Expand/Collapse</div>"});
			toggleBtn = listItem.down();
			
			if (parentItem.hasClassName('selected'))
			{
				toggleBtn.removeClassName('expandBtn');
				toggleBtn.addClassName('collapseBtn');
			}
			else
			{
				var selectedItems = menu.select('a.selected');
				if (selectedItems.length > 0)
				{
					toggleBtn.removeClassName('expandBtn');
					toggleBtn.addClassName('collapseBtn');
				}
				else
				{
					menu.toggleClassName('hideSubNav');
				}
			}
			
			toggleBtn.observe('click', function(e)
			{
				menu.toggleClassName('hideSubNav');
				tBtn = Event.element(e);
				if(tBtn.hasClassName('expandBtn'))
				{
					tBtn.removeClassName('expandBtn');
					tBtn.addClassName('collapseBtn');
				}
				else
				{
					tBtn.removeClassName('collapseBtn');
					tBtn.addClassName('expandBtn');
				}
			});
			//menuCount++;
		});
		
		var secMenus = $$('#' + menu.id + '>li>ul>li>ul');
		var menuCount = 1;
		secMenus.each(function(menu)
		{
			var parentItem = menu.previous();
			var listItem = parentItem.up();
			listItem.insert({top:"<div class='expandBtn'>Expand/Collapse</div>"});
			toggleBtn = listItem.down();
			if (parentItem.hasClassName('selected'))
			{
				toggleBtn.removeClassName('expandBtn');
				toggleBtn.addClassName('collapseBtn');
			}
			else
			{
				var selectedItems = menu.select('a.selected');
				if (selectedItems.length > 0)
				{
					toggleBtn.removeClassName('expandBtn');
					toggleBtn.addClassName('collapseBtn');
				}
				else
				{
					menu.toggleClassName('hideSubNav');
				}
			}
			toggleBtn.observe('click', function(e)
			{
				menu.toggleClassName('hideSubNav');
				tBtn = Event.element(e);
				if(tBtn.hasClassName('expandBtn'))
				{
					tBtn.removeClassName('expandBtn');
					tBtn.addClassName('collapseBtn');
				}
				else
				{
					tBtn.removeClassName('collapseBtn');
					tBtn.addClassName('expandBtn');
				}
			});
			//menuCount++;
		});
		
		var terMenus = $$('#' + menu.id + '>li>ul>li>ul>li>ul');
		var menuCount = 1;
		terMenus.each(function(menu)
		{
			var parentItem = menu.previous();
			var listItem = parentItem.up();
			listItem.insert({top:"<div class='expandBtn'>Expand/Collapse</div>"});
			toggleBtn = listItem.down();
			if (parentItem.hasClassName('selected'))
			{
				toggleBtn.removeClassName('expandBtn');
				toggleBtn.addClassName('collapseBtn');
			}
			else
			{
				var selectedItems = menu.select('a.selected');
				if (selectedItems.length > 0)
				{
					toggleBtn.removeClassName('expandBtn');
					toggleBtn.addClassName('collapseBtn');
				}
				else
				{
					menu.toggleClassName('hideSubNav');
				}
			}
			toggleBtn.observe('click', function(e)
			{
				menu.toggleClassName('hideSubNav');
				tBtn = Event.element(e);
				if(tBtn.hasClassName('expandBtn'))
				{
					tBtn.removeClassName('expandBtn');
					tBtn.addClassName('collapseBtn');
				}
				else
				{
					tBtn.removeClassName('collapseBtn');
					tBtn.addClassName('expandBtn');
				}
			});
			//menuCount++;
		});
		
	}
});


// // // // // // // //
//                   //
//    SUBNAV MENU    //
//                   //
// // // // // // // //
var SubMenuHide = Class.create(
{
	initialize: function()
	{
		if (navigator.appVersion.indexOf('MSIE 6') >= 0)
		{
			var dropDowns = $$('#navigation li>ul');
			dropDowns.each(function(item)
		  {
				$(item).hide();
		  });
		}
		else
		{
			var dropDowns = $$('#navigation li>ul');
			dropDowns.each(function(item)
		  {
				var parentItem = item.previous();
				parentItem.observe('mouseover', function(e)
				{
					if (!Prototype.Browser.IE6) {
				  	$(item).setStyle('display:block');
					}
				});
				parentItem.observe('mouseout', function(e)
				{
					if (!Prototype.Browser.IE6) {
				  	$(item).setStyle('display:none');
					}
				});
				item.observe('mouseover', function(e)
				{
					if(!parentItem.hasClassName('stayOn'))
					{
						parentItem.addClassName('selected');
					}
				  $(item).setStyle('display:inline');
				});
				item.observe('mouseout', function(e)
				{
					if(!parentItem.hasClassName('stayOn'))
					{
						parentItem.removeClassName('selected')
					}
					$(item).setStyle('display:none');
				});
		  });
		}
	}
});


// // // // // // // // //
//                      //
//  AJAX RATING FORM    //
//                      //
// // // // // // // // //

var AjaxRatingForm = Class.create(
{
	initialize: function() 
	{
		if($('ratingForm'))
		{
			var isClicked = false;
			Event.observe('ratingForm', 'submit', function(event)
			{
				if (isClicked) 
				{
					alert('You have already submitted this form...');
				}
				else
				{
					new Ajax.Request(location.href,
				  {
				    method:     'post',
						parameters: $('ratingForm').serialize(true),
				    onSuccess:  function (transport)
				    {
				      var errorExp = /Duplicate\ submissions\ are\ not\ allowed/;
				      if (transport.responseText && transport.responseText.match(errorExp))
				      {
				        alert('You have already submitted this form...');
				      }
				      else
				      {
					      var overallCount = parseInt($('overallCount').innerHTML);

								overallCount++;
								$('overallCount').update(overallCount);
						  }
							isClicked = true;
				    },
				    onFailure:  function(){ alert('Error submitting your rating, please try again...') }
				  });
				}
				Event.stop(event); // stop the form from submitting
			});
		}
	}
});

var RightMostButtonFix = Class.create(
{
	initialize: function() 
	{
		var rightMostBtn = $('rightMostBtn');
		if(rightMostBtn){
			rightMostBtn.observe('mouseover', function(e)
			{
			  $('navRight').addClassName('navRightOn');
			}.bind(this));
			rightMostBtn.observe('mouseout', function(e)
			{
			  $('navRight').removeClassName('navRightOn');
			}.bind(this));
		}
	}
});

var SiteNavPops = Class.create(
{
	initialize: function()
	{
		popupFlags = new Array();
		htmlStrings = new Array();
		htmlStrings['swimmingSite'] = '<div class="popUp pngFix" id="swimmingIconPop"><a href="http://www.swimming.org" class="imgReplace pngFix swimmingLogo" title="Visit swimming.org">swimming.org</a><div class="dottedLineBreak"></div><p>Swimming.org is home to everything you need to know about swimming. If you are a parent, a non swimmer or just want to improve your technique this is the section for you.</p></div>';
		htmlStrings['britishSwimmingSite'] = '<div class="popUp pngFix" id="britishSwimmingIconPop"><a href="http://www.swimming.org/britishswimming/" class="imgReplace pngFix britishSwimmingLogo" title="Visit British Swimming">britishswimming.org</a><div class="dottedLineBreak"></div><p>In British Swimming you will find information about the world of high performance sport, including the disciplines of Swimming, Diving, Synchronised Swimming, Water Polo and Disability Swimming.</p></div>'
		htmlStrings['asaSite'] = '<div class="popUp pngFix" id="asaIconPop"><a href="http://www.swimming.org/asa/" class="imgReplace pngFix asaLogo" title="Visit the ASA">theasa.org</a><div class="dottedLineBreak"></div><p>The ASA is the governing body for the sport in England. In this section you will find all you need to know about joining a club or competing in England and becoming a swimming teacher or coach.</p></div>'
		htmlStrings['iosSite'] = '<div class="popUp pngFix" id="iosIconPop"><a href="http://www.swimming.org/ios/" class="imgReplace pngFix isoLogo" title="Visit the IoS">theiso.org</a><div class="dottedLineBreak"></div><p>The IoS delivers the ASA\'s courses and is a member organisation. Whether you are a teacher, coach, employer or club you will find everything you need to know about qualifications or educating your workforce.</p></div>';
		htmlStrings['ourSwimBtn'] = '<div class="popUp pngFix" id="ourSwimmingOrgPop"><a href="http://www.swimming.org" class="imgReplace pngFix swimmingLogo" title="Visit swimming.org">swimming.org</a><div class="dottedLineBreak"></div><p>Swimming.org is home to everything you need to know about swimming. If you are a parent, a non swimmer or just want to improve your technique this is the section for you.</p></div>';
		htmlStrings['ourBritishBtn'] = '<div class="popUp pngFix" id="ourBritishSwimmingPop"><a href="http://www.swimming.org/britishswimming/" class="imgReplace pngFix britishSwimmingLogo" title="Visit British Swimming">britishswimming.org</a><div class="dottedLineBreak"></div><p>In British Swimming you will find information about the world of high performance sport, including the disciplines of Swimming, Diving, Synchronised Swimming, Water Polo and Disability Swimming.</p></div>';
		htmlStrings['ourASABtn'] = '<div class="popUp pngFix" id="ourASAPop"><a href="http://www.swimming.org/asa/" class="imgReplace pngFix asaLogo" title="Visit the ASA">theasa.org</a><div class="dottedLineBreak"></div><p>The ASA is the governing body for the sport in England. In this section you will find all you need to know about joining a club or competing in England and becoming a swimming teacher or coach.</p></div>'
		htmlStrings['ourIOSBtn'] = '<div class="popUp pngFix" id="ourIOSPop"><a href="http://www.swimming.org/ios/" class="imgReplace pngFix isoLogo" title="Visit the IoS">theiso.org</a><div class="dottedLineBreak"></div><p>The IoS delivers the ASA\'s courses and is a member organisation. Whether you are a teacher, coach, employer or club you will find everything you need to know about qualifications or educating your workforce.</p></div>';
		if (!parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))) 
		{
			$('swimmingSite').observe('mouseover', this.showPop);
			$('swimmingSite').observe('mouseout', this.hidePop);
			$('britishSwimmingSite').observe('mouseover', this.showPop);
			$('britishSwimmingSite').observe('mouseout', this.hidePop);
			$('asaSite').observe('mouseover', this.showPop);
			$('asaSite').observe('mouseout', this.hidePop);
			$('iosSite').observe('mouseover', this.showPop);
			$('iosSite').observe('mouseout', this.hidePop);
			if($('ourSwimBtn'))
			{
				$('ourSwimBtn').observe('mouseover', this.showPop);
				$('ourSwimBtn').observe('mouseout', this.hidePop);
				$('ourBritishBtn').observe('mouseover', this.showPop);
				$('ourBritishBtn').observe('mouseout', this.hidePop);
				$('ourASABtn').observe('mouseover', this.showPop);
				$('ourASABtn').observe('mouseout', this.hidePop);
				$('ourIOSBtn').observe('mouseover', this.showPop);
				$('ourIOSBtn').observe('mouseout', this.hidePop);
			}
		}
	},
	showPop: function(e)
	{
		if (!parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))) 
		{
			var icon = Event.element(e);
			if (popupFlags[icon.id]) 
			{
				var icon = Event.element(e);
				var popUp = icon.up().id + "Pop";
				$(popUp).setStyle('display:inline');
			}
			else
			{
				var icon = Event.element(e);
				if (icon.id == 'swimmingSite' || icon.id == 'britishSwimmingSite' || icon.id == 'asaSite' ||icon.id == 'iosSite') 
				{
					$('popUps').insert(htmlStrings[icon.id]);
				}
				else
				{
					$('ourSites').insert(htmlStrings[icon.id]);
				}
				popupFlags[icon.id] = true;
			}
		}
	},
	hidePop: function(e)
	{
		if (!parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))) 
		{
			var icon = Event.element(e);
			var popUp = icon.up().id + "Pop";
			$(popUp).setStyle('display:none');
		}
	}
});


// Add mouse wheel event to Prototype's Event object
Object.extend(Event, {
	wheel:function (event){
		var delta = 0;
		if (!event) event = window.event;
		if (event.wheelDelta) {
			delta = event.wheelDelta/120; 
			if (window.opera) delta = -delta;
		} else if (event.detail) { delta = -event.detail/3;	}
		return Math.round(delta); //Safari Round
	}
});


// // // // // // // //
//                   //
//  EXPLORER WIDGET  //
//                   //
// // // // // // // //

var Explorer = Class.create(
{
	initialize: function() 
	{
	
		this.exploreBar = $('tabSiteMap');
	  this.explorer   = $('explore');
	  this.isOpen     = false;
	  
	  this.explorer.hide();
	  
		
		
	  if (this.exploreBar)
	  {
	    var exploreButton = $('showSiteMap');
			
			if (navigator.appVersion.indexOf('MSIE 5') >= 0)
			{
				exploreButton.hide();
			}
			else
			{
				
		    exploreButton.observe('click', function(e)
		    {
					
		      if (!this.isOpen)
		      {
						$('showSiteMap').addClassName('siteMapUp');
		        $('explorerWrapper').setStyle({display: 'block'});
	        
		        new Effect.Parallel([
	            new Effect.SlideDown(this.explorer, { sync: true }),
	            new Effect.Appear(this.explorer, { sync: true }) 
	          ], { 
	            duration: 0.8
	          });
						this.isOpen = true;
	        }

					else
					{
						this.closeExplorer();
						$('showSiteMap').removeClassName('siteMapUp');
					}
	      
		      Event.stop(e);
		    }.bind(this))
	    
		    var exploreButton = $('siteMapBtnUp');
		    exploreButton.observe('click', function(e)
		    {
		      this.closeExplorer();
		      $('showSiteMap').removeClassName('siteMapUp');
		      Event.stop(e);
		    }.bind(this))
	
			}
			
	  }
	},
	
	closeExplorer: function()
	{
		new Effect.Parallel([
      new Effect.SlideUp(this.explorer, { sync: true }),
      new Effect.Fade(this.explorer, { sync: true }) 
    ], { 
      duration: 0.8
    });
		this.isOpen = false;
	}
	
});

// // // // // // // //
//                   //
//  EVENTS FORM      //
//                   //
// // // // // // // //

var Events = Class.create(
{
	initialize: function(form) 
	{
	  this.form         = form;
	  
	  this.eventTypeEl      = this.form.select('.eventType')[0];
	  this.courseLevelEl    = this.form.select('.courseLevel')[0];
	  this.courseTypeEl     = this.form.select('.courseType')[0];
	  this.internationalEl  = this.form.select('.international')[0];
		this.regionalEl  			= this.form.select('.regionSelect')[0];
		this.disciplineEl  		= this.form.select('.discipline')[0];
		this.organisationEl  	= this.form.select('.organisation')[0];
		this.competitionEl  	= this.form.select('.competition')[0];
		this.boardEl  				= this.form.select('.board')[0];
		this.conferenceEl  		= this.form.select('.conference')[0];
		this.confRegionalEl  	= this.form.select('.confRegionSelect')[0];
	  
	  this.eventTypeEl.observe('change', function(e)
	  {
	    this.updateFilters();  
	  }.bind(this));
	
		this.competitionEl.observe('change', function(e)
	  {
	    this.updateRegions();  
	  }.bind(this));
	
		this.conferenceEl.observe('change', function(e)
	  {
	    this.updateRegions2();  
	  }.bind(this));
	  
	  this.updateFilters();
	},
	
	updateFilters: function()
	{
    var eventType = this.eventTypeEl.options[this.eventTypeEl.selectedIndex].value;
		
    if (eventType == 'events')
    {
			$('disciplineLabel').show();
			this.disciplineEl.show();
			$('organisationDiv').show();
			$('competitionDiv').show();
			$('regionLabel').hide();
			this.regionalEl.hide();
    }
    else 
    {
			$('disciplineLabel').hide();
			this.disciplineEl.hide();
			$('organisationDiv').hide();

			$('competitionDiv').hide();
			$('regionLabel').hide();
			this.regionalEl.hide();
    }
    
    if (eventType == 'courses')
    {
			$('disciplineLabel').show();
			this.disciplineEl.show();
			$('courseTypeLabel').show();
      this.courseLevelEl.show();
  	  this.courseTypeEl.show();
			$('courseRegionDiv').show();
    }
    else 
    {
			$('courseTypeLabel').hide();
      this.courseLevelEl.hide();
  	  this.courseTypeEl.hide();
			$('courseRegionDiv').hide();
    }

    if (eventType == 'meetings')
    {
			$('boardDiv').show();
    }
    else 
    {
			$('boardDiv').hide();
    }

		if (eventType == 'conferences')
    {
			$('conferenceDiv').show();
			$('confRegionLabel').hide();
			this.confRegionalEl.hide();
    }
		else
		{
			$('conferenceDiv').hide();
		}
		
		if (eventType == 'licensed-meets')
    {
			$('courseRegionDiv').show();
    }
		
  },

	updateRegions: function()
	{
		var compType = this.competitionEl.options[this.competitionEl.selectedIndex].value;
		if (compType == 'Regional')
		{
			$('regionLabel').show();
			this.regionalEl.show();
		}
	},
	
	updateRegions2: function()
	{
		var confType = this.conferenceEl.options[this.conferenceEl.selectedIndex].value;
		if (confType == 'Regional')
		{
			$('confRegionLabel').show();
			this.confRegionalEl.show();
		}
	}
	
	
});

// // // // // // // //
//                   //
//  FEATURE WIDGET   //
//                   //
// // // // // // // //

var Feature = Class.create(
{
	initialize: function(el) 
	{
	  this.el         = $(el);
	  
	  // CLASS CONSTANTS
	  this.FEATURE1_ARTICLE_HEIGHT  = 257;
	  this.FEATURE2_ARTICLE_WIDTH   = 442;
	  this.SCROLL_ACCELERATE        = 5;
	  this.SCROLL_TIME              = 0.001;
	  this.FADE_TIME                = 0.5;
	  this.ROTATE_INTERVAL          = 7;
	
		this.rotateFlag				= true;
	  
	  if (this.el.hasClassName('feature1')) 
	  {
	    this.size = 'feature1';
	  }
	  else if (this.el.hasClassName('feature2')) 
	  {
	    this.size = 'feature2';
	  }
	  
	  if (this.size == 'feature1' || this.size == 'feature2')
	  {
	    this.setup();
	    //if (this.articleCount > 1) this.rotate(); // Only rotate if there is more than one article
	  }	
	},
	
	rotate: function()
	{
	  if (this.rotatePE) 
	  {
	    //console.log(this.rotatePE)
	    if (this.rotatePE.timer)
	    {
	      //console.log('cancelling:' + this.rotatePE.timer)
	      //console.log(this.rotatePE)
	      
	      this.rotatePE.stop();
	      this.startRotating();
	    }
	  }
	  else this.startRotating();	  
	},
	
	startRotating: function()
	{/*
	  //console.log('New Rotator')
	  new PeriodicalExecuter(function(pe)
	  {
	    //console.log('Executing: ' + pe.timer)
	    this.rotatePE = pe;
	    //console.log("start rotating");
	    this.nextArticle();
	  }.bind(this), this.ROTATE_INTERVAL);*/
	},
	
	setup: function()
	{
	  this.articles     = this.el.select('.articles')[0];
	  this.listElement  = this.articles.down();
	  this.headlineEl   = this.el.select('.headline')[0];
    this.headlines    = new Array();
    this.mainTextEl   = this.el.select('.mainText')[0];
		this.mainTextEl2   = this.el.select('.mainText')[1];
		this.articleCount = 0; // added by jonny
    this.articleIndex = 0;
    
	  // Initialise styles
    this.articles.setStyle({overflow: 'hidden'});
	  
	  this.currentImage = this.headlineEl.getElementsByTagName('img')[0];
	  this.currentLink  = Element.down(this.articles.getElementsByTagName('li')[0]);
	
	  	  
	  Element.observe(this.currentImage, 'click', function(e)
    {
      window.location = this.currentLink.href;
    }.bind(this));
    
	  var count           = 0;
    var listItems       = $A(this.articles.getElementsByTagName('li'));
    
	  this.articleCount   = listItems.length; // added by jonny
	  var totalDimension  = 0;
		
	  listItems.each(function(item)
	  {
	    var img   = item.getElementsByTagName('img')[0];
      var link  = item.getElementsByTagName('a')[0];    
	    
	    if (img)
	    {
	      // Make the images clickable
        Element.observe(img, 'click', function(e)
  	    {
  	      window.location = link.href;
  	    }.bind(this));

  	    this.headlineEl.insert({
  	      bottom: img
  	    });

  	    img.hide();
	    }
			
			/***
      var linkSummary = Element.select(link, '.summary')[0];
	    if (linkSummary) Element.hide(linkSummary);
	    
	    if (count ==  0)
	    {
	      img = this.currentImage;
	      if (linkSummary) Element.show(linkSummary)
	    }
			*/
			
		// Attach behaviors to links 
	    Element.observe(link, 'mouseover', function(e)
	    {
			//////////////// ADD FLAG IN HERE TO SWITCH OFF AUTO ROTATE
				// console.log('mouseover'+link)
				if (link != this.currentLink)
				{
					this.rotate();
					this.showArticle(link);
					e.stop();
				}

				//this.rotatePE.stop();
				this.rotateFlag = false;
	    }.bind(this));
	
		// Attach behaviors to links 
	    Element.observe(link, 'mouseout', function(e)
	    {
				//console.log('mouseout')
				//this.startRotating();
				this.rotateFlag = true;
	    }.bind(this));


	    // Attach behaviors to links 
	    Element.observe(link, 'click', function(e)
	    {
	      if (link != this.currentLink)
	      {
	        this.rotate();
	        this.showArticle(link);
					e.stop();
        	}
	    }.bind(this));
	    
	    // Build array of headline text/images
	    this.headlines[count] = {
	      img: img,
	      text: link.down().innerHTML
	    }
	    count++;
	    
	    if (this.size == 'feature1')
  	  {
        totalDimension += Element.getHeight(item);
      }
      else if (this.size == 'feature2')
  	  {
  	    totalDimension += Element.getWidth(item);
	    }
	    
	  }.bind(this));
	  
	  var needToScroll = false;
	  
	  if (this.size == 'feature1')
	  {
	    if (totalDimension > 317)
	    {
	      needToScroll = true;
	      this.articles.setStyle({ height: this.FEATURE1_ARTICLE_HEIGHT + 'px'});
	    }
	  }
	  else
	  {
	    if (totalDimension > this.articles.getWidth())
	    {
	      needToScroll = true;
	      this.articles.setStyle({ width: this.FEATURE2_ARTICLE_WIDTH + 'px'});
	    }
	  }

	  if (needToScroll)
	  {
	    if (this.size == 'feature2')
      {
    	  this.listElement.setStyle({'width': count * 160 + 'px'});
      }
	   
  	  // Attach mousewheel event
  	  this.articles.observe('DOMMouseScroll', function(e)
  	  {
  	    this.doScroll(Event.wheel(e));
  	    Event.stop(e);
  	  }.bind(this));
	  
  	  this.articles.observe('mousewheel', function(e)
  	  {
  	    this.doScroll(Event.wheel(e));
  	    Event.stop(e);
  	  }.bind(this));
	  
	  
  	  // Create up/down button elements and attach behaviours
  	  $(this.articles).insert({
        before: '<div class="scrollButton scrollUp backgroundColour pngFix">Up</div>'
      });

      $(this.articles).insert({
        after: '<div class="scrollButton scrollDown backgroundColour pngFix">Down</div>'
      });
    
      var upButton    = this.el.select('.scrollUp')[0];
      var downButton  = this.el.select('.scrollDown')[0];
  
      if (this.size == 'feature2')
      {
        upButton.setStyle({height: this.articles.getHeight()+'px'});
        downButton.setStyle({height: this.articles.getHeight()+'px'});
      }
    
      upButton.observe('mouseover', function(e)
      {
        this.startScroll(-1);
        upButton.addClassName('backgroundColorHover');
				this.rotateFlag = false;
      }.bind(this));
    
      upButton.observe('mouseout', function(e)
      {
        if (this.pe) this.pe.stop();
        upButton.removeClassName('backgroundColorHover');
				this.rotateFlag = true;
      }.bind(this));
    
      downButton.observe('mouseover', function(e)
      {
        this.startScroll(1);
        downButton.addClassName('backgroundColorHover');
				this.rotateFlag = false;
      }.bind(this));
    
      downButton.observe('mouseout', function(e)
      {
        if (this.pe) this.pe.stop();
        downButton.removeClassName('backgroundColorHover');
				this.rotateFlag = true;
      }.bind(this));
    
    }
	},
	
	startScroll: function(direction)
	{
	  this.pe = new PeriodicalExecuter(function()
	  {
	    this.doScroll(direction);
	    
	  }.bind(this), this.SCROLL_TIME);
	},
	
	doScroll: function(direction)
	{
	  if (this.size == 'feature1')
    {
      this.articles.scrollTop += (direction*this.SCROLL_ACCELERATE);
    }
    else if (this.size == 'feature2')
    {
      this.articles.scrollLeft += (direction*this.SCROLL_ACCELERATE);
    }
	},
	
	nextArticle: function()
	{
		if (this.rotateFlag) 
		{
			if (this.articleIndex == this.articleCount - 1)
			{
			this.articleIndex = 0;
			}
			else
			{
			this.articleIndex++;
			}
			var link = Element.down(this.articles.getElementsByTagName('li')[this.articleIndex]);
			this.showArticle(link);
		}
	},

	showArticle: function(link)
	{
		
	  var articleNo = parseInt(link.rel.replace('headline_', '')) - 1;
    var headline  = this.headlines[articleNo]
    var summary   = link.select('.summary')[0];
  
    // Update text
    var mainAnchor  = this.mainTextEl.down();
    mainAnchor.href = link.href;
		
    mainAnchor.update(headline['text']);
  
	// function to stop the image dissapearing when quickly hovered over
	function fadey(link, elem){
		new Effect.Appear(elem, { duration: 0.3 });
	}

    //***var currentSummary = this.currentLink.select('.summary')[0];

		if (this.size == 'feature1') 
		{
			mainAnchor.update(headline['text'] + '<span class="summary"><span>' + summary.innerHTML + '</span></span>');
				// Update image
		    /*new Effect.Parallel([
		      new Effect.Fade(this.currentImage, { sync: true }), 
		      new Effect.Appear(headline['img'], { sync: true }),
		      new Effect.BlindUp(currentSummary, { sync: true }), 
		      new Effect.BlindDown(summary, { sync: true })
		    ], { 
		      duration: this.FADE_TIME
		    });*/
	    

	
		    if (this.currentImage) 
		    {
  		      new Effect.Fade(this.currentImage, { duration: 0.3, afterFinish: function(){
  		      		fadey(link,headline['img']);
  		      	}
			}); 
			
		   	}

	      //       	if (headline['img']) 
	      // {
	      //   new Effect.Appear(headline['img'], { duration: this.FADE_TIME });
	      // }

	      //***new Effect.BlindUp(currentSummary, { duration: this.FADE_TIME }); 
	      //***new Effect.BlindDown(summary, { duration: this.FADE_TIME });
		}
		else
		{
		  /*
	    new Effect.Parallel([
	      new Effect.Fade(this.currentImage, { sync: true }), 
	      new Effect.Appear(headline['img'], { sync: true })
	    ], { 
	      duration: this.FADE_TIME
	    });*/
	    mainAnchor.update(headline['text']);
	    if (this.currentImage) new Effect.Fade(this.currentImage, { duration: this.FADE_TIME });
      if (headline['img']) new Effect.Appear(headline['img'], { duration: this.FADE_TIME });
	    
		}
    this.currentLink.up().removeClassName('selected');
    
    var linkListElement = link.up();
    linkListElement.addClassName('selected');
    this.articleIndex = linkListElement.previousSiblings().length; // Set current index to this list item
    
    this.currentImage = headline['img'];
    this.currentLink  = link;
	}	
});
if(typeof(Control) == 'object'){
	if(typeof(Control.Modal) == 'function'){ 
		var window_factory = function(container,options){  
			
		    var window_close = new Element('div',{  
		        className: 'modal_close'  
		    });  
		    var w = new Control.Modal(container,Object.extend({  
			    overlayOpacity: 0.75,  
			    className: 'modal',  
			    fade: true,
			    height:626,
			    width:976,
			    iframe:true,
		        closeOnClick: window_close
		    },options || {}));  
		    w.container.insert(window_close);  
		    return w;  
		};  
	}
}

var launch = function(f,b){

	var x = document.getElementById(f);
	var y = x.contentWindow.document.getElementById(b);
	
	var modal = window_factory(y,'');
}

//Element.observe(window, 'load', function()
document.observe("dom:loaded", function() 
{
	if(typeof(window_factory) == 'function'){
		var locker_room_links = new Array('side_lr','landing_locker-room');
		var i = 1;
		locker_room_links.each(function(i){

			var modal = window_factory($(i),'');
			
			var viewport = document.viewport.getDimensions(); 
			var width = viewport.width; 
			var height = viewport.height;
			
			if(height < 700){
						
				if($(i)){
					Event.observe($(i),'click', function(event){

						Effect.ScrollTo( 'superLogo', 100, {axis:'x'} )

						event.stop();

					});	
				}		

			} 
			
		});
	}
	
	var subNav = $('subNavigation');
	if (subNav)
	{
		if(!$('channel_library'))
		{
			var subNavList = subNav.down().next();
	            //alert(subNavList.id);
		  if (subNavList) new SubNavigation(subNavList);
		}
	}
	
  var feature1Elements = $$('.feature');
   feature1Elements.each(function(el)
   {
     new Feature(el);
   });
   
   new Explorer();
  	
  	new AjaxRatingForm();	
  	//new SiteNavPops();
  	
  	new SubMenuHide();
  	
  	var eventsFilter = $('eventsFilter');
  	
  	if (eventsFilter)
  	{
  	  if(!$('channel_library')) new Events(eventsFilter);
  	}
  	
  	var scroller = new Scroller('sponsors');
  	var scroller2 = new EventScroller('swimmingEvents');
  	
  	styleTables();
  
  	new RightMostButtonFix();
  	
  	(function(){var s=function(){__flash__removeCallback=function(i,n){if(i)i[n]=null;};window.setTimeout(s,10);};s();})();
  	
  	if ($('subscribeNewsletter')) {$('subscribeNewsletter').observe('change', showOptIns)};

  	if ($('m_field_id_37')) {$('m_field_id_37').observe('change', hideWhereHeard)};
  
  	if ($('hearSwimfit')) {$('hearSwimfit').observe('change', showHearOther)};
  
  
  	if(readCookie('counter') != "off"){		
  		
  		if($('num2')){
  			$('num2').insert(no_days(3,3,2012));
  		}

  		//add margin to bottom of each page - outerWrapper
  		//check to make sure outerWrapper exists & we're not on the 2012trials

  		if($('outerWrapper') && !$('aqua') && !$('channel_2012trials')){
  			$('outerWrapper').morph('padding-bottom: 62px');
  		}
  		if($('site_counter_wrap')){
  			$('site_counter_wrap').setStyle('display: block');
  		}
  
  		
  	}	

	// Hide the counter
	if ($('count_close') != undefined){
		Event.observe('count_close','click', function(event){
		
			// Fade out counter
		    new Effect.Fade('site_counter_wrap', { afterFinish: function(){
			
				// change the padding back to normal
				new Effect.Morph('outerWrapper', {
				style: {
				paddingBottom: '0px'
				},
				duration: 0.6 
				});
			
				createCookie('counter','off',0);
			
			}});
	
			event.stop();
		});
	}
	
	
	/**
	 * Swimfit Expand Table
	 *
	 * @author Steve W
	 */
	
	$$('.showSwim').each(function(element){
		show_table(element);
	});
	
	$$('.hideSwim').each(function(element){
		hide_table(element);
	});

	/**
	 * Careers - Job Search reorder
	 *
	 * @author Tom M
	 */

	 if ($('careersOrderBy') != undefined){
	 	$('careersOrderBy').observe('change',function(element){
		 	this.form.submit();
		});
	}
});


function showHearOther()
{
	var hearSwimfit = $('hearSwimfit').getValue();
	if(hearSwimfit == "Other (please tell us)"){
		$('hearOther').setStyle('display:block');
	} else {
	 	$('hearOther').setStyle('display:none');
	}
}


function showOptIns()
{
	$('optIns').setStyle('display:inline');
	$('dataProtStatement').setStyle('display:block');
}
function hideWhereHeard()
{
	$('whereDidYouHear').setStyle('display:none');
}

// countdown bar cookie - sugary cookie functions from quirksmode.org

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	return null;
}

function readCookie(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 "FAILED";
}

/**
 * Countdown bar values
 *
 * @author Steve W, @update Tom M
 */

function no_days(d,m,y){
	
 var x = new Date(y,(m-1),d);
 var y = new Date();
 var tl = x.getTime() - y.getTime();
 var days = Math.ceil(tl / (1000 * 60 * 60 * 24));	

 if(days<=0){
  return "000";
 } else if(days<=9) {
  return "00" + days;
 } else if(days<=99) {
 return "0" + days;
 } else {
  return days;
 } 
}

/**
 * Swimfit expand & close table functions
 *
 * @author Steve W
 */

function show_table(el){
	Event.observe(el,'click', function(event){

		Event.stop(event)

	
		el_1 = $(el).up('h3');
		
		el_2 = el_1.next('table');
			
		showElement(el_2);
		
		$(el).removeClassName('showSwim');
		$(el).addClassName('hideSwim');
		
		$(el).stopObserving('click');
		
		hide_table(el);		
		

	});
}
function hide_table(el){
	Event.observe(el,'click', function(event){
	
		el_1 = $(el).up('h3');
		
		el_2 = el_1.next('table');
			
		hideElement(el_2);
		
		$(el).removeClassName('hideSwim');
		$(el).addClassName('showSwim');
		
		$(el).stopObserving('click');
		
		show_table(el);		
		
		event.stop();
	});
}

/**
 * ?
 *
 * @author ?
 */

function resizeFrame(f) {

	// f.style.height = f.contentWindow.document.body.scrollHeight + "px";

};

