﻿(function($) {
    // 'PromoSlider' is the name of the plugin
    $.fn.promoSlider = function(options) {
        // Define the default values of the options of the plugin
        var defaults = {
            height: 200,
            width: 500,
            boxType: "div",
            boxesToMove: 1,
            boxesPerScreen: 1,
            enableRotate: true,
            nextButtonText: "next",
            previousButtonText: "previous"
        };
        // Get all user defined options and the defaults
        var options = $.extend(defaults, options);
        // For each instance of the plugin do the following:

        var loadedContext = $(this);

        return this.each(function() {
            var isMoving; // is set to true if the user slider is in action
            var body; // the element the plugin has been assigned too
            var items; // a collection of the items within the slider
            var widthOfItem; // the width of each item
            var widthOfitemContainer; // width of the outter contianer
            var numberOfBoxes; // total of boxes in the slider
            var amountToMove; // distance, in pixel, that the slider should move - calculated further down
            var boxesToMove; // how many boxes should be moved at a time
            var pageNumber; // number of pages that will be available (total boxed divided by how many to move)
            var pagesVisitCount; // the number of slides the user has seen
            var boxesPerScreen; // number of boxes the user should see, per slide

            pagesVisitCount = 0; // On load, set the number of visits to zero
            isMoving = false; // slider not currently moving
            body = $(this); // body equals the container that invoked this mesage
            items = $(this).children(); // a collection of all boxes within the slider
            widthOfitemContainer = 0; // this will be set later, current value set to 0
            numberOfBoxes = $(this).children().length; // total number of boxes, equals the items collection length

            if (numberOfBoxes < options.boxesPerScreen) {
                // IF the number of items in the slider is less than the amount the user has specified 
                // should be shown per slide, just show as many as possible
                boxesPerScreen = numberOfBoxes;
            } else {
                // Otherwise, show as many as they've entered
                boxesPerScreen = options.boxesPerScreen;
            }
            if (options.boxesToMove > boxesPerScreen) {
                // if the user is trying to move more boxes than are available, overwrite the value
                boxesToMove = boxesPerScreen;
            } else {
                // Otherwise their choice is fine
                boxesToMove = options.boxesToMove;
            }
            if (options.enableRotate == false) {
                // Only do the following if the user does not want the slider to constantly loop thru the boxes:
                // This is to stop the slider loading blank slides
                if ((numberOfBoxes - boxesPerScreen) % boxesToMove != 0) {
                    boxesToMove = 1;
                }
                // This is to stop the slider loading blank slides
                if ((numberOfBoxes % boxesToMove) != 0) {
                    boxesToMove = 1;
                }
            }
            // If the user is trying to move more boxes per screen than is possible overwrite it 
            if ((numberOfBoxes - boxesPerScreen) < boxesToMove) {
                boxesToMove = 1;
            }
            // Number of total slider pages
            pageNumber = ((numberOfBoxes - boxesPerScreen) / boxesToMove);

            // Determine what state the navigation should be in:
            function navState(override) {
                // Override is only present when this function is called manually at the start of the code
                if (override) {
                    // set the context to ALL boxes
                    context = $(override).parent().parent();
                } else {
                    // set the context to the container of the active box
                    context = $(this).parent().parent();
                }
                // only do the following if the slider doesn't loop
                if (options.enableRotate == false) {
                    // if the number of pages the user has visited equals the total number of pages they are on the last page
                    if (pagesVisitCount == pageNumber) {
                        // disable the next button
                        $(".js-nav-next", context).hide();
                        // Check the status of the previous button
                        if (pagesVisitCount != 0) {
                            // If pagesVisitCount greater than 0 there are previous pages to visit
                            $(".js-nav-prev", context).show();
                        } else {
                            // if no previous pages exist hide the previous button
                            $(".js-nav-prev", context).hide();
                        }
                    } else {
                        // if not on the final page, show the next button
                        $(".js-nav-next", context).show();
                        if (pagesVisitCount != 0) {
                            // If pagesVisitCount greater than 0 there are previous pages to visit
                            $(".js-nav-prev", context).show();
                        } else {
                            // if no previous pages exist hide the previous button
                            $(".js-nav-prev", context).hide();
                        }
                    }
                }
                showTitle();
            }
            body.addClass("js-slider-container"); // add this to the element that invoked it. This is used for styles and a JQ selector
            body.width(options.width); // set the width of this to the width specified by the options
            body.height(options.height); // set the height of this to the width specified by the options

            widthOfItem = (body.width() / boxesPerScreen); // each individual box will be calculated based on the overal with of the visible container divided by the number of boxes on display
            amountToMove = (widthOfItem * boxesToMove); // the slider needs to move by the width of the boxes multiplied by the amount of visible boxes

            // Only add navigation controls if there is more than one box AND if the total number of boxes is greater than the number to show per slide
            if (boxesPerScreen != numberOfBoxes && numberOfBoxes > 1) {
                body.wrapInner('<div class="js-slider-wrapper" />'); // create the element that does the sliding
                // add the nav dynamically
                body.append('<div class="js-slider-nav"><a href="javascript:void(0)" class="js-nav-prev">' + options.previousButtonText + '</a> <a href="javascript:void(0)" class="js-nav-next">' + options.nextButtonText + '</a>');
            }

            body.append('<div class="js-animated-title"></div>');

            //            if ($(this).attr("associatedtitle") == "" || $(this).attr("associatedtitle") == null) {
            //                // Do Nothing
            //            } else {
            //                //alert("test " + $(".js-slider-wrapper").parent().attr("associatedtitle"));
            //                
            //                $(".js-animated-title").animate({
            //                    bottom: "-160px"
            //                }, 1000);
            //            }



            // Assign the event handler for the next button
            $(".js-slider-nav a.js-nav-next", this).click(function() {
                var context = $(this).parent().parent(); // the context of this is the outter container of the item that raised the event
                if (!isMoving) { // only do this if the slider is not moving
                    pagesVisitCount++; // increment the pagesVisitCount
                    $(".js-nav-next", context).fadeTo(100, 0.3); // Move boxes backwards if clicking is not disabled. Fade out button.
                    $(".js-slider-wrapper", context).animate({
                        left: '-=' + amountToMove // move the slider the calculated amount
                    }, 1000, function() {
                        // Allow clicking again, unfade button.
                        isMoving = false;
                        $(".js-nav-next", context).fadeTo(100, 1, navState);
                        for (var x = 0; x < boxesToMove; x++) {
                            // place the boxes that have been moved into the visible area
                            $(".js-slider-content-box", context).eq(0).insertAfter($(".js-slider-content-box", context).eq(numberOfBoxes - 1));
                        }
                        $(".js-slider-wrapper", context).animate({
                            left: '+=' + amountToMove
                        }, 0);
                    });
                    // Clicking is disabled whilst completing the loop.
                    isMoving = true;
                }
            });
            $(".js-slider-nav a.js-nav-prev", this).click(function() {
                var context = $(this).parent().parent(); // the context of this is the outter container of the item that raised the event
                if (!isMoving) {
                    pagesVisitCount--; // decrement the PagesVisitCount
                    // Move boxes forward if clicking is not disabled. Fade out button.
                    for (var x = 0; x < boxesToMove; x++) {
                        // place the boxes that have been moved into the visible area
                        $(".js-slider-content-box", context).eq(numberOfBoxes - 1).insertBefore($(".js-slider-content-box", context).eq(0));
                    }
                    $(".js-nav-prev", context).fadeTo(100, 0.3);
                    $(".js-slider-wrapper", context).animate({
                        left: '-=' + amountToMove
                    }, 0);
                    $(".js-slider-wrapper", context).animate({
                        left: '+=' + amountToMove
                    }, 1000, function() {
                        // Allow clicking again, unfade button.
                        isMoving = false;
                        $(".js-nav-prev", context).fadeTo(100, 1, navState);
                    });
                    // Clicking is disabled whilst completing the loop.
                    isMoving = true;
                }
            });

            function showTitle() {
                if ($(".js-slider-content-box", loadedContext).attr("associatedtitle") == "" || $(".js-slider-content-box", loadedContext).attr("associatedtitle") == null) {
                    $(".js-animated-title", loadedContext).hide();
                } else {
                $(".js-animated-title", loadedContext).show().html($(".js-slider-content-box", loadedContext).attr("associatedtitle"));
                }
            }

            for (var i = 0; i < numberOfBoxes; i++) {
                // Only perform the following for items that user says should be sliders
                if (items[i].nodeName == options.boxType.toUpperCase()) {
                    $(items[i]).addClass("js-slider-content-box"); // add a wrapper class
                    $(items[i]).css('height', options.height); // add the specified height
                    $(items[i]).css('width', widthOfItem); // add the specified width
                    widthOfitemContainer += $(items[i]).outerWidth(); // calculate the width of the slider
                    $(".js-slider-wrapper", this).css('width', widthOfitemContainer + options.width); // add this to the slider
                }
            }
            // Once all the elements have been dynamically created check what state the nav should be in.
            // This is the only time this is done manually - from now on it is done on the call back of each slide
            navState(loadedContext);
        });
    };
})(jQuery);    
