﻿(function($) {

    var activeIdx = 0;
    var delay = 5000;

    $.fn.featureFlipper = function(options) {

        return this.each(function() {

            var opt = jQuery.extend({
                data: null // (JSON) Image file paths, five max {image0 :  'mypath/myimage1.jpg', image1 : 'mypath/myimage1.jpg'}.
            }, options);

            var bDiv = document.createElement('div');
            bDiv.id = 'featureButtonContainer';

            var aAnchor = null;

            var fImage = null;

            var bImage = null;

            var featureContainer = this;

            $.each(opt.data.images, function(idx, value) {

                var bImage = new Image();
                bImage.src = 'Images/Test1/dot2.jpg';
                bImage.id = 'imgButton' + idx;
                $(bImage).addClass('featureButton');

                $(bImage).click(function() {
                    flipImage(this, idx)
                });

                aAnchor = document.createElement('a');
                aAnchor.href = 'Article.aspx?UserFeedGuid=cdf79da1-6017-4c09-a75f-b181c34a416e&articleid=' + value.id;

                fImage = new Image();
                fImage.border = 0;
                fImage.src = value.src;
                fImage.alt = value.alt;
                fImage.id = 'imgFeature' + idx;
                $(fImage).addClass('featureImage');
                $(fImage).hide();

                $(aAnchor).append(fImage)
                $(featureContainer).append(aAnchor);
                $(bDiv).append(bImage);

            });

            $(this).append(bDiv);
            flipImage($('#imgButton0'), 0);

            window.setInterval(function() {
                flipImage($('#imgButton' + activeIdx), activeIdx);
                //activeIdx = activeIdx == 4 ? 0 : activeIdx + 1;
            }, delay);

        });

    };

    function flipImage(button, idx) {
        $('.featureButton').attr('src', 'Images/Test1/dot2.jpg');
        $(button).attr('src', 'Images/Test1/dot1.jpg');
        $('.featureImage').fadeOut();
        $('#imgFeature' + idx).fadeIn();
        activeIdx = idx == 4 ? 0 : idx + 1;
    }

})(jQuery);
