/* Banner slideshow with controls */
function SlideShow(slides, controls) {
    /* Slides container */
    this.slides = slides;
    /* Controls container */
    this.controls = controls;
    /* Active slide number container */
    this.active_slide = 0;
    /* Interval handler */
    this.interval = null;

    /* Changes active slide to new_slide. new_slide is INT */
    this.changeSlide = function(new_slide) {
        if(this.active_slide == new_slide) return false;
        if($('lightbox-starter')) {
            $('lightbox-starter').className = 'lightbox-start-'+new_slide;
        }
        this.slides[this.active_slide].fade({
            duration:0.5
        });
        this.active_slide = new_slide;
        this.slides[this.active_slide].appear({
            duration:0.5
        });
        return true;
    }

    /* Change to next */
    this.changeToNext = function() {
        var next_slide = this.active_slide + 1;
        if(next_slide == this.slides.length) next_slide = 0;
        this.changeSlide(next_slide);
    }

    /* Timed executioner */
    this.runTimer = function() {
        if(this.slides.length < 2) return false;
        this.interval = setInterval(this.changeToNext.bind(this), 7000);
        return true;
    }

    /* Map slides to controls */
    this.mapSlides = function() {
        var self = this;
        this.controls.each(function(control){
            control.observe('mouseover', function(event){
                self.changeSlide(this.id.replace('slide-control-', '') - 1);
                clearInterval(self.interval);
            });
            control.observe('mouseout', function(event){
                self.runTimer();
            });
        });
    }

    /* Apply height of image to slides container */
    this.applyHeight = function() {
        var maxHeight = 0;
        this.slides.each(function(slide){
            if(slide.getHeight() > maxHeight) maxHeight = slide.getHeight();
        });
        this.slides.first().up().setStyle({height: maxHeight+'px'});
    }


    /* Initialize */
    this.mapSlides();
    this.applyHeight();
    this.runTimer();
}

/* Initailise slideshow on the page */
document.observe("dom:loaded", function() {
    new SlideShow($$('div.slide'), $$('div#thumbnails img'));
});
