var currentPage = 1;

window.addEvent('domready', function(){
                    getComments();
                });

function getComments(){
    var url = "commentSvc.php";
    var req = new Request.JSON({url: url,
                                onComplete: function(message){
                                    if (message.status == 'success'){
                                        message.data.each(displayComment);
                                    }
                                }
                               });
    req.send("a=c&p=" + currentPage);
    
}

function getMore(){
    currentPage++;
    getComments();
}


function addComment(){
    centerElement($('addCommentForm'));
    $('addCommentForm').fade('in');
}

function hideAddComment(){
    $('addCommentForm').fade('out');
}

function finishAddComment(){
    var message = '';
    if ($('commentText').value == ''){
        message += 'You need to add some text for you comment.\n';
    }
    if ($('commentName').value == ''){
        message += 'Please supply a commenter name';
    }

    if (message != ''){
        alert(message);
        return false;
    }

    var url = "commentSvc.php";
    var req = new Request.JSON({url: url,
                                onComplete: function(message){
                                    if (message.status == 'success'){
                                        displayComment(message.data);
                                        $('addCommentForm').fade('out');
                                        $('commentText').value = '';
                                        $('commentName').value = '';
                                    }
                                    else {
                                        alert("There was an error saving your comment.");
                                    }
                                }
                                
                                
                               });
    req.send("a=a&t=" + $('commentText').value + "&n=" + $('commentName').value);
    

}

function centerElement(el){
    
    if (!el) return;

    var w = window.getSize().x;
    var h = window.getSize().y;

    var left = (w - el.getStyle('width').toInt()) / 2;
    var top = ((h - el.getStyle('height').toInt()) / 2) + window.getScroll().y;

    el.setStyles({'top': top,
                'left': left});

}

function displayComment(comment){
    var commentTime = comment.commentTime;

    if (commentTime != ''){
        var d = new Date();
        d.parse(commentTime);

        commentTime = d.format("%x %X");
    }

    var c = new Element('div', {'class': 'commentWrap'})
        .adopt(new Element('div', {'class': 'comment'})
               .appendText(comment.commentText)
              )
        .adopt(new Element('div', {'class': 'commenter'})
               .appendText(comment.commentName + '@' + commentTime)
              );
    c.inject($('comments').getFirst(), 'after'); 
}

