//
// Based on ].
//
// Ucucha has stopped maintaining their version, so this is a fork with some
// fixes and changes.
//

mw.hook('wikipage.content').add(function($content) {
  // first check: do links in Harvard citations point to a valid citation?
  var href;
  var links = $content.find('a');

  links.each(function(i, elem) {
    href = elem.getAttribute('href').substring(1); //skip the # until escaped
    // IDs can contain characters like . that have meaning in selectors
    // use $.escapeSelector to make sure they are escaped
    if ($content.find('#' + $.escapeSelector(href)).length < 1) {
      $(elem).parent().append(
        " <strong class=error>Harv error: link from " + href +
        " doesn't point to any citation.</strong>"
      );
    }
  });

  // second check: do CITEREF IDs have Harvard citations pointing to them?
  var cites = $content.find('.citation');
  for (var i = 0; i < cites.length; i++) {
    var id = cites.getAttribute('id');

    // Do all cites have a linkable ID?
    if (!id || id.indexOf('CITEREF') !== 0) {
      $(
        " <small>This citation has no ID and can't be linked to.</small>"
      ).addClass('error').css({'font-size': 'xx-small'}).appendTo(cites);
      $(cites).addClass('warning').css({'background-color': '#FFF9D2'});
      continue; // No ID so all other checks fail as well.
    }

    // don't do cites that are inside a ref
    var parentid = cites.parentNode.parentNode.getAttribute('id');
    if (parentid && parentid.indexOf('cite_note') === 0)
      continue;
    // check for links to this citation
    var query = 'a';
    if ($content.find(query).length === 0) {
      $(
        ' <small>There is no link pointing to this citation (' + id + ').</small>'
      ).addClass('error').css({'font-size': 'xx-small'}).appendTo(cites);
      $(cites).addClass('warning').css({'background-color': '#FFDFDF'});
    }
  }
});