if (typeof (HWS) == "undefined") var HWS = {};
var toolbar = null;

function $(elementId) {
    return document.getElementById(elementId);
}

HWS.Editor = function(container, focus) {
    function onkeydown(ev) {
        var e = ev || window.event;
        if (e.keyCode != 13) return;
        e.returnValue = false;

        if (e.shiftKey)
            document.selection.createRange().pasteHTML("<p>");
        else {
            var r = document.selection.createRange();
            r.pasteHTML("<br />");
            r.select();
            r.move('character', 1);
        }
    }

    this.Cancel = function() {
        container.onkeydown = null;
        container.contentEditable = false;
    }

    this.execCommand = function(command, userInterface, value) {
        container.focus();
        document.execCommand(command, userInterface, value);
    }

    this.insertHTML = function(html) {
        container.focus();
        document.selection.createRange().pasteHTML(html);
    }

    this.switchMode = function() {
        if (mode == "wysiwyg") {
            mode = "text";
            var html = container.innerHTML;
            html = html.replace(/&/ig, "&amp;");
            html = html.replace(/</ig, "&lt;");
            html = html.replace(/>/ig, "&gt;");
            container.innerHTML = html;
        }
        else {
            mode = "wysiwyg";
            var html = container.innerHTML;
            html = html.replace(/&amp;/ig, "&");
            html = html.replace(/&lt;/ig, "<");
            html = html.replace(/&gt;/ig, ">");
            container.innerHTML = html;
        }
    }

    container.onkeydown = function(ev) { onkeydown(ev); };
    container.contentEditable = true;
    var mode = "wysiwyg";
    if (focus) container.focus();
}

HWS.Login = function (params) {
    this.login = function () {
        var login = $("inpName").value;
        var pass = $("inpPass").value;
        if (login == "" || pass == "") return;

        var f = "login=" + encodeURIComponent(login) + "&pass=" + encodeURIComponent(pass);
        document.body.style.cursor = "wait";
        aj(function (resp) { instance.respLogin(resp); }, "/forumx/checkstuff.aspx?fid=" + params.fid + "&action=login", f);
    }

    this.checkSubmit = function (ev) {
        var e = ev || window.event;
        if (e.keyCode == 13) instance.login();
    }

    this.respLogin = function (resp) {
        document.body.style.cursor = "default";
        if (resp == "OK") {
            popup.close();
            return;
        }

        alert(resp);
    }

    var instance = this;
    var lp = {};
    lp.content = params.content;
    lp.headline = "Session timeout";
    lp.button = {};
    lp.button.id = "btnLogin";
    lp.button.onclick = this.login;
    var popup = new HWS.Popup(lp);
    $("inpName").focus();
    $("divLogin").onkeypress = instance.checkSubmit;
}

function extendedSearch() {
    var div = $("divExtendedSearch");
    if (div == null) return false;
    div.style.display = div.style.display == "" ? "none" : "";
    return false;
}

function doSearch(fid, ev) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (ev) keycode = ev.which;
    if (keycode != 13) return true;

    var qs = new HWS.QueryString();
    qs.set("fid", fid);
    qs.set("key", encodeURIComponent(document.getElementById("keywords").value));

    var since = $("inpSearchFrom");
    if (since != null && since.value != "") qs.set("since", since.value.replace(/[^0-9]/g, "") + "000000");

    var thru = $("inpSearchTo");
    if (thru != null && thru.value != "") qs.set("thru", thru.value.replace(/[^0-9]/g, "") + "000000");

    document.location = "/forumx/search.aspx" + qs.getAll();
    return false;
}

function respAddAttachment(resp) {
    document.body.style.cursor = "default";
    editor.focusEditor();
    editor.insertHTML(resp);
}

function addAttachment(fid, id) {
    document.body.style.cursor = "wait";
    ajg(respAddAttachment, "/forumx/toolbar.aspx?fid=" + fid + "&id=" + id + "&mode=addattachment");
}

function respCreateThumbnail(resp, fid) {
    var pos = resp.indexOf(";");
    var id = resp.substr(0, pos);
    resp = resp.substr(pos + 1);

    var div = document.getElementById("divAttachments");
    if (div) div.innerHTML = resp;

    document.body.style.cursor = "wait";
    ajg(respAddAttachment, "/forumx/toolbar.aspx?fid=" + fid + "&id=" + id + "&mode=addthumbnail");
}

function createThumbnail(fid, id) {
    var qs = "/forumx/toolbar.aspx?fid=" + fid + "&id=" + id + "&mode=createthumbnail";
    if (toolbar) qs += "&toolbar=1";
    showWaitImage("divAttachments");
    ajg(function(resp) { respCreateThumbnail(resp, fid); }, qs);
}

function respDeleteAttachment(resp) {
    var div = document.getElementById("divAttachments");
    if (div) div.innerHTML = resp;
}

function deleteAttachment(fid, id) {
    var qs = "/forumx/toolbar.aspx?fid=" + fid + "&id=" + id + "&mode=deleteattachment";
    if (toolbar) qs += "&toolbar=1";
    showWaitImage("divAttachments");
    ajg(respDeleteAttachment, qs);
}

