<?
$grid = new \gridEdit;
$grid -> id               = 'cron';
$grid -> include_plugins  = true;
$grid -> title            = 'Cron';
$grid -> default_buttons  = false;
$grid -> external_code    = '<div class="countdown callback"></div><div id="cron-container"></div>';
echo $grid -> draw();
?>
<script type="text/javascript" src="/libraries/countdown/jquery.countdown.js"></script>
<script type="text/javascript">
  var delay = 1;
  $( document ).ready( function()
  {
    $( '#content_wrapper' ).css( 'margin', '0px' );
    
    $( '.countdown.callback' ).countdown(
    {
      date: +(new Date) + 1000,
      render: function(data) 
      {
        $( this.el ).text( this.leadingZeros( data.sec, 2 ) + " sek" );
      },
      onEnd: function() 
      {
        $( this.el ).addClass( 'ended' );
        cron();
      }
    }).stop();
  });
  
  function cron()
  {
    $( '.msg:gt(48)' ).remove();
    $.ajax(
    {
      type: 'POST',
      cache: false,
      url: '/cron.php',
      timeout: ( 30 * 1000 ),
      data: 
      {
        cron: 'true'
      },
      beforeSend: function() 
      {
        jQuery( '#cron-container' ).css( 'opacity', '0.8' );
      },
      success: function( data ) 
      {
        response = jQuery.parseJSON( data );
        
        jQuery( '#cron-container' ).css( 'opacity', '1' );
        
        if ( response.status === 'empty' )
        {
          delay++;
          if ( delay > 60 )
            delay = 60;
          
          $( '.countdown.callback' ).removeClass('ended').data('countdown').update( +( new Date ) + delay * 1000 ).start();
          if ( typeof value === "undefined"  )
            $( '#cron-container' ).prepend( '<div class="msg">W tej chwili nie ma nic do wykonania.</div>' );
          else
            $( '#cron-container' ).prepend( '<div class="msg">' + response.msg + '</div>' );
        }
        else
        {
          delay = 1;
          $( '#cron-container' ).prepend( '<div class="msg">' + response.msg + '</div>' );
          $( '.countdown.callback' ).removeClass('ended').data('countdown').update( +( new Date ) + 1 ).start();
        }
      },
      error: function(data)
      {
        delay++;
        if ( delay > 120 )
          delay = 120;
          
        $( '#cron-container' ).prepend( '<div class="msg">Błąd podczas połączenia.</div>' );
        $( '.countdown.callback' ).removeClass('ended').data('countdown').update( +( new Date ) + delay * 1000 ).start();
      },
      statusCode: 
      {          
        500: function() {
          
          delay++;
          if ( delay > 120 )
            delay = 120;
          
          $( '#cron-container' ).prepend( '<div class="msg">Błąd podczas połączenia.</div>' );
          $( '.countdown.callback' ).removeClass('ended').data('countdown').update( +( new Date ) + delay * 1000 ).start();
        }
      }
    });
  }
</script>