jQuery(function() {
  jQuery('<div id="full_statement_layer"></div><div id="full_statement"><a href="javascript:void(0)" class="close">Close</a><div id="full_statement_body"></div></div>').appendTo('body');
  $('#full_statement_layer, #full_statement a.close').click(function() {
    $('#full_statement_layer, #full_statement').hide();
    return false;
  })

  jQuery('.bubble_container.random').each(function(i) {
    var container = this;
    setTimeout(function() {replaceStatement(container)}, 3000 + Math.random()*20000);
  })
  
  $('#random_organisation').each(function(i) {
    var container = this;
    setTimeout(function() {replaceOrganisation(container)}, 3000 + Math.random()*20000);
  })
  
  ajaxifyFullStatementLinks('#join_the_campaign');
});

usedStatements = [];

function replaceStatement(container) {
  if (statements.length == 0) {
    /* ran out of statements and still awaiting AJAX response, so recycle some */
    statements = usedStatements.splice(0,10);
  }
  var newStatement = statements.shift();
  usedStatements.push(newStatement);
  if (statements.length == 5) { /* fetch next batch when there are only 5 remaining */
    jQuery.getJSON('/add_your_voice/statements', function(response) {
      statements = statements.concat(response);
      /* if there aren't very many, recycle some */
      if (response.length < 10) {
        statements = statements.concat(usedStatements.splice(0,10));
      }
    })
  }
  jQuery('.bubble',container).fadeOut("slow",function(){
    jQuery(container).empty();
    var newStatementDom = jQuery(newStatement.html).hide();
    ajaxifyFullStatementLinks(newStatementDom);
    newStatementDom.appendTo(container).fadeIn(2000, function() {
      setTimeout(function() {replaceStatement(container)}, 16000 + Math.random()*10000);
    });
  });
}

var countUntilWI = 0;

function replaceOrganisation(container) {
  countUntilWI = (countUntilWI - 1) % 5;
  if (countUntilWI == 0) {
    var newOrganisation = organisationStatements[0];
  } else {
    var newOrganisation = organisationStatements[Math.floor(Math.random()*organisationStatements.length)];
  }
  jQuery('.bubble',container).fadeOut("slow",function(){
    jQuery(container).empty();
    var newStatementDom = jQuery(newOrganisation.html).hide();
    ajaxifyFullStatementLinks(newStatementDom);
    newStatementDom.appendTo(container).fadeIn(2000, function() {
      setTimeout(function() {replaceOrganisation(container)}, 8000 + Math.random()*5000);
    });
  });
}

function ajaxifyFullStatementLinks(context) {
  jQuery('a.more', context).click(function() {
    $('#full_statement_layer').height($('body').height()).show();
    $('#full_statement_body').empty().load(this.href);
    $('#full_statement').css('left', (($('body').width() - $('#full_statement').width()) / 2) + 'px').show();
    return false;
  });
}