$(document).ready(function () {
    
    //comment button click
    $("#comment").click(function () {
        //remove all error messages
        asengine.removeErrorMessages();
        
        var comment = $("#comment-text"),
             btn    = $(this);
             
        //validate comment
        if($.trim(comment.val()) == "") {
            asengine.displayErrorMessage(comment, "Field cannot be empty!");
            return;
        }
        
        //set button to posting state
        asengine.loadingButton(btn, "Posting...");
        
         $.ajax({
            url: "ASEngine/ASAjax.php",
            type: "POST",
            data: {
                action : "postComment",
                comment: comment.val()
            },
            success: function (result) {
                //return button to normal state
                asengine.removeLoadingButton(btn);
                try {
                   //try to parse result to JSON
                   var res = JSON.parse(result);
                   
                   //generate comment html and display it
                   var html  = "<li class='user clearfix'>";
                        html += "<a href='#' class='avatar'>";
                        html += "<img src='images/avatar3.jpeg' />";
                        html += "</a>";
                        html += "<div class='message'>";
                        html += "<div class='head clearfix'>";
                        html += "<span class='name'><strong>"+res.user+"</strong> says:</span>";
                        html += "<span class='time'>"+res.postTime+"</span>";
                        html += "</div>";
                        html += "<p>"+res.comment+"</p>";
                        html += "</div>";
                        html += "</li>";
						
						
                    if( $(".comments-comments li").length >= 7 )
                        $(".comments-comments li").last().remove();
                    $(".comments-comments").prepend($(html));
                    comment.val("");
                }
                catch(e){
                   //parsing error, display error message
                   asengine.displayErrorMessage(comment, "Error writing to database. Please try again.");
                }
            }
        });
    });
	
});
