var Flipbook = {
    obj          : {},
    frameRate    : 6,
    fadeSpeed    : 0,
    ajaxPhp      : '/js/flipbook.php',
    frames       : $('<div></div>'),
    imageCount   : 0,
    loadedImages : 0,
    isBuilt      : 0,
    loadingAjax  : 0,
    
    init : function( source ) {
        Flipbook.obj.wrapper  = $('#flipbook');
        
        if ( typeof( source ) == 'undefined' ) Flipbook.startFlipping();
        else {
            Flipbook.processSource( source );
            
            Flipbook.isBuilt = 1;
            
            // if the images loaded faster than we were able to set the isBuilt variable, we make sure to start the flipbook here...just a failsafe
            if ( Flipbook.imageCount == Flipbook.loadedImages && !Flipbook.loadingAjax ) Flipbook.startFlipping();
        }
    },
    
    processSource : function( source ) {
        if ( typeof( source ) == 'string' ) source = [ source ];
        for ( var i = 0; i < source.length; i++ ) {
            if ( !Flipbook.isImage( source[i] ) ) Flipbook.addDirectory( source[i] );
        }
    },
    
    isImage : function( source ) {
        var theExt = source.substr( source.length - 4 );
        if ( theExt == '.jpg' || theExt == '.png' || theExt == '.gif' || theExt == '.bmp' ) {
            Flipbook.imageCount++;
       
            // append an image with this source, adding to the loaded images variable once the image is loaded in the browser

            var img = new Image();
            $img = $(img);
            if ( Flipbook.imageCount == 1 ) $img.addClass('active bananas');
            
            $img.load( function() {
                Flipbook.loadedImages++;
                
                // if all images are processed and imageCount == loadedImages and not currently loading any AJAX, start Flipping 
                if ( Flipbook.isBuilt && Flipbook.imageCount == Flipbook.loadedImages && !Flipbook.loadingAjax) Flipbook.startFlipping();
                
            }) . attr('src', source ) . appendTo( Flipbook.frames );

            return 1;
        }
        else return 0;
    },
    
    addDirectory : function( dir ) {
        Flipbook.loadingAjax++;
        $.ajax({
            type    : 'POST',
            url     : Flipbook.ajaxPhp,
            data    : 'dir=' + dir,
            cache   : false,
            success : function(html) {                
                if ( html ) {
                    //console.log( html );
                    
                    Flipbook.loadingAjax--;
                    
                    if ( html != 'empty.dir' && html != 'out of scope' && html != 'doesn\'t exist') {
                        var newSource = html.split(',');
                        Flipbook.processSource( newSource );
                    }
                }
            }
        });
    },
    
    startFlipping : function() {
        // if the flipbook built dynamically, set the flipbook html here, otherwise leave what was on page
        var framesHTML = Flipbook.frames.html();
        if ( framesHTML.length ) Flipbook.obj.wrapper.html( framesHTML );
        
        Flipbook.obj.theFirst = $(':first', Flipbook.obj.wrapper);
        
        $active = $('.active', Flipbook.obj.wrapper);
        if ( !$active.length ) $active = $(':last', Flipbook.obj.wrapper);
        
        Flipbook.obj.active = $active;
        
        Flipbook.play = setInterval( "Flipbook.slideSwitch()", Math.floor( 1000 / Flipbook.frameRate ) );
    },
    
    slideSwitch : function() {
        var $active = Flipbook.obj.active;
    
        var $next =  $active.next().length ? $active.next()
            : Flipbook.obj.theFirst;
    
        if ( Flipbook.fadeSpeed ) {
            $active.addClass('last-active');
            
            $next.css({opacity: 0.0})
                .addClass('active')
                .animate({opacity: 1.0}, Flipbook.fadeSpeed, function() {
                    $active.removeClass('active last-active');
                });
        }
        else {
            $next.addClass('active');
            $active.removeClass('active');
        }
        
        Flipbook.obj.active = $next;
    }

}

$(function() {
    Flipbook.init('../img/baby-elephant/');
});