/*global jQuery, document, window */
(function($) {

    function to_css_url(s) {
        // IE cannae handle full URLs, presumably for security reasons
        s = s.replace(/^http:\/\/[^\/]+/i,'');
        return 'url('+s+')';
    }

    function rotate_image(bkgd_lower,bkgd_upper,image_list,i) {
        // Swap the image of whichever div we can't see
        if(bkgd_upper.css('display') === 'block') {
          bkgd_lower.css('background-image',to_css_url(image_list[i]));
        } else {
          bkgd_upper.css('background-image',to_css_url(image_list[i]));
        }
        window.setTimeout(function() {
            bkgd_upper.fadeToggle(500,function() {
                rotate_image( bkgd_lower, bkgd_upper
                            , image_list
                            , (i+1) % image_list.length
                            );
            });
        }, 10000);
    }

    $(document).ready(function() {
         $("div.background-container").each(function(index) {
            // Find the background image list, if nonexistent or empty don't do anything
            var backgrounds = $(this).attr('data-backgrounds');
            var image_list = backgrounds ? backgrounds.split(/\s+/) : [];
            if(image_list.length <= 1) { return; }

            // Add in extra div; will toggle this on/off to change background
            var grid_background = $(this).children("div.grid-background");
            var bkgd_upper = $("<div/>")
                             .attr('class','secondary-background')
                             .css("position","absolute")
                             .css("top","0px")
                             .css("left","0px")
                             .css("display","none")
                             .css("width",grid_background.width())
                             .css("height",grid_background.height());
            $(this).prepend(bkgd_upper);
            rotate_image($(this),bkgd_upper,image_list,1);
        });
    });

}(jQuery));

