var userId;
var numConsecutiveFailedRequests = 0;
var newMsgUpdateIntervalId;
var idleTimer = new Date().getTime();
var _userPopupTimer;

$(document).ready(function() {
    // vote
    $("span[id='vote'] span").click(function() {
        var voteSpan = $(this);
        var dir = $(this).attr("id");
        var messageId = $(this).parents("div").attr("messageId");
        $.ajax({
            type: "POST", url: "/callback/registerVote.ashx",
            data: "dir=" + dir + "&messageId=" + messageId,
            dataType: "html", cache: false, timeout: 4000,
            success: function(c, textStatus) {
                voteSpan.parent().html("<span style=\"font-size: 8pt; font-family: arial; \">" + c + "</span>").fadeOut(3000);
            }, error: function(XMLHttpRequest, textStatus, errorThrown) { }
        });
    });

    // hover username in message header
    $("a.messageUser").mouseover(function(e) {
        _userPopupTimer = setTimeout("UserPopup(\"" + $(this).parents("div").attr("userId") + "\", " + e.pageX + ", " + e.pageY + ");", 300);
    });
    $("a.messageUser").mouseout(function() {
        UserPopupDone();
    });

    // support for "cut text" [jj 09Jun22]
    $("div.cut").each(function() {
        var text = $(this).attr("text");
        if (text == null || text == "") text = "Click here to view the cut text...";
        $(this).before("<span class='cutlink'>" + text + "</span>");
    });

    // display a block of cut text
    $("span.cutlink").click(function() {
        // remove unwanted BRs
        var cutDisplay = $(this).next().html().trim();
        if (cutDisplay.startsWith("<br>")) cutDisplay = cutDisplay.substring(4);
        if (cutDisplay.endsWith("<br>")) cutDisplay = cutDisplay.substring(0, cutDisplay.length - 4);
        $(this).next().html(cutDisplay);
        $(this).next().next().hide();
        // toggle display
        $(this).hide().next().show();
    });

    // despoiler // added [jj 11Mar28]
    $("span.spoiler").click(function() {
        $(this).removeClass("spoiler").addClass("despoil");
    });

    // add cut text html to the post box
    $("span#addcuttext").click(function() {
        AppendToPostbox("\r\n\r\n<div class=\"cut\" text=\"Click here to view the cut text...\">\r\nThis is the concealed text.\r\n</div>", true);
    });

    // add spoiler code to the post box
    $("span#spoiler").click(function() {
        AppendToPostbox("\r\n\r\n<span class=\"spoiler\"> Spoiler Text </span>", true);
    });

    userId = $("head").attr("userId");
    newMsgUpdateIntervalId = setInterval(UpdateNumNewMsgs, 15000);

    // "goto room by name" [jj 11Jan21]
    $("div#gotoPanel input#gotoRoomByName").click(function() {
        GotoRoomByName($("div#gotoPanel input#text_roomByName").val());
    });

    // clear the response field when typing in the roomname text box
    $("div#gotoPanel input#text_roomByName").keyup(function(eventData) {
        $("div#gotoPanel span").text("");
        // on "enter" just click the button 
        if (eventData.which == 13) $("div#gotoPanel input#gotoRoomByName").click();
    });
});

function AppendToPostbox(appendText, switchToSourceMode) {
    // this is sufficient for tghe simple textarea
    $("textarea#msg").val($("textarea#msg").val() + appendText);
    $("textarea#msg").val($("textarea#msg").val().trimFront());
    $("textarea#msg").focus();

    // more work required for the ckeditor
    if (typeof CKEDITOR === "undefined") return;
    CKEDITOR.instances.msg.setMode("wysiwyg"); // UGH. have to switch to wysiwyg on subsequent attempts or it just doesn't work (bug in ckeditor I guess)
    CKEDITOR.instances.msg.setData(CKEDITOR.instances.msg.getData() + appendText.replace(new RegExp("\n", "g"), "<br>\n"), new function() {
        if (switchToSourceMode) CKEDITOR.instances.msg.setMode("source");
        CKEDITOR.instances.msg.focus();
    });
}

function QuoteMessage(msgId) {
    var lines = document.getElementById(msgId).innerHTML.split("<br>\n");
    var quoth = "\r\n";
    for (i = 0; i < lines.length; i++) {
        if (lines[i] != "") quoth += "> " + lines[i] + "\r\n";
        else quoth += "\r\n";
    }
    AppendToPostbox(quoth + "\r\n", false);
}

