var g_firstCacheCheck = true;
var CACHE_DEBUG = false;

// Convenience array of status values
var cacheStatusValues = [];
cacheStatusValues[0] = 'uncached';
cacheStatusValues[1] = 'idle';
cacheStatusValues[2] = 'checking';
cacheStatusValues[3] = 'downloading';
cacheStatusValues[4] = 'updateready';
cacheStatusValues[5] = 'obsolete';

// Listeners for all possible events
var cache = window.applicationCache;
if ( cache != null ) 
{
    cache.addEventListener( 'cached', logEvent, false );
    if ( CACHE_DEBUG )
        cache.addEventListener( 'checking', logEvent, false );
    if ( CACHE_DEBUG )
        cache.addEventListener( 'downloading', logEvent, false );
    cache.addEventListener( 'error', logEvent, false );
    cache.addEventListener( 'obsolete', logEvent, false );
    if ( CACHE_DEBUG )
        cache.addEventListener( 'progress', logEvent, false );
    cache.addEventListener( 'noupdate', logEvent, false );
    cache.addEventListener( 'updateready', logEvent, false );

    // Swap in newly downloaded files when update is ready
    cache.addEventListener(
        'noupdate', 
        function() {
            //alert( 'noupdate' );
            console_log( "app cache: no updates" );
            g_firstCacheCheck = false;
        }, 
        false
    );
    cache.addEventListener(
        'cached', 
        function() {
            if ( isMobileDevice() && location.href.match( /mobile.html/ ) )
                openLightBox( { text: "Application is now ready for off-line use.", canClose: true, onClose: "initialize();" } );
        },
        false
    );
    cache.addEventListener(
        'error', 
        function() {
            console_log( "app cache: error" );
            // you always get an error when offline, and given that we already
            // check online status before calling initializeIfReady then this
            // call to initialize would be redundant
            if ( isOnline() && ! isAppleMobileDevice() )
            {
                alert( "error caching application" );
                initialize();
            }
            else
                closeLightBox();            // just in case
        },
        false
    );
    cache.addEventListener(
        'cached', 
        function() {
            //alert( "error" );
            console_log( "app cache: cached" );
            initialize();
        },
        false
    );
    // Swap in newly downloaded files when update is ready
    cache.addEventListener(
        'updateready', 
        function() {
            var timestamp = getLocalStorage( "last-appcache" );
            if ( timestamp == null )
                timestamp = 0;

            var now = getServerTimestamp();
            var isRelease = location.href.indexOf( "test" ) == -1;
            if ( false && isRelease && now - timestamp < 5*60000 )
            {
                console_warn( "app cache: skipping update.... (only " + ((now-timestamp)/1000) + " s since last update)" );
                g_firstCacheCheck = false;
                initialize();
                return;         // outta here
            }

            try
            {
                setLocalStorage( "last-appcache", now );
                window.applicationCache.swapCache();
                console_log('swap cache has been called');
            } 
            catch ( err )
            {
                console_warn( 'problem swapping cache' );
                if ( ! g_firstCacheCheck )
                    openLightBox( { text: "Error updating application.  Try again.", canClose: true, onClose: "initialize();" } );
            }
            var strInstruction = "The application will now restart.";
            if ( ! window.navigator.standalone )
                strInstruction = "The page will now reload.";
            openLightBox( { text: "Application updated.  " + strInstruction, canClose: true, onClose: "window.location.reload(true);" } );
            g_firstCacheCheck = false;
        }, 
        false
    );
}
else
{
    console_log( "no application cache" );
    initialize();
}

// Log every event to the console
function logEvent( e )
{
    var strMessage = 'online: ' + (navigator.onLine) ? 'yes' : 'no';
    strMessage += ', event: ' + e.type;
    strMessage += ', status: ' + cacheStatusValues[cache.status];

    if ( e.type == 'error' && navigator.onLine )
        strMessage += ' (prolly a syntax error in manifest)';
    
    console_log( strMessage );
};

