(function(global) {
  var FUSEJS_LOGO = 'img/fuse_logo.png',
    FUSEJS_PIRATE_LOGO = 'img/fuse_logo_pirate.png';

  var fuse = global.fuse, $ = fuse.query, showcaseSection, speedTestIframe,
    speedTestButton, speedTestTable, isSpeedTestRunning = false;

  function showShowcaseTab(name) {
    var tabs = showcaseSection.down('.showcase-list'),
      pages = showcaseSection.down('.showcase-items');

    tabs.down('li').removeClassName('active');
    pages.down('.showcase-item').removeClassName('active');

    tabs.down('a.' + name).up().addClassName('active');
    pages.down('.showcase-item.' + name).addClassName('active');
  }

  function handleChangeLogoClick(e) {
    e.stop();

    var target = fuse(e.getCurrentTarget()), heroImage = $('.hero .logo img');

    if (heroImage.getAttribute('src') == FUSEJS_PIRATE_LOGO) {
      target.update('Run Code');
      heroImage.setAttribute('src', FUSEJS_LOGO);
    } else {
      target.update('Reset');
      heroImage.setAttribute('src', FUSEJS_PIRATE_LOGO);
    }
  }

  function handleStartSpeedTestClick(e) {
    e.stop();

    if (isSpeedTestRunning) {
      return;
    }

    isSpeedTestRunning = true;

    if (!speedTestIframe) {
      initSpeedTestIframe();
    }

    // reset the results
    speedTestTableResults.getChildren().update('0');

    // expose the handle iframe load
    global.__handleSpeedTestIframeLoad = handleSpeedTestIframeLoad;
    speedTestIframe.setAttribute('src', 'taskspeed/index.php?unique=' + +new Date);

    // update our button and show the loading icon
    speedTestButton.update('Running...').setAttribute('title', 'Running...');
    speedTestButton.next('.loading-icon').show();
  }

  function handleSpeedTestIframeLoad(win) {
    // remove global handler for speed test iframe load
    global.__handleSpeedTestIframeLoad = null;

    // temporarily assign our speed test results handler so the iframe can call
    // it when finished
    global.__handleSpeedTestResults = handleSpeedTestResults;

    // start the tests in the iframe
    win.startTest();
  }

  function handleSpeedTestResults(data) {
    var k;

    // reset the start button and remove the loading indicator
    speedTestButton.update('Finished').setAttribute('title', 'Finished');
    speedTestButton.next('.loading-icon').hide();

    // map results
    for (k in data) {
      speedTestTableResults.getChildren('.' + k).update(data[k].innerHTML);
    }

    isSpeedTestRunning = false;

    // remove our global reference to speed test results handler
    global.__handleSpeedTestResults = null;
  }

  function initSpeedTestIframe() {
    if (speedTestIframe) {
      return;
    }

    // create our iframe
    speedTestIframe = fuse(document.createElement('iframe'));

    // finally, append it to our body
    $('body').appendChild(speedTestIframe);

    // bug right now when appending an element created with fuse and appending
    // to body in IE.
    speedTestIframe = fuse(document.getElementsByTagName('iframe')[0]);

    speedTestIframe
      .setAttribute('id', '__speed_test_iframe')
      .setAttribute('name', '__speed_test_iframe')
      .setStyle({
        'position': 'absolute',
        'top': '-9999px',
        'left': '-9999px',
        'width': '1px',
        'height': '1px'
      });

    return speedTestIframe;
  }

  function handleShowShowcaseClick(e) {
    e.stop();

    var target = fuse(e.getCurrentTarget());

    showShowcaseTab(target.getAttribute('class'));
  }

  function setShowcaseHeight() {
    var height = 0;

    fuse.query('.showcase-item')
      .each(function(item) {
        height = Math.max(height, +fuse(item).getHeight('content'));
      })
      .setStyle({ 'height': height + 'px' });
  }

  fuse(document).observe('dom:loaded', function() {
    // pre-load the pirate logo just in case
    (new Image()).src = FUSEJS_PIRATE_LOGO;

    showcaseSection = $('.section.showcase');

    $('.hero .speed').observe('click', handleShowShowcaseClick)
    $('.run-code').observe('click', handleChangeLogoClick);

    speedTestButton = $('.start-speed-test').observe('click', handleStartSpeedTestClick);
    speedTestTableResults = $('.showcase-item.speed table tbody tr');

    setShowcaseHeight();
  });
})(this);
