  /*
  
      Generátor náhodného fraktálu
      
      @author Adam Hořčica, 2007
      @see http://notepad.jslab.net/tvorba/fraktaly/nahodny-fraktal.html
  */

  
  var can, ctx;
  
  onload = function(){
  
    can = document.createElement('canvas');
    document.getElementById('canvasframe').appendChild(can);
    
    if( can.getContext === undefined ){
      alert('Váš prohlížeč nepodporuje objekt canvas, který je nutný pro vykreslení fraktálu.');
      return;
    }
    
    ctx = can.getContext("2d");    
    
    can.setAttribute('width',  HRANA);
    can.setAttribute('height',  HRANA);
    
    frac(0, 0, HRANA, ITERACE);
     
  };
  
  function rec( x, y, a, color, bg){
    if( bg && BACKGROUND ) return;
    
    ctx.fillStyle = bg ? "white" : color;
    ctx.fillRect(x, y, a, a);
  }
  
  function getColor(n){
    if(!COLOR) return "black";
    if(n <= 1) return FINAL_COLOR;
  
    var c = Math.round(256 - (ITERACE - n + 1) * 3 * (ITERACE - n) / 2 );
    return "rgb(" + c + "," + c + "," + c + ")";
  }
  
  function element( x, y, a, w , color ){
    a = Math.ceil(a/2);
    
    rec( x      , y       , a , color , w==0 );
    rec( x + a  , y       , a , color , w==1 );
    rec( x      , y + a   , a , color , w==2 );
    rec( x + a  , y + a   , a , color , w==3 );
  }
  
  function frac( x, y, a, n ){
    
    var rnd = getRnd(x,y,a,n);
    element(x, y, a, rnd , getColor(n) );
    if( (n = n - 1) == 0 ) return;
    
 
    if(rnd != 0) sequence( function(){ frac( x, y, a/2, n); });
    if(rnd != 1) sequence( function(){ frac( x + a/2, y, a/2, n); });
    if(rnd != 2) sequence( function(){ frac( x, y + a/2, a/2, n); });
    if(rnd != 3) sequence( function(){ frac( x + a/2, y + a/2, a/2, n); });

  } 
    
  
  var sequence = (function(){
    
    var time = 10;
    
    var list = []; 
    var timer = null;
    
    function onTime(){
    
      var item = DIRECTION ? list.shift() : list.pop();
      if(item === undefined){
        timer = null;
        return;
      }
      item.call();
      timer = setTimeout( onTime, time );
          
    }
    
    return function( fce ){
      list.push(fce);
      if(timer === null) timer = setTimeout( onTime, time );
    }
  
  })();
