/**
 * Site specific javascript code.
 *
 * requires jquery to be already loaded
 */

/* ============================ image rotator ============================ */
var Rotator = new Object;

Rotator.operating = false;  // set to true if rotator is 'on'
Rotator.delay = 1500;       // time to transition from one image to the next
Rotator.duration = 4000;    // time a single image stays on view
Rotator.current = 0;
Rotator.nextSlide = -1;
Rotator.slides = new Array();
Rotator.timeoutId = 0;

Rotator.initiate = function() {

    Rotator.slides = $('#slideshow .slide');
	if (Rotator.slides.length <= 1) {
	  // not enough slides to rotate ... abort
	  return;
	}
	
	// hide all but the initial slide
	for (var i=1; i < Rotator.slides.length; i++) {
	  $(Rotator.slides[i]).hide();
	}

    // set onClick handler to stop/start rotation
	$('#slideshow').click( Rotator.toggle );	

	// start rotating
	Rotator.start();	
}

Rotator.start = function() {
    if (Rotator.timeoutId || Rotator.slides.length <= 1) return;
	
	Rotator.operating = true;
    Rotator.timeoutId = setTimeout(Rotator.transition, Rotator.duration);
}
Rotator.stop = function() {
    clearTimeout(Rotator.timeoutId);
	Rotator.timeoutId = 0;
	Rotator.operating = false;
}

Rotator.transition = function() {
    Rotator.timeoutId = 0;

    Rotator.nextSlide = Rotator.current+1;
    if (Rotator.nextSlide >= Rotator.slides.length) {
	    Rotator.nextSlide = 0;
    }

    $(Rotator.slides[Rotator.nextSlide]).show();
    $(Rotator.slides[Rotator.current]).fadeOut(Rotator.delay, function() {
        $(Rotator.slides[Rotator.nextSlide]).css('position','relative');
        $(Rotator.slides[Rotator.current]).css('position','static');
	  
        Rotator.current = Rotator.nextSlide;
        if (Rotator.operating) {
		  Rotator.start();
		}
	});
}
Rotator.toggle = function() {
  if (Rotator.operating) {
    Rotator.stop();
  } else {
    Rotator.start();
  }
}
/* =========================== formlet control ============================ */

/* ============================ document ready ============================ */
$(document).ready( function() {

    // set up image rotator (home page only)
	if ($('#slideshow').length) {
          Rotator.initiate();
	}
	
});
