/* Author: Kalley Powell

*/

var root = $(document).on('ready', function() {

$('div.collapsible').each(function() {
    var section = $(this), content = section.find('div.collapsible-content'), figure = content.find('figure'), img = figure.find('img'), completed = 0;
    img.one('load', function() {
        if(++completed == img.length) {
            section.toggleClass('opened');
            figure.height(content.height()-parseInt(figure.css('margin-top'))-parseInt(figure.css('margin-bottom'))-parseInt(figure.css('padding-top'))-parseInt(figure.css('padding-bottom')));
            section.toggleClass('opened');
            section.find('h3').wrapInner('<a href=#></a>').find('a').bind('click', function() {
                section.toggleClass('opened');
                return false;
            });
         }
    }).each(function() {
        if(this.complete) $(this).trigger('load');
    });

});

$('#banners').each(function() {
    var bannerNav = $('<ul id=banner-nav></ul>'), t,
        swapBanners = function(banner) {
            clearTimeout(t);
            t = setTimeout(swapBanners, 7000);
            if( ! banner) {
                var active = banners.find('div.banner:visible');
                banner = active.next('.banner')[0] ? active.next() : banners.find('div.banner:first');
            }
            banner.show().fadeTo(400,1).siblings('.banner').fadeTo(400, 0, function() { $(this).hide(); });
            banner.data('navLI').addClass('active').siblings('.active').removeClass('active');
        },
        banners = $(this).find('div.banner').each(function(i) {
            var banner = $(this).css('opacity', +(i == 0))[i == 0 ? 'show' : 'hide'](),
                navLI = $('<li id=b'+i+(i == 0 ? ' class=active' : '')+'><a href=#><b></b></a></li>').on('click', 'a', function() {
                    swapBanners(banner);
                    return false;
                }).appendTo(bannerNav);
            banner.data('navLI', navLI);
        }).end().append(bannerNav);
    t = setTimeout(swapBanners, 7000);
});

});
