var interval;
var imageWidth;
var $originalSlides;
var slideToEnd;
var totalSlides;
var slideToStart;
var previousSlide;
var activeSlide;
var inAnimation;
var ie7;

// onload, initialize the slides
$(window).load(function () {
    initSlides();
});

// on window resize, call add or remove slides
$(window).resize(function () {
    addOrRemoveSlides()
});

// add the on click event
function bindClickEvents() {

    // unbind first to make sure it doesn't get doubly bound
    $(".slideshow .slide").unbind("click").bind('click', function () {
        stopSlides();
        setActiveSlide($(this).index())
        startSlides();
    });
}

// unbind the click events
function unbindClickEvents() {
    $(".slideshow .slide").unbind('click');
}


// Setting up stuff
function initSlides() {

    // determine if we're using ie7
    ie7 = false;
    var browserVersion = navigator.appVersion;
    if (browserVersion.indexOf('MSIE 7') >= 0 && browserVersion.indexOf('Trident/4.0') == -1) {
        ie7 = true;
    }

    //initialize variables
    slideToEnd = 0;
    inAnimation = 0;
    imageWidth = $(".slideshow .slide:first").width();
    activeSlide = 0;

    // make a clone of the original slides for adding and removing in propper order
    $originalSlides = $(".slideshow").clone().attr("id", "originalSlideShow");
    totalSlides = $originalSlides.children(".slide").length;
    slideToStart = totalSlides - 1;
    previousSlide = totalSlides - 1;

    slideHeight = $(".slide img:first").height();
    slideHeight += 15;

    $("#bodyContent").css('padding-top', slideHeight);

    if (EditMode != true) {
        addOrRemoveSlides();
        reCenterSlideShow();
        bindClickEvents();
        startSlides();
    }
}

// start the slide rotation on an interval
function startSlides() {
    interval = setInterval("setActiveSlide()", 12000);
}

// clear the timer interval
function stopSlides() {
    clearInterval(interval);
}


function reCenterSlideShow() {
    //figure out how far to move to get the left back to 0
    var moveToAlign = -($(".slideshow").offset().left);

    // get the location where the middle left corner of the center slide needs to be
    var middleLeftCorner = ($(window).width() / 2) - (imageWidth / 2);

    // go through each image
    var currentSlide = 0;
    $('.slideshow img').each(function () {

        // get the image position
        currentImagePos = $(this).offset().left;

        // if this is the first image at or past the middle after the alignment move
        if ((currentImagePos + moveToAlign) >= middleLeftCorner) {
            // set the active slide
            setActiveSlide(currentSlide);

            // break out of the each
            return false;
        }
        currentSlide++;
    });
}

function setActiveSlide(slideToCenter, offsetMove) {
    if (inAnimation)
        return;

    inAnimation = 1;

    // clicking during animation causes things to blow up
    unbindClickEvents();

    var $slides = $(".slideshow .slide");
    var middleLeftCorner = ($(window).width() / 2) - (imageWidth / 2);

    // if no offset was passed in, set it to 0
    if (offsetMove == null)
        offsetMove = 0;

    // save the previous slide
    previousSlide = activeSlide;

    // if no slide is specified, use the next slide
    if (slideToCenter == null) {
        slideToCenter = ++activeSlide;
    }
    else {
        activeSlide = slideToCenter;
    }

    // if we aren't just doing a recenter
    if (previousSlide != activeSlide) {

        // fade out the active caption
        // $slides.children(".slideCaption").fadeOut(500);
        $slides.children(".slideTitle").eq(previousSlide).animate({ left: -3000 }, { duration: 1100, easing: 'easeInOutCubic',
            complete: function () {
                $slides.children(".slideTitle").eq(previousSlide).fadeOut();
            }
        });
        $slides.children(".slideCaption").eq(previousSlide).animate({ left: 1000 }, { duration: 1100, easing: 'easeInOutCubic',
            complete: function () {
                $slides.children(".slideCaption").eq(previousSlide).fadeOut().animate({ left: 0 }, 0);
            }
        });
    }


    // calculate how far the image needs to move to be centered
    var imagePos = $slides.eq(slideToCenter).offset().left;
    var moveToCenter = middleLeftCorner - (imagePos);

    // if browser is ie7, then subtract 10 from the move
    if (ie7)
        moveToCenter -= 10;
    // adjusting for a slight offness of the banner to the left of the menu
    else
        moveToCenter -= 2;


    // check to see if we need to add images to the left to fill in before the move
    while (moveToCenter > -($(".slideshow .slide:first").offset().left)) {
        $originalSlides.children().eq(slideToStart).clone().insertBefore(".slideshow .slide:first");
        $(".slideshow").animate({ left: "+=" + -imageWidth }, 0);
        firstImagePos = $(".slideshow .slide").first().offset().left;

        slideToStart--;
        activeSlide++;
        if (slideToStart < 0)
            slideToStart = totalSlides - 1;
    }

    // check to see if we need to add images to the right to fill in before the move
    while (-moveToCenter > ($(".slideshow .slide:last").offset().left - $(window).width())) {
        $originalSlides.children().eq(slideToEnd).clone().insertAfter(".slideshow .slide:last");
        lastImagePos = $(".slideshow .slide:last").offset().left;
        slideToEnd++;
        slideToEnd = slideToEnd % totalSlides;
    }

    // bring in the new active slide's title
    $activeSlideTitle = $(".slideshow .slide").eq(activeSlide).children(".slideTitle");
    var top = $activeSlideTitle.attr("top");
    var left = $activeSlideTitle.attr("left");
    $activeSlideTitle.css("top", top);
    $activeSlideTitle.css("left", 2700);
    //        $activeSlideTitle.fadeIn(0);
    $activeSlideTitle.animate({ left: left }, { duration: 1700, easing: 'easeInOutCubic' });

    // bring in the new active slide's caption
    $activeSlideCaption = $(".slideshow .slide").eq(activeSlide).children(".slideCaption");
    var top = $activeSlideCaption.attr("top");
    var left = $activeSlideCaption.attr("left");
    $activeSlideCaption.css("top", top);
    $activeSlideCaption.css("left", -3000);
    $activeSlideCaption.fadeIn(0);
    $activeSlideCaption.animate({ left: left }, { duration: 2000, easing: 'easeInOutCubic' });

    // move to the slide to center
    $(".slideshow").animate({ left: "+=" + moveToCenter },
          { duration: 1500,
              easing: 'easeInOutCubic',
              complete: function () {

                  // add or remove images as necessary          
                  addOrRemoveSlides(true);

                  // rebind the click event
                  bindClickEvents();



                  // set the animation flag to 0 (resizing can now occur again)
                  inAnimation = 0;
              }
          });
}