function addComment(fid, tid, dx, dy) {
    var div = document.getElementById("addcomment");
    if (!div) {
        document.location = "/forumx/post.aspx?FId=" + fid + "&Id=" + tid;
        return;
    }

    if (toolbar == null) {
        toolbar = new Toolbar(fid, tid, "new", dx, dy);
    }
    else {
        toolbar.Edit(fid, tid, "new");
    }
}

function fedit(fid, tid, pid, dx, dy) {
    var con = document.getElementById("content" + pid);
    if (!con.contentEditable) {
        document.location = "/forumx/post.aspx?FId=" + fid + "&Id=" + tid + "&Edit=" + pid;
        return;
    }

    if (toolbar == null) {
        toolbar = new Toolbar(fid, tid, pid, dx, dy);
    }
    else {
        toolbar.Edit(fid, tid, pid);
    }
}

function facebookShare(id) {
    var url = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(document.location);
    var divSubject = document.getElementById("subject" + id);
    if (divSubject) url += "&t=" + encodeURIComponent(divSubject.innerHTML);
    window.open(url, "facebookshare");
}

function MessageMasta(fid,poolid,popupMessenger,invisible) {
    this.respMessageMasta = function(resp) {
        if (resp == "") {
            this.idleCounter++;
            if (this.idleCounter < 45) setTimeout(timer, 20000);
            return;
        }

        this.idleCounter = 0;
        //alert(resp);
        setTimeout(timer, 20000);
    }

    this.timer = function() {
        ajg(respMessageMasta, "/forumx/NewMessageMasta.aspx?fid=" + fid + "&poolid=" + poolid + "&popupMessenger=" + popupMessenger + "&invisible=" + invisible);
    }

    this.idleCounter = 0;
    ajg(respMessageMasta, "/forumx/NewMessageMasta.aspx?init=1&fid=" + fid + "&poolid=" + poolid + "&popupMessenger=" + popupMessenger + "&invisible=" + invisible);
}

function googleConnect(fid) {
    var iframe = document.createElement("iframe");
    iframe.src = "http://hondos.org/forumx/googlefriendconnect.aspx?fid=" + fid + "&host=" + encodeURIComponent(window.location.host);
    iframe.style.display = "none";
    document.body.appendChild(iframe);
}

function twitterConnect(fid) {
    this.respTwitter = function(resp) {
        document.body.style.cursor = "default";
        if (resp == "")
            alert("twitter login failed somehow");
        else
            document.location = resp;
    }

    document.body.style.cursor = "wait";
    var url = encodeURIComponent(document.location);
    ajg(respTwitter, "/forumx/thirdpartyconnect.aspx?mode=twitter&fid=" + fid + "&backto=" + url);
}

function fbConnect(apiKey, fid) {
    this.respFacebook = function(resp) {
        document.body.style.cursor = "default";
        if (resp == "OK")
            document.location.reload();
        else
            alert("facebook login failed somehow!");
    }

    this.fbAfterLogin = function() {
        document.body.style.cursor = "wait";
        ajg(respFacebook, "/forumx/thirdpartyconnect.aspx?fid=" + fid);
    }

    FB.init(apiKey, "/xd_receiver.htm");
    FB.ensureInit(function() {
        FB.Connect.requireSession(fbAfterLogin, null, true);
    });
}

