// JavaScript Document

$(document).ready(function() { //once the page had loaded do the following

$("#advertPanel li").fadeOut('fast'); //find all li and hide them.
$("#advertPanel li:first").fadeIn('slow');  //find the first li and show it.

$("#advertPanel .paging").show();
$("#advertPanel .paging a:first").addClass("active");


var counter = 0; //remember which advert class to use.
var counterPrev = 2; //works out which is the previous advert
var slideButton = false; // notes when the slide button is clicked

fadeAdvert = function(){
if(!slideButton){  //if the slide button hasn't been clicked carry on as normal
	if (counter == 0){ 
		counterPrev =4;
	}	
	else { 
		counterPrev = counter-1;
	}
}
else {
	slideButton = false; //reset the slideButton
}
$("#advertPanel li").eq(counterPrev).css({'display':'none'}); //hide the current advert
$("#advertPanel li").eq(counter).fadeIn(1000); //fade in the new advert
		
$("#advertPanel .paging a").removeClass('active'); //Remove all active class
$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

}

//Rotation  and Timing Event
rotateSwitch = function(){
    play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
		$active = $('#advertPanel .paging a.active').next(); //Move to the next paging
        if ( $active.length === 0) { //If paging reaches the end...
            $active = $('#advertPanel .paging a:first'); //go back to first
        }
		
		if(counter == 4){  //if the counter is 4, start again from zero
			counter = 0;
		}
		else {
		counter ++;  //otherwise add one to the counter
		}
		
		fadeAdvert();
    }, 10000); //Timer speed in milliseconds (10 seconds)
};

rotateSwitch();

//On Hover pauses the rotation
$("#advertPanel li").hover(function() {
    clearInterval(play); //Stop the rotation
}, function() {
    rotateSwitch(); //Resume rotation timer
});

//On Click
$("#advertPanel .paging a").click(function() {
	slideButton = true; //a button has been clicked
	counterPrev = $active.attr("rel"); //remember the current slide
    $active = $(this); //Activate the clicked paging
	counter = $(this).attr("rel"); //activate the correct new advert
	
    //Reset Timer
    clearInterval(play); //Stop the rotation
    fadeAdvert(); //Trigger rotation immediately
    rotateSwitch(); // Resume rotation timer
    return false; //Prevent browser jump to link anchor
});

});
