String.prototype.pad = function(l, s, t){
  return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
    + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
    + this + s.substr(0, l - t) : this;
};

$(document).ready(function() {
  var ie6 = ($.browser.msie && $.browser.version < 7);
  var disableEffects = ($.browser.msie && $.browser.version < 8);
  
  $('.launch-game').click(function() {
    var xy = 'width=1000,height=580';
    if (screen.width <= 1024 || screen.height < 600) {
      if (ie6) {
        xy = 'width=1017,height=580';
      } else if ($.browser.msie) {
        xy = 'width=1020,height=597';
      }
    } else if ($.browser.msie) {
      xy = 'width=1017,height=580';
    }
    var realGame = window.open('/game/', 'realGame', xy + ',resizable=0,toolbar=0,scrollbars=1,menubar=0');
    if (screen.width > 1000 && screen.height > 580 && !$(document).hasClass('chrome')) {
      var x = (screen.width / 2) - 500;
      var y = (screen.height / 2) - 280;
      setTimeout(function() { realGame.moveTo(x, y) }, 100);
    }
    realGame.focus();
    return false;
  });
  
  // Load tweets
  $("#tweets").tweet({
    username: 'dayinthecloud',
    count: 5,
    auto_join_text_default: "",
    auto_join_text_ed: "",
    auto_join_text_ing: "",
    auto_join_text_reply: "",
    auto_join_text_url: "",
    loading_text: '<ul class="tweet_list"><li class="tweet_first"><span class="tweet-text"><span class="tweet-inner">Loading tweets...</span></span></li></ul>'
  });
  
  $('a#more-tweets').click(function() {
    if ($('#tweets li:last:visible').length) {
      $('#tweets li').not('.tweet_first').slideUp('fast');
      $(this).html('more tweets');
    } else {
      $('#tweets li').slideDown('fast');
      $(this).html('less tweets');
    }
    return false;
  })

  $('#social li').hover(function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
  
  $('#social li a').click(function() {
    share($(this).parents('li').attr('id').split('-')[1]);
  });
  
  SHARE_LINKS = {
    facebook: 'http://www.facebook.com/sharer.php?u={url}&t={title}',
    twitter: 'http://twitter.com/home?status=' + encodeURIComponent('Accept the challenge. Scour the Earth. Please remain seated. June 24th. http://bit.ly/DITC (via @dayinthecloud) #dayinthecloud'),
    digg: 'http://digg.com/submit?phase=2&url={url}&title={title}',
    delicious: 'http://del.icio.us/post?url={url}&title={title}',
    orkut: 'http://www.orkut.com/FavoriteVideos.aspx?u={url}',
    myspace: 'http://www.myspace.com/Modules/PostTo/Pages/?u={url}',
    live: 'http://spaces.live.com/BlogIt.aspx?Title={title}&amp;SourceURL={url}&amp;description=',
    bebo: 'http://www.bebo.com/c/share?Url={url}&Title={title}&MID=8974376238&TUUID=fc7850b8-964c-47bd-8a91-db1d2a5cad3c'
  }

  function share(what) {
    var properties = {title: encodeURIComponent(document.title), url: encodeURIComponent(document.location.href)};
    var url = SHARE_LINKS[what].replace('{title}', properties.title).replace('{url}', properties.url);
    window.open(url, '_blank');
    return false;
  }
  
  $('a[rel=external]').click(function(e) {
    window.open($(this).attr('href'), '_blank');
    e.preventDefault();
  });
  $('a[rel=popup]').click(function(e) {
    window.open($(this).attr('href'), 'ditc_popup', 'width=600,height=500,scrollbars=1');
    e.preventDefault();
  });
  
  $('a[rel=tutorial]').click(function(e) {
    window.open($(this).attr('href'), 'ditc_tutorial', 'width=1000,height=580');
    e.preventDefault();
  });
  
  $('a.signup-toggle').click(function(e) {
    e.preventDefault();
    $('#signup-link').toggleClass('active');
    $('#signup').toggle();
    $('#signup input.form-text:visible:first').focus();
    if (e.target !== $('#signup-link')[0]) {
      $(document.body).scrollTo(0, 300);
    }
  });
  
  // Special treatment for the cloud page
  if ($(document.body).attr('id') == 'page-cloud') {
    $('#illustration').append('<div id="illustration-overlay"></div>');
    $('#illustration2').append('<div id="illustration2-inner"></div>');
  }
  
  var pageScroller = $('#content .page-scroller');
  var pages = $('#content .page');
  var currentPage = 0;
  function scrollToPage(page) {
    pageScroller
      .animate({height: $('#page-' + page).height() + (ie6 ? 50 : 0)}, {queue: false, duration: 300, easing:'easeOutExpo'})
      .scrollTo($('#page-' + page), 500, {easing:'easeOutExpo'});
    
    if (page == (pages.length - 1)) {
      $('#paginator .next a').addClass('disabled');
    } else if (page == 0) {
      $('#paginator .prev a').addClass('disabled');
    } else {
      $('#paginator .prev a').removeClass('disabled');
      $('#paginator .next a').removeClass('disabled');
    }
    
    if (page > 0 && $(document.body).attr('id') == 'page-cloud' && $('#illustration1:visible').length) {
      if (disableEffects) {
        $('#illustration1').hide();
        $('#illustration2').show();
      } else {
        $('#illustration1').fadeOut();
        $('#illustration2').fadeIn();
      }
      
      if (!ie6) {
        $('#illustration-overlay').show();
      }
    } else if (page == 0 && $('#illustration2:visible').length) {
      if (disableEffects) {
        $('#illustration1').show();
        $('#illustration2').hide();
      } else {
        $('#illustration1').fadeIn();
        $('#illustration2').fadeOut({complete: function() {
          $('#illustration-overlay').hide();
        }});
      }
    } else if (page == 2) {
      if (!ie6) {
        $('#illustration2-inner').animate({left: '-550px'}, {duration: 500, easing:'easeOutExpo'});
      }
    } else if (page == 1) {
      if (!ie6) {
        $('#illustration2-inner').animate({left: '-65px'}, {duration: 500, easing:'easeOutExpo'});
      }
    }
    currentPage = page;
  }
  $('#paginator .next a').click(function() {
    if (currentPage < (pages.length - 1)) {
      scrollToPage(currentPage + 1);
    }
    return false;
  });
  $('#paginator .prev a').click(function() {
    if (currentPage > 0) {
      scrollToPage(currentPage - 1);
    }
    return false;
  });
  if (pages.length) {
    scrollToPage(0);
  }
  
  $('a.coming-soon').hover(function() {
    if (disableEffects) {
      $(this).find('span.coming-soon').show();
    } else {
      $(this).find('span.coming-soon').fadeIn('fast');
    }
  }, function() {
    $(this).find('span.coming-soon').hide();
  });
  
  var bloggerFeed = $('#blogger-feed');
  var currentIndex = 0;
  function updateBlogger() {
    if (bloggerFeed.length > 0) {
      $.getJSON('http://dayinthecloudblog.blogspot.com/feeds/posts/default?alt=json-in-script&start-index=1&max-results=100&callback=?', function(json) {
        var posts = [];
        var post = '';
        if (json.feed.entry && json.feed.entry.length > 0) {
          $.each(json.feed.entry, function(i, entry) {
            var hours = entry.published.$t.substring(11,13);
            var minutes = entry.published.$t.substring(14,16);
            var suffix = 'AM';
            if (parseInt(hours) > 12) {
              if (parseInt(hours) == 24) {
                suffix = 'AM';
              } else {
                suffix = 'PM';
              }
              hours = parseInt(hours) - 12;
            } else {
              if (parseInt(hours) == 12) {
                suffix = 'PM';
              }
              hours = hours;
            }
            post = '<div class="post clearfix"' + (i >= 10 ? ' style="display:none"' : '') + '>';
            post += '<strong>June ' + entry.published.$t.substring(8,10) + ' ' + hours + ':' + minutes + ' ' + suffix + '</strong>';
            post += '<h3>' + entry.title.$t + '</h3>';
            post += '<div class="summary">' + entry.content.$t + '</div>';
            post += '</div>';
            posts.push(post);
          });
          bloggerFeed.html(posts.join(''));
        } else {
          bloggerFeed.html('<p>No posts available.</p>');
        }
        if (json.feed.entry.length > 10) {
          var link = $('<a></a>')
            .text('Show 10 more...')
            .attr({href: '#', 'class': 'more'})
            .click(function() {
              currentIndex += 10;
              bloggerFeed.find('.post:gt(' + (currentIndex - 1) + ')').filter('.post:lt(10)').show();
              if ((currentIndex + 20) > json.feed.entry.length) {
                $(this).text('Show ' + (json.feed.entry.length % (currentIndex + 10)) + ' more...');
              }
              if ((currentIndex + 10) >= json.feed.entry.length) {
                $(this).hide();
              }
              return false;
            });
          bloggerFeed.append(link);
        }
      });
    }
  }
  updateBlogger();
});

function initAutoclearFields() {
  $.each($('p.autoclear'), function() {
    var p = $(this);
    var label = p.find('label.autoclear');
    var field = p.find('input');

    // Sometimes browsers leave values in the field on refresh
    if (field.val() != '') {
      label.hide();
    }

    label.click(function() {
      field.focus();
    });
    field.focus(function() {
      label.addClass('dimmed');
      // In case of auto-complete
      if (field.val() != '') {
        label.hide();
      }
    })
    field.blur(function() {
      label.removeClass('dimmed');
      if (field.val() == '') {
        label.show();
      }
    })
    field.keydown(function(e) {
      // Ignore modifier keys
      if ($.inArray(e.keyCode, [9, 27, 16, 17, 18, 20, 144, 224, 91, 92, 93]) == -1) {
        label.hide();
      }
    })
    field.change(function() {
      if (field.val() == '') {
        label.show();
      }
    })
  });
}
