(function ($) {

    $.fn.DynamicHeaderImage = function () {
        return this.each(function () {
            var box = $(this);
            var current_img = box.find('img');
            var all_alternatives = box.find('span.dynamicHeaderImage');

            var getRandomImage = function(exclude) {
                var alternatives = all_alternatives.not('#'+exclude);
                var total = alternatives.length;
                if (!total) return;
                var aleat = Math.round(Math.random() * (total-1));
                var span_img = alternatives.eq(aleat);

                return '<img src="'+ span_img.attr('src') + '" alt="'
                       + span_img.attr('alt') + '" class="dynamicHeaderImage" id="'
                       + span_img.attr('id') + '" />'
            }

            var initMainImage = function() {
                if (current_img.length) return;
                newimg = getRandomImage('');
                box.prepend(newimg);
            }

            var changeImage = function() {
                current_img = box.find('img');
                new_img = getRandomImage(current_img.attr('id'));
                if (!new_img) return;
                current_img.after(new_img);
		var newimg = current_img.next('img').hide();
                newimg.load(function() {
                    current_img.fadeOut(3000, function() {
                        $(this).remove();
                    });
		    newimg.fadeIn(3000, function() {
                        setTimeout(changeImage, 20000);
                    });
                });
            }

            initMainImage();
            setTimeout(changeImage, 20000);
        });
    }


    $(document).ready(function () {
        $(".HeaderImageBox").DynamicHeaderImage();
    });

})(jQuery);

