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 * -120) + 'px' });
        Effect.Appear(this.scroller, { duration: fadeDuration });
      }.bind(this)
    })
	},
	
	startAnimation: function() 
	{
	  new PeriodicalExecuter(function(pe)
	  {
	    this.scroll(1);
	  }.bind(this), 6);
	}
});

/*
document.observe("dom:loaded", function() 
{
  var scroller = new Scroller('clients');
  var scroller = new Scroller('media')
});
*/

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

var SubNavigation = Class.create(
{
	initialize: function(menu) 
	{
	  var subMenus = $$('#' + menu.id + '>li>ul');
	  
	  subMenus.each(function(menu)
	  {
	    var parentItem = menu.previous();
	    if (!parentItem.hasClassName('selected'))
	    {
	      var selectedItems = menu.select('a.selected');

  	    if (selectedItems.length == 0)
  	    {
  	      menu.hide();
  	    }
      }
	  });
  }
});


// // // // // // // // //
//                      //
//  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');
		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="ourSwimPop"><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="ourBritishPop"><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 = $('searchLogin');
	  this.explorer   = $('explore');
	  this.isOpen     = false;
	  
	  this.explorer.setStyle({display: 'block'});
	  this.explorer.hide();
	  
	  if (this.exploreBar)
	  {
	    var exploreButton = $('exploreBtn');
	    exploreButton.observe('click', function(e)
	    {
	      if (!this.isOpen)
	      {
	        $('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;
        }
				/// ADDED IN THIS TO CLOSE THE EXPLORER USING THE TOP BUTTON AS WELL AS THE CLOSE - JONNY
				else
				{
					this.closeExplorer();
				}
	      
	      Event.stop(e);
	    }.bind(this))
	    
	    var exploreButton = $('exploreBtnUp');
	    exploreButton.observe('click', function(e)
	    {
	      this.closeExplorer();
	      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.eventTypeEl.observe('change', function(e)
	  {
	    this.updateFilters();  
	  }.bind(this));
	  
	  this.updateFilters();
	},
	
	updateFilters: function()
	{
    var eventType = this.eventTypeEl.options[this.eventTypeEl.selectedIndex].value;

    if (eventType == 'events')
    {
  	  this.internationalEl.show();
    }
    else 
    {
      this.internationalEl.hide();
    }
    
    if (eventType == 'courses')
    {
			$('courseTypeLabel').show();
      this.courseLevelEl.show();
  	  this.courseTypeEl.show();
    }
    else 
    {
			$('courseTypeLabel').hide();
      this.courseLevelEl.hide();
  	  this.courseTypeEl.hide();
    }
  }
});

// // // // // // // //
//                   //
//  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.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
				if (link != this.currentLink)
				{
					this.rotate();
					this.showArticle(link);
					e.stop();
				}
				//console.log('mouseover')
				//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']);
  
    var currentSummary = this.currentLink.select('.summary')[0];

		if (this.size == 'feature1') 
		{
			// 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: this.FADE_TIME}); 
      }
      
      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
	    });*/
	    
	    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;
	}	
});

//Element.observe(window, 'load', function()
document.observe("dom:loaded", function() 
{
	var subNav = $('subNavigation');
	if (subNav)
	{
		if(!$('channel_library'))
		{
			var subNavList = subNav.down().next();
		  if (subNavList) new SubNavigation(subNavList);
		}
	}
	
  var feature1Elements = $$('.feature');
  feature1Elements.each(function(el)
  {
    new Feature(el);
  });
  
  new Explorer();
	new AjaxRatingForm();	
	new SiteNavPops();
	
	var eventsFilter = $('eventsFilter');
	
	if (eventsFilter)
	{
	  if(!$('channel_library')) new Events(eventsFilter);
	}
	
	var scroller = new Scroller('sponsors');
	
	styleTables();

	new RightMostButtonFix();
	
});