
$(document).ready(function() {

var currentSlide = -1; //keeps track of current slide
var prevSlide = null; //keeps track of last selected slide.
var slides = $('#headerImage div'); // all the slides
var interval = null; //For setInerval
var FADE_SPEED = 1500;  //How long it takes to transition.
var DELAY_SPEED = 5500; //How long each slide stays up.

$("div#headerImage div").hide();
$("div#headerImage div:first").show();

//get things started.
nextSlide();

//Goes to the next slide.
function nextSlide (){

    //if the current slide is at the end, loop to the first slide.
    if (currentSlide >= slides.length -1){
        currentSlide = 0;
    }else{
        currentSlide++
    }

    //Go to the slide.
    gotoSlide(currentSlide);

}


//Go to the slide specified in the argument.
function gotoSlide(slideNum){

    //If the slide they're trying to access isn't
    //the currently selected slide...
    if (slideNum != prevSlide){
    
        //The very first slide the prevSlide will be null.
        //No point in trying to hide the slide when it doesn't
        //exist yet.
        if (prevSlide != null){
            //Hide previoius slide and deselect old tab.
            //$(slides[prevSlide]).stop().hide();
            $(slides[prevSlide]).fadeOut(FADE_SPEED, function(){
               $(slides[slideNum]).fadeIn(FADE_SPEED); 
            });
        }

        //Display new slide.
        //$(slides[slideNum]).stop().fadeIn(FADE_SPEED*2);
       
        //Make the currentSlide the old slide for next transition.
        prevSlide = currentSlide;

        //if the auto slide advance is set, stop it, then start again.
        if (interval != null){
            clearInterval(interval);
        }
       
        //Goes to next slide every couple of seconds.
        interval = setInterval(nextSlide, DELAY_SPEED);
    }

}
});
