function reply(page, id, prefix, context) {
    replyWnd.display(page, id, null, prefix, context);
}

function edit(page, id, prefix, context) {
    replyWnd.displayEdit(page, id, prefix, context);
}

function cancelReply() {
    replyWnd.hide();
}

function submitReply() {
    replyWnd.post();
}


var replyWnd={
    shown: false,
    inited: false,
    id: 0,
    page: '',
    editor: null,
    btn: null, btnPanel: null, editPanel: null, editMode: false, 
    context: null, prefix: null,

    displayEdit: function(page, id, prefix, context) {
        if (id != 'new') {
            var a = document.getElementById('reply'+id);
            // anchor -> span.reply -> span.title -> div.comment
            var textNode = findChildByClassName(a.parentNode.parentNode.parentNode,'text');
            this.editMode = true;

            this.display(page,id, textNode, prefix, context);
        }
    },
    display: function(page, id, content, prefix, context) {
        if (!this.shown) {
            this.id = id;
            this.page = page;
            this.context = context;
            this.prefix = prefix;
            this.editMode = false;
            // anchor -> span.reply -> span.title -> div.comment
            var a = document.getElementById('reply'+id);

            var replyNode = (id != 'new');

//      MK: HIDING does not work in IE when div, does not know why, so replaced with textarea
            var editorPane = document.createElement("textarea");
            editorPane.id = 'reply'+id + 'edit';
            editorPane.className = 'editorPane';
            if (content != null) {
//                copyNode(content, editorPane);
                editorPane.value= patchIE(content.innerHTML);
            }
            var buttonPane = document.createElement("div");
            buttonPane.className = 'buttonPane';
            var okButton = document.createElement("button");
            if (!this.editMode) {
                okButton.appendChild(document.createTextNode('Post'));
            } else {
                okButton.appendChild(document.createTextNode('Save'));
            }
            okButton.onclick=submitReply;
            this.btn = okButton;
            var cancelButton = document.createElement("button");
            cancelButton.appendChild(document.createTextNode('Cancel'));
            cancelButton.onclick=cancelReply;
            buttonPane.appendChild(okButton);
            buttonPane.appendChild(document.createTextNode(' '));
            buttonPane.appendChild(cancelButton);

            this.btnPanel = buttonPane;
            this.editPanel = editorPane;
            if (replyNode) {
                obj = a.parentNode.parentNode.parentNode;
                var text= findChildByClassName(obj, 'text');
                editorPane.style.width = text.offsetWidth+"px";
                buttonPane.style.width = (text.offsetWidth-2)+"px";
                obj.insertBefore(buttonPane, findChildByClassName(obj, 'comment'));
                obj.insertBefore(editorPane, buttonPane);
            } else {
                editorPane.style.width = a.parentNode.offsetWidth+"px";
                buttonPane.style.width = (a.parentNode.offsetWidth-2)+"px";
                a.parentNode.insertBefore(buttonPane, a.nextSibling);
                a.parentNode.insertBefore(editorPane, buttonPane);
            }
            this.shown = true;
            this.editor = initEditor('reply'+this.id+'edit');
        }
    },

    hide: function() {
        if (tinymce.isIE6) {
            document.location.reload();
        }
        if (this.shown) {
            this.editor.hide();
            this.editor.remove();
            // remove editor
            this.btnPanel.parentNode.removeChild(this.btnPanel);
            // remove buttons
            this.editPanel.parentNode.removeChild(this.editPanel);
            this.shown = false;
        }
    },

    post: function() {
        if (this.shown) {
            this.btn.disabled = true;
            this.btn.removeChild(this.btn.firstChild);
            this.btn.appendChild(document.createTextNode('Sending...'));
            postReply(this.page, this.id, this.editor.getContent(), this.editMode, this.prefix, this.context);
        }
    },

    sendOk: function() {
        this.hide();
        document.location.reload();
    }

};

function findChildByClassName(node, className) {
    n = node.firstChild;
    while (true) {
        if (n.className == className) {
            return n;
        }
        if (n == node.lastChild) {
            return null;
        }
        n = n.nextSibling;
    }
}

function copyNode(src, dst) {
    n = src.firstChild;
    while (n != null) {        
        dst.appendChild(n.cloneNode(true));
        if (n == src.lastChild) {
            break;
        }
        n = n.nextSibling;
    }
}


function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		return null;
	}
}

var replyReq = getXmlHttpRequestObject();


function postReply(page, id, str, editMode, prefix, context) {
//    alert('Sending: ' + page + ','+id+':  '+str);
    if (replyReq && (replyReq.readyState == 4 || replyReq.readyState == 0)) {
        replyReq.open("POST", 'discuss?', true);
        replyReq.onreadystatechange = handleReplySubmit;
        replyReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        var action = (editMode ? 'commitEdit' : 'commitAdd');
        var params = "do="+action+"&parent="+page+"&id="+id+"&content="+escape(str)
                +"&wcontext=" + context + "&wprefix=" + prefix;
        replyReq.setRequestHeader("Content-length", params.length);
        replyReq.send(params);
	}

}

function handleReplySubmit() {
	if (replyReq.readyState == 4) {
        if (replyReq.status == 200) {
            replyWnd.sendOk();
		}
	}
}

function patchIE(str) {
    if (!tinymce.isIE) {
        return str;
    }

    pos = -1;
    while (true) {
        pos = str.toLowerCase().indexOf('<table', pos + 1);
        if (pos < 0 ) {
            break;
        }
        pend = str.toLowerCase().lastIndexOf('</p>', pos);
        pstart = str.toLowerCase().lastIndexOf('<p>', pos);
        if (pend < pstart) {
            // need to remove extra </p>
            str = str.substring(0, pstart) + str.substring(pstart + '<p>'.length);
            pos = pstart;
            pEnd = findEnd(str,pos, 'p');
            if (pEnd >= 0) {
                pos = pEnd;
                str = str.substring(0, pEnd) + str.substring(pEnd + '</p>'.length);
            }

        }
    }

    return str;
}

function findEnd(str, pos, tag) {
    d = 1;
    while (d > 0) {
        pstart = str.toLowerCase().indexOf('<'+tag, pos+1);
        pend = str.toLowerCase().indexOf('</'+tag+'>', pos+1);
        if (pstart > 0 && pstart < pend) {
            d++; pos = pstart;
            continue;
        } 
        // pstart < 0 || pstart > pend, so pend is the next
        if (pend < 0) {
            return -1; // we expected closing tag
        } else {    // 0 <= pend < pstart
            d--; pos = pend; // closing tag found - reduce depth
        }
    }
    // pos shows position of last </table>
    return pos;
}