﻿$(document).ready(function () {

    //Set Default State of each portfolio piece
    $(".paging").show();

    //Get size of images, how many there are, then determin the size of the image reel.
    var imageWidth = $(".window").width();
    var imageSum = $(".image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;
    var currentSlide = 1;

    // default text
    $('#pagerText').text('');
    $('#pagerText').text(currentSlide + ' of ' + imageSum);

    //Adjust the image reel to its new size
    $(".image_reel").css({ 'width': imageReelWidth });

    //Paging + Slider Function
    rotate = function () {

        //alert(currentSlide);

        $('#pagerText').text('');
        $('#pagerText').text(currentSlide + ' of ' + imageSum);

        var triggerID = currentSlide - 1; //Get number of times to slide
        var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

        //Slider Animation
        $(".image_reel").animate({
            left: -image_reelPosition
        }, 500);

    };

    //Rotation + Timing Event
    rotateSwitch = function (offset) {
        play = setInterval(function () { //Set timer - this will repeat itself every 3 seconds
            setCurrentSlide(offset);
            rotate(); //Trigger the paging and slider function
        }, 4500); //Timer speed in milliseconds (3 seconds)
    };

    rotateSwitch(1); //Run function on launch

    //On Hover
    $(".image_reel a").hover(function () {
        clearInterval(play); //Stop the rotation
    }, function () {
        rotateSwitch(1); //Resume rotation
    });

    //On Click
    $(".paging a").click(function () {
        //alert($(this).attr("rel"));
        setCurrentSlide($(this).attr("rel"));
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(0); // Resume rotation (dont update currentSlide
        return false; //Prevent browser jump to link anchor
    });

    function setCurrentSlide(offset) {
        if (offset == 1) { // moving forwards
            if (currentSlide == imageSum)
                currentSlide = 1;
            else
                currentSlide++;
        }

        if (offset == -1) { // moving backwards
            if (currentSlide == 1)
                currentSlide = imageSum;
            else
                currentSlide--;
        }
    }

});
