/*
* Talk JS module
*/

(function($) {  

	$.fn.Talk = function(options) {
	
		// Set defaults
		var defaults = {
			
		};
		
		var options = $.extend(defaults, options); 
		
		this.each(function() {
			posting = false;
			$T = $(this);
			// Load the cache of this talk page.
			function load() {
				channel = $T.attr('channel');
				if(channel == '') return;
				$.post('/talk', {channel: channel}, function(data){
					$T.html(data);
					init();
				});
			}
			load();
			
			// Initiate
			function init()
			{
				$('.talkpost').click(function(){
					post();
				});
				
				$('.talkarea', $T).keyup(function(){
					m = $(this).val();
					$('.talkcounter', $T).html(m.length + "/1000");
				});
			}
			
			// Posting
			function post() {
				if(posting) return;
				posting = true;
				msg = $('.talkarea', $T).val();
				if(msg.length > 1000) return;
				$.post('/talk', {msg: msg, channel: $T.attr('channel')}, function(data){
					$('.talkhr', $T).after(data);
					posting = false;
					$('.talkarea', $T).val('');
				});
			}
		});
	}
})(jQuery);

$(document).ready(function(){
   $('.talk').Talk();
});

