function requestCreate() {
    try {
        request = new XMLHttpRequest();
    } catch (microsoft) {
        try {
            request = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (oldMicrosoft) {
            try {
                request = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (failure) {
                request = null;
           }
        }
    }
}

function commentSubmit() {
    var commentName = document.getElementById('commentName').value;
    var commentEmail = document.getElementById('commentEmail').value;
    var commentUrl = document.getElementById('commentUrl').value;
    var commentBody = document.getElementById('commentBody').value;
    var commentPage = document.getElementById('commentPage').value;
    var commentChris = document.getElementById('commentChris').value;

    requestCreate();
    request.open('POST', 'http://shiflett.org/comment', true);
    request.onreadystatechange = commentPreview;
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.setRequestHeader('X-Ajax', 'shiflett.org');
    request.send('commentName=' + encodeURI(commentName) +
                 '&commentEmail=' + encodeURI(commentEmail) +
                 '&commentUrl=' + encodeURI(commentUrl) +
                 '&commentBody=' + encodeURI(commentBody) +
                 '&commentChris=' + encodeURI(commentChris) +
                 '&commentPage=' + encodeURI(commentPage));
}

function commentPreview() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            var comments_container = document.getElementById("comments");
            if (document.getElementById("preview") == null) {
                var preview = document.createElement("div");
                preview.id = "preview";
                comments_container.appendChild(preview);
            } else {
                var preview = document.getElementById("preview");
            }
            var blockquote = document.getElementById("preview-blockquote");
            preview.innerHTML = request.responseText;
            doCodeView(blockquote);
            location.hash = "preview";
        }
    }
}


function buttonReplace() {
    if(!document.getElementById) return;

    var commentPreviewButton = document.getElementById('commentPreviewButton');

    if(!commentPreviewButton) return;

    commentPreviewButton.onclick = function(e) {
        stopDefaultEvent(e);
        commentSubmit(this);
    }

    if (commentPreviewButton.captureEvents) {
        commentPreviewButton.captureEvents(Event.CLICK);
    }
}

function stopDefaultEvent(e) {
    if (window.event) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }

    if (e && e.preventDefault && e.stopPropagation) {
        e.preventDefault();
        e.stopPropagation();
    }
}

addLoadEvent(buttonReplace);
