﻿$(function () {
    // Define attributes
    var currentPosition = 0;
    var slideWidth = 370;
    var slides = $(".slide");
    var numberOfSlides = slides.length;

    // Add active class to first element
    $("div#promo_link ul li:first-child").addClass("active");

    // Add slideInner
    slides.wrapAll('<div id="slideInner"></div>').css({
        'float': 'left',
        'width': slideWidth
    });

    // Calculate and set width of #slideInner
    $("#slideInner").css({
        'width': slideWidth * numberOfSlides
    });


    // Add click function to arrows
    $(".control").click(function () {
        // Set current position
        currentPosition = ($(this).attr("id") == 'rightcontrol') ? currentPosition + 1 : currentPosition - 1;
        if (currentPosition >= numberOfSlides) {
            currentPosition = 0;
        } else if (currentPosition < 0) {
            currentPosition = numberOfSlides - 1;
        }

        if (currentPosition > -1 && currentPosition < numberOfSlides) {
            // Animate to the right location
            $("#slideInner").animate({
                'marginLeft': slideWidth * (-currentPosition)
            });
        }

        // Set active class to right list items and remove from all other list items
        i = 0;

        $.each($("div#promo_link ul li"), function () {
            if (currentPosition == i)
                $(this).addClass("active");
            else
                $(this).removeClass("active");
            i++;
        });
    });

    // Add click function to list items
    $("#promo_link ul li").click(function () {
        var activeId = $(this).attr("id");
        var i = 0;

        // Loop through all list items
        $.each($("div#promo_link ul").children(), function () {
            // Check if list item is clicked list item
            if ($(this).attr("id") == activeId) {
                // Set current position
                currentPosition = i;
            }
            // Remove active class from all list items
            $(this).removeClass("active");
            i++;
        });

        // Animate to select list item
        $("#slideInner").animate({
            'marginLeft': slideWidth * (-currentPosition)
        });

        // Add active class to clicked list item
        $(this).addClass("active");

        // Stop the timer
        window.clearInterval(interval_id);
    });
});
