// (C) GPLed, Wybo Wiersma

Typer = (function() {
  var construct;

  construct = function(selector_string, keystrokes) {
    this.selector_string = selector_string;
    this.keys_limit = keystrokes + 2;
    this.reset();
  };

  construct.prototype.reset = function() {
    this.previous_flipper = null;
    this.flipper = null;
    this.next_flipper = null;
    this.index = 0;
  };

  construct.prototype.mark = function(flipper) {
    $(flipper).addClass('typing');
  };

  construct.prototype.flip = function(flipper) {
    //$(flipper).html(Math.round(Math.random()));
  };

  construct.prototype.unmark = function(flipper) {
    $(flipper).removeClass('typing');
  };

  construct.prototype.random_index = function(list) {
    return Math.floor(Math.random() * list.length);
  };

  construct.prototype.select_random = function() {
    list = $(this.selector_string);
    return list[this.random_index(list)];
  };

  construct.prototype.run = function() {
    this.previous_flipper = this.flipper;
    this.flipper = this.next_flipper;
    this.next_flipper = this.select_random();
    if (this.index < this.keys_limit - 2) {
      this.mark(this.next_flipper);
    }
    if (this.flipper && this.index < this.keys_limit - 1) {
      this.flip(this.flipper);
    }
    if (this.previous_flipper && this.index < this.keys_limit) {
      this.unmark(this.previous_flipper);
    }
    if (this.index == this.keys_limit) {
      this.reset();
      return false
    }
    this.index++;
    return true
  };

  return construct;
}());

Swapper = (function() {
  var construct;

  var SYMBOLS = ['_', '#', '`', '@', ';', '{', '}', '1', 'C', '-', 'O',
      'B', ':', '~', '%', '0', '!', '_'];

  construct = function() {
    this.index = SYMBOLS.length - 2;
  };

  construct.prototype.run = function() {
    $('#photo').html($('#photo').html().replace(
        new RegExp(SYMBOLS[this.index], 'g'), SYMBOLS[this.index + 1]));
    if (this.index == 0) {
      this.index = SYMBOLS.length - 1;
    }
    this.index--;
  };

  return construct;
}());

Runner = (function() {
  var construct;

  construct = function(selector_string, keystrokes) {
    this.typer = new Typer(selector_string, keystrokes);
    this.swapper = new Swapper();
  };

  construct.prototype.run = function() {
    if (!this.typer.run()) {
      this.swapper.run();
    }
  }

  return construct;
}());

function animate_photo(selector_string) {
  runner = new Runner(selector_string, 2);
  setInterval('runner.run()', 30);
}

function enable_javascript() {
  $('div.js_enabled').each(function() {$(this).toggle()});
  $('div.js_disabled').each(function() {$(this).toggle()});
}

