var WORDLIST = new Array();
var NEXT_REQUEST_ALLOWED = true;

function replace_shit() {
  jQuery('#altContent').remove();
  jQuery('#player').append('<p id="the-word"></p>');
  jQuery('#the-word').hide();
  jQuery.get('getwordlist.php', process_wordlist);
}

function process_wordlist(data) {
  data = data.split('&');
  // Get WORDLIST object from string data.
  for (i=0; i<data.length; i++) {
    var variable = new Array();
    variable = data[i].split('=');
    if (variable[0] != 'list') {
      WORDLIST[variable[0]] = parseFloat(variable[1]);
    } else {
      WORDLIST[variable[0]] = variable[1];
    }
  }
  WORDLIST['list'] = WORDLIST['list'].split(',');
  // Set initial values.
  var delay = WORDLIST['ttl_list'] - (Math.floor(WORDLIST['ttl_list'] / WORDLIST['delay_word']) * WORDLIST['delay_word']);
  var recentWordId = WORDLIST['word_count'] - Math.ceil(WORDLIST['ttl_list'] / WORDLIST['delay_word']);
  // Check if list is going to die soon.
  // console.log('recentWordId:' + recentWordId, '\nWORDLIST[word_count]:' + WORDLIST['word_count'], '\nWORDLIST[ttl_list]:' + WORDLIST['ttl_list'], '\ndelay:' + delay);
  if (delay < WORDLIST['delay_word'] && delay > 0) {
    setTimeout('jQuery.get(\'getwordlist.php\', process_wordlist)', delay * 1000);
    return;
  }
  // Recent list loop.
  setWord(recentWordId, delay);
}

function setWord(wordId, delay) {
  delay = (setWord.arguments.length == 2) ? delay : WORDLIST['delay_word'];
  animateIn(WORDLIST['list'][wordId]);
  if (wordId < WORDLIST['word_count']) {
    setTimeout('setWord(' + (wordId + 1) + ')', delay * 1000)
  }
  else if (wordId == WORDLIST['word_count']) {
    if (NEXT_REQUEST_ALLOWED) {
      jQuery.get('getwordlist.php', process_wordlist);
    }
    else{
      setTimeout('setWord(' + wordId + ')', 100);
    }
  }
}

function animateIn(word) {
  jQuery('#the-word').text(word);
  jQuery('#the-word').fadeIn('slow');
}
