﻿(function($) {

    // name plugin
    $.fn.frostFade = function(options) {

        var currentItem = 0;
        var currentLink = 0;
        var storyTimer;

        var defaults = {
            play: true,
            controller: false,
            controllerName: null,
            buttonNext: null,
            buttonPrevious: null,
            playButton: null,
            teaser: null,
            timer: 5000
        },

        // overide the default settings with any setting passed through into options
        // assign the settings variable to a new object {} with the result of the merge
        settings = $.extend({}, defaults, options);

        return this.each(function() {

            // == Cache Variables
            var $container = $(this);
            var $containerID = $container.attr('id');
            var $controllerName = $(settings.controllerName);
            var numItems = $('ul', $container).children().length;

            // == Get children count
            if (numItems <= 1) {
                settings.controller = false;
                settings.play = false;
            };

            // == get children as objects
            var itemObj = $('ul', $container).children();

            // == Set parent styling
            itemObj.parent().css({
                "position": "relative",
                "visibility": "visible"
            });

            // == Add styling to children
            itemObj.each(function(num) {

                var layerIndex = 100 - num;

                $(itemObj[num])
                .css({
                    zIndex: layerIndex,
                    'top': 0,
                    'left': 0,
                    'position': 'absolute',
                    'display': 'none'
                })
                .attr('id',
                function() {
                    return $container.attr('id') + num
                })
                .end();
            });

            // == Show first slide
            $(itemObj[0]).show();

            // == Add controlls to fader
            if (settings.controller) {
                var result = '';
                for (var x = 0; x < numItems; x++) {
                    // if first a tag to be added, give itemLinkSelected class
                    (x == 0) ? itemClass = "itemLinkSelected" : itemClass = "itemLink";
                    result += '<a class="' + itemClass + '" title="feature" href="#' + itemObj[x].id + '">' + (x + 1) + '</a>';
                    var orderItems = '#' + itemObj[x].id;
                }

                $controllerName.html(result);
                var $controllerChildren = $controllerName.children();
            }

            // == Fade function
            autoFader = function(nextID, clicked) {

                // == So if not clicked
                if (nextID) {
                    var selectedDiv = nextID;
                } else {
                    // == If clicked stop playing, get the a href hash
                    stopTimer();
                    var selectedDiv = String(clicked.substr(1));
                }

                for (var x = 0; x < numItems; x++) {
                    var hideItem = $container.attr('id') + x;
                    if (hideItem !== selectedDiv) $('#' + hideItem).fadeOut('slow');
                }

                $('#' + selectedDiv).fadeIn('slow');

                // == remove items that were previously selected
                var checkItems = $(settings.controllerName).children();
                for (var x = 0; x < checkItems.length; x++) {

                    if ($(checkItems[x]).hasClass('itemLinkSelected')) {
                        $(checkItems[x]).removeClass('itemLinkSelected');
                        $(checkItems[x]).addClass('itemLink');
                    }
                }

                // add the selected class to the button
                lastIndex = String(selectedDiv).length - 1;
                stringSelectedDiv = String(selectedDiv);
                currentLink = Number(stringSelectedDiv.charAt(lastIndex))

                $(checkItems[currentLink]).addClass('itemLinkSelected');
                $(checkItems[currentLink]).removeClass('itemLink');
            }

            // when previous is clicked
            reverseOrder = function() {
                // what is the current item?
                var currentDisplayed;
                var itemLinks = $controllerChildren;

                for (var x = 0; x < itemLinks.length; x++) {
                    if ($(itemLinks[x]).hasClass('itemLinkSelected')) {
                        currentDisplayed = x;
                    }
                }

                var previousItem = currentDisplayed;
                // if previous item is less the zero, the fade in last item in the number of items
                if (previousItem <= 0) {
                    previousItem = numItems - 1;
                }
                else {
                    previousItem--;
                }
                var itemtoCall = $container.attr('id') + previousItem;
                currentItem = previousItem;
                autoFader(itemtoCall, null);
            }
            // Work out what is the a item showing
            callFader = function() {
                var totalItemsAvail = numItems - 1;
                if (currentItem >= totalItemsAvail) {
                    currentItem = 0;
                } else {
                    currentItem++;
                }

                var itemtoCall = $container.attr('id') + currentItem;

                autoFader(itemtoCall, null);
            }

            stopTimer = function() {
                clearInterval(storyTimer);
            }

            // play fader
            if (settings.play) {
                storyTimer = setInterval(callFader, settings.timer);
            }

            if (typeof $controllerChildren != 'undefined') {
                $controllerChildren.bind('click',
                function(e) {
                    e.preventDefault();
                    var clickedItem = $(this).attr('href');
                    autoFader(clickedItem);
                });
            }

            if (settings.buttonPrevious && settings.buttonNext) {
                $(settings.buttonNext).bind('click',
                function(event) {
                    callFader()
                });
                $(settings.buttonPrevious).bind('click',
                function(event) {
                    reverseOrder();
                });
            };

        });
        // end each
    }

})(jQuery);
