$(document).ready(function() {
    $('form#commentform').jcomm();
});

$.fn.jcomm = function(e) {
    $("#comment-personaldetails").hide();
    $("#showinfo").click(function() {
	$("#comment-personaldetails").slideDown();
	$(this).hide();
	$("#hideinfo").show();
	return false;
    }).show();
    $("#hideinfo").click(function() {
	$("#comment-personaldetails").slideUp("slow");
	$(this).hide();
	$("#showinfo").show();
	return false;
    }).hide();
    $(this).submit(function(e){
	e.preventDefault();
	$.ajax({
	    type: "POST",
	    url: scriptpath + "/comments-ajax.php", 
	    data: $.param($('#commentform').formToArray()), 
	    dataType: "json",
	    success: function(json){
		var r = json.response[0];
    		if (r.error == "true") {
		    Growl.show('<p><span id="error"></span>' + r.msg + '</p>');
		} else {
		    var cls = 'alt';
		    if ($('ul#commentlist li:last-child').attr('class') == "alt") {cls = ''};
		    $('ul#commentlist').append('<li class="response '+cls+'" id="comment-'+r.id+'" style="display:none;"><span 
class="commentNumber">'+(Math.round($('ul#commentlist li:last .commentNumber').text())+1)+'</span><p class="commenter"><cite><a 
href="'+r.link+'">'+r.author+'</a> kommentoi'+r.text+' <p class="commentDate"><a 
href="#comment-'+r.id+'"">'+r.date+'</a></p></cite></p></li>');
	    	    $('ul#commentlist li:last-child').slideDown('slow').fadeTo("slow",1);
		    if (json.response[1] && json.response[1].alert == "true") {
			Growl.show('<p><span id="alert"></span>' + json.response[1].msg + '</p>');
		    }
		    $('textarea#comment').val("");
		    $('span#comments').html((Math.round($('#comments').text())+1));
		    $('h3#postcomment').html('Kommenti on lis&auml;tty');
	    	    $('li#nocomment').remove();
	    	    $('li#hidelist').remove();
		}
	    }
	});
    });
}
$.fn.formToArray = function() {
    var a = [];
    var q = 'input,textarea';
    $(q, this).each(function() {
        var n = this.name;
        var t = this.type;
        a.push({name: n, value: this.value});
    });
    return a;
};
