function spoiler(id) {
    $("#" + id).toggleClass("hide");
}

function processTypeChange(polyId, typeName) {
    var selectors = document.getElementsByClassName("type_selector_" + polyId);
    for (var i = 0; i < selectors.length; i++) {
        var selector = selectors[i];
        if (selector.value != typeName) {
            selector.value = typeName;
        }
    }
    var blocks = document.getElementsByClassName("poly_block_" + polyId);
    for (var i = 0; i < blocks.length; i++) {
        var block = blocks[i];
        if (block.id == "poly_block_" + polyId + "_" + typeName) {
            block.style.display = "inline";
        } else {
            block.style.display = "none"
        }
    }
}

function injectOptions(polyId, types) {
    var selectors = document.getElementsByClassName("type_selector_" + polyId);
    for (var i = 0; i < selectors.length; i++) {
        for (var j = 0; j < types.length; j++) {
            var opt = document.createElement("option");
            opt.setAttribute("value", types[j]);
            opt.textContent = types[j];
            selectors[i].appendChild(opt);
        }
    }
}

var displayComments = false;

function toggleComments(display) {
    if (display == undefined) {
        display = !displayComments;
    }
    displayComments = display;
    if (display) {
        $('.json-fake').show();
        $('.xml-fake').show();
    } else {
        $('.json-fake').hide();
        $('.xml-fake').hide();
    }
}

// Popup
var onPopupClose = unhash(location.hash);
var popupMaxHeight = 400;

function unhash(hash) {
    if (hash.length > 0 && hash.charAt(0) == "#") {
        return hash.substring(1);
    }
    return hash;
}

function centerPopup() {

    var winWidth = $(window).width();
    var winHeight = $(window).height();
    var docHeight = $(document).height();
    var scrollPos = $(window).scrollTop();


    $('.popup-box').filter(":visible").each(function () {
        var elem = $(this);
        var titleElem = elem.children(".popup-header");
        var closeElem = elem.children(".popup-close");
        var contentElem = elem.children(".popup-content");
        var titleHeight = Math.max(titleElem.outerHeight(), closeElem.outerHeight());
        var contentHeight = contentElem.outerHeight();
        var totalHeight = titleHeight + contentHeight + 10;
        var totalWidth = elem.width();
        var left = (winWidth - totalWidth) / 2;
        var top = scrollPos + (winHeight - totalHeight) / 2;
        elem.css({
            'height': totalHeight + "px",
            'left': left + 'px',
            'top': top + 'px'
        });
    });

    $('#blackout').css({'width': winWidth + 'px', 'height': docHeight + 'px'});
}

function showPopup(id) {
    $('.popup-box').hide();
    $("#" + id).show();
    $('#blackout').show();
    $('html,body').css('overflow', 'hidden');
    centerPopup();
}

function hidePopups() {
    var blackout = $("#blackout");
    if (blackout.css("display") != "none") {
        location.hash = "#nav(" + onPopupClose + ")";
        $('.popup-box').hide();
        blackout.hide();
        $("html,body").css("overflow", "auto");
    }
}

function getParentId(id) {
    var element = $("#" + id);
    if (element.length == 1) {
        var parentId = element.attr("parentid");
        if (typeof parentId == "string") {
            return getParentId(parentId);
        }
    }
    return id;
}

function tabBox(tabBoxId, pageIndex) {
    var $tabContent = $("#" + tabBoxId);
    var children = $tabContent.children();
    for (var i = 0; i < children.length; i++) {
        $(children[i]).toggleClass("hide", i != pageIndex);
    }
    var $selectors = $("." + tabBoxId + "-selector");
    var activeSelectorClass = tabBoxId + "-selector-" + pageIndex;
    $selectors.each(function () {
        var $selector = $(this);
        var isActive = $selector.hasClass(activeSelectorClass);
        $selector.toggleClass("active", isActive);
    });
}

function hashAsAction() {
    var hash = location.hash;
    if (hash.length < 2) {

    } else {
        var re = /^#(.+)\((.*)\)$/;
        var matchRes = re.exec(hash);
        if (matchRes != null) {
            var action = matchRes[1];
            var id = matchRes[2];
            return {"action": action, id: id};
        }
    }
    return null;
}

function processOpenAction() {
    var action = hashAsAction();
    if (action != null && action.action == "open") {
        var id = action.id;

        var element = $('#' + id);
        if (element.length == 1) {
            var invisibles = $("#invisibles");
            if (element.hasClass("popup-box")) {
                onPopupClose = getParentId(id);
                showPopup(id);
            }
        }
    } else {
        hidePopups();
    }
}

function processNavigationActions() {
    var action = hashAsAction();
    if (action != null && action.action == "nav") {
        location.hash = "#" + action.id;
    } else if (action != null && action.action == "open") {
        $(window).scrollTop($('#' + getParentId(action.id)).offset().top);
        processOpenAction();
    }
}

$(document).ready(function () {
    // Hiding comments when ctrl or mac command are pressed
    window.addEventListener("keydown", function (event) {
        if (event.keyCode == 17 || event.keyCode == 224 || event.keyCode == 91 || event.keyCode == 93) {
            toggleComments(false);
        }
    }, false);

    window.addEventListener("keyup", function (event) {
        if (event.keyCode == 17 || event.keyCode == 224 || event.keyCode == 91 || event.keyCode == 93) {
            toggleComments(true);
        }
    }, false);

    $('.json-brackets').hover(
        function () {
            var clazz = $(this).attr('class').match(/brackets-pair-\d+/);
            $('.' + clazz).addClass('bracket-highlighted');
        },
        function () {
            var clazz = $(this).attr('class').match(/brackets-pair-\d+/);
            $('.' + clazz).removeClass('bracket-highlighted');
        }
    );

    // Popup
    $(window).resize(centerPopup);
    $(window).scroll(centerPopup);
    var invisibles = $("#invisibles");
    var popupBoxes = $(".popup-box");
    popupBoxes.each(function () {
        $(this).appendTo(invisibles);
    });
    popupBoxes.click(function (e) {
        e.stopPropagation();
    });
    $('.popup-close').click(hidePopups);

    $('html').click(hidePopups);

    $(window).bind('hashchange', processOpenAction);

    $("#blackout").bind('mousewheel DOMMouseScroll', function (e) {
        e.stopPropagation();
        e.preventDefault();
    });

    $(".section").hover(function () {
        $(this).toggleClass("hover", true)
    }, function () {
        $(this).toggleClass("hover", false)
    });

    $(".tabs-content").each(function () {
        tabBox($(this).attr("id"), 0);
    });

    processNavigationActions();
});