function UserPopup(userId, x, y) {
    $.ajax({
        type: "POST",
        url: "/callback/getUserStatus.ashx",
        data: "userId=" + userId,
        dataType: "html",
        cache: false,
        timeout: 4000,
        success: function(c, textStatus) {
            x += 20;
            y += 5;
            $("body").append("<div class='userPopup' style='top: " + y + "px; left: " + x + "px;'>" + c + "</div>");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { }
    });
}
function UserPopupDone() {
    clearTimeout(_userPopupTimer);
    $("div.userPopup").remove();
}

function GotoRoomByName(roomName) {
    $("div#gotoPanel span").text("searching...");
    $.ajax({
        type: "POST",
        url: "/callback/getRoomByName.ashx",
        data: "roomName=" + $.trim(roomName),
        dataType: "text",
        cache: false,
        timeout: 4000,
        success: function(roomId, textStatus) {
            if (roomId == "not found" || roomId == "error" || roomId == "not logged in") {
                $("div#gotoPanel span").text(roomId);
            } else {
                window.open("showRoom.aspx?roomId=" + roomId, '_self');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $("div#gotoPanel span").text(errorThrown);
        }
    });
}

// asynchronously update the number of new messages [jj 09Nov19]
function UpdateNumNewMsgs() {
    $.ajax({
        type: "POST",
        url: "/callback/getNewMessagesCount.ashx",
        dataType: "text",
        cache: false,
        timeout: 4000,
        success: function(c, textStatus) {
            $("span#newMsg").text(c);
            $("span#newMsg").css("background-color", "");
            numConsecutiveFailedRequests = 0;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $("span#newMsg").css("background-color", "yellow");
            numConsecutiveFailedRequests++;
            if (numConsecutiveFailedRequests > 3) $("span#newMsg").css("background-color", "red");
        }
    });

    if (new Date().getTime() - idleTimer > 60000) {	// after 1 min idle time, slow down the new msg counter
        clearInterval(newMsgUpdateIntervalId);
        newMsgUpdateIntervalId = setInterval(UpdateNumNewMsgs, 30000); // every 30 seconds
    }
    if (new Date().getTime() - idleTimer > 900000) { // after 15 min, stop entirely
        clearInterval(newMsgUpdateIntervalId);
    }
}

function ChooseRecipient(authorId) {
    var recipSelectList = document.getElementById('chooseRecipient');
    for (var i = 0; i < recipSelectList.options.length; i++) {
        if (recipSelectList.options[i].value == authorId)
            recipSelectList.options[i].selected = true;
    }
}

function DCMSelect() {
    var dcmCommand = document.getElementById('dcmCommand').value;
    if (dcmCommand == "delete" || dcmCommand == "neuter") {
        document.getElementById('dcmDelete').style.display = 'inline';
        document.getElementById('dcmCopyMove').style.display = 'none';
    } else {
        document.getElementById('dcmDelete').style.display = 'none';
        document.getElementById('dcmCopyMove').style.display = 'inline';
    }
}

function ToggleDisplay(elementId) {
    var block = document.getElementById(elementId);
    if (block.style.display == 'none') block.style.display = 'block';
    else block.style.display = 'none';

    Set_Cookie(elementId, block.style.display, cookie_expire_date, "/", false);
}

// Check for cookie and set the specified block display to that value.
function RestoreBlockState(elementId) {
    var val = Get_Cookie(elementId);
    if (val != "") document.getElementById(elementId).style.display = val;
}

var oldUsernameValue;
function ToggleAnony() {
    var anon = document.getElementById('postAnonymously');
    var senderName = document.getElementById('senderName');

    if (anon.value == "False") {
        anon.value = "True";
        oldUsernameValue = senderName.innerHTML;
        senderName.innerHTML = "Anonymous";
    } else {
        anon.value = "False";
        senderName.innerHTML = oldUsernameValue;
    }
}

String.prototype.startsWith = function(str) { return (this.match("^" + str) == str); }
String.prototype.endsWith = function(str) { return (this.match(str + "$") == str); }
String.prototype.trim = function() { return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")); }
String.prototype.trimFront = function() { return (this.replace(/^[\s\xA0]+/, "")); }
