/*
 * Addon to jQuery Cycle Plugin
 * Original examples and documentation at: http://malsup.com/jquery/cycle/
 * Dayspring additions provide image preloading features.
 * 
 * Images are defined in an Javascript array and are loaded individually as necessary.
 */
;(function($) {
$.fn.dsCycle = function(elements, opts) {
    // array (stack) to hold loaded but not inserted images
    var stack = [];
    var img = null;
    var loading = false;
    
    // remove any existing content, such as noscript content
    $(this).empty();
    
    // merge our default options for before and after hooks with passed options
    var options = $.extend({after: onAfter, before: onBefore}, opts);
    
    // insert first two images directly into the DOM so we can start the cycle
    for (var i = 0; i < 2; i++){
        if (elements.length)
            $('<img/>').attr('src', elements.shift()).appendTo(this);
    }  

    // wrap the slideshow div with another div of specified height (for borders or padding)
    $(this).wrap('<div/>');
    $(this).parent().height(options.height);
    
    // init cycle
    $(this).cycle(options);
    
    // after a transition is complete, load the next pending image in the list
    function onAfter(){
        if (!loading && elements.length){
            loading = true;
            img = new Image();
            img.onload = imgLoaded;
            img.src = elements.shift();
        }            
    }
    
    function imgLoaded(){
        if (loading)
            stack.push(img);
        loading = false;
    }
    
    // before a transition, insert any loaded but not inserted images
    function onBefore(curr, next, opts){
        if (opts.addSlide) // <-- important!
            while(stack.length)
                opts.addSlide(stack.shift());
    }
};
})(jQuery);
