window.addEvent('domready', function() {
  
  // Clouds!
  
  var clouds = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  var heights = [];
  var w = document.getCoordinates().width;
  var n = Math.min(Math.round(w / 150), 10);
  for (var i = 0; i < n; i++) {
    heights.push(25 + i / n * 400);
  }
  clouds.sort(function(a, b) {
    return 1 - Math.floor(Math.random() * 2) * 2;
  });
  heights.sort(function(a, b) {
    return 1 - Math.floor(Math.random() * 2) * 2;
  });
  for (var i = 0; i < n; i++) {
    var cloud = clouds.pop();
    var x = i / n * w;
    var y = heights.pop();
    var img = new Element('img', {
      'src': '/images/' + cloud + '.png',
      'class': 'cloud',
      'styles': {
        'top': y,
        'left': x,
        'z-index': i
      }
    });
    img.inject(document.body);
  }
  
  if ($$('form').length == 0) {
    return;
  }
  
  $$('form')[0].addEvent('submit', function(e) {
    new Event(e).preventDefault();
    if ($('input').value == '') {
      return;
    }
    new Request({
      'method': 'get',
      'url': './?url=' + encodeURIComponent($('input').value) + '&minimal=1',
      'onSuccess': function() {
        $('output').value = this.response.text;
        $('urlx').removeClass('hidden');
        if (this.response.text.substr(0, 4) == 'http') {
          $('output').focus();
          $('output').select();
          $('output').removeClass('error');
          $('output').addClass('focus');
        } else {
          $('output').addClass('error');
          $('output').removeClass('focus');
        }
      }
    }).send();
  });
  
  $('input').addEvent('focus', function() {
    this.addClass('focus');
  });
  $('input').addEvent('blur', function() {
    this.removeClass('focus');
  });
  
  $('output').addEvent('focus', function() {
    if (!this.hasClass('error')) {
      this.addClass('focus');
    }
  });
  $('output').addEvent('blur', function() {
    this.removeClass('focus');
  });
  $('output').addEvent('click', function() {
    if (!this.hasClass('error')) {
      this.focus();
      this.select();
    }
  });
  
  if ($('urlx').hasClass('hidden')) {
    $('input').focus();
  } else {
    $('output').focus();
    $('output').select();
  }
  
});