// determine if slides need to be added to the right or the left for continuity
function addOrRemoveSlides(bypassCheck) {

    bypassCheck = typeof (bypassCheck) != 'undefined' ? bypassCheck : false;

    // if we are in animation, bail out!
    // calling this function in the middle of animation will cause errors as slides
    // will be added and removed dynamically
    if (!bypassCheck && (inAnimation || $originalSlides == null)) {
        return;
    }

    // get first and last image position
    lastImagePos = $(".slideshow .slide").last().offset().left;
    firstImagePos = $(".slideshow .slide").first().offset().left;

    // add images to the right if needed
    while ($(window).width() > lastImagePos) {
        // insert a new slide after the last slide
        $originalSlides.children().eq(slideToEnd).clone().insertAfter(".slideshow .slide:last");

        // calculate the new last slide's position
        lastImagePos = $(".slideshow .slide:last").offset().left;

        // increment the slide to end counter
        slideToEnd++;
        slideToEnd = slideToEnd % totalSlides;
    }

    // remove images from the right if needed
    while ($(window).width() < (lastImagePos - imageWidth)) {
        // remove the last slide
        $(".slideshow .slide").last().remove();

        // calculate the new last slide's position
        lastImagePos = $(".slideshow .slide").last().offset().left;

        // decrement the slide to end counter
        slideToEnd--;
        if (slideToEnd < 0)
            slideToEnd = totalSlides - 1;
    }

    // add images to the left if needed
    while (firstImagePos > 0) {
        // add a new slide to the beginning
        $originalSlides.children().eq(slideToStart).clone().insertBefore(".slideshow .slide:first");

        // shift the slideshow left to account for the new slide
        $(".slideshow").animate({ left: "+=" + -imageWidth }, 0);

        // determine the new first slide's position
        firstImagePos = $(".slideshow .slide").first().offset().left;

        // decrement the slide to the start counter
        slideToStart--;
        if (slideToStart < 0)
            slideToStart = totalSlides - 1;

        // increment the active slide counter to account for the new slide before it
        activeSlide++;

    }

    // remove images from the left if needed
    while (-(firstImagePos) > imageWidth) {

        // remove the first slide
        $(".slideshow .slide").first().remove();

        // reposition the slide show to account for the removed slide
        $(".slideshow").animate({ left: "+=" + imageWidth }, 0);

        // calculate the new position of the first slide
        firstImagePos = $(".slideshow .slide").first().offset().left;

        // increment the slide to start counter          
        slideToStart++;
        slideToStart = slideToStart % totalSlides;

        // decrement the active slide counter to account for the removed slide
        activeSlide--;
    }
}

// smart resizing function to stop double call in IE
(function ($, sr) {

    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced() {
            var obj = this, args = arguments;
            function delayed() {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
            };

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 100);
        };
    }

    // smartresize 
    jQuery.fn[sr] = function (fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery, 'smartresize');

// on smart resize, stop the animation, recenter the slides, and start the animation
$(window).smartresize(function () {
    stopSlides();
    reCenterSlideShow();
    startSlides();
});
