if(typeof(Tutoria) == "undefined")
  Tutoria = {};

Tutoria.CountdownClock = function(divId, timeoutInSeconds) {
  var clockDiv = $(divId);
  var timeout  = timeoutInSeconds;
  var minute   = 60;
  var hour     = 60 * minute;
  var timeLeft = null;
  var lastTick = null;

  function currentTime() {
    // Seconds since midnight, 1 January 1970
    return Math.floor((new Date()).getTime() / 1000);
  };

  function updateTimeout() {
    var time = currentTime();
    timeout -= lastTick == null ? 0 : (time - lastTick);

    if(timeout <= 0) {
      window.location.reload(false);
      return false;
    }

    lastTick = time;
    return true;
  };

  function updateTimeLeft() {
    timeLeft = {
      hours: Math.floor(timeout / hour),
      minutes: Math.floor((timeout % hour) / minute),
      seconds: timeout % minute
    };
  }

  function updateDisplay() {
    function segment(number) {
      var str = new String(number);
      str = str.length == 1 ? '0' + str : str;
      image(str.charAt(0));
      image(str.charAt(1));
    }

    function colon() {
      image('colon');
    }

    function image(src) {
      var image = document.createElement('img');
      image.src = '/images/clock/' + src + '.gif';
      clockDiv.insert({bottom: image});
    }

    clockDiv.update('');

    segment(timeLeft.hours);
    colon();
    segment(timeLeft.minutes);
    colon();
    segment(timeLeft.seconds);
  }

  function tick() {   
    if(updateTimeout()) {
      updateTimeLeft();
      updateDisplay();
      setTimeout(tick, 200);
    }
  };

  return tick();
};
