
(function($) { $(function() {
  var console = window['console'] || {error:function() {}};
  var parents = (/spoke\/api\/in\/(.*?)(\.[^\.\/]*)?$/.exec($('#comments').attr('rel'))||[])[1];
	var replyparents = [];
  var spoke = SpokeContainer( );

  function createTemplate( str ) {
    return C5.Template.templatize( /((--)|(-!)|(-d!))(.*?)--/g, function(m) {
      if (m[2])  return (function(o) { return o[m[5]]; });
      var f = new Function('o','return ' +m[5]);
      if (m[4]) return function(o) { return formatDate(f(o)); };
      return f;
    }, str );
  }

  var timezoneOffset = new Date().getTimezoneOffset() * 60 * 1000;
  function formatDate( millis ) {
    var d = new Date(millis-timezoneOffset), dy=d.getYear(), dh=d.getHours(), dd = d.getDate(), dm=d.getMinutes();
    return (d.getMonth()+1) + '/' + (dd<10?'0'+dd:dd) + '/' + (dy>99?dy-100:dy)
          + ' at ' + (((dh+11)%12)+1) + ':' + (dm<10?'0'+dm:dm) + (dh<12?'a.m.':'p.m.');
  }    

  var postTemplate = createTemplate("<div class='header'>" 
            + "<span class='name'>-! o.author||'anonymous' --</span>"
            + "<span class='time'>| posted at -d! o.created.getTime() --</span> | "
            + "<span class='reply'>Reply</span> | "
            + "<span class='report'>Report</span></div>");
            
  $.fn.as_comment = function() {
    $(this).each(function() {
      var data = {created: new Date($('.created', this).html())};
      data.key = $('span.key', this).html();
      data.comment = $('.content', this).html();
      // if ( $('div.author-info span.name', this).html() ) data.author = $.trim($('div.author-info span.name', this).html());
            $(this).prepend( postTemplate( data ) );
      $('span.report',this).click( function() { 
          spoke.updateState(data.key, 'FLAGGED', function() {}); 
          $(this).closest('div.comment').hide(100, function() { 
            $(this).remove(); 
            console.debug($('#comments div.comment').length > 0);
            updateHeader();
          });
        });
			$('span.reply',this).click( function() { 
			  $('#reply-to-parent').remove();
				$('#new-post').before('<div id="reply-to-parent">Reply to:<blockquote>"'+data.comment+'"</blockquote></div>');
				$(window).scrollTop($('#reply-to-parent').offset().top);
				var replyIds = [];
				$(this).parents('.comment').children('.meta').find('.key').each(function() {
				  replyIds.push($.trim($(this).html()))	
				  })
				replyparents = parents + '/' + replyIds.join('/');
    	});
    });
  }
  
  function updateHeader() {
    $('#comments-header')[$('#comments div.comment').length > 0 ? 'show' : 'hide'](100); 
    $('#reply-to-parent').remove();
  }

  function fetchComments() {
	    spoke.list( parents, function(posts) { 
	        $('#comments .postList').html(posts).find("div.comment").as_comment(); 
          updateHeader();
	    });
	    
  }
 
  var submittingPost = false;
  $('#new-post').inputHintOverlay().validate({
    showErrors: function(errors) {
      this.validElements().closest('li').removeClass('error');
      this.invalidElements().closest('li').addClass('error');
      (this.numberOfInvalids() ? $.fn.show:$.fn.hide).call($('#comment-validation-message'));
    },
    submitHandler:function() {
      if (submittingPost) return;
      submittingPost = true;			
      spoke.post( replyparents != '' ? replyparents : parents, $('#comment-author-name').val(), $('#comment-author-email').val(), 'comment-post', $('#message').val(), 
        function(m) { 
          $('#new-post textarea').val('');
          fetchComments(); 
          submittingPost = false;
					_gaq.push(['_trackEvent', 'Forms', 'Comment']);
        } );
      return false;
    }});

  $('#comments div.comment').as_comment();
  updateHeader();
}); })(jQuery);

