view open-web-challenges.js @ 27:74f52b4966d7

Rewording of my last commit.
author Atul Varma <varmaa@toolness.com>
date Tue, 31 Mar 2009 10:36:41 -0700
parents 06309561d361
children
line wrap: on
line source

var OWC = {
  _makeHintButton: function makeHintButton(hints) {
    var hintButtonContainer = $('<div class="hint-button"></div>');
    var hintButton = $('<span></span>');
    hintButton.text($('#msg-show-first-hint').text());
    hintButton.click(
      function() {
        hints.find('p:hidden:first').fadeIn();
        if (hints.find('p:hidden').length)
          $(this).text($('#msg-show-another-hint').text());
        else
          $(this).text($('#msg-no-more-hints').text());
      });
    hintButtonContainer.append(hintButton);
    return hintButtonContainer;
  },

  load: function load(id) {
    var challenge = $('#challenge-' + id);
    if (!challenge.length)
      challenge = $('#challenge-does-not-exist');
    var content = challenge.find('.content').clone();
    var current = $('#current-challenge');
    current.empty();

    var headerText = $('#msg-header').text().replace('{id}', id);
    current.append($('<h1></h1>').text(headerText));
    document.title = headerText;

    current.append(content);

    var hints = $('<div class="hints"></div>');
    hints.append(challenge.find('.hints').clone());
    current.append(this._makeHintButton(hints));
    current.append(hints);

    var validatorCode = challenge.find('.validator').text();

    var validate = eval('(' + validatorCode + ')');

    function maybeDisplaySuccess() {
      if (validate(current)) {
        var success = $('<div id="success"></div>');
        success.text($('#msg-success').text());
        success.wrapInner('<h1></h1>');
        success.hide();
        current.children().addClass('completed');
        current.append(success);
        var next = $('<a target="_self"></a>');
        next.attr("href", "?" + (id+1));
        next.text($('#msg-next-challenge').text());
        success.append(next);
        success.fadeIn('slow');
        window.clearInterval(intervalId);
      }
    }
    var intervalId = window.setInterval(maybeDisplaySuccess, 100);

    $(".challenge").remove();

    current.fadeIn();
  }
};

$(window).ready(
  function() {
    var queryIndex = window.location.href.indexOf('?');
    var challengeId;
    if (queryIndex == -1)
      challengeId = 1;
    else
      challengeId = Number(window.location.href.slice(queryIndex+1));

    function showChallenge() {
      OWC.load(challengeId);
    }

    showChallenge();
  });