// document ready
$(function()
{	
	var currentTitle = 1,
		allImages = $('ul.mainImages li img'),
      	allTitles = $('article h2'),
      	autoRotateFlag = true,
      	rotateSpeed = 6000;
	
	// first and second image (used for transition)
	var firstImage = $('#imageSwapper img')[0];
	var secondImage = $('#imageSwapper img')[1];
	$(secondImage).addClass('placeOnTop');
	
	// submit button on index page roll-over states
	$('input.submitBtn').mouseover(function(){
		$(this).removeClass('mouseOut');
		$(this).addClass('mouseOver');
	});
	
	$('input.submitBtn').mouseout(function(){
		$(this).removeClass('mouseOver');
		$(this).addClass('mouseOut');
	});
	
  	// Click event for all links and future links
	$('h2 a').live('click', function() 
	{
		var idx = $.inArray($(this).parent()[0], allTitles);
	    autoRotateFlag = false;
	    showImage(idx);
	    return false;
	});

	// Show an image, hide the current one
	function showImage(idx)
	{
		if(idx == allImages.length)
		{
			idx = 0;
    	}
		
		// image transition trick
		var image = allImages[idx];
		
		// fade the second image (the hidden one on top) in
		$(secondImage).attr('src', image.src).fadeIn(4000, function(){
			// when fadeIn is complete, update the src attribute for the first image (the one below)
			$(firstImage).attr('src', image.src);
			
			// then, fade out the second image (no-one can see the effect because the image below is the same as this one)
			$(this).fadeOut('fast');
		});
		
		// update selected item
    	var selectedTitle = $('article h2.selected').removeClass('selected');
    	selectedTitle.html($('<a/>').attr('href', '#').text(selectedTitle.text()));

		// the new selected item
    	var title = $(allTitles[idx]);
    	var aNode = $(title.children()[0]);
    	title.addClass('selected');
    	aNode.replaceWith(aNode.text());
	}

  // gallery rotation method
  function autoRotate() {
    if(autoRotateFlag) {
      showImage(currentTitle++ % allTitles.length);
      setTimeout(autoRotate, rotateSpeed);
    }
  }
  // run again
  setTimeout(autoRotate, rotateSpeed);
});
