(function($){
	$.fn.refreshComment = function(options) {
		$.ajax({
			type: "post",
			url: "app/includes/ajax.php",
			data: {"action": "get_comments", "obj": options.obj, "label": options.label, "label_plu": options.label_plu}
		}).done(function(data){
			data = JSON.parse(data);
			$("#comment-container-"+options.obj).html(data);
		})
	}
})(jQuery);

jQuery(document).ready(function($){

	$(document).on("click", ".submit-comment-btn", function(e){
		e.preventDefault();
		var text = $(this).html();
		var btn = $(this);
		$(this).html("<em>Submitting...</em>").attr("disabled", true);
		var obj = $(this).data("id");
		var comment = $("#comment-input-"+obj).val();
		var key = $("#key-"+obj).val();
		if(comment.trim() !== "") {
			$.ajax({
				type: "post",
				url: "app/includes/ajax.php",
				data: {"action": "new_comment", "comment": comment, "obj": obj, "key": key}
			}).done(function(data){
				try {
					data = JSON.parse(data);
					console.log($("#comment-input-"+obj));
					if(data.error == 0) {
						$("#comment-input-"+obj).val("");
						$(".trumbowyg-editor").html("");
					}
					$(document).refreshComment(obj);
				}
				catch(err) {
					console.log(err);
				}
				finally {
					$(btn).html(text).attr("disabled", false);
					console.log(data);
				}
			})
		}
	})

	function refreshCommentTimer() {
	    setTimeout(function () {
	    	$( ".submit-comment-btn" ).each(function( index ) {
	    		var options = new Object();
	    		options.obj = $(this).data("id");
	    		options.label = $(this).data("label");
	    		options.label_plu = $(this).data("labelPlu");
	    		$(document).refreshComment(options);
	    	})
	        refreshCommentTimer();
	    }, 10000);
	}

	refreshCommentTimer();
})