//on page load
$(document).ready(function() {
    //initialize slideshow
    $("#slideShow").each(function() { $(this).initSlideShow() });
});

/* SlideShow
--------------------------------------------------------------------------*/
$.fn.initSlideShow = function() {
    var slideShow = $(this);
    var slideWidth = 670;
    var totalslides = $(".slide", slideShow).length - 1;
    var canvasWidth = -(totalslides - 1) * slideWidth;
    var slideSpeed = 1;
    var WaitTime = 8;
    var timeUnit = 1000; //timeUnit = seconds
    var speed = slideSpeed * timeUnit;
    var slideTimer = null;
    var activeSlide = 0; //which slide is active

    //init startitem
    $(".directaccess li a:eq(0)", slideShow).addClass("active");

    function getCurrentPos(pos) {
        return $(".directaccess li a:eq(" + pos + ")", slideShow).position().left;
    }
    function clearCurrentState() {
        $(".directaccess", slideShow).find(".active").removeClass("active");
    }

    slideShow.bind("mouseleave", function() {
        autoplay();
    });

    slideShow.bind("mouseenter", function() {
        stopAutoplay();
    });

    //init directaccess ----------
    $(".directaccess li a", slideShow).each(function(i) {
        $(this).attr('href', 'javascript:void(0)').click(function() {
            clearInterval(slideTimer);
            clearCurrentState();
            $(this).addClass("active");
            slide(i);
        })
    })

    //init slide magic ----------
    function autoplay() {
        slideTimer = setInterval(function() { slideNext() }, WaitTime * timeUnit);
    }

    function stopAutoplay() {
        clearInterval(slideTimer);
    }

    function slideNext() {
        if (activeSlide < totalslides) { slide(activeSlide + 1) }
        else { slide(0) }
    }

    function slidePrev() {
        if (activeSlide == 0) { slide(totalslides) }
        else { slide(activeSlide - 1) }
    }

    function slide(pos) {
        $("#canvas", slideShow).animate({ "margin-left": -slideWidth * pos }, speed / 2);
        $(".current", slideShow).animate({ "margin-left": getCurrentPos(pos) }, timeUnit / 2, function() {
            clearCurrentState();
            $(".directaccess li a:eq(" + pos + ")", slideShow).addClass("active");
        });
        activeSlide = pos;
    }

    //start the show
    autoplay();

}