function Toolbar(fid, tid, pid, dx, dy) {
    this.onkeydown = function(ev, src) {
        ev = ev || window.event;
        if (src == "subj") this.subjectChanged = true;

        if (ev.keyCode != 13) return;
        ev.returnValue = false;
        if (src == "subj") return;

        if (ev.shiftKey)
            document.selection.createRange().pasteHTML("<p>");
        else {
            var r = document.selection.createRange();
            r.pasteHTML("<br />");
            r.select();
            r.move('character', 1);
        }
    }

    this.showError = function(dom, message) {
        if (!dom) return;
        dom.innerHTML = typeof(message) == "undefined" ? "" : message;
    }

    this.respAddNew = function(resp) {
        try {
            resp = eval("(" + resp + ")");
        }
        catch (e) {
            alert("something strange happened: " + resp)
            return;
        }

        this.showError($("erroremail"), resp.erroremail);
        this.showError($("errorusername"), resp.errorname);

        if (resp.status == "ok") {
            if (resp.releasestate == 0) {
                document.location = document.location;
            }
            else if (resp.releasestate == 1) {
                document.location = "/forumx/info.aspx?fid=" + this.fid + "&id=5";
            }
            else if (resp.releasestate == 2) {
                document.location = "/forumx/info.aspx?fid=" + this.fid + "&id=2";
            }
        }
    }

    this.respAddComment = function(resp) {
        document.body.style.cursor = "default";
        var div = document.getElementById("addcomment");
        if (!div) return;
        div.innerHTML = resp;
        div.scrollIntoView(false);
        this.loadToolbar();
    }

    this.respTb = function(resp) {
        if (resp.substr(0, 6) == "error:") {
            alert(resp.substr(6));
            return;
        }

        this.tb.innerHTML = resp;
        this.tb.style.display = "";
    }

    this.respAttachments = function(resp) {
        var div = document.getElementById("divFilelist");
        if (div == null) return;
        div.innerHTML = resp;
    }

    this.respUpdate = function(resp) {
        alert(resp);
    }

    this.refreshAttachments = function() {
        var instance = this;
        ajg(function(resp) { instance.respAttachments(resp); }, "/forumx/toolbar.aspx?fid=" + this.fid + "&tid=" + this.tid + "&pid=" + this.pid + "&mode=attachments");
    }

    this.update = function() {
        var f = "x";
        var subj = document.getElementById("subject" + this.pid);
        var con = document.getElementById("content" + this.pid);
        if (subj && this.subjectChanged) f = "subject=" + encodeURIComponent(subj.innerHTML);
        if (con) {
            f += "&body=" + encodeURIComponent(con.innerHTML);
        }

        var instance = this;
        if (this.pid == "new") {
            var username = document.getElementById("username");
            if (username) f += "&username=" + encodeURIComponent(username.value);
            var email = document.getElementById("email");
            if (email) f += "&email=" + encodeURIComponent(email.value);

            aj(function(resp) { instance.respAddNew(resp); }, "/forumx/toolbar.aspx?fid=" + this.fid + "&tid=" + this.tid + "&pid=" + this.tid + "&mode=addcomment", f);
        }
        else
            aj(function(resp) { instance.respUpdate(resp); }, "/forumx/toolbar.aspx?fid=" + this.fid + "&tid=" + this.tid + "&pid=" + this.pid + "&mode=edit", f);
    }

    this.cancel = function() {
        if (this.pid) {
            var subj = document.getElementById("subject" + this.pid);
            if (subj) subj.contentEditable = false;
            var con = document.getElementById("content" + this.pid);
            if (con) {
                con.onkeydown = null;
                con.contentEditable = false;
            }

            if (this.pid == "new") {
                var div = document.getElementById("addcomment");
                div.innerHTML = "";
            }
        }

        if (this.tb) this.tb.style.display = "none";
        this.pid = null;
    }

    this.toggleAttachments = function() {
        var divAtt = document.getElementById("divAttachments");
        var imgAtt = document.getElementById("imgToolbarAttachments");

        if (divAtt.style.display == "none") {
            var frm = document.getElementById("frmUpload");
            if (frm.src == "") frm.src = "/forumx/toolbar.aspx?fid=" + this.fid + "&pid=" + this.pid + "&tid=" + this.tid + "&mode=upload";
            imgAtt.src = "/forumx/graphics/minus.gif";
            divAtt.style.display = "";
        }
        else {
            imgAtt.src = "/forumx/graphics/plus.gif";
            divAtt.style.display = "none";
        }
    }

    this.formatText = function(command, option) {
        document.execCommand(command, false, option);
    }

    this.loadToolbar = function() {
        var instance = this;
        var subj = document.getElementById("subject" + this.pid);
        if (subj) {
            subj.onkeydown = function(ev) { instance.onkeydown(ev, "subj"); };
            subj.contentEditable = true;
        }

        var con = document.getElementById("content" + this.pid);
        if (con) {
            con.onkeydown = function(ev) { instance.onkeydown(ev, "con"); };
            con.contentEditable = true;
            con.focus();
            this.tb.style.top = findPosy(con) + this.dy + "px";
        }

        if (con || subj) {
            ajg(function(resp) { instance.respTb(resp); }, "/forumx/toolbar.aspx?FId=" + this.fid + "&TId=" + this.tid + "&PId=" + this.pid + "&mode=edit");
        }
    }

    this.startEdit = function() {
        if (this.pid == "new") {
            document.body.style.cursor = "wait";
            var instance = this;
            ajg(function(resp) { instance.respAddComment(resp); }, "/forumx/toolbar.aspx?fid=" + this.fid + "&tid=" + this.tid + "&pid=" + this.tid + "&mode=addcomment");
        }
        else
            this.loadToolbar();
    }

    this.Edit = function(fid, tid, pid) {
        this.cancel();
        this.fid = fid;
        this.tid = tid;
        this.pid = pid;
        this.subjectChanged = false;
        this.startEdit();
    }

    this.fid = fid;
    this.tid = tid;
    this.pid = pid;
    this.dx = dx || 0;
    this.dy = dy || 0;

    this.tb = document.getElementById("toolbar");
    if (!this.tb) this.tb = document.createElement("div");
    this.tb.id = "toolbar";
    this.tb.className = "toolbar";
    this.tb.style.left = 10 + this.dx + "px";
    this.tb.style.display = "none";
    document.body.appendChild(this.tb);

    this.startEdit();
}

function FormGenerator() {
    var items = [];

    this.Add = function(item) {
        if (items.length == 0)
            items[0] = item;
        else
            items[items.length] = item;
    }

    this.Submit = function() {
        var form = document.createElement("form");
        for (var i = 0; i < items.length; i++) {
            form.appendChild(items[i]);
        }
        form.action = this.Action;
        form.method = "post";
        document.body.appendChild(form);
        form.submit();
    }
}
