// Download stream of latest posts and render
function download_stream (stream) {
   var url = '/stream/' + stream;
   $.getJSON(url, {}, function (posts) {
      // Note that we downloaded this stream and save the results
      stream_registry[stream] = posts;
   });
}


function render_post (post) {
   console.log(post);
   frame = $("<div class='post'></div>");
   streams = $("<div class='post-streams'></div>").appendTo(frame);
   for (var i = 0; i < post.streams.length; i++) {
      $("<span class='stream'></span>").text(post.streams[i]).appendTo(streams);
   }
   title = $("<h3></h3>").appendTo(frame);
   title_link = $("<a href='#'></a>").text(post.title).appendTo(title);
   lead = $("<p class='lead'></p>").text(post.content).appendTo(frame);
   byline = $("<div class='byline'>Posted by <em></em></div>").appendTo(frame);
   $('em', byline).text(post.author);

   frame.appendTo($('#posts'));
}

function set_stream(stream_name) {
   STREAM = stream_name;
   $.each($('span.stream'), function (index, stream) {
      if ($(stream).text() == stream_name) {
         $(stream).addClass('active');
      } else {
         $(stream).removeClass('active');
      }
   })
}

// Eventually this will be some sort of fancy merge strategy but for now let's
// just clobber everything unlol
function render_stream () {

   // Ok, so we're here because we have posts cached and ready to display, and
   // because those cached posts are not currently displayed.
   var stream = window.location.hash.split('/')[1];
   if (stream != STREAM) {
      $('#posts').html('');
      $.each(stream_registry[stream], function (index, post) {
         render_post(post);
      });
      set_stream(stream);
   }
}

// Current stream. Blanks means show all posts.
var STREAM = '';

// keys are post ids, values are post objects
var post_registry = {};
var stream_registry = {};

// Monitors window.location.hash for changes
var hash_monitor = {

   // As returned from window.setInterval
   handler_id: null,

   // How many times to check the location hash for changes
   checks_per_second: 5,

   handler: function () {
      // Check the location hash periodically with this function. The job of
      // this function is to ensure that the state of the page matches the
      // URL.

      var stream = window.location.hash.split('/')[1];

      // If we haven't downloaded this yet, create a task to do so
      if (!(stream in stream_registry)) {
         download_stream(stream);
      } else {
         if (stream != STREAM) {
            render_stream(stream);
         }
      }
   },


   setup: function(n) {
     this.handler_id = window.setInterval(this.handler,
        1000/this.checks_per_second)
   },

   // Stop checking.
   kill: function() {
      window.clearInterval(this.handler_id);
   }
}

function Init() {

   function setup_hash_monitor() {
      hash_monitor.setup();
   }

   function handle_form_defaults() {
      // Handle form defaults...
      $.each($('input[default], textarea[default]'), function(index, input) {
         input = $(input);
         // Load defaults.
         if (input.attr('default') && !input.val()) {
            input.val(input.attr('default'));
         }
      });

      // On focus, add className "focused"; remove on blur.
      $('input[default], textarea[default]').focus(function() {
         var defaultValue = $(this).attr('default');
         var value = $(this).val();
         if (value === defaultValue) {
            $(this).val('');
         }
         $(this).addClass('focused');    
         $(this).parent('div').addClass('focused');
      });

      $('input[default], textarea[default]').blur(function() {
         if (!$(this).val()) {
            $(this).val($(this).attr('default'));
         }
         $(this).removeClass('focused'); 
         $(this).parent('div').removeClass('focused');
      });
   }


   // For testing: Duplicate the first post found and create X more copies
   function create_fake_posts(n) {
      n = n || 10;
      var p = $('.post').first();
      if (!p) return;
      for (var i=0; i<n; i++) {
         p.clone().appendTo($('#posts'))
      }
   }

   // What happens when the user clicks 'submit'?
   function handle_post_submit () {
      $('#submit').click(function() {
         var title = $('#post-title'),
             content = $('#post-content');

         if (title.val() && title.val() != title.attr('default')) {
            if (content.val() && content.val() != content.attr('default')) {
               $.ajax({
                  type: 'post',
                  data: $('input, textarea', '#form').serialize()
               });
            }
         }
      });
   }


   return [
      handle_form_defaults,
      handle_post_submit,
      setup_hash_monitor
   ];
}

$(document).ready(function() {
   $.each(Init(), function (index, initializer) {
      initializer();
   });

});

