function setChapterActive($chapter, hash) {
    // No chapter and no hash means first chapter
    if (!$chapter && !hash) {
        $chapter = $chapters.first();
    }

    // If hash is provided, set as active chapter
    if (!!hash) {
        // Multiple chapters for this file
        if ($chapters.length > 1) {
            $chapter = $chapters.filter(function() {
                var titleId = getChapterHash($(this));
                return titleId == hash;
            }).first();
        }
        // Only one chapter, no need to search
        else {
            $chapter = $chapters.first();
        }
    }

    // Don't update current chapter
    if ($chapter.is($activeChapter)) {
        return;
    }

    // Update current active chapter
    $activeChapter = $chapter;

    // Add class to selected chapter
    $chapters.removeClass('active');
    $chapter.addClass('active');

    // Update history state if needed
    hash = getChapterHash($chapter);

    var oldUri = window.location.pathname + window.location.hash,
        uri = window.location.pathname + hash;

    if (uri != oldUri) {
        history.replaceState({ path: uri }, null, uri);
    }
}