(function () {
'use strict';

const QUERIES = ['page','sort','tag'];

const URLQueries = {};
location.search.slice(1).split('&').forEach( q => {
  const [key,value] = q.split('=');
  if (!key) return;
  URLQueries[key] = decodeURIComponent(value).split('+').join(' ');
});

for (let k = 0; k < QUERIES.length; k++) {
  const key = QUERIES[k];
  if (URLQueries[key])
    sessionStorage['BLOG-'+key] = URLQueries[key];
}

if (!location.search) {
  for (let k =0; k<QUERIES.length; k++) {
    delete sessionStorage['BLOG-' + QUERIES[k]];
  }
}

const DO_BLOG = {
  
  // DON'T TOUCH THE ALLCAPS >:0
  CURRENT_PAGE: Number(URLQueries.page - 1) || 0,
  SORT: !!Number(URLQueries.sort),
  ARTICLE: URLQueries.article || '',
  
  // blogging experience
  new_post: '#',
  tag_cmd: '[tag]',
  sign_cmd: '[sign]',
  
  title: 'Blog',
  
  no_posts_msg: 'This person has not posted yet! Come back later :3',
  none_tagged_msg: 'There are no posts under this tag!',
  
  // blog post
  title_is_link: true,
  link_text: '[link]', // if title is not link
  tags_in_footer: false,
  cut_long_posts: .75 * window.innerHeight,
  img_height: 300,
  show_more: 'Open full post',
  
  replacers: [],
  newTitle: (post) => { // when post has no title
    const temp = document.createElement('div');
    temp.innerHTML = post.getBodyHTML();
    const arr = temp.textContent.slice(0,20).split(/\s+/);
    arr.pop();
    return arr.join(' ') + '…';
  },
  getDate: (date) => {
    return date.toUTCString().slice(0,16);
  },
  signature: (post) => {
    return 'Posted ' + post.date.toLocaleDateString();
  },
  
  // nav
  links_heading: 'Archive',
  skip_to_content: 'Skip to content',
  open_navs: 2,
  months: [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ],
  navTitle: (post) => {
    return post.date.toLocaleDateString();
  },
  
  // tag form
  tag_label: 'Tag: ',
  all_tags: '--All tags--',
  tag_search: 'Go',
  
  // sort form
  sort_old_to_new: 'Sort old to new',
  sort_new_to_old: 'Sort new to old',
  
  // search pages nav
  load_limit: 2,
  pagination_limit: 6,
  skip_pagination: 'Skip pagination',
  previous_page: 'Prev page!',
  page_label: 'Page: ',
  next_page: 'Next page!',
  
  // breadcrumb nav
  breadcrumb_trail: '/',
  breadcrumb_article: 'Article',
  breadcrumb_tag: 'Tag',
  
  // article nav
  next_post: '← Next',
  post_nav_separator: ' | ',
  previous_post: 'Prev →',
  
  // aria-label (for pagination and tags)
  aria_goto_page: 'Goto page ',
  aria_current_page: 'Current page, page ',
  aria_page_of: ['Page ', ' of '],
  aria_pagination: 'Pagination',
  aria_breadcrumbs: 'Breadcrumbs',
  aria_tags: 'Tags',
  
  do_onload: (posts) => {}
};

if (typeof MY_BLOG !== 'undefined') {
  for (const k in MY_BLOG) {
    DO_BLOG[k] = MY_BLOG[k];
  }
}

const blog = document.querySelector('#blog');
blog.innerHTML = '';

const titleE = document.querySelector('title') || document.createElement('title');
document.querySelector('head').append(titleE);

titleE.textContent = DO_BLOG.title;

const ARCHIVE_TEXT = (function () {
  const archive = document.querySelector('#blog-archive');
  if (!archive)
    return '';
  return archive.innerHTML;
})();

const POSTS = []; // all posts
const TAGS = [];  // filtering
const PAGES = []; // pagification

const block = /^<\/?(?:body|article|address|aside|footer|header|h\d|hgroup|main|nav|section|blockquote|dd|div|dl|dt|figcaption|hr|li|menu|nav|ol|p|pre|el|area|map|table|col|colgroup|tbody|td|tfoot|th|thead|tr|fieldset|section|script|noscript|form|details|summary|dialog|figure)(?:\s+\w+\W+?.*?\W?)*\s*\/?>/i;

const markdownish = /\*\*\*(.*?)\*\*\*|\*\*(.*?)\*\*|\*(.*?)\*|(\!)?\[(.*?)\]\(('.*?'|".*?"|`.*?`|.*?)\)|`(.*?)`/gmi;

// NAVIGATION (so we don't have to re-iterate over every post again later on...
const blogNav = document.createElement('nav');
blogNav.innerHTML = '<h2 class=links>'+DO_BLOG.links_heading+'</h2><a href="#blog-content" class=skip-to-content>'+DO_BLOG.skip_to_content+'</a>';

// BLOGIFICATION

ARCHIVE_TEXT
  .split(RegExp('^\\s*'+ DO_BLOG.new_post,'m'))
    .forEach ( blogpost => {
    
  if (!blogpost.trim()) return;
  
  const lines = blogpost.split(/\n\s*\n/);
    
  const post = {
    // first line
    title: lines.shift(),
    // second line
    date: new Date(
      !Number(lines[0]) ? lines.shift()
        : Number( lines.shift() )
    ),
    
    // filtering is case-insensitive and ignores
    // non-alphanumeric characters
    tags: [],         // filtering
    visible_tags: [], // display
    
    body: ''
  }
  
  const trimmedTitle = post.title.trim();
  
  if (trimmedTitle)
    post.visible_title = trimmedTitle;
  
  const idPrefix = !trimmedTitle ?
    DO_BLOG.title.replace(/\W+/g,'-') : trimmedTitle.replace(/\W+/g,'-');
  
  post.id =  idPrefix + '-' + post.date.getTime();
  
  lines.forEach( line => {
    
    if (line.startsWith(DO_BLOG.tag_cmd)) {
      const [tags, vis] = addTag(line.replace(DO_BLOG.tag_cmd,''));
      post.tags.push(...tags);
      post.visible_tags.push(...vis);
      return;
    }
    
    if (line === DO_BLOG.sign_cmd)
      return post.body += '<p class=signature>' + sign(post);
    
    if (!block.test(line))
      return post.body += '<p>' + line.replace(markdownish,markdownify);
    else
      return post.body += line.replace(markdownish,markdownify);
    
  });
  
  POSTS.push( new Post(post) );
  
  // blogNav
  
  const yyyy = post.date.getFullYear();
  const mm = post.date.getMonth();
  const month = DO_BLOG.months[post.date.getMonth()];
  
  let yrD = blogNav.querySelector('#nav-' + yyyy + ' > ul');
  if (!yrD) {
    const details = document.createElement('details');
    details.classList.add('year');
    details.id = 'nav-' + yyyy;
    const summary = document.createElement('summary');
    summary.textContent = yyyy;
    const ul = document.createElement('ul');
    ul.classList.add('months');
    details.append(summary,ul);
    blogNav.append(details);
    yrD = ul;
  }
  
  let moD = yrD.querySelector('#nav-' + mm + '-' + yyyy);
  if (!moD) {
    const li = document.createElement('li');
    const details = document.createElement('details');
    details.classList.add('month');
    details.id = 'nav-' + mm + '-' + yyyy;
    const summary = document.createElement('summary');
    summary.textContent = month;
    details.append(summary);
    li.append(details);
    yrD.append(li);
    moD = details;
  }
  
  let psU = moD.querySelector('.posts');
  if (!psU) {
    const ul = document.createElement('ul');
    ul.classList.add('posts');
    moD.append(ul);
    psU = ul;
  }
  
  const li = document.createElement('li');
  const a = document.createElement('a');
  a.textContent = DO_BLOG.navTitle(post);
  
  a.href = location.pathname + '?article=' + post.id + '#blog';
  
  li.append(a);
  psU.append(li);
  
});

// Post CLASS

function Post(post) {
  for (let k in post) {
    this[k] = post[k];
  }
}

Post.prototype.getArticle = function() {
  
  if (this.article)
    return this.article;
  
  const article = document.createElement('article');
  article.id = this.id;
  article.classList.add('post');
  
  this.article = article;
  
  const headerE = document.createElement('header');
  const titleE  = document.createElement('h1');
  const dateE   = document.createElement('p');
  const bodyE   = document.createElement('div');
  
  headerE.classList.add('header');
  titleE.classList.add('title');
  dateE.classList.add('date');
  bodyE.classList.add('body');
  
  const articleLink = location.pathname + '?article=' + this.id + '#blog';
  
  if (DO_BLOG.title_is_link && DO_BLOG.ARTICLE !== this.id)
    titleE.innerHTML = '<a href="'+ articleLink +'">' + this.getTitleHTML() + '</a>';
  else {
    titleE.innerHTML = this.getTitleHTML();
  }

  // Day, DD MMM YYYY
  dateE.innerHTML = '<time datetime="' + this.date.toJSON() +
    '">' + DO_BLOG.getDate(this.date) + '</time>';
  
  let body = this.getBodyHTML();
  
  bodyE.innerHTML = body;
  const minheight = Math.min(blog.offsetWidth, DO_BLOG.img_height);
  
  headerE.append(titleE,dateE);
  
  if (DO_BLOG.ARTICLE !== this.id && !DO_BLOG.title_is_link ) {
    const a = document.createElement('a');
    a.href = articleLink;
    a.innerHTML = DO_BLOG.link_text;
    a.classList.add('blog-link');
    headerE.append(a);
  }
  
  article.append(headerE,bodyE);
  
  if (this.tags.length) {
    
    const tagsE   = document.createElement('ul');
    tagsE.classList.add('tags');
    tagsE.setAttribute('aria-label', DO_BLOG.aria_tags);
    
    this.visible_tags.forEach( tag => {
      tagsE.innerHTML += '<li class=tag><a href="' + location.pathname + '?tag='+ encodeURIComponent(tag) + '#blog-content">' + tag + '</a>';
    });
    
    if (!DO_BLOG.tags_in_footer)
      headerE.append(tagsE);
    else {
      const footer = document.createElement('footer');
      footer.classList.add('footer');
      footer.append(tagsE);
      article.append(footer);
    }
  }
  
  return article;
  
}

Post.prototype.getBodyHTML = function() {
  if (this.visible_body)
    return this.visible_body;
  
  let str = this.body;
  
  DO_BLOG.replacers.forEach ( e => {
    const arr = str.split(e[0]);
    str = arr.join(e[1]);
  });
  
  this.visible_body = str;
  
  return str;
  
}

Post.prototype.getTitleHTML = function() {
  if (this.visible_title)
    return this.visible_title;
  
  const str = DO_BLOG.newTitle(this);
  
  this.visible_title = str;
  return str;
}

// LOAD ARTICLE ONLY

if (URLQueries.article) {
  
  // there would normally not be more than one article with the same title and date, but if there are, all of them will be displayed:
  
  const filtered = POSTS.filter( post => {
    return post.id === URLQueries.article;
  });
  
  delete URLQueries.article;
  
  // make sure blog post actually exists
  if (filtered.length > 0) {
    
    blog.classList.add('article');
    
    let lastPageQueries = '';
    for (let i=0; i<QUERIES.length; i++) {
      let key = QUERIES[i];
      if (sessionStorage['BLOG-' + key])
        lastPageQueries += '&' + key + '=' + sessionStorage['BLOG-'+key];
    }
    
    blogNav.setAttribute('aria-label',DO_BLOG.aria_breadcrumbs);
    blogNav.classList.add('breadcrumbs');
    blogNav.innerHTML = '<a class=breadcrumb href="' + location.pathname + '?'+ lastPageQueries.slice(1) + '#' + filtered[0].id + '">'+ DO_BLOG.title +'</a>'+
      '<span class=trail>' + DO_BLOG.breadcrumb_trail + '</span>'+
      '<span class=breadcrumb>'+DO_BLOG.breadcrumb_article+'</span>' +
      '<span class=trail>' + DO_BLOG.breadcrumb_trail + '</span>'+
      '<a class="current breadcrumb" href="'+ location.pathname + '?article=' + filtered[0].id +'" aria-current=breadcrumb>'+ (filtered[0].getTitleHTML().trim() ? filtered[0].getTitleHTML() : DO_BLOG.getDate(filtered[0].date)) + '</a>';
    
    blog.append(blogNav);
    
    const titleTemp = document.createElement('span');
    titleTemp.innerHTML = filtered[0].getTitleHTML();
    
    const blogTemp = document.createElement('span');
    blogTemp.innerHTML = DO_BLOG.title;
    
    titleE.textContent = titleTemp.textContent + ' - ' + blogTemp.textContent;
    
    while (filtered.length) {
      blog.append(
        getAdjacentPostsPagination('top',filtered[0]),
        filtered[0].getArticle(),
        getAdjacentPostsPagination('bottom',filtered.shift())
      );
    }
    
    return // load article ONLY
    
  }
  // else keep going like no article was singled out welp
  
}

// ELSE SHOW ALL BLOGS

blog.classList.add('blog');

POSTS.sort( (a,b) => {
  return b.date.getTime() - a.date.getTime();
});


// NAVIGATION AND FORMS

blogNav.id = 'blog-nav';

// open first $DO_BLOG.open_navs details
const navDetails = blogNav.querySelectorAll('details');
for (let i = 0; i < Math.min(DO_BLOG.open_navs, navDetails.length); i++) {
  navDetails[i].open = true;
}

const blogBar = document.createElement('div');
blogBar.classList.add('blog-bar');
//blogBar.tabIndex = 0;

TAGS.sort();

const tagSelect = document.createElement('select');
tagSelect.name = 'tag';
tagSelect.innerHTML = '<option value="">'+DO_BLOG.all_tags+'</option>';

TAGS.forEach( tag => {
  const op = document.createElement('option');
  op.textContent = tag;
  op.value = tag;
  tagSelect.append(op);
});

const qSort = DO_BLOG.SORT + 0;
const qTag = URLQueries.tag || '';

const tagForm = document.createElement('form');
tagForm.innerHTML = '<input type=hidden value="' + (URLQueries['sort'] || '0') + '" name=sort>' + '<label id=tag-search>'+DO_BLOG.tag_label+'</label> <button onclick="location.hash=\'#blog-content\'">'+DO_BLOG.tag_search+'</button>';
tagForm.querySelector('#tag-search').append(tagSelect);
tagForm.id = 'tag-form';

const sortForm = document.createElement('form');

sortForm.innerHTML = '<input type=hidden value="'+ (!qSort + 0) +'" name=sort>'+ 
(qTag ? '<input type=hidden value="'+ qTag +'" name=tag>' : '') + '<button onclick="location.hash=\'#blog-content\'">'+ (qSort ? DO_BLOG.sort_new_to_old : DO_BLOG.sort_old_to_new) + '</button>';
sortForm.id = 'sort-form';


// APPEND EVERYTHING

  // NAV and FORMS:

blogBar.append(
  blogNav,
  document.createElement('hr'),
  tagForm,
  sortForm
);

const main = document.createElement('div');
main.classList.add('blog-main');
main.id = 'blog-content';

blog.append(blogBar,main);

  // BLOG POSTS:

loadPages();

loadCurrentPage();


addEventListener('load', do_onload);

// FUNCTIONS

function do_onload (e) {
  return DO_BLOG.do_onload(POSTS);
}

function addTag (line) {
  const [tags, visible] = [[],[]];
  line.split(',').forEach( str => {
    const tag = str.trim();
    visible.unshift(tag);
    tags.unshift(tag.toLowerCase().replace(/\W+/g,''));
    if (visible[0].trim() && TAGS.indexOf(visible[0]) < 0)
      TAGS.push(visible[0]);
  });
  return [tags, visible.reverse()];
}

function sign (post) {
  if (typeof DO_BLOG.signature === 'string')
    return DO_BLOG.signature;
  return DO_BLOG.signature(post)
}

function loadPages() {
  const vistag = URLQueries.tag || '';
  const tag = vistag ?
    vistag.trim().toLowerCase().replace(/\W+/g,'') : '';
  
  let filteredPosts = POSTS.filter(p => {return true});
  
  if (tag) {
    filteredPosts = filteredPosts.filter( post => {
      if (tag) {
        return post.tags.indexOf(tag) > -1;
      }
    });
  }
  
  if (DO_BLOG.SORT) {
    filteredPosts = filteredPosts.sort( (a,b) => {
      return a.date.getTime() - b.date.getTime();
    });
  }
  
  let page = 0;
  while (filteredPosts.length) {
    PAGES[page] = [];
    while (filteredPosts.length &&
        PAGES[page].length < DO_BLOG.load_limit) {
      PAGES[page].push(filteredPosts.shift());
    }
    ++page;
  }
}

function loadCurrentPage () {
  
  // archive empty?
  if (!POSTS.length) {
    main.innerHTML = '<p class="no-posts msg">' + DO_BLOG.no_posts_msg;
    return;
  }
  
  const numberOfPages = PAGES.length;
  const page = DO_BLOG.CURRENT_PAGE;
  const cur = page + 1;
  
  const tag = URLQueries.tag;
  if (tag) {
    
    const nav = document.createElement('nav');
    
    nav.setAttribute('aria-label',DO_BLOG.aria_breadcrumbs);
    nav.classList.add('breadcrumbs');
    nav.innerHTML = '<a class=breadcrumb href="' + location.pathname + '">'+ DO_BLOG.title +'</a>'+
      '<span class=trail>'+ DO_BLOG.breadcrumb_trail +'</span>'+
      '<span class=breadcrumb>'+DO_BLOG.breadcrumb_tag+'</span>'+
      '<span class=trail>' + DO_BLOG.breadcrumb_trail + '</span>'+
      '<a class="current breadcrumb" href="' + location.pathname + '?tag=' + encodeURIComponent(tag) +'" aria-current=breadcrumb>'+ tag + '</a>';
    
    main.append(nav);
    
  }
  
  // pagination
  if (numberOfPages > 1)
    main.append(newPagination('top', numberOfPages, cur, page));
  
  if (!numberOfPages) {
    const p = document.createElement('p');
    p.classList.add('msg');
    p.classList.add('no-posts');
    p.innerHTML = DO_BLOG.none_tagged_msg;
    main.append(p);
  } else {
  
    for (let i = 0; i < PAGES[page].length; i++) {
      
      const post = PAGES[page][i];
      
      const yyyy = post.date.getFullYear();
      const mm = post.date.getMonth();
      const [yrid,moid] = ['y-'+yyyy,'m-'+mm+'-'+'yyyy']
      
      // display new year
      if (!main.querySelector('#'+yrid)) {
        const h2 = document.createElement('h2');
        h2.id = yrid;
        h2.classList.add('year');
        h2.classList.add('section');
        h2.textContent = yyyy;
        main.append(h2);
      }
      
      // display new month
      if (!main.querySelector('#'+moid)) {
        const h3 = document.createElement('h3');
        h3.id = moid;
        h3.classList.add('month');
        h3.classList.add('section');
        h3.textContent = DO_BLOG.months[mm];
        main.append(h3);
      }
      
      const article = post.getArticle();
      const bod = article.querySelector('.body');
      const postImgs = [];
      
      main.append(article);
      
      if (DO_BLOG.cut_long_posts && bod.scrollHeight > DO_BLOG.cut_long_posts) {
        
        bod.id = post.id + '-' + 'content-body';
        
        let cutoff = false;
        const topBod = bod.offsetTop;
        
        const bouncer = [[],[]];
        
        for (let n = 0; n < bod.children.length; n++) {
          
          const node = bod.children[n];
          
          const imgs = node.querySelectorAll('img');
          if (DO_BLOG.cut_long_posts && imgs.length) {
            
            imgs.forEach( img => {
              
              postImgs.push(img);
              
              if (!img.getAttribute('height') && !img.offsetHeight) {
                img.setAttribute('height',DO_BLOG.img_height);
                img.classList.add('do_blog-height-added');
              }
            
            });
          }

          const checkpoint = node.offsetTop + (3*node.offsetHeight/4);
          
          if (node.offsetParent === bod.offsetParent) {
            
            if (checkpoint - topBod > DO_BLOG.cut_long_posts)
              cutoff = true;
          
          }
          
          else if (node.offsetParent === bod) {
            
            if (checkpoint > DO_BLOG.cut_long_posts)
              cutoff = true;
            
          }
          
          else {
            
            // this shouldn't happen? but jic
            
            const parentTop = node.offsetParent.offsetTop - topBod;
            
            if (checkpoint + parentTop - topBod > DO_BLOG.cut_long_posts)
              cutoff = true;
            
          }
          
          if (cutoff)
            bouncer[1].push(node);
          else
            bouncer[0].push(node);
          
        }
        
        const btn = document.createElement('button');
        btn.classList.add('show-more');
        btn.setAttribute('aria-expanded','false');
        btn.setAttribute('aria-controls', blog.id);
        btn.innerHTML = DO_BLOG.show_more;
        
        btn.onclick = e => {
          const stynow = bod.getAttribute('style');
          
          bod.style.height = bod.offsetHeight + 'px';
          bod.style.setProperty('transition','.5s height');
          bod.style.setProperty('overflow-y','hidden');
          
          bod.append(...bouncer[1]);
          
          btn.setAttribute('aria-expanded','true');
          btn.setAttribute('disabled','');
          
          bod.style.height = bod.scrollHeight + 'px';
          
          setTimeout( e => {
            if (stynow)
              bod.setAttribute('style', stynow);
            else
              bod.removeAttribute('style');
          }, 500);
          
          bod.classList.remove('cut-off');
        };
        
        if (!bouncer[0].length)
          bouncer[0].push(bouncer[1].shift());
        
        if (bouncer[1].length)
          bouncer[0].push(btn);
        
        bod.innerHTML = '';
        bod.append(...bouncer[0]);
        bod.classList.add('cut-off');
        article.classList.add('cut-off');
        
        postImgs.forEach( img => {
          if (img.classList.contains('do_blog-height-added')) {
            img.classList.remove('do_blog-height-added');
            img.removeAttribute('height');
          }
        });
        
      }
      
      
    }
    
  }
  
  // pagination
   if (numberOfPages > 1)
    main.append(newPagination('bottom', numberOfPages, cur, page));
  
}

function getQueries() {
  let href = '';
  for (let k = 0; k < QUERIES.length; k++) {
    const key = QUERIES[k];
    if (URLQueries[key])
      href += '&' + key + '=' + encodeURIComponent(URLQueries[key]);
  }
  return href;
}

function markdownify (m, bem, b, em, img, linktxt, link, code) {
  if (code) {
    return '<code>'+code+'</code>';
  }
  if(link && linktxt !== null) {
    const arr = link.split(/^(?:"|'|`)|(?:"|'|`)$/);
    link = arr[1] || link;
    if (img)
      return `<img src="${link}" alt="${linktxt}">`;
    else
      return `<a href="${link}">${linktxt}</a>`
  }
  if (bem)
    return '<strong><em>'+bem+'</em></strong>';
  if (b)
    return '<strong>'+b+'</strong>';
  if (em)
    return '<em>'+em+'</em>';
}

function newPagination(loc,numberOfPages,cur,page) {
  
  const nav = document.createElement('nav');
  nav.classList.add(loc);
  
  if (loc === 'bottom')
    nav.append(document.createElement('hr'));
  
  if (loc === 'top') {
    const a = document.createElement('a');
    a.classList.add('skip-to-content');
    a.textContent = DO_BLOG.skip_pagination;
    a.href = '#y-' + PAGES[page][0].date.getFullYear();
    nav.append(a,' ');
  }
  
  if (numberOfPages < DO_BLOG.pagination_limit) {
  
    nav.classList.add('pagination','link-navigation');
    nav.setAttribute('aria-label', DO_BLOG.aria_page_of[0] + cur + DO_BLOG.aria_page_of[1] + numberOfPages + '; ' + DO_BLOG.aria_pagination);
  
    for (let i = 0; i < numberOfPages; i++) {
      const a = document.createElement('a');
      URLQueries.page = i + 1;
      a.setAttribute('aria-label',DO_BLOG.aria_goto_page+ (i+1));
      if (URLQueries.page === cur) {
        a.classList.add('current');
        a.setAttribute('aria-current','page');
        a.setAttribute('aria-label',DO_BLOG.aria_current_page + (i+1));
      }
      
      a.href = location.pathname + '?' + getQueries().slice(1) + '#blog-content';
      a.textContent = i + 1;
      nav.append(a, '\n');
    }
  
  } else {
    
    nav.classList.add('pagination','select-navigation');
    nav.setAttribute('aria-label',DO_BLOG.aria_page_of[0] + (page+1) + DO_BLOG.aria_page_of[1] + numberOfPages + '; '+DO_BLOG.aria_pagination);
    
    if (page > 0) {
      const prev = document.createElement('a');
      prev.innerHTML = DO_BLOG.previous_page;
      prev.classList.add('previous-page');
      URLQueries.page = String(cur - 1);
      prev.href = '?' + getQueries() + '#blog-content';
      nav.append(prev,' ');
    }
    
    const label = document.createElement('label');
    const pageSel = document.createElement('select');
    
    for (let i = 0; i < numberOfPages; i++) {
      const op = document.createElement('option');
      op.value = i + 1;
      op.textContent = i + 1;
      if (i === page) {
        op.setAttribute('selected','true');
      }
      pageSel.append(op);
    }
    label.append(DO_BLOG.page_label,pageSel);
    
    pageSel.oninput = (e) => {
      URLQueries.page = e.target.value;
      const a = document.createElement('a');
      a.href = '?' + getQueries() + '#blog-content';
      a.click();
    }
    
    nav.append(label);
    
    if (cur < numberOfPages) {
      const next = document.createElement('a');
      next.textContent = DO_BLOG.next_page;
      next.classList.add('next-page');
      URLQueries.page = String(cur + 1);
      next.href = '?' + getQueries() + '#blog-content';
      nav.append(' ',next);
    }
    
  }
  
  if (loc === 'top')
    nav.append(document.createElement('hr'));

  URLQueries.page = cur;
  
  return nav;
  
}

function getAdjacentPostsPagination(loc, post) {
  const index = POSTS.indexOf(post);
  const nav = document.createElement('nav');
  nav.classList.add('post-navigation',loc,'pagination');
  nav.setAttribute('aria-label',DO_BLOG.aria_pagination)
  
  const [p,n] = [
    POSTS[index + 1],
    POSTS[index - 1]
  ];
 
  if (n) {
    const a = document.createElement('a');
    a.classList.add('next-post');
    a.textContent = DO_BLOG.next_post;
    a.href = location.pathname + '?article=' + n.id + '#blog';
    nav.append(a,' ')
  }
  const sep = document.createElement('span');
  sep.classList.add('separator');
  sep.innerHTML = DO_BLOG.post_nav_separator;
  nav.append(sep);
  if (p) {
    const a = document.createElement('a');
    a.classList.add('previous-post');
    a.textContent = DO_BLOG.previous_post;
    a.href = location.pathname + '?article=' + p.id + '#blog';
    nav.append(' ',a);
  }
  
  return nav;
}

})();