$(function() {

  var balloon = $("#balloon").hide();
  var balloon_ = $("#balloon_").hide();
  var gtalk;
  var gtalkqueue = [];

  function setup_ghost() {
    change_ghost_size();
    ghost_talk("greet", false);
  }

  function change_ghost_size() {
    //ghost.css({width: CONF.ghost.size});
    balloon.css({
      "min-width": CONF.balloon.minWidth + "px",
      "margin-left": CONF.balloon.marginLeft + "px"
    });
    balloon_.css({
      "margin-left": ~~(CONF.ghost.size*0.5 - CONF.balloon.trisize) + "px",
      "margin-bottom": CONF.balloon.marginBottom + "px"
    });
  }

  function mkrand(max) {
    return Math.floor(Math.random()*(max+1));
  }

  function _ghost_talk(str, wait, end, ast) {
    setTimeout(function() {
      window.electron.ipcRenderer.send('ghostasset-message', ast);
      balloon.html(str).show();
      balloon_.show();
      if (end) {
        setTimeout(function() {
          balloon.html("").hide();
          balloon_.hide();
          if (gtalkqueue.length) {
            var g = gtalkqueue.shift();
            _ghost_talk(g[0], g[1], g[2], g[3]);
          } else {
            ghost_talk("normal");
          }
        }, end);
      } else {
        if (gtalkqueue.length) {
          var g = gtalkqueue.shift();
          _ghost_talk(g[0], g[1], g[2], g[3]);
        } else {
          setTimeout(function() {
            ghost_talk("normal");
          }, CONF.ghost.interval);
        }
      }
    }, wait);
  }


  function ghost_talk(ttype, nowait) {
    var tk;
    switch (ttype) {
    case "normal":
      tk = TALK[mkrand(TALK.length-1)];
      break;
    case "greet":
      tk = GREET[mkrand(GREET.length-1)];
      break;
    }
    switch (tk.type) {
    case "normal":
      for (var i = 0; i < tk.talk.length; i++) {
        gtalkqueue.push([
          tk.talk[i][1],
          (i == 0 && nowait) ? 0
            : (i == 0 ? CONF.ghost.interval
               : tk.talk[i][0]*tk.talk[i-1][1].length),
          i == tk.talk.length - 1
            ? tk.talk[i][1].length*CONF.balloon.disptime
            : 0,
          tk.talk[i].length > 2 ? tk.talk[i][2] : "default"
        ]);
      }
      var q = gtalkqueue.shift();
      _ghost_talk(q[0], q[1], q[2], q[3]);
      break;
    }
  }

  setup_ghost();
});
