// get host where this javascript runs
var host = $('script[data-main="content-js"]').attr('src');
host = host.substring(0, host.indexOf("/wps"));
var baseURL = '/wps/wcm/connect/Public+Content/SA+Health+Internet'.toLowerCase();
$.ajaxSetup({
  beforeSend: function (xhr) {
    xhr.setRequestHeader('accept-language', 'EN');
  }
});

/* Category Driven Colours */
defaultColours = [];defaultColours[0] = '285093';
var catColours = [];

catColours['COVID-19 RAT Pick up points'] = '646464';
catColours['COVID-19 RAT Pick up points'] = '646464';

/* NOT (YET) USED/REQUIRED
[*Component name="design/_theme/colours/tax - colours - a - z clinical resources"]
[*Component name="design/_theme/colours/tax - colours - a - z health advisory councils"]
[*Component name="design/_theme/colours/tax - colours - a - z health clinics"]
[*Component name="design/_theme/colours/tax - colours - a - z health topics"]
[*Component name="design/_theme/colours/tax - colours - a - z public health"]
[*Component name="design/_theme/colours/tax - colours - all locations"]
[*Component name="design/_theme/colours/tax - colours - audience"]
[*Component name="design/_theme/colours/tax - colours - foi"]
[*Component name="design/_theme/colours/tax - colours - functional"]
[*Component name="design/_theme/colours/tax - colours - news types"]
[*Component name="design/_theme/colours/tax - colours - organisational structure"]
[*Component name="design/_theme/colours/tax - colours - policies"]
[*Component name="design/_theme/colours/tax - colours - publications resources"]
[*Component name="design/_theme/colours/tax - colours - translated information"]
*/

/* HTML component definitions */
var pgNav = function (o) {
  return '<nav role="navigation" aria-label="pagination">' + o.prev + '<ul>' + o.pging + '</ul>' + o.next + '</nav>\
  <div class="search-result-count pagination">\
    Viewing <span class="results-displaying">' + o.first + ' - ' + o.last + '</span> of <span class="total-results">' + o.total + '</span> results</div></div>';
};
var pgCount = function (o) {
  var terms = '';
  if( o.cat && o.cat != '') {
    var terms = '';
    var cats = o.cat.split('~');
    for(var i in cats) {
      if (cats[i]) {
        if(terms) terms += ' and ';
        terms += "<span class='search-term-wrapper'><span class='search-term-inner'>'" + getCatName(cats[i]) + "'</span></span>";
	  }
    }
	if(terms) terms = ' for ' + terms;
  }
  return '<span class="results-displaying">' + o.first + ' - ' + o.last + '</span> of <span class="total-results">' + o.total + '</span> results' + terms;
};
var pgNoResult = function (o) {
  var terms = '';
  if( o.cat && o.cat != '') {
    var terms = '';
    var cats = o.cat.split('~');
    for(var i in cats) {
      if (cats[i]) {
        if(terms) terms += ' and ';
        terms += "<span class='search-term-wrapper'><span class='search-term-inner'>'" + getCatName(cats[i]) + "'</span></span>";
	  }
    }
	if(terms) terms = ' for ' + terms;
  }
  return '<span class="results-displaying">No results' + terms;
};
var pgPrev = function (o) {
  return '<div class="pagingation-prev-wrapper">\
  <a class="pagination-item pagination-nav previous" aria-label="Goto previous page" href="#" onclick="' + o.fn + '(' + o.pg + ',' + o.ipp + ',this,\'' + (o.sel ? o.sel.replace(/"/g, '&quot;') : '') + '\');return false;">Previous</a></div>'
};
var pgNext = function (o) {
  return '<div class="pagingation-next-wrapper">\
    <a class="pagination-item pagination-nav next" aria-label="Goto next page" href="' + o.pg + '" onclick="' + o.fn + '(' + o.pg + ',' + o.ipp + ',this,\'' + (o.sel ? o.sel.replace(/"/g, '&quot;') : '') + '\');return false;">Next</a></div>';
};
var pgLi = function (o) {
  return '<li><a class="pagination-item" href="#" onclick="' + o.fn + '(' + o.pg + ',' + o.ipp + ',this,\'' + (o.sel ? o.sel.replace(/"/g, '&quot;') : '') + '\');return false;" aria-label="Go to page ' + o.pg + '">' + o.pg + '</a></li>';
};
var pgLiCur = function (o) {
  return '<li><a class="pagination-item" onclick="return false;" aria-current="true" aria-label="Page ' + o.pg + ', Current Page">' + o.pg + '</a></li>';
};
var ell = '<span class="pagination__ellipsis">• • •</span>';

/* Plural START */
function plural(change, revert) {
try {
  var plural = {
    '(quiz)$': "$1zes",
    '^(ox)$': "$1en",
    '([m|l])ouse$': "$1ice",
    '(matr|vert|ind)ix|ex$': "$1ices",
    '(x|ch|ss|sh)$': "$1es",
    '([^aeiouy]|qu)y$': "$1ies",
    '(hive)$': "$1s",
    '(?:([^f])fe|([lr])f)$': "$1$2ves",
    '(shea|lea|loa|thie)f$': "$1ves",
    'sis$': "ses",
    '([ti])um$': "$1a",
    '(tomat|potat|ech|her|vet)o$': "$1oes",
    '(bu)s$': "$1ses",
    '(alias)$': "$1es",
    '(octop)us$': "$1i",
    '(ax|test)is$': "$1es",
    '(us)$': "$1es",
    '([^s]+)$': "$1s"
  };

  var singular = {
    '(quiz)zes$': "$1",
    '(matr)ices$': "$1ix",
    '(vert|ind)ices$': "$1ex",
    '^(ox)en$': "$1",
    '(alias)es$': "$1",
    '(octop|vir)i$': "$1us",
    '(cris|ax|test)es$': "$1is",
    '(shoe)s$': "$1",
    '(o)es$': "$1",
    '(bus)es$': "$1",
    '([m|l])ice$': "$1ouse",
    '(x|ch|ss|sh)es$': "$1",
    '(m)ovies$': "$1ovie",
    '(s)eries$': "$1eries",
    '([^aeiouy]|qu)ies$': "$1y",
    '([lr])ves$': "$1f",
    '(tive)s$': "$1",
    '(hive)s$': "$1",
    '(li|wi|kni)ves$': "$1fe",
    '(shea|loa|lea|thie)ves$': "$1f",
    '(^analy)ses$': "$1sis",
    '((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$': "$1$2sis",
    '([ti])a$': "$1um",
    '(n)ews$': "$1ews",
    '(h|bl)ouses$': "$1ouse",
    '(corpse)s$': "$1",
    '(us)es$': "$1",
    's$': ""
  };

  var irregular = {
    'move': 'moves',
    'foot': 'feet',
    'goose': 'geese',
    'sex': 'sexes',
    'child': 'children',
    'man': 'men',
    'tooth': 'teeth',
    'person': 'people'
  };

  var uncountable = [
    'sheep',
    'fish',
    'deer',
    'moose',
    'series',
    'species',
    'money',
    'rice',
    'information',
    'equipment'
  ];

  // save some time in the case that singular and plural are the same
  if (uncountable.indexOf(change.toLowerCase()) >= 0)
    return change;

  // check for irregular forms
  for (word in irregular) {

    if (revert) {
      var pattern = new RegExp(irregular[word] + '$', 'i');
      var replace = word;
    } else {
      var pattern = new RegExp(word + '$', 'i');
      var replace = irregular[word];
    }
    if (pattern.test(change))
      return change.replace(pattern, replace);
  }

  if (revert) var array = singular;
  else var array = plural;

  // check for matches using regular expressions
  for (reg in array) {

    var pattern = new RegExp(reg, 'i');

    if (pattern.test(change))
      return change.replace(pattern, array[reg]);
  }

  return change;
} catch(e){return '';}
}
/* Plural END */

/* Partial refresh URL Parameter handlers */
function getParam(key) {
  var pStr = (new URLSearchParams(window.location.search)).get(key);
  if (pStr) return pStr;
  else return '';
}

function removeParam(key) {
  var urlParams = new URLSearchParams(window.location.search);
  urlParams.delete(key);
  var pStr = urlParams.toString();
  if (pStr.length > 0) pStr = '?' + pStr;
  window.history.replaceState(null, '', location.pathname + pStr);
}

function setParam(key, value) {
  var urlParams = new URLSearchParams(window.location.search);
  urlParams.set(key, value);
  window.history.replaceState(null, '', '?' + urlParams.toString());
}

function getParamItem(key, index) {
  var pStr = (new URLSearchParams(window.location.search)).get(key);
  var result = '';
  if (pStr) {
    pStr = pStr.split(',');
    if (pStr[index]) result = pStr[index];
  }
  return result;
}

function removeParamItem(key, index) {
  var urlParams = new URLSearchParams(window.location.search);
  var pStr = urlParams.get(key);
  if (pStr) {
    var map = pStr.split(',');
    if (map[index]) delete map[index];
    if (map.some(Boolean))
      urlParams.set(key, map);
    else
      urlParams.delete(key);
  }
  pStr = urlParams.toString();
  if (pStr.length > 0) pStr = '?' + pStr;
  window.history.replaceState(null, '', location.pathname + pStr);
}

function setParamItem(key, index, value) {
  var urlParams = new URLSearchParams(window.location.search);
  var pStr = urlParams.get(key);
  var map = [];
  if (pStr)
    map = pStr.split(',');
  map[index] = value;
  urlParams.set(key, map);
  window.history.replaceState(null, '', '?' + urlParams.toString());
}

function sortSelectOptions(selector, skip_first) {
  var options = (skip_first) ? $(selector + ' option:not(:first)') : $(selector + ' option');
  var arr = options.map(function (_, o) {
    return {
      t: $(o).text(),
      v: o.value,
      s: $(o).prop('selected')
    };
  }).get();
  arr.sort(function (o1, o2) {
    var t1 = o1.t.toLowerCase(),
      t2 = o2.t.toLowerCase();
    return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
  });
  options.each(function (i, o) {
    o.value = arr[i].v;
    $(o).text(arr[i].t);
    if (arr[i].s) {
      $(o).attr('selected', 'selected').prop('selected', true);
    } else {
      $(o).removeAttr('selected');
      $(o).prop('selected', false);
    }
  });
}


/* A-Z Lists */
function toTopAZ(t) {
  var p = $(t).closest('div[role=tabpanel]');
  $(this).blur();
  p.find('.a-z-key-list').focus();
  p.closest('.finder')[0].scrollIntoView({
    behavior: "smooth",
    block: "start"
  });
  return false;
}

function collapseAZ(t) {
  var p = $(t).closest('div[role=tabpanel]');
  p.find('input.filterAZ').val('');
  p.find('.pagination-wrapper, .results-all li, span.result-key').show();
  p.find('.results-block,.results-all').hide();
  p.find('.finder-key').attr('aria-pressed', false);
  var pId = $('.a-z-panel').index(p.closest('.a-z-panel'));
  removeParamItem('az', pId);
  $(this).blur();
  p.find('.a-z-key-list').focus();
  p.closest('.finder')[0].scrollIntoView({
    behavior: "smooth",
    block: "start"
  });
  return false;
}

function pageUI(pg, ipp, t, sel) {
  var wrap = $(t).closest('.pagination-wrapper').prev('.results-list,.panel-content__results-list,.a-z-links');
  if (wrap.length < 1) wrap = $(t).closest('.pagination-wrapper').closest('.results-list,.panel-content__results-list,.a-z-links');
  addUIPaging('pageUI', wrap, sel, ipp, pg);
}

function addUIPaging(fn, p, sel, ipp, cpg, cat) {
  var items = p.children(sel);
  if (items.length == 0) items = p.children('.results-block').children(sel);
  var total = items.length;
  if (!ipp) ipp = parseInt(p.closest('[data-rows]').data('rows')) || 25;
  if (!cpg) cpg = 1;
  var tpg = Math.ceil(total / ipp);
  var pager = {
    'first': ((cpg - 1) * ipp + 1),
    'last': Math.min(cpg * ipp, total),
    'total': total,
    'prev': '',
    'pging': '',
    'next': ''
  };
  if (tpg > 1) {
    if (cpg > 1) pager.prev = [{
      'fn': fn,
      'pg': (cpg - 1),
      'ipp': ipp,
      'sel': sel
    }].map(pgPrev).join('');
    if (cpg < tpg) pager.next = [{
      'fn': fn,
      'pg': (cpg + 1),
      'ipp': ipp,
      'sel': sel
    }].map(pgNext).join('');
    var pages = "";
    var x = 1;
    var show = 2;
    if (cpg == 2 || cpg == (tpg - 1)) show = 3;
    else if (cpg == 1 || cpg == tpg) show = 4;
    if (x == cpg) pages += [{
      'pg': x
    }].map(pgLiCur).join('');
    else pages += [{
      'fn': fn,
      'pg': x,
      'ipp': ipp,
      'sel': sel
    }].map(pgLi).join('');
    var needDots = true;
    for (x = 2; x < tpg; x++) {
      if (x == cpg) {
        pages += [{
          'pg': x
        }].map(pgLiCur).join('');
        needDots = true;
      } else if (Math.abs(x - cpg) < show) {
        pages += [{
          'fn': fn,
          'pg': x,
          'ipp': ipp,
          'sel': sel
        }].map(pgLi).join('');
        needDots = true;
      } else if (needDots) {
        pages += ell;
        needDots = false;
      }
    }
    var x = tpg;
    if (x == cpg) pages += [{
      'pg': x
    }].map(pgLiCur).join('');
    else pages += [{
      'fn': fn,
      'pg': x,
      'ipp': ipp,
      'sel': sel
    }].map(pgLi).join('');
    pager.pging = pages;
  }
  var wrap = p.children('.pagination-wrapper');
  if (wrap.length < 1) wrap = p.next('.pagination-wrapper');
  if (wrap.length < 1 && tpg > 1) {
    /* only create pager if > 1 page */
    var w = $('<div class="pagination-wrapper"></div>');
    p.after(w);
    wrap = p.next('.pagination-wrapper');
  }
  if (wrap && pager.total > 0) wrap.html([pager].map(pgNav).join(''));
  else if (wrap) wrap.html('');
  var ct = p.prev('.media-release-results-header');
  if (ct && ct.find('.search-result-count')) {
    pager.cat = cat ? cat : '';
    if (total > 0)
      ct.find('.search-result-count').html([pager].map(pgCount).join(''));
    else
      ct.find('.search-result-count').html([pager].map(pgNoResult).join(''));
  }
  if (tpg > 1) {
    items.hide();
    items.slice(pager.first - 1, pager.last).show();
  } else
    items.show();
}
var findOne = function (a, b) {
  return b.some(function (c) {
    return a.indexOf(c) >= 0;
  });
};
var findAll = function (a, b) {
  return b.every(function (c) {
    return a.indexOf(c) >= 0;
  });
};

function setUpAZ(_header, _section, _results) {
  var _alphabets = _header.find('button');
  var _filter = _header.find('input.filterAZ');
  if (_alphabets.length < 26) {
    /* ensure alphabet buttons have been loaded */
    setTimeout(function () {
      setUpAZ(_header, _section, _results)
    }, 100);
  } else {
    var _allRows = _results.children('a');
    if (_results.data('cat')) {
      var cats = _results.data('cat').split(',');
      if (_results.data('matchall') === 'true')
        _allRows.filter(function () {
          return !findAll($(this).data('cat').split(','), cats);
        }).remove();
      else
        _allRows = _allRows.filter(function () {
          return !findOne($(this).data('cat').split(','), cats)
        }).remove();
      _allRows = _results.children('a');
    }
    _allRows.each(function () {
      var c = this.text.replace(/[^A-Za-z0-9\s]/g, '').toLowerCase().trim();
      $(this).attr('data-sort', c);
      $(this).attr('data-letter', c[0].replace(/[0-9]/, '0-9'));
    });
    _allRows = $(_allRows.toArray().sort(function (a, b) {
      return ($(a).data('sort') > $(b).data('sort')) ? 1 : -1;
    }));
    _results.append(_allRows);

    _alphabets.each(function () {
      var _letter = $(this).data('search-key');
      $(this).attr('id', 'az-' + _letter);
      if (_letter != 'all') {
        var _letterRows = _allRows.filter(function () {
          return $(this).data('letter') == _letter;
        });
        if (_letterRows.length == 0) {
          $(this).prop('disabled', true);
          _results.append('<div class="results-block results-' + _letter + '" style="display:none"><span class="result-key"><h4>' + _letter.toUpperCase() + '</h4></span><div class="a-z-links no-results"><span>No results found for ' + _letter.toUpperCase() + '.</span></div></div>');
        } else {
          $(this).prop('disabled', false);
          $(this).addClass('hasResults');
          _letterRows.wrapAll('<div class="results-block results-all results-' + _letter + '"><ul class="a-z-links"/></div>');
          _letterRows.parent().before('<span class="result-key"><h4>' + _letter.toUpperCase() + '</h4></span>');
          _letterRows.parent().parent().after('<button class="repeatable back-to-top-button results-all results-' + _letter + '" role="button" tabindex="0" onClick="return toTopAZ(this)"><a onclick="return false" href="#maincontent"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 31.5 31.5" style="enable-background:new 0 0 31.5 31.5;" xml:space="preserve"><path class="st1" d="M21.2,5c-0.4-0.4-1.1-0.4-1.6,0c-0.4,0.4-0.4,1.1,0,1.6l8,8H1.1c-0.6,0-1.1,0.5-1.1,1.1c0,0.6,0.5,1.1,1.1,1.1 h26.6l-8,8c-0.4,0.4-0.4,1.2,0,1.6c0.4,0.4,1.2,0.4,1.6,0l10-10c0.4-0.4,0.4-1.1,0-1.6L21.2,5z"></path></svg><span>Back to top</span></a></button><button tabindex="0" class="icon-button finder-close collapse-az-button repeatable results-all results-' + _letter + '" role="button" onClick="collapseAZ(this)"><svg version="1.1" aria-label="close icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 47.971 47.971" style="enable-background:new 0 0 47.971 47.971;" xml:space="preserve"><g><path d="M28.228,23.986L47.092,5.122c1.172-1.171,1.172-3.071,0-4.242c-1.172-1.172-3.07-1.172-4.242,0L23.986,19.744L5.121,0.88 c-1.172-1.172-3.07-1.172-4.242,0c-1.172,1.171-1.172,3.071,0,4.242l18.865,18.864L0.879,42.85c-1.172,1.171-1.172,3.071,0,4.242 C1.465,47.677,2.233,47.97,3,47.97s1.535-0.293,2.121-0.879l18.865-18.864L42.85,47.091c0.586,0.586,1.354,0.879,2.121,0.879 s1.535-0.293,2.121-0.879c1.172-1.171,1.172-3.071,0-4.242L28.228,23.986z"></path></g></svg></button>');
        }
      } else {
        $(this).addClass('hasResults');
      }
    });
    _allRows.wrap('<li/>');

    _section.find('.results-list.a-z-category .a-z-links').each(function () {
      addUIPaging('pageUI', $(this), 'li');
    });

    _alphabets.click(function () {
      var _text = $(this).attr('data-search-key');
      var _section = $(this).closest('.a-z-panel');
      var pId = $('.a-z-panel').index(_section[0]);
      setParamItem('az', pId, 'az-' + _text);
      _section.find('input.filterAZ').val('');
      _section.find('.pagination-wrapper, .results-all li, span.result-key').show();
      if (_text == 'all') {
        _section.find('div.results-list .results-all').show().find('a').first().focus();
      } else {
        _section.find('div.results-list.a-z-category').children().hide();
        _section.find('div.results-list .results-' + _text).show().find('a').first().focus();
      }
    });

    _filter.on('input propertychange', function () {
      var _text = this.value;
      var _section = $(this).closest('.a-z-panel');
      _section.find('.finder-key').attr('aria-pressed', false);
      _section.find('.pagination-wrapper, .results-all, span.result-key').hide();
      _section.find('div.results-list .results-block.results-all').show();
      _section.find('div.results-list .results-block.results-all li').hide().filter(function () {
        var reg = new RegExp(_text, 'i');
        return reg.test($(this).children('a').text());
      }).show();
    });

    /* Set up initial display */
    _header.prepend('<button tabindex="0" class="icon-button finder-close collapse-az-button repeatable" style="padding-top:0" role="button" onClick="collapseAZ(this)"><svg version="1.1" aria-label="close icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 47.971 47.971" style="enable-background:new 0 0 47.971 47.971;" xml:space="preserve"><g><path d="M28.228,23.986L47.092,5.122c1.172-1.171,1.172-3.071,0-4.242c-1.172-1.172-3.07-1.172-4.242,0L23.986,19.744L5.121,0.88 c-1.172-1.172-3.07-1.172-4.242,0c-1.172,1.171-1.172,3.071,0,4.242l18.865,18.864L0.879,42.85c-1.172,1.171-1.172,3.071,0,4.242 C1.465,47.677,2.233,47.97,3,47.97s1.535-0.293,2.121-0.879l18.865-18.864L42.85,47.091c0.586,0.586,1.354,0.879,2.121,0.879 s1.535-0.293,2.121-0.879c1.172-1.171,1.172-3.071,0-4.242L28.228,23.986z"></path></g></svg></button>');
    _section.find('div.results-list.a-z-category').children().hide();
    var _letter = null;
    var pId = $('.a-z-panel').index(_section[0]);
    if (getParamItem('az', pId)) {

      _letter = _section.find('#' + getParamItem('az', pId));
    } else if (_section.find('.a-z-key-list button[aria-pressed="true"]').length > 0) {
      _letter = _section.find('.a-z-key-list button[aria-pressed="true"]').first();
    }
    if (_letter) {
      _letter.attr('aria-pressed', true);
      var _text = _letter.data('search-key');
      if (_text == 'all') {
        _section.find('div.results-list .results-all').show();
      } else {
        _section.find('div.results-list.a-z-category').children().hide();
        _section.find('div.results-list .results-' + _text).show();
      }
    }
    _section.find('div.results-list.a-z-category').show();
  }
}

/* Media Release START */
function getCatName(catPath) {
  var catOpt = $('.media-releases select.category [value="' + catPath + '"]');
  if (catOpt.length > 0)
    return catOpt[0].label;
  return catPath.substring(('/' + catPath).lastIndexOf('/'));
}

function pageMediaUI(pg, ipp, t) {
  var wrap = $(t).closest('.media-releases');
  var res = wrap.children('.results-list');
  var pId = $('.media-releases').index(wrap[0]);
  var catTxt = getParamItem('mr-cat', pId);
  var cats = catTxt .split('~');
  var filter = 'article';
  for (var i in cats) {
    if (cats[i]) {
      filter += '[data-cat*="' + cats[i] + '"]';
    }
  }
  res.children('article').hide();
  if (res.data('days')) {
    var sd = new Date(new Date() - res.data('days')*1000*60*60*24);
    res.children('article').filter(function() {
      return (new Date($(this).data('date')) < sd);
    }).remove();
  }
  setParamItem('mr-pg', pId, pg);
  addUIPaging('pageMediaUI', res, filter, ipp, pg, catTxt);
}

function filterResults(catSel) {
  var wrap = $(catSel).closest('.media-releases');
  var cats = [];
  wrap.find('select.category').each(function () {
    cats.push(this.value)
  });
  var res = wrap.children('.results-list');
  var ipp = 10;
  if (res.data('rows')) ipp = res.data('rows');
  var pId = $('.media-releases').index(wrap[0]);
  setParamItem('mr-cat', pId, cats.join('~'));
  pageMediaUI(1, ipp, catSel);
}

function sortResults(sortSel) {
  var wrap = $(sortSel).closest('.media-releases');
  var res = wrap.children('.results-list');
  var ipp = 10;
  if (res.data('rows')) ipp = res.data('rows');
  var sort = sortSel.value.split('-');
  var x = 1;
  if (sort[1] && sort[1] == 'desc') x = -1;
  res.append(res.children('article').sort(function (a, b) {
      return $(a).data(sort[0]).toLowerCase().trim() > $(b).data(sort[0]).toLowerCase().trim() ? x : -x
  }));
  var pId = $('.media-releases').index(wrap[0]);
  setParamItem('mr-sort', pId, sortSel.value);
  pageMediaUI(1, ipp, sortSel);
}
/* Media Release END */

/* Finder START */
function closeFinder(t) {
  var s = $(t).closest('section.finder');
  s.find('button[role=tab]').attr('aria-selected', false);
  s.find('div[role=tabpanel]').attr('hidden', true);
}

function finderGetDetails(t) {
  var p = $(t).closest('div[role=tabpanel]');
  var det = {
    'title': p.closest('.tabs').children('div[role=tablist]').children('#' + (p.attr('aria-labelledby'))).text().trim()
  };
  det.name = det.title.replace(/[^A-Za-z]/g, '').toLowerCase();
  det.namepg = det.name + '-pg';
  det.elCat = p.find('.panel-content.categories');
  det.elRes = p.find('.panel-content.results');
  if (det.elRes.length < 1) {
    p.append('<div class="panel-content results"></div>');
    det.elRes = p.find('.panel-content.results');
  }
  return det;
}

function finderBackToCats(t) {
  var det = finderGetDetails(t);
  var focus = getParam(det.name);
  removeParam(det.name);
  removeParam(det.namepg);
  det.elRes.hide();
  det.elCat.show();
  det.elCat.find('[data-name="' + focus + '"]').focus();
}

function finderGetResults(t, cat) {
  var det = finderGetDetails(t);
  if (det.elCat.length > 0) setParam(det.name, cat);
  removeParam(det.namepg);
  finderRenderResults(det);
  return false;
}

function finderAddPaging(det) {
  var pgnav = det.elRes.find(".pagination-wrapper nav");
  if (pgnav.length == 1) {
    var cpg = parseInt(pgnav.children('.currentPage').text());
    var tpg = parseInt(pgnav.children('.totalPages').text());
    var ipp = parseInt(pgnav.children('.itemsPerPage').text());
    var pages = "";
    if (tpg > 1) {
      if (cpg > 1) pages += [{
        'fn': 'finderGetPage',
        'pg': (cpg - 1),
        'ipp': ipp
      }].map(pgPrev).join('');
      pages += '<ul>';
      var x = 1;
      var show = 2;
      if (cpg == 2 || cpg == (tpg - 1)) show = 3;
      else if (cpg == 1 || cpg == (tpg)) show = 4;

      if (x == cpg) pages += [{
        'pg': x
      }].map(pgLiCur).join('');
      else pages += [{
        'fn': 'finderGetPage',
        'pg': x,
        'ipp': ipp
      }].map(pgLi).join('');
      var needDots = true;
      for (x = 2; x < tpg; x++) {
        if (x == cpg) {
          pages += [{
            'pg': x
          }].map(pgLiCur).join('');
          needDots = true;
        } else if (Math.abs(x - cpg) < show) {
          pages += [{
            'fn': 'finderGetPage',
            'pg': x,
            'ipp': ipp
          }].map(pgLi).join('');
          needDots = true;
        } else if (needDots) {
          pages += ell;
          needDots = false;
        }
      }
      var x = tpg;
      if (x == cpg) pages += [{
        'pg': x
      }].map(pgLiCur).join('');
      else pages += [{
        'fn': 'finderGetPage',
        'pg': x,
        'ipp': ipp
      }].map(pgLi).join('');
      pages += '</ul>';
      if (cpg < tpg) pages += [{
        'fn': 'finderGetPage',
        'pg': (cpg + 1),
        'ipp': ipp
      }].map(pgNext).join('');
    }
    pgnav.html(pages);
  }
  UpdateLinks(det.elRes);
}

function finderShowResults(det) {
  det.elCat.hide();
  finderAddPaging(det);
  det.elRes.show();
  det.elRes.find('.selected-filter').focus();
}

function finderRenderResults(det) {
  var cat = getParam(det.name);
  if (!cat) cat = det.elRes.data('cat');
  if (cat) {
    var title = det.elCat.find('[data-name="' + cat + '"]').text();
    if (!title) title = cat;
    var par = 'source=library&srv=cmpnt';
    var id = det.elCat.children('ul').data('menuid');
    if (!id) id = det.elRes.data('menuid');
    if (id) par += '&cmpntid='+id.trim();
    var it = det.elCat.children('ul').data('itemtitle');
    if(!it) it = det.elRes.data('itemtitle');
    if (it) par += '&itemtitle='+(it.trim());
    var ic = det.elCat.children('ul').data('labelcat');
    if(!ic) ic = det.elRes.data('labelcat');
    if (ic) par += '&labelcat='+encodeURIComponent(ic.trim());
    var urlParams = new URLSearchParams(par);
    urlParams.set('cat', cat);
    urlParams.set('title', title);
    urlParams.set('type', det.title);
    var pg = getParam(det.namepg);
    if (pg) urlParams.set('WCM_Page.' + id, pg);
    det.elRes.load(baseURL + '?' + urlParams.toString(), function () {
      finderShowResults(det);
    });
  } else {
    det.elRes.hide();
    det.elCat.show();
    det.elCat.parent().focus();
  }
}

function finderGetPage(page, ipp, t) {
  var det = finderGetDetails(t);
  setParam(det.namepg, page);
  finderRenderResults(det);
}
/* Finder END */

/* Partial refresh paging */
function addPaging(fnName, parentSelector) {
  if ($(parentSelector + " .pagination-wrapper").length == 1) {
    var c = parseInt($(parentSelector + " .pagination-wrapper .currentPage").text());
    var t = parseInt($(parentSelector + " .pagination-wrapper .totalPages").text());
    var i = parseInt($(parentSelector + " .pagination-wrapper .itemsPerPage").text());
    var pages = "";
    if (t > 1) {
      if (c > 1) pages += '<div class="pagingation-prev-wrapper"><a class="pagination-item pagination-nav previous" aria-label="Go to page ' + (c - 1) + '" href="#" onclick="' + fnName + '(' + (c - 1) + ');return false;">Previous</a></div>';
      pages += '<ul>';
      var x = 1;
      var show = 2;
      if (c == 2 || c == (t - 1)) show = 3;
      else if (c == 1 || c == (t)) show = 4;

      if (x == c) pages += '<li><a class="pagination-item" aria-current="true" aria-label="Page ' + x + ', Current Page">' + x + '</a></li>';
      else pages += '<li><a class="pagination-item" href="#" onclick="' + fnName + '(' + x + ');return false;" aria-label="Go to page ' + x + '">' + x + '</a></li>';
      var needDots = true;
      for (x = 2; x < t; x++) {
        if (x == c) {
          pages += '<li><a class="pagination-item" aria-current="true" aria-label="Page ' + x + ', Current Page">' + x + '</a></li>';
          needDots = true;
        } else if (Math.abs(x - c) < show) {
          pages += '<li><a class="pagination-item" href="#" onclick="' + fnName + '(' + x + ');return false;" aria-label="Go to page ' + x + '">' + x + '</a></li>';
          needDots = true;
        } else if (needDots) {
          pages += ell;
          needDots = false;
        }
      }
      var x = t;
      if (x == c) pages += '<li><a class="pagination-item" aria-current="true" aria-label="Page ' + x + ', Current Page">' + x + '</a></li>';
      else pages += '<li><a class="pagination-item" href="#" onclick="' + fnName + '(' + x + ');return false;" aria-label="Go to page ' + x + '">' + x + '</a></li>';
      pages += '</ul>';

      if (c < t) pages += '<div class="pagingation-next-wrapper"><a class="pagination-item pagination-nav next" aria-label="Go to page ' + (c + 1) + '" href="#" onclick="' + fnName + '(' + (c + 1) + ');return false;">Next</a></div>';
    }
    $(parentSelector + " .pagination-wrapper nav").html(pages);
  }
}

/* Adds hover text to new window and external links */
function UpdateLinks(parent) {
  parent.find('.pills').each(function(){
    var li = $(this);
    var pills = li.data('pill').split(',');
    var cats = li.data('cat').split(',');
    cats.sort();
    var spans = "";
    li.children('.label-cat').remove();
    cats.forEach(function(cat) {
      pills.forEach(function(pill) {
        if(cat.startsWith(pill) && cat.includes("CPC")) {
          var span = cat;
          span = span.replace(pill+"/","");
          span = span.replace("CPC - ","")+"/";
          span = span.split("/")[0];
          spans+="<span class='label-cat'>"+span+"</span>";
        }
      });
    });
    li.append(spans);
  });

  /* force wcm links lowercase */
  parent.find('a[href^="/wps/wcm/"]').each(function (i, e) {
    var url = $(e).attr('href');
    var q = '';
    if (url.indexOf('?') > -1) {
      q = url.substr(url.indexOf('?'));
      url = url.substr(0, url.indexOf('?'));
    }
    e.href = (url.toLowerCase() + q).replace(/ /g, '+').replace(/\/$/, '').replace('/?', '?');
    $(e).attr('target', ''); /* force all internal links to same tab */
  });

  /* Old code to open in new window
  parent.find('a[target="_blank"]').attr('title', 'Link opens in a new window.');
  parent.find('a[href^="http"]').attr('target', '_blank').attr('title', 'Link to external site, opens in a new window.').addClass('external-link');*/
  /* New code to open in same */
  parent.find('a[target="_blank"]').attr('target', ''); /* open ALL links in same window */
  parent.find('a[href^="http"]').attr('title', 'Link to external site.').addClass('external-link');
}

/* Autocomplete START */
var autoListTimeout = null,
  autoShowTimeout = null;

/* Autocomplete END */

/* Google Maps */
var customStyle = [{
  featureType: "water",
  elementType: "geometry",
  stylers: [{
    color: "#e9e9e9"
  }, {
    lightness: 17
  }]
}, {
  featureType: "landscape",
  elementType: "geometry",
  stylers: [{
    color: "#f5f5f5"
  }, {
    lightness: 20
  }]
}, {
  featureType: "road.highway",
  elementType: "geometry.fill",
  stylers: [{
    color: "#ffffff"
  }, {
    lightness: 17
  }]
}, {
  featureType: "road.highway",
  elementType: "geometry.stroke",
  stylers: [{
    color: "#ffffff"
  }, {
    lightness: 29
  }, {
    weight: .2
  }]
}, {
  featureType: "road.arterial",
  elementType: "geometry",
  stylers: [{
    color: "#ffffff"
  }, {
    lightness: 18
  }]
}, {
  featureType: "road.local",
  elementType: "geometry",
  stylers: [{
    color: "#ffffff"
  }, {
    lightness: 16
  }]
}, {
  featureType: "poi",
  elementType: "geometry",
  stylers: [{
    color: "#f5f5f5"
  }, {
    lightness: 21
  }]
}, {
  featureType: "poi.park",
  elementType: "geometry",
  stylers: [{
    color: "#dedede"
  }, {
    lightness: 21
  }]
}, {
  elementType: "labels.text.stroke",
  stylers: [{
    visibility: "on"
  }, {
    color: "#ffffff"
  }, {
    lightness: 16
  }]
}, {
  elementType: "labels.text.fill",
  stylers: [{
    saturation: 36
  }, {
    color: "#333333"
  }, {
    lightness: 40
  }]
}, {
  elementType: "labels.icon",
  stylers: [{
    visibility: "off"
  }]
}, {
  featureType: "transit",
  elementType: "geometry",
  stylers: [{
    color: "#f2f2f2"
  }, {
    lightness: 19
  }]
}, {
  featureType: "administrative",
  elementType: "geometry.fill",
  stylers: [{
    color: "#fefefe"
  }, {
    lightness: 20
  }]
}, {
  featureType: "administrative",
  elementType: "geometry.stroke",
  stylers: [{
    color: "#fefefe"
  }, {
    lightness: 17
  }, {
    weight: 1.2
  }]
}];
var customActiveStyle = [{
  elementType: "labels.icon",
  stylers: [{
    visibility: "off"
  }]
}];

function getOptions(lat, lng) {
  return {
    zoom: 16,
    zoomControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    fullscreenControls: true,
    streetViewControl: false,
    mapTypeControl: false,
    center: new google.maps.LatLng(lat, lng),
    styles: customStyle
  }
}
var geocoder;
var map;
var markers = [];

function initMaps() {
  var allMapPlaceholders = document.querySelectorAll('.map-wrapper');

  function createMap(mapPlaceholder) {
    var mapData = JSON.parse(mapPlaceholder.getAttribute('data-map').replace(/[\r\n]/g, '').replace(/},]/g, '}]').replace(/:--/g, ':-'));
    if(mapData && mapData.length > 0) {
      setUpList(mapData);
      var options = getOptions(+mapData[0].lat, +mapData[0].long);
      map = new google.maps.Map(mapPlaceholder, options);
      for (var i = 0; i < mapData.length; i++) {
        addMapData(map, mapData[i]);
      }
    }
  }

  for (var i = 0; i < allMapPlaceholders.length; i++) {
    createMap(allMapPlaceholders[i]);
  }

  function addMapData(mapElement, element) {
    var contentString = '<div class="map-popup">';
    contentString += '<div class="contact-detail"><a href="' + element.link + '"><h4>' + element.name + '</h4></a></div>';
    contentString += '<div class="contact-detail"><a href="https://www.google.com.au/maps?q=' + element.lat + ',' + element.long + '" >' + element.address + '</a></div>';
    if (element.phone) {
      contentString += '<div class="contact-detail">Phone: ';
      contentString += '<a href="tel:' + element.phone + '">' + element.phone + '</a>';
      contentString += '</div>';
    }
    if (element.referral)
      contentString += '  <div class="chip-container"><span class="chip">' + element.referral + '</span></div>';
    if (element.email)
      contentString += '<div class="contact-detail">Email: <a href="mailto:' + element.email + '" >' + element.email + '</a></div>';
    if (element.fax)
      contentString += '<div class="contact-detail">Fax: <a href="fax:' + element.fax + '">' + element.fax + '</a></div>';

    contentString += '</div></div>';

    var infowindow = new google.maps.InfoWindow({
      content: contentString
    });

    var o_latlng = new google.maps.LatLng(element.lat, element.long);

    var svgCol = svg;

    if (element.categories) {
      var cats = element.categories.split("~");
      for(var ci = 0; ci < cats.length; ci++)
        if( catColours[cats[ci]] ) {
          element.primary = catColours[cats[ci]];
          element.onprimary = 'FFFFFF';
          ci=cats.length;
        }
    }

    if (element.primary)
      svgCol = '<svg version="1.1" width="40" height="40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 434.2 434.2" style="enable-background:new 0 0 434.2 434.2;" xml:space="preserve"><style type="text/css">.map-pin{fill:#' + (element.onprimary ? element.onprimary : 'FFFFFF') + ';}</style><g><path style="fill:#' + (element.primary ? element.primary : '3A75D3') + ';" d="M217.1,0C125.2,0,50.5,74.7,50.5,166.6c0,38.9,13.4,74.8,35.9,103.2l130.7,164.4l130.7-164.4 c22.5-28.4,35.9-64.2,35.9-103.2C383.7,74.7,309,0,217.1,0z M217.1,239.4c-41.4,0-75-33.6-75-75s33.6-75,75-75s75,33.6,75,75 S258.4,239.4,217.1,239.4z"/><circle class="map-pin" cx="217.1" cy="164.4" r="75.5"/></g></svg>';

    var marker = new google.maps.Marker({
      position: o_latlng,
      map: mapElement,
      title: element.name,
      icon: {
        url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svgCol),
        scaledSize: new google.maps.Size(40, 40)
      },
      closeBoxMargin: "10px 20px 2px 2px"
    });

    google.maps.event.addListener(marker, 'click', function () {
      infowindow.open(mapElement, marker);
      changeMapToDefaultStyles(mapElement);
    });
    markers.push(marker);

    setMapListeners(['click', 'dragstart'], mapElement);

  }
  var mapChangedOptions = myOptions = {
    zoomControl: true,
    gestureHandling: 'greedy',
    fullscreenControls: true,
    streetViewControl: false,
    mapTypeControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    styles: customActiveStyle
  }

  function setMapListeners(eventTypes, mapToListenTo) {
    var mapIsShowingDefaultStyles = false;
    var i;
    for (i = 0; i < eventTypes.length; i++) {
      if (!mapIsShowingDefaultStyles) {
        google.maps.event.addListener(mapToListenTo, eventTypes[i], function (e) {
          changeMapToDefaultStyles(this);
        });
      } else {
        return;
      }
    }
  }

  function changeMapToDefaultStyles(mapToChangeStyles) {
    mapToChangeStyles.setOptions(mapChangedOptions);
    mapIsShowingDefaultStyles = true;
  }
}

var mapIsActive = false;

function codeAddress(autocompleteAddress) {
  if (!mapIsActive) {
    mapIsActive = true;
  }
  var address = document.getElementById("location-search").value;
  if (autocompleteAddress) {
    toggleMapIsActive(address, true);
    map.setCenter(autocompleteAddress.geometry.location);
    var canSee = false;
    var zoom = 14;
    setTimeout(function () {
      map.setZoom(zoom);
      while (!canSee && zoom > 7) {
        markers.forEach(function (a) {
          canSee = canSee || map.getBounds().contains(a.position)
        });
        zoom -= 1;
        map.setZoom(zoom);
      }
    }, 500);
  } else {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'address': address,
      componentRestrictions: {
        country: 'AU',
        administrativeArea: 'SA'
      }
    }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        toggleMapIsActive(address, true);
        map.setCenter(results[0].geometry.location);
        var canSee = false;
        var zoom = 14;
        setTimeout(function () {
          map.setZoom(zoom);
          while (!canSee && zoom > 7) {
            markers.forEach(function (a) {
              canSee = canSee || map.getBounds().contains(a.position)
            });
            zoom -= 1;
            map.setZoom(zoom);
          }
        }, 500);
      } else {
        toggleMapIsActive(true, false);
        alert("Please use a valid address in South Australia.");
      }
    });
  }
}

function toggleMapIsActive(query, queryIsValid) {
  var mapPanel = $('#map-results-panel');
  var currentQueryText = $('#current-map-query');
  var mapSearchForm = $('#finder-search-button').parents('.find-site-panel');

  if (queryIsValid) {
    mapSearchForm.hide();
    mapPanel.show();
    currentQueryText.text(query);
  } else {
    mapSearchForm.show();
    mapPanel.hide();
    currentQueryText.text(query);
  }
}

function setUpList(mapData) {
  var mapList = document.getElementById("maps-site-list");
  if (mapList) {
    $(mapList).prepend('<button tabindex="0" class="icon-button finder-close" onClick="closeFinder(this)" data-active="true"><svg version="1.1" aria-label="close icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 47.971 47.971" style="enable-background:new 0 0 47.971 47.971;" xml:space="preserve"><g><path d="M28.228,23.986L47.092,5.122c1.172-1.171,1.172-3.071,0-4.242c-1.172-1.172-3.07-1.172-4.242,0L23.986,19.744L5.121,0.88 c-1.172-1.172-3.07-1.172-4.242,0c-1.172,1.171-1.172,3.071,0,4.242l18.865,18.864L0.879,42.85c-1.172,1.171-1.172,3.071,0,4.242 C1.465,47.677,2.233,47.97,3,47.97s1.535-0.293,2.121-0.879l18.865-18.864L42.85,47.091c0.586,0.586,1.354,0.879,2.121,0.879 s1.535-0.293,2.121-0.879c1.172-1.171,1.172-3.071,0-4.242L28.228,23.986z"></path></g></svg></button>');
    addUIPaging('pageUI', $(mapList).find('.panel-content__results-list'), 'li');
  }
}

function changeSiteListActive(x) {
  var tabs = $('[role="tab"]');
  var panels = $('[role="tabpanel"]');
  tabs.each(function (i, element) {
    element.setAttribute('tabindex', '-1');
    element.setAttribute('aria-selected', 'false');
  })
  panels.each(function (i, element) {
    element.setAttribute('hidden', 'true');
  })
  panels[x].removeAttribute('hidden');
  tabs[x].setAttribute('tabindex', '0');
  tabs[x].setAttribute('aria-selected', 'true');
  $(tabs[x]).closest('.finder')[0].scrollIntoView();
}

function distance(lat1, lon1, lat2, lon2) {
  if ((lat1 == lat2) && (lon1 == lon2)) {
    return 0;
  } else {
    var radlat1 = Math.PI * lat1 / 180;
    var radlat2 = Math.PI * lat2 / 180;
    var theta = lon1 - lon2;
    var radtheta = Math.PI * theta / 180;
    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    if (dist > 1) {
      dist = 1;
    }
    dist = Math.acos(dist);
    dist = dist * 180 / Math.PI;
    dist = dist * 60 * 1.1515 * 1.609344;
    return dist;
  }
}
var serviceResultHeader = function (o) {
  return '<h3>Displaying all results' + (o.cat ? " for selected service <span class='query'>'" + o.cat + "'" : "") + '</span>&nbsp;near&nbsp;<span class="query">\'' + o.loc + '\'</span></h3>';
};
var serviceNoResultHeader = function (o) {
  return '<h3>' + (o.msg ? o.msg : "No results found" + (o.cat ? " for selected service <span class='query'>'" + o.cat + "'" : "") + "</span>&nbsp;near&nbsp;<span class='query'>'" + o.loc + "'</span>") + '</h3>';
};

function filterServicePostcode() {
  var loc = $("#postcode").val();
  var lat = parseFloat(getParam('lat'));
  var lng = parseFloat(getParam('lng'));
  var cat = $("#selectServiceFinder").val();
  var catTxt = $("#selectServiceFinder option:selected").text();
  setParam('s_loc', loc);
  setParam('s_cat', cat);
  var res = $('.panel-content--location-search .panel-content__results-list');
  var pg = $('.panel-content--location-search .pagination-wrapper');
  var all = res.children('li');
  res.hide();
  pg.hide();
  all.hide();
  all.attr('aria-show', 'false');

  var filtered = all.filter(function () {
    return !(cat && $(this).data('cat').indexOf("~" + cat + "~") < 0)
  });
  if (!loc) {
    $('.panel-content--location-search .panel-content__results-header').html([{
      'cat': '',
      'loc': '',
      'msg': 'Please provide a location'
    }].map(serviceNoResultHeader).join(''));
    res.closest('[role="tabpanel"]').focus();
  } else if (filtered.length < 1) {
    $('.panel-content--location-search .panel-content__results-header').html([{
      'cat': (catTxt),
      'loc': loc,
      'msg': ''
    }].map(serviceNoResultHeader).join(''));
    res.closest('[role="tabpanel"]').focus();
  } else if (lat && lng) {
    filtered.each(function (i, a) {
      $(a).attr('aria-show', 'true');
      var dist = distance(lat, lng, $(a).data('lat'), $(a).data('lng'));
      if ($(a).data('important') == 'True') $(a).attr('data-dist', '-1');
      else {
        $(a).attr('data-dist', dist);
        var distStr = '';
        if (dist < 1) distStr = (Math.round(dist * 1000)).toFixed(0) + ' m';
        else if (dist < 10) distStr = (Math.round(dist * 10.0) / 10).toFixed(1) + ' km';
        else distStr = Math.round(dist).toFixed(0) + ' km';
        var p = $(a).find('.service-item__address');
        p.children('strong').remove();
        p.append('<strong>' + distStr + '</strong>');
      }
    });

    $('.panel-content--location-search .panel-content__results-header').html([{
      'cat': (catTxt),
      'loc': loc
    }].map(serviceResultHeader).join(''));
    $('.panel-content--location-search .panel-content__results-list').prepend($('.panel-content--location-search .panel-content__results-list li[aria-show=true]').sort(function (a, b) {
      if (a.getAttribute('data-dist') < 0 && b.getAttribute('data-dist') < 0)
        return (($(a).find('h3').text().trim().toLowerCase()) > ($(b).find('h3').text().trim().toLowerCase())) ? 1 : -1;
      else return a.getAttribute('data-dist') - b.getAttribute('data-dist')
    }));
    addUIPaging('pageUI', $('.panel-content--location-search .panel-content__results-list'), 'li[aria-show=true]', 10);
    res.show();
    pg.show();
    res.closest('[role="tabpanel"]').focus();
  } else {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'address': loc,
      componentRestrictions: {
        country: 'AU',
        administrativeArea: 'SA'
      }
    }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        loc = results[0].formatted_address;
        lat = results[0].geometry.location.lat();
        lng = results[0].geometry.location.lng();
        setParam('s_loc', loc);
        setParam('lat', lat);
        setParam('lng', lng);
        filtered.each(function (i, a) {
          $(a).attr('aria-show', 'true');
          var dist = distance(lat, lng, $(a).data('lat'), $(a).data('lng'));
          if ($(a).data('important') == 'True') $(a).attr('data-dist', '-1');
          else {
            $(a).attr('data-dist', dist);
            var distStr = '';
            if (dist < 1) distStr = (Math.round(dist * 1000)).toFixed(0) + ' m';
            else if (dist < 10) distStr = (Math.round(dist * 10.0) / 10).toFixed(1) + ' km';
            else distStr = Math.round(dist).toFixed(0) + ' km';
            var p = $(a).find('.service-item__address');
            p.children('strong').remove();
            p.append('<strong>' + distStr + '</strong>');
          }
        });

        $('.panel-content--location-search .panel-content__results-header').html([{
          'cat': (catTxt),
          'loc': loc
        }].map(serviceResultHeader).join(''));
        $('.panel-content--location-search .panel-content__results-list').prepend($('.panel-content--location-search .panel-content__results-list li[aria-show=true]').sort(function (a, b) {
          if (a.getAttribute('data-dist') < 0 && b.getAttribute('data-dist') < 0)
            return (($(a).find('h3').text().trim().toLowerCase()) > ($(b).find('h3').text().trim().toLowerCase())) ? 1 : -1;
          else return a.getAttribute('data-dist') - b.getAttribute('data-dist')
        }));
        addUIPaging('pageUI', $('.panel-content--location-search .panel-content__results-list'), 'li[aria-show=true]', 10);
        res.show();
        pg.show();
        res.closest('[role="tabpanel"]').focus();
      } else {
        $('.panel-content--location-search .panel-content__results-header').html([{
          'cat': '',
          'loc': loc,
          'msg': 'Could not find that location, please try again'
        }].map(serviceNoResultHeader).join(''));
        res.closest('[role="tabpanel"]').focus();
      }
    });
  }
}

/* called after google maps API loads */
function setupMaps() {
  var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-38.5, 129),
    new google.maps.LatLng(-25.9, 141));
  var options = {
    bounds: defaultBounds,
    fields: ["formatted_address", "geometry", "name"],
    strictBounds: true
  };

  initMaps();

  if (document.getElementById('postcode')) {
    var searchInput = document.getElementById('postcode');
    searchInput.onkeydown = (function (event) {
      if (event.keyCode == 13) {
        event.preventDefault();
        filterServicePostcode();
        return false;
      }
    });
    var autocomplete = new google.maps.places.Autocomplete(searchInput, options);
    autocomplete.addListener('place_changed', function () {
      var place = autocomplete.getPlace();
      if (place && place.geometry) {
        setParam('lat', place.geometry.location.lat());
        setParam('lng', place.geometry.location.lng());
        filterServicePostcode();
      }
    });
  }

  if (document.getElementById('location-search')) {
    var searchInput = document.getElementById('location-search');
    searchInput.onkeydown = (function (event) {
      if (event.keyCode == 13) {
        event.preventDefault();
        codeAddress();
        return false;
      }
    });
    var autocomplete = new google.maps.places.Autocomplete(searchInput, options);
    autocomplete.addListener('place_changed', function () {
      var place = autocomplete.getPlace();
      codeAddress(place);
    });
  }
}

/* iFrame manager */
var iframeid = 0;
$('iframe').on('load', function (a, b) {
  try {
    /* resize when iframe content size changes */
    setTimeout(function () {
      var iframeWin = this.contentWindow || (this.contentDocument ? this.contentDocument.parentWindow : null);
      if (iframeWin && iframeWin.document.body.scrollHeight > 0)
        $(this).height(iframeWin.document.body.scrollHeight + 'px');
      if (iframeWin) {
        $(iframeWin).on('resize', function () {
          if (this.document.body.scrollHeight > 0)
            $(this.frameElement).height(this.document.body.scrollHeight + 'px');
        });
      }
    }, 100);
  } catch (e) {
    if (!this.id) {
      this.id = "iframe" + iframeid;
      iframeid++;
    }
    iFrameResize({
      /* allow for external iFrames, iframe must load iframeResizer.contentWindow.min.js */
      inPagteLinks: true,
      heightCalculationMethod: 'bodyScroll'
    }, this.id);
  }
});
$(window).on('resize', function () {
  $('iframe').each(function () {
    /* resize when main window size changes */
    var iframeWin = this.contentWindow || this.contentDocument.parentWindow;
    try {
      $(this).height(iframeWin.document.body.scrollHeight + 'px');
    } catch (e) {}
  });
});

/* RECITEME START */
var setupReciteButtons = true;
var serviceUrl = "//au-api.reciteme.com/asset/js?key=";
var serviceKey = "536b754b293d9834d9d7301d88154bca6608c543";
//OLD  var serviceKey = "000df56317caba8bf563c50a02cb51b62ca8957b";
var rmopts = {
  showBrand: false,
  Controls: {
    Core: {
      zoomThreshold: 100
    }
  },
  Tracker: {
    Ga: {
      enabled: true
    }
  }
};
var autoLoad = false;
var enableFragment = "#reciteEnable";
var showLangDrop = false;
var loaded = [],
  frag = !1;
window.location.hash === enableFragment && (frag = !0);

function loadScript(c, b) {
  var a = document.createElement("script");
  a.type = "text/javascript";
  a.readyState ? a.onreadystatechange = function () {
    if ("loaded" == a.readyState || "complete" == a.readyState) a.onreadystatechange = null, void 0 != b && b()
  } : void 0 != b && (a.onload = function () {
    b()
  });
  a.src = c;
  document.getElementsByTagName("head")[0].appendChild(a)
}

function _rc(c) {
  c += "=";
  for (var b = document.cookie.split(";"), a = 0; a < b.length; a++) {
    for (var d = b[a];
      " " == d.charAt(0);) d = d.substring(1, d.length);
    if (0 == d.indexOf(c)) return d.substring(c.length, d.length)
  }
  return null
}

function loadService(c) {
  for (var b = serviceUrl + serviceKey, a = 0; a < loaded.length; a++)
    if (loaded[a] == b) return;
  loaded.push(b);
  loadScript(serviceUrl + serviceKey, function () {
    "function" === typeof _reciteLoaded && _reciteLoaded();
    "function" == typeof c && c();
    Recite.load(rmopts);
    Recite.Event.subscribe("Recite:load", function () {
      $('clevertar-chat').attr('data-recite-skip', 'true');
      Recite.enable()
    })
  })
}
"true" == _rc("Recite.Persist") && loadService();
(autoLoad && "false" != _rc("Recite.Persist") || frag) && loadService();

function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) {
  var startTimeInMs = Date.now();
  (function loopSearch() {
    if (document.querySelector(selector) != null) {
      callback();
      return;
    } else {
      setTimeout(function () {
        if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs)
          return;
        loopSearch();
      }, checkFrequencyInMs);
    }
  })();
}

function loadShowLang() {
  waitForElementToDisplay("#recite-toolbar-button-language", function () {
    setTimeout(function () {
      $('#recite-toolbar-button-language').focus();
      $('#recite-toolbar-button-language').click();
    }, 100);
  }, 100, 20000);
}

function _reciteLoaded() {
  /* only show when banner not displayed */
  if (setupReciteButtons && _rc("Recite.Persist") != "true") {
    setupReciteButtons = false;
    $('.accessibility-section').removeClass('hidden');
    $('.reciteme').css('display', '');

    Recite.Event.subscribe("Preferences:load", function () {
      if (Recite.Preferences.get('language'))
        Recite.Language.Translate.translate(document.body, Recite.Preferences.get('language'));
    });
    Recite.Preferences.load();

    // Bind to select element click
    $('.myEle.lang').click(function () {
      var lang = $(this).data('lang');
      $('.lang-btn').removeClass('show');
      $('.language-options').removeClass('show');
      $('clevertar-chat').attr('data-recite-skip', 'true');
      Recite.Preferences.set('language', lang);
      Recite.Language.Translate.translate($('BODY')[0], lang);
    });
    $('.myEle.more').click(function () {
      var lang = $(this).data('lang');
      $('.lang-btn').removeClass('show');
      $('.language-options').removeClass('show');
      $('clevertar-chat').attr('data-recite-skip', 'true');
      loadService(loadShowLang);
      if ("function" === typeof _reciteLoaded) {
        loadShowLang();
      }
    });
    $('.lang-btn').click(function () {
      var t = $(this);
      var lo = t.closest('.lang').siblings('.language-options');
      if (t.hasClass('show')) {
        lo.removeClass('show');
        t.removeClass('show');
      } else {
        lo.addClass('show');
        t.addClass('show');
      }
    });
    $('.reciteme button').click(function () {
      $('.lang-btn').removeClass('show');
      $('.language-options').removeClass('show');
      $('clevertar-chat').attr('data-recite-skip', 'true');
      $('.accessibility-section').addClass('hidden');
      loadService();
      return false;
    });
  }
  $('clevertar-chat').attr('data-recite-skip', 'true');
  var ttsIgnore = document.getElementById('clWidget');
  if (ttsIgnore) {
    ttsIgnore.setAttribute('data-recite-skip', 'true');
  }
}

function _removeBtns(btns) {
  Recite.Util.each(btns, function (id, btn) {
    Recite.Util.each(Recite.Sizzle(".recite-sprite-button-" + btn), function (id, element) {
      element.remove();
    });
  });
}
/* RECITEME END */

/* Data Map Table START */
var tierTitles = ['Close contact', 'Casual contact', 'Low risk casual contact', 'Other'];
var tierColours = ['F02D60', 'F69900', 'FFD451', '3A75D3'];
function getExposureColour(title) {
  for(var i=0;i<tierTitles.length;i++)
    if(title.toLowerCase().substr(0,4) == tierTitles[i].toLowerCase().substr(0,4))
      return tierColours[i];
  return '';
}

function getThemeColour(existing) {
  for(var i=0; i<defaultColours.length; i++)
    if(Object.values(existing).indexOf(defaultColours[i]) < 0) return defaultColours[i];
  return defaultColours[0];
}
var lt = null;
function toJSDate(serial) {
  if(isNaN(serial)) return new Date(serial);
  var utc_days = Math.floor(serial - 25569);
  var utc_value = utc_days * 86400;
  var date_info = new Date(utc_value * 1000);
  var fractional_day = serial - Math.floor(serial) + 0.0000001;
  var total_seconds = Math.floor(86400 * fractional_day);
  var seconds = total_seconds % 60;
  total_seconds -= seconds;
  var hours = Math.floor(total_seconds / (60 * 60));
  var minutes = Math.floor(total_seconds / 60) % 60;
  return new Date(date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds);
}

function getN(cell) {
  var str = 0;
  if (cell !== null)
    if (!isNaN(cell.v))
      str = Number(cell.v);
    else if(!isNaN(cell.v.replace(/<|>|(|)|,/gi,'')))
      str = Number(cell.v.replace(/<|>|(|)|,/gi,''));
  return str;
}

function getUniqueLngLat(cellLng, cellLat) {
  var lng = getN(cellLng);
  var lat = getN(cellLat);
  return [lng, lat];
}

function getT(cell) {
  var str = "";
  if (cell && cell.v)
    str += cell.v;
  return str.replace(/<[^>]+>/ig,'').trim();
}

function getRT(cell, head) {
  var str = "";
  if (cell !== null) {
    if (typeof cell.h !== 'undefined')
      str += cell.h;
    else if (typeof cell.r !== 'undefined')
      str += cell.r;
    else
      str += cell.v;

    if (typeof cell.l !== 'undefined') {
      if (cell.l.Target.substr(0, 5).toLowerCase() == '?head')
        str = '<a href="#" onClick="scrollToHeading(' + cell.l.Target.substr(6) + ');return false;">' + str + '</a>';
      else if (cell.l.Target.substr(0, 1).toLowerCase() == '#')
        str = '<a href="' + cell.l.Target + '" onClick="$(' + cell.l.Target + ')[0].scrollIntoView({behavior: "smooth", block: "start"});return false;">' + str + '</a>';
      else
        str = '<a href="' + cell.l.Target + '">' + str + '</a>';
    }
  }
  return str.trim().replace('\r\n', '<br/>').replace('\n', '<br/>');
}

function getDR(cellS, cellE, fmtD) {
  var str = "";
  if (cellS !== null) {
    str = moment(toJSDate(cellS.v)).format(fmtD);
    if (cellE !== null) {
      if (Math.floor(cellS.v) < Math.floor(cellE.v))
        str += ' - ' + moment(toJSDate(cellE.v)).format(fmtD);
    }
  }
  return str;
}

function getTR(cellS, cellE, fmtD, split) {
  var str = "";
  if (cellS !== null) {
    str = moment(toJSDate(cellS.v)).format(fmtD);
    if (cellE !== null) {
      str += split + moment(toJSDate(cellE.v)).format(fmtD);
    }
  }
  return str;
}

function getND(cell, fix, pre) {
  var str = "";
  if (cell !== null) {
    if (!isNaN(cell.v))
      str = pre + Number(cell.v).toFixed(fix);
  }
  return str;
}

function getH2Link(cell) {
  var str = "";
  if (cell !== null) {
    str = ('' + cell.v).trim();
    var h = $(".page-contents-list a:contains('" + str + "')");
    if (h.length > 1) {
      h = $(".page-contents-list a:contains('Tier " + str + "')");
    }
    if (h.length > 0) {
      str = '<a href="' + h[0].hash + '">' + h[0].innerText.trim() + '</a>';
    }
  }
  return str.trim().replace('\r\n', '<br/>').replace('\n', '<br/>');
}

function getLinkURL(cell) {
  var str = "";
  if (cell !== null) {
    if (typeof cell.l !== 'undefined' && typeof cell.l.Target !== 'undefined') {
        return ' data-link="' + cell.l.Target + '"';
    }
  }
  return '';
}

function scrollToHeading(txt) {
  $(".page-contents-list a:contains('" + txt + "')").click();
}

function getFileDate(workbook, formatStr) {
  if (workbook && workbook.Props) {
    var dstr = moment(workbook.Props.ModifiedDate.toJSON()).format(formatStr);
    if(dstr != 'Invalid date') return dstr;
  }
  return '';
}

function getDT(cell, fmt) {
  var str = "";
  if (cell && cell.v) {
    str = moment(toJSDate(cell.v)).format(fmt);
  }
  return str;
}

function getDoT(cell, fmtD, fmtT) {
  var str = "";
  if (cell !== null) {
    var dt = moment(toJSDate(cell.v));
    str = dt.format(fmtD);
    if (dt.format("HH:mm") !== '00:00')
      str += ' ' + dt.format(fmtT);
  }
  return str;
}

function getDTA(cellS, cellE, fmt) {
  var str = "";
  if (cellS !== null) {
    var s = Math.floor(cellS.v);
    var e = s;
    if (cellE !== null)
      e = Math.floor(cellE.v);
    for (var i = s; i <= e; i++)
      str += moment(toJSDate(i)).format(fmt) + ' ';
  }
  return str;
}

function getDTR(cellS, cellE, fmtD, fmtT) {
  var str = "";
  if (cellS !== null) {
    str = moment(toJSDate(cellS.v)).format(fmtD);
    str += '<br/>' + moment(toJSDate(cellS.v)).format(fmtT);
    if (cellE !== null) {
      str += ' - ';
      if (Math.floor(cellS.v) < Math.floor(cellE.v))
        str += '<br/>' + moment(toJSDate(cellE.v)).format(fmtD) + '<br/>';
      str += moment(toJSDate(cellE.v)).format(fmtT);
    }
  }
  return str;
}

function expSearch(t) {
  var p = $(t).closest('.media-release-controls');
  var suburb = $.fn.dataTable.util.escapeRegex(p.find('#locationSuburbs').val());
  if (suburb == '') suburb = '.*';
  var dateS = p.find('#exposureDate').val();
  if (dateS) dateS = moment(dateS, "ddd D MMMM YYYY").format("YYYY-MM-DD");
  if (dateS)
    lt.column(2).search(dateS).column(0).search('^' + suburb + '$', true, false).draw();
  else
    lt.column(0).search('^' + suburb + '$', true, false).draw();
}

function expSearchClear(t) {
  var p = $(t).closest('.media-release-controls');
  p.find('#locationSuburbs').val('');
  p.find('#exposureDate').val('');
  lt.column(0).search('').column(2).search('').draw();
}

function getMapIcon(outerC, innerC) {
  var svg = "data:image/svg+xml,%3Csvg width='40' height='40' version='1.1' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cg%3E%3Cpath d='m20 40 11.2-12.6h-22.4l11.2 12.6' stroke='%23FFFFFF' stroke-width='2'/%3E%3Cellipse cx='20' cy='16' rx='16' ry='16' stroke='%23FFFFFF' stroke-width='2'/%3E%3Cpath d='m20 40 11.2-12.6h-22.4l11.2 12.6' fill='%23";
  svg += outerC + "'/%3E%3Cellipse cx='20' cy='16' rx='16' ry='16' fill='%23" + outerC + "'/%3E%3Cellipse cx='20' cy='16' rx='7' ry='7' fill='%23" + innerC + "' stroke='%23FFFFFF' stroke-width='1'/%3E%3C/g%3E%3C/svg%3E";
  return svg;
}

/* Exposure Locations END */

/* Filter Search START */
function filterSearch(frm) {
  frm.action = "/wps/wcm/connect/Public+Content/SA+Health+Internet/search";
  return true;
}
/* Filter Search END*/

$(function () {
  /* hide sidebar */
  if($('.on-this-page li').length === 0)
    $('.on-this-page,.show-contents').remove();
  else {
    if($('.sidebar-siblings li').length === 0) $('.sidebar-siblings').remove();
    if($('.this-section-list li').length === 0) $('.this-section-list').prev().remove(),$('.this-section-list').remove();
    if($('.page-contents-list li').length === 0) $('.page-contents-list').prev().remove(),$('.page-contents-list').prev().remove(),$('.page-contents-list').remove();
  }

  /* Remove empty sidebar-siblings divs */  
  $('.sidebar-siblings').filter(function() {
    return $.trim($(this).text()).length === 0;
  }).remove();

  /* hide map results panel and remove any empty rows */
  $('#map-results-panel').css('display', 'none');

  /* Clear empty sections */
  $('.clear-empty').each(function() {
    if ($(this).text().trim().length == 0 && $(this).find('iframe').length == 0) {
      $(this).remove()
    }
  });

  /* Theme icon images */
  if($('.primary-color-filter').length > 0) {
    var rgb = hexToRgb('#'+themePrimary);
    if (rgb.length == 3) {
      var color = new Color(rgb[0], rgb[1], rgb[2]);
      var tries = 0;
      var result = (new Solver(color)).solve();
      while(tries < 20 && result.loss > Math.max(0.5, tries/10)) {
        result = (new Solver(color)).solve();
        tries++;  
      }
      if ( result.loss < 5 )
        $('.primary-color-filter').css('filter', result.filter);
      else
        $('.primary-color-filter').css('filter', 'brightness(0%)'); // default to black
    }
  }

  /* Alert Banner START */
  var ab = $(".alert-banner");
  if (ab.data('key') !== localStorage.getItem('closed-alert-banner')) {
    $(".alert-banner").show();
    ab.find('.close-alert').click(function () {
      localStorage.setItem('closed-alert-banner', ab.data('key'));
    });
  } else {
    ab.remove();
  }
  /* Alert Banner END */

  /* On This Page Buttons START */
  $('.on-this-page-buttons a.button').click(function(){
    $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top
    }, 500);
  });
  /* On This Page Buttons END*/

  /* SORT: Popular Searches / Trending Topics / Related Information START */
  $('.results-list,.au-link-list,.panel-content__results-list').each(function () {
    var list = $(this);
    if (list.children().length < 1) {
      list.prev('h2').remove();
      list.remove();
    } else if (list.children(':first').data('text')) {
      list.children().sort(function (a, b) {
        return ($(a).data('text').toLowerCase()) > ($(b).data('text').toLowerCase()) ? 1 : -1;
      }).appendTo(list);
      sort = list.data('sort');
      if (sort) {
        ('' + sort).split(',').reverse().forEach(function (i) {
          list.children('[data-order="' + i.trim() + '"]').prependTo(list);
        });
      }
    }
  });
  $('.popular-searches').each(function () {
    if ($(this).find('a').length < 1) $(this).remove();
  });
  /* SORT: Popular Searches / Trending Topics / Related Information END */

  /* Latest News START */
  $('.newsCategories').each(function (i, n) {
    n.innerText.split('~').forEach(function (a) {
      var found = false;
      if (!found && (a.indexOf('/News Types/') > 0 || a.indexOf('/News Events and Updates/') > 0)) {
        n.innerText = (a.substr(a.lastIndexOf('/') + 1));
        n.style.display = '';
        found = true;
      }
    });
  });
  /* Latest News END */

  /* Load results */
  $('ul.panel-content__results-list--location[data-menuid*="-"]').each(function () {
    var url = baseURL + '?source=library&srv=cmpnt&cmpntid=' + $(this).data('menuid').trim();
    var p = $(this);
    var it = p.data('itemtitle');
    if (it) url += '&itemtitle='+(it.trim());
    var ic = p.data('labelcat');
    if (ic) url += '&labelcat='+encodeURIComponent(ic.trim());
    p.load(url, function () {
      p.find(".show-hide").tipso({
        position: "bottom",
        size: "small",
        background: "#FFFFFF",
        color: "#000000",
        speed: 200,
      }), p.find(".tool-tip").keydown((function (t) {
        27 !== t.keyCode && 13 !== t.keyCode && 32 !== t.keyCode || ($(this).hasClass("clicked") && ($(this).removeClass("clicked"),
          $(this).find(".show-hide").tipso("hide")), t.preventDefault()), 13 !== t.keyCode && 32 !== t.keyCode || ($(this).addClass("clicked"), $(this).find(".show-hide").tipso("show"), t.preventDefault())
      })), p.find(".tool-tip").on("click", (function (t) {
        $(this).hasClass("clicked") ? ($(this).removeClass("clicked"), $(this).find(".show-hide").tipso("hide")) : ($(this).addClass("clicked"), $(this).find(".show-hide").tipso("show")), t.preventDefault()
      }));
      $("#selectServiceFinder").val(getParam('s_cat'));
      $("#postcode").val(getParam('s_loc'));
      if (getParam('lat') && getParam('lng')) filterServicePostcode();
      UpdateLinks(p);
    });
  });

  /* A-Z lists */
  $('.a-z-key-list').each(function () {
    var _header = $(this);
    var _section = _header.closest('.a-z-panel');
    var _results = _section.find('div.results-list.a-z-category');
    if (!_results.data('menuid')) setUpAZ(_header, _section, _results);
    else {
      var url = baseURL + '?source=library&srv=cmpnt&cmpntid=' + _results.data('menuid').trim();
      var it = _results.data('itemtitle');
      if (it) url += '&itemtitle='+(it.trim());
      var ic = _results.data('labelcat');
      if (ic ) url += '&labelcat='+encodeURIComponent(ic.trim());
      if (_results.data('cat') && _results.data('limit') == true) {
        var cats = "&findcat=" + encodeURIComponent(_results.data('cat'));
        if (url.length + cats.length > 2000) {
          cats = {
            'findcat': _results.data('cat')
          };
          _results.load(url, cats, function () {
            setUpAZ(_header, _section, _results);
            UpdateLinks(_results);
          });
        } else {
          url = url + cats;
          _results.load(url, function () {
            setUpAZ(_header, _section, _results);
            UpdateLinks(_results);
          });
        }
      } else {
        _results.load(url, function () {
          setUpAZ(_header, _section, _results);
          UpdateLinks(_results);
        });
      }
    }
  });

  /* Media releases */
  $('.media-releases').each(function (pId) {
    var wrap = $(this);
    var res = wrap.children('.results-list');
    var catSel = wrap.children('.media-release-results-header').find('.category');
    var sortSel = wrap.children('.media-release-results-header').find('.sort');
    catSel.each(function () {
      $(this).children('option').each(function () {
        if (!this.text) {
          var p = $(this);
          var vs = this.value.split(',');
          vs.sort(function (a, b) {
            var t1 = (a.substring(('/' + a).lastIndexOf('/'))).toLowerCase();
            var t2 = (b.substring(('/' + b).lastIndexOf('/'))).toLowerCase();
            return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
          });
          vs.forEach(function (a, i) {
            p.after('<option value="' + a + '">' + a.substring(('/' + a).lastIndexOf('/')) + '</option>');
          });
          p.remove();
        }
      });
    });
    if (getParamItem('mr-cat', pId)) {
      var cats = getParamItem('mr-cat', pId).split('~');
      for (var i in cats) {
        catSel[i].value = cats[i];
      }
    }
    if (getParamItem('mr-sort', pId)) sortSel.val(getParamItem('mr-sort', pId));

    var url = baseURL + '?source=library&srv=cmpnt&cmpntid=' + res.data('menuid').trim();
    var it = res.data('itemtitle');
    if (it) url += '&itemtitle='+(it.trim());
    var ic = res.data('labelcat');
    if (ic ) url += '&labelcat='+encodeURIComponent(ic.trim());
    var ipp = 10;
    if (res.data('rows')) ipp = res.data('rows');
    var cats = {};
    if (res.data('cat')) {
      cats = {
        'mediacat': res.data('cat')
      };
      res.load(url, cats, function () {
        catSel.children('option').each(function () {
          if (this.value != "" && res.find('article[data-cat*="' + this.value + '"]').length < 1)
            this.remove();
        });
        if (sortSel.length) {
          sortResults(sortSel[0]);
        } else {
          pageMediaUI(1, ipp, res);
        }
        UpdateLinks(res);
        wrap.show();
      });
    } else {
      res.load(url, function () {
        catSel.children('option').each(function () {
          if (this.value != "" && res.find('article[data-cat*="' + this.value + '"]').length < 1)
            this.remove();
        });
        if (sortSel.length) {
          sortResults(sortSel[0]);
        } else {
          pageMediaUI(1, ipp, res);
        }
        UpdateLinks(res);
        wrap.show();
      });
    }
  });

  /* Finder */
  $('.panel-content.categories').each(function () {
    finderRenderResults(finderGetDetails(this));
  });

  /* Related info tabs START */
  $('#related-info-finder').each(function (i, item) {
    var rif = $(item);
    var tabs = rif.find('div[role="tablist"] button');
    var tabSel, panelSel;
    var total = 0;
    tabs.each(function () {
      var tab = $(this);
      var panel = rif.find('#' + tab.attr('aria-controls'));
      var items = panel.find('.panel-content ul li').length;
      total += items;
      if (items < 1) {
        $(".scroll-link-related-info-finder.scroll-" + tab[0].id).remove();
        tab.remove();
        panel.remove();
      } else if ((tab.text() === tab.parent().data('tab')) || !tabSel) {
        tabSel = tab;
        panelSel = panel;
      }
    });
    if (total > 0) {
      var pId = $('.finder').index(item);
      if (!getParamItem('finderTab', pId)) {
        if (!tabSel) tabSel = $(tabs[0]);
        tabSel.attr('aria-selected', true);
        panelSel.attr('hidden', false);
      }
      rif.show();
    }
  });
  /* Related info tabs END */

  /* Select finder tab START */
  $('.finder').each(function (pId, item) {
    var finderTab = getParamItem('finderTab', pId);
    if (finderTab) {
      var tabs = $(item).children('.tabs');
      var tabList = tabs.children('div[role="tablist"]');
      var tab = tabList.children('#' + finderTab);
      tabList.children('button[role="tab"]').attr('aria-selected', false);
      tabs.children('div[role="tabpanel"]').prop('hidden', true);
      tab.attr('aria-selected', true);
      tabs.children('#' + tab.attr('aria-controls')).attr('hidden', false);
    }
    $('.finder button[role="tab"]').click(function (e) {
      var fid = e.target.id;
      var pId = $('.finder').index($(e.target).closest('.finder')[0]);
      setParamItem('finderTab', pId, fid);
    });

    var f = $(item);
    var pt = $(item).prev('h2');
    if (pt && pt.length > 0) {
      f.find('.finder-title h2').html(pt.html());
      pt.remove();
    }
  });
  /* Select finder tab END */

  /* Media Release Sort START */
  sortSelectOptions("#mediaReleaseCategories", true);
  /* Media Release Sort END */

  /* ED Widget START */
  if ($('.article-card-wait-time').length > 0) {
    $.getJSON(host + "/wps/themes/html/Portal/js/OBI_DATA/json/ED001.json", function (items) {
      $('.article-card-wait-time').each(function () {
        var article = $(this);
        var status = 'normal';
        var hosp = article.data('hosp');
        var data = items.filter(function (a) {
          return hosp === a.HOSP_SHORT
        })[0];
        if (data) {
          var aw = parseFloat(data.AVG_WAIT);
          var awtxt = '';
          if (aw < 60) awtxt = Math.round(Math.ceil(aw / 5) * 5) + " mins";
          else awtxt = Math.round(Math.ceil(aw / 15)) / 4 + " hours";
          article.find(".wait-time").text(awtxt);
          article.find(".wait-time").attr('data-time', awtxt);
          var vol = (parseInt(data.WTBS) + parseInt(data.COM_TREAT)) / parseInt(data.CAP);
          if (isNaN(vol)) {
            status = 'error';
          } else if (vol < .8) {
            status = 'normal';
          } else if (vol < .95) {
            status = 'busy';
          } else {
            status = 'vbusy';
          }
          article.attr("data-wait", status);
          article.find(".last-updated time").text(moment(new Date(data.DTM)).format('hh:mma D MMM YYYY'));
          article.find(".last-updated time").attr('datetime', data.DTM);
        }

      });
    });
  }
  /* ED Widget END */

  /* COVID Test Sites Widget START */
  if ($('.article-card-covid-test').length > 0) {
    $.getJSON(host + "/wps/themes/html/Portal/js/OBI_DATA/json/COVID_TEST_001.JSON", function (items) {
      $('.article-card-covid-test').each(function () {
        var article = $(this);
        var site = article.data('site');
        var data = items.filter(function (a) {
          return site === a.CLINIC_SHORT
        })[0];
        if (data) {
          var aw = parseFloat(data.AVG_WAIT);
          var awtxt = '';
          if (aw < 60) awtxt = (Math.ceil(aw / 5.0) * 5) + " mins";
          else awtxt = (Math.ceil(aw / 15.0) / 4) + " hours";
          article.find(".wait-time").text(awtxt);
          article.find(".wait-time").attr('data-time', awtxt);
          
          aw = parseFloat(data.AVG_BOOK_WAIT);
          awtxt = '';
          if (aw < 60) awtxt = (Math.ceil(aw / 5.0) * 5) + " mins";
          else awtxt = (Math.ceil(aw / 15.0) / 4) + " hours";
          article.find(".wait-time-book").text(awtxt);
          article.find(".wait-time-book").attr('data-time', awtxt);

          article.find(".last-updated time").text(moment(new Date(data.DTM)).format('hh:mma D MMM YYYY'));
          article.find(".last-updated time").attr('datetime', data.DTM);
        }

      });
    });
  }
  /* COVID Test Sites Widget END */


  /* Anchor Lists START */
  $('#anchordata').each(function (index, adata) {
    var listData = Papa.parse(adata.innerHTML).data;
    if (listData) {
      var GROUP = 0,
        CAT = 2,
        NAME = 3,
        PHONE = 4,
        MOBILE = 5,
        EMAIL = 6,
        LOC = 7,
        CONCLASS = 8,
        EXP = 9,
        MSG = 10;
      var cats = [];
      for (var i = 1; i < listData.length; i++) {
        var g = listData[i][GROUP].trim();
        var c = listData[i][CAT];
        if (c && !cats.some(function (x) {
            return x.name === c;
          })) {
          cats.push({
            name: c,
            group: g
          });
          if ($('section.main-content ul.anchor-list[data-group="' + g + '"]').length < 1)
            $('section.main-content').append('<ul class="anchor-list" data-group="' + g + '"></ul>');
        } /* finds groups and categories, appends any missing groups */
      }
      var contentContactItem = function (obj) {
        if (obj[MSG] && !obj[NAME])
          return '<div class="content-item col-lg-12"><p>' + obj[MSG] + '</p></div>';
        var res = '<article class="contact-item col-lg-4 col-sm-6"><div class="contact-name">';
        if (obj[NAME]) res += '<h3>' + obj[NAME] + '</h3></div>';
        if (obj[PHONE] || obj[MOBILE] || obj[EMAIL]) {
          res += '<ul class="contact-method-list">';
          if (obj[PHONE]) obj[PHONE].split("~").forEach(function (o) {
            res += '<li><svg aria-label="phone" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 384 384" style="enable-background:new 0 0 384 384;" xml:space="preserve"><g><g><path d="M353.188,252.052c-23.51,0-46.594-3.677-68.469-10.906c-10.719-3.656-23.896-0.302-30.438,6.417l-43.177,32.594 c-50.073-26.729-80.917-57.563-107.281-107.26l31.635-42.052c8.219-8.208,11.167-20.198,7.635-31.448 c-7.26-21.99-10.948-45.063-10.948-68.583C132.146,13.823,118.323,0,101.333,0H30.813C13.823,0,0,13.823,0,30.813 C0,225.563,158.438,384,353.188,384c16.99,0,30.813-13.823,30.813-30.813v-70.323C384,265.875,370.177,252.052,353.188,252.052z"></path></g></g></svg><span class="sr-only">' + listData[0][PHONE] + '</span><a href="tel:' + o.trim() + '">' + o.trim() + '</a></li>';
          });
          if (obj[MOBILE]) obj[MOBILE].split("~").forEach(function (o) {
            res += '<li><svg aria-label="phone" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 384 384" style="enable-background:new 0 0 384 384;" xml:space="preserve"><g><g><path d="M353.188,252.052c-23.51,0-46.594-3.677-68.469-10.906c-10.719-3.656-23.896-0.302-30.438,6.417l-43.177,32.594 c-50.073-26.729-80.917-57.563-107.281-107.26l31.635-42.052c8.219-8.208,11.167-20.198,7.635-31.448 c-7.26-21.99-10.948-45.063-10.948-68.583C132.146,13.823,118.323,0,101.333,0H30.813C13.823,0,0,13.823,0,30.813 C0,225.563,158.438,384,353.188,384c16.99,0,30.813-13.823,30.813-30.813v-70.323C384,265.875,370.177,252.052,353.188,252.052z"></path></g></g></svg><span class="sr-only">' + listData[0][MOBILE] + '</span><a href="tel:' + o.trim() + '">' + o.trim() + '</a></li>';
          });
          if (obj[EMAIL]) obj[EMAIL].split("~").forEach(function (o) {
            res += '<li><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve" aria-hidden="true"><title>Envelope</title><g><g><g><path d="M10.688,95.156C80.958,154.667,204.26,259.365,240.5,292.01c4.865,4.406,10.083,6.646,15.5,6.646 c5.406,0,10.615-2.219,15.469-6.604c36.271-32.677,159.573-137.385,229.844-196.896c4.375-3.698,5.042-10.198,1.5-14.719 C494.625,69.99,482.417,64,469.333,64H42.667c-13.083,0-25.292,5.99-33.479,16.438C5.646,84.958,6.313,91.458,10.688,95.156z"></path><path d="M505.813,127.406c-3.781-1.76-8.229-1.146-11.375,1.542c-46.021,39.01-106.656,90.552-152.385,129.885 c-2.406,2.063-3.76,5.094-3.708,8.271c0.052,3.167,1.521,6.156,4,8.135c42.49,34.031,106.521,80.844,152.76,114.115 c1.844,1.333,4.031,2.01,6.229,2.01c1.667,0,3.333-0.385,4.865-1.177c3.563-1.823,5.802-5.49,5.802-9.49V137.083 C512,132.927,509.583,129.146,505.813,127.406z"></path><path d="M16.896,389.354c46.25-33.271,110.292-80.083,152.771-114.115c2.479-1.979,3.948-4.969,4-8.135 c0.052-3.177-1.302-6.208-3.708-8.271C124.229,219.5,63.583,167.958,17.563,128.948c-3.167-2.688-7.625-3.281-11.375-1.542 C2.417,129.146,0,132.927,0,137.083v243.615c0,4,2.24,7.667,5.802,9.49c1.531,0.792,3.198,1.177,4.865,1.177 C12.865,391.365,15.052,390.688,16.896,389.354z"></path><path d="M498.927,418.375c-44.656-31.948-126.917-91.51-176.021-131.365c-4-3.26-9.792-3.156-13.729,0.24 c-9.635,8.406-17.698,15.49-23.417,20.635c-17.563,15.854-41.938,15.854-59.542-0.021c-5.698-5.135-13.76-12.24-23.396-20.615 c-3.906-3.417-9.708-3.521-13.719-0.24c-48.938,39.719-131.292,99.354-176.021,131.365c-2.49,1.792-4.094,4.552-4.406,7.604 c-0.302,3.052,0.708,6.083,2.802,8.333C19.552,443.01,30.927,448,42.667,448h426.667c11.74,0,23.104-4.99,31.198-13.688 c2.083-2.24,3.104-5.271,2.802-8.323C503.021,422.938,501.417,420.167,498.927,418.375z"></path></g></g></g></svg><span class="sr-only">' + listData[0][EMAIL] + '</span><a href="mailto:' + o.trim() + '" >' + o.trim() + '</a></li>';
          });
          res += '</ul>';
        }
        if (obj[LOC])
          res += '<div class="contact-info"><h4>' + listData[0][LOC] + '</h4><ul class="au-link-list au-link-list--inline"><li>' + obj[LOC].replace(/~/g, '</li><li>') + '</li></ul></div>';
        if (obj[CONCLASS])
          res += '<div class="contact-info"><h4>' + listData[0][CONCLASS] + '</h4><ul class="au-link-list au-link-list--inline"><li>' + obj[CONCLASS].replace(/~/g, '</li><li>') + '</li></ul></div>';
        if (obj[EXP])
          res += '<div class="contact-info"><h4>' + listData[0][EXP] + '</h4><ul class="au-link-list au-link-list--inline"><li>' + obj[EXP].replace(/~/g, '</li><li>') + '</li></ul></div>';
        return res + '</article>';
      };
      var btnTop = '<a href="#maincontent"><button class="repeatable back-to-top-button" role="button" tabindex="0"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 31.5 31.5" style="enable-background:new 0 0 31.5 31.5;" xml:space="preserve"><path class="st1" d="M21.2,5c-0.4-0.4-1.1-0.4-1.6,0c-0.4,0.4-0.4,1.1,0,1.6l8,8H1.1c-0.6,0-1.1,0.5-1.1,1.1c0,0.6,0.5,1.1,1.1,1.1 h26.6l-8,8c-0.4,0.4-0.4,1.2,0,1.6c0.4,0.4,1.2,0.4,1.6,0l10-10c0.4-0.4,0.4-1.1,0-1.6L21.2,5z"></path></svg><span>Back to top</span></button></a>';
      var bodyList = $('section.content-lists-container');
      cats.forEach(function (cat, i) {
        var id = cat.name.replace(/[^A-Za-z]/g, '') + '-' + i;
        var results = listData.filter(function (a) {
          return a[CAT] === cat.name
        });
        var anchorList = $('section.main-content ul.anchor-list[data-group="' + cat.group + '"]');
        anchorList.append('<li><a href="#' + id + '" class="anchor-link">' + cat.name + '</a></li>');
        bodyList.append('<div class="content-list"><div id="' + id + '" class="heading-container"><h2 tabindex="0">' + cat.name + '</h2></div><div class="content-container">' + results.map(contentContactItem).join('') + '</div>' + btnTop + '</div>');
      });
    }
    $(adata).remove();
  });
  /* Anchor Lists END */

  /* Autocomplete */
  $('input[type="search"][name!="location-search"]').attr('autocomplete', 'off'); // hide default suggestions
  $('input[type="search"][name!="location-search"]').parent().on('focusout', function () {
    var f = $(this);
    if (autoShowTimeout != null) clearTimeout(autoShowTimeout);
    autoShowTimeout = setTimeout(function () {
      autoShowTimeout = null;
      f.removeClass('focus');
    }, 500);
  }).on('focusin', function () {
    clearTimeout(autoShowTimeout);
    $(this).addClass('focus');
  });
  if (typeof isIntranet !== 'undefined' && isIntranet) {
    $('form[role="search"]').submit(function () {
      var q = $(this).find('input[type="search"]').val();
      window.location = $(this).attr('action') + '#/query=' + encodeURIComponent(q);
      return false;
    });
  } else {
    $('input[type="search"][name!="location-search"][data-autocomplete!="false"]').autocomplete({
      position: {
        my : "right top",
        at: "right bottom"
      },
      source: function (request, response) {
        $.ajax({
            url: "/asponte-wcm-seedlist/TypeaheadService?libs=Public Content",
            dataType: "json",
            data: {
                term: request.term
            },
            success: function (data) {
                response(data);
            },
            error: function (jqXHR, errorMsg) {
                console.log(errorMsg);
            },
            complete: function (jqXHR) {
            }
        });
      },
      select: function( event, ui ) {
        $("#searchButton").trigger('click');
        return false;
      },
      minLength: 2
    });
  }

  $('.current-map-query-wrapper').click(function () {
    $('#location-search').val("");
    toggleMapIsActive("", false);

  });
  $('a#allSitesLink').click(function (e) {
    e.preventDefault();
    changeSiteListActive(1);
  });
  $('#allSitesLink a').each(function(x){
    $(this).click(function (e) {
      e.preventDefault();
      changeSiteListActive(x+1);
    });
  });

  UpdateLinks($('body'));

  /* START COVID */
  if ($('#convid-stats').length > 0) {
    var v = Math.random() * 10 + 1;
    $.getJSON( "/wps/themes/html/Portal/js/OBI_DATA/json/Covid_dashboard_summary_01.json"+"?v="+v, 
    function( dataArr ) {
      function formatNum(nStr) {
        try {
          var n = Number.parseInt(nStr);
          return n.toLocaleString();
        } catch(e){return '';}
      }
      var data = dataArr [0];
      $('.PCR_tests_yesterday').text(formatNum(data.PCR_tests_yesterday));
      $('.Total_PCR_tests').text(formatNum(data.Total_PCR_tests));
      $('.New_cases').text(formatNum(data.New_cases));
      $('.Active_cases').text(formatNum(data.Active_cases));
      $('.Total_cases').text(formatNum(data.Total_cases));
      $('.Patients_in_hospital').text(formatNum(data.Patients_in_hospital));
      $('.Patients_in_ICU').text(formatNum(data.Patients_in_ICU));
      $('.New_deaths').text(formatNum(data.New_deaths));
      $('.Total_Deaths').text(formatNum(data.Total_Deaths));
    });
  }
  /* END COVID */

  UpdateLinks($('body'));

  /* Scroll heading into view */
  if (getParam("head") != "") {
    $(".page-contents-list a:contains('" + getParam("head") + "')").click();
  }

  /* RECITEME START */
  loadScript(serviceUrl + serviceKey, function () {
    _reciteLoaded();
  });
  /* RECITEME END */

  /* Exposure Locations START */
  if (typeof exposureListTitle !== 'undefined' && typeof exposureListURL !== 'undefined') {
    var req = new XMLHttpRequest();
    req.open("GET", exposureListURL, true);
    req.responseType = "arraybuffer";
    req.onload = function (e) {
      var data = new Uint8Array(req.response);
      workbook = XLSX.read(data, {
        type: "array"
      });

      var sheet = workbook.Sheets[workbook.SheetNames[0]];
      var listData = [],
        rowNum, colNum;
      var range = XLSX.utils.decode_range(sheet['!ref']);
      var subs = [];
      for (rowNum = range.s.r + 1; rowNum <= range.e.r; rowNum++) { // ignore header row
        var row = [];
        for (colNum = range.s.c; colNum <= range.e.c; colNum++) {
          var nextCell = sheet[XLSX.utils.encode_cell({
            r: rowNum,
            c: colNum
          })];
          if (typeof nextCell === 'undefined' || nextCell.v == null || nextCell.v == "") {
            row.push(null);
          } else
            row.push(nextCell);
        }
        if (row[0] != null) {
          listData.push(row);
          var s = row[0].v.trim();
          if (s && !subs.some(function (x) {
              return x === s;
            }))
            subs.push(s);
        }
      }
      subs.sort();

      var headings = ["Suburb", "Site", "Exposure period", "Notes", "Date added", "Health advice"];
      var SUBURB = 0,
        SITE = 1,
        EP_S = 2,
        EP_E = 3,
        NOTE = 4,
        DADD = 5,
        ADVICE = 6,
        LAT = 7,
        LNG = 8;

      var optRow = function (obj) {
        return '<option value="' + obj + '">' + obj + '</option>';
      };
      var headRow = function (obj) {
        return '<th>' + obj + '</th>';
      };
      var dataRow = function (obj) {
        var res = '<tr>';
        res += '<td data-sort="' + getT(obj[SUBURB]).toLowerCase() + '">' + getRT(obj[SUBURB], 0) + '</td>';
        res += '<td data-sort="' + getT(obj[SITE]).toLowerCase() + '">' + getRT(obj[SITE], 0) + '</td>';
        res += '<td data-sort="' + getDT(obj[EP_S], "YYYY-MM-DD HH:mm") + ' ' + getDT(obj[EP_E], "YYYY-MM-DD  HH:mm") + '" data-search="' + getDTA(obj[EP_S], obj[EP_E], "YYYY-MM-DD") + '">';
        res += getDTR(obj[EP_S], obj[EP_E], "ddd D MMMM YYYY", " h:mma") + '</td>';
        res += '<td data-sort="' + getT(obj[NOTE]).toLowerCase() + '">' + getRT(obj[NOTE], 0) + '</td>';
        res += '<td data-sort="' + getDT(obj[DADD], "YYYY-MM-DD") + '">' + getDoT(obj[DADD], "ddd D MMMM YYYY", "hh:mma") + '</td>';
        res += '<td data-sort="' + getT(obj[ADVICE]).toLowerCase() + '">' + getH2Link(obj[ADVICE]) + '</td>';
        return res + '</tr>';
      };

      var btnTop = '<a href="#maincontent"><button class="repeatable back-to-top-button" role="button" tabindex="0"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 31.5 31.5" style="enable-background:new 0 0 31.5 31.5;" xml:space="preserve"><path class="st1" d="M21.2,5c-0.4-0.4-1.1-0.4-1.6,0c-0.4,0.4-0.4,1.1,0,1.6l8,8H1.1c-0.6,0-1.1,0.5-1.1,1.1c0,0.6,0.5,1.1,1.1,1.1 h26.6l-8,8c-0.4,0.4-0.4,1.2,0,1.6c0.4,0.4,1.2,0.4,1.6,0l10-10c0.4-0.4,0.4-1.1,0-1.6L21.2,5z"></path></svg><span>Back to top</span></button></a>';
      var html = '<div class="media-release-results-header"><div class="media-release-controls"><div class="au-control-input">';
      html += '<label for="locationSuburbs">Search by suburb</label>';
      html += '<select id="locationSuburbs" class="au-select au-select--block category" onchange="expSearch(this)">';
      html += '<option value="">All Suburbs</option>' + subs.map(optRow);
      html += '</select></div><div class="au-control-input"><label for="sortBy">Exposure date</label>'
      html += '<input id="exposureDate" class="au-text-input au-text-input--block pac-target-input" onchange="expSearch(this)"/>';
      html += '</div><div class="au-control-input" style="padding: 1.5rem 1rem 0 1rem;"><a href="#" onclick="expSearchClear(this);return false;">Show&nbsp;All</a></div></div></div>';
      html += '<table><thead><tr>' + headings.map(headRow).join('') + '</tr></thead><tbody>' + listData.map(dataRow).join('') + '</tbody></table>';
      $('#locationTable').html(html);

      lt = $('#locationTable table').DataTable({
        dom: 'Brtip',
        lengthChange: false,
        pageLength: 25,
        order: [
          [4, 'desc']
        ],
        responsive: {
          details: {
            display: $.fn.dataTable.Responsive.display.childRowImmediate,
            type: 'none',
            target: ''
          }
        },
        buttons: [{
            extend: 'excelHtml5',
            filename: exposureListTitle + '  ' + getFileDate(workbook, "YYYY-MM-DD HH.mm"),
            title: exposureListTitle,
            messageTop: getFileDate(workbook, "ddd D MMMM YYYY  hh:mma"),
          },
          {
            extend: 'pdfHtml5',
            filename: getFileDate(workbook, "YYYY-MM-DD HH.mm"),
            title: exposureListTitle,
            messageTop: getFileDate(workbook, "ddd D MMMM YYYY  hh:mma"),
          }
        ],
      });
      $.fn.DataTable.ext.pager.numbers_length = 5;

      $('.dt-buttons').append("<div class='dtLastUpdate'>Last updated: " + getFileDate(workbook, "ddd D MMMM YYYY  hh:mma") + "</div>");
      var expDT = new DateTime(document.getElementById('exposureDate'), {
        format: 'ddd D MMMM YYYY',
        buttons: {
          today: false,
          clear: true
        }
      });
      // Handle scrolling on paging
      $(document).scroll(function () {
        dtOff = $('.dataTables_paginate').offset().top - $(document).scrollTop();
      });
      $(document).on('click', '.paginate_button', function () {
        $(document).scrollTop($('.dataTables_paginate').offset().top - dtOff);
      });

      /* Exposure Location Map START */
      lmfeatures = [];
      listData.forEach(function (element, i) {
        if (getT(element[LNG]) !== '' && getN(element[LNG]) != 0 &&
          getT(element[LAT]) !== '' && getN(element[LAT]) != 0) {
          var c = getExposureColour('Other');
          if (getExposureColour(getT(element[ADVICE])))
            c = getExposureColour(getT(element[ADVICE]));
          var res = '<b>' + getRT(element[SUBURB]) + '</b><br/>';
          res += getRT(element[SITE]) + '<br/><br/>';
          res += '<b>Exposure period</b><br/>' + getDTR(element[EP_S], element[EP_E], "ddd D MMMM YYYY", "h:mma") + '<br/><br/>';
          res += '<b>Notes</b><br/>' + getRT(element[NOTE]) + '<br/><br/>';
          res += '<b>Date added</b><br/>' + getDoT(element[DADD], "ddd D MMMM YYYY", " hh:mma") + '<br/><br/>';
          res += '<b>Health advice</b><br/>' + getH2Link(element[ADVICE]) + '<br/>';
          var feature = new ol.Feature({
            geometry: new ol.geom.Point(ol.proj.fromLonLat(getUniqueLngLat(element[LNG], element[LAT]))),
            popup: res,
            color: c,
          });
          lmfeatures.push(feature);
        }
      });

      // Popup overlay
      var popup = new ol.Overlay.Popup({
        popupClass: "default",
        closeBox: true,
        positioning: 'auto',
        autoPan: true,
        autoPanAnimation: {
          duration: 250
        }
      });

      // Cluster
      var source = new ol.source.Vector({
        features: lmfeatures,
      });
      var clusterSource = new ol.source.Cluster({
        source: source,
        distance: 50,
        minDistance: 50,
      });
      var styleCache = {};
      var lmSites = new ol.layer.Vector({
        source: clusterSource,
        style: function (feature) {
          var size = feature.get('features').length;
          if (size == 1) {
            var f = feature.get('features')[0];
            return new ol.style.Style({
              image: new ol.style.Icon({
                anchor: [0.5, 1],
                src: getMapIcon(themePrimary, f.get('color'))
              })
            });
          }
          var style = styleCache[size];
          if (!style) {
            style = new ol.style.Style({
              image: new ol.style.Circle({
                radius: 20,
                stroke: new ol.style.Stroke({
                  color: '#FFFFFF',
                }),
                fill: new ol.style.Fill({
                  color: '#' + themePrimary,
                }),
              }),
              text: new ol.style.Text({
                text: size.toString(),
                fill: new ol.style.Fill({
                  color: '#' + themeOnPrimary,
                }),
                font: '16px proxima-nova',
                offsetY: 1,
                offsetX: 1
              }),
            });
            styleCache[size] = style;
          }
          return style;
        },
      });

      var lmMap = new ol.layer.Tile({
        source: new ol.source.OSM()
      });
      lm = new ol.Map({
        layers: [
          lmMap,
          lmSites
        ],
        target: 'locationMap',
        view: new ol.View({
          center: [0, 0],
          zoom: 1
        }),
        overlays: [popup]
      });

      if ($('#locationMap.showLegend').length > 0) {
        // Define a new legend
        var legend = new ol.legend.Legend({
          title: 'Exposure Sites',
          style: new ol.style.Style({
            image: new ol.style.Icon({
              anchor: [0.5, 1],
              src: getMapIcon(themePrimary, 'FFFFFF')
            })
          })
        });
        for (var i = 0; i < tierColours.length; i++) {
          legend.addItem({
            title: tierTitles[i],
            typeGeom: 'Point',
            style: new ol.style.Style({
              image: new ol.style.Icon({
                anchor: [0.5, 1],
                src: getMapIcon(themePrimary, tierColours[i])
              })
            })
          });
        }
        var legendCtrl = new ol.control.Legend({
          legend: legend,
          collapsed: false
        });
        lm.addControl(legendCtrl);
      }

      var layerExtent = ol.extent.boundingExtent(
        lmfeatures.map(function(r){return r.getGeometry().getCoordinates()})
      );
      if (layerExtent && lmfeatures.length > 0)
        lm.getView().fit(layerExtent, {
          padding: [60, 40, 50, 60]
        });

      // Control Select 
      var select = new ol.interaction.Select({
        style: null
      });
      lm.addInteraction(select);


      // hover hand
      lm.on('pointermove', function (e) {
        var pixel = lm.getEventPixel(e.originalEvent);
        var hit = lm.hasFeatureAtPixel(pixel);
        lm.getViewport().style.cursor = hit ? 'pointer' : '';
      });

      var maxZoom = 20;
      lm.on('click', function (e) {
        lmSites.getFeatures(e.pixel).then(function (clickedFeatures) {
          if (clickedFeatures.length) {
            // Get clustered Coordinates
            var features = clickedFeatures[0].get('features');
            if (features.length > 1 && lm.getView().getZoom() < maxZoom) {
              var extent = ol.extent.boundingExtent(
                features.map(function (r) {
                  return r.getGeometry().getCoordinates()
                })
              );
              lm.getView().fit(extent, {
                duration: 500,
                maxZoom: maxZoom,
                padding: [60, 40, 50, 80]
              });
            } else {
              var popupText = '';
              features.sort(function compareFn(a, b) {
                return (tierColours.indexOf(a.get('color')) < tierColours.indexOf(b.get('color')) ? -1 : 1);
              }).forEach(function (f, index) {
                popupText += '<div class="note" style="border-color: #' + f.get('color') + '; margin: 4px 0; padding: 12px">';
                if (features.length > 1) popupText += '<h4 style="margin:-8px -8px 0 0;color:#616161; text-align:right">Site ' + (index + 1) + ' of ' + features.length + '</h4>';
                popupText += f.get("popup") + '</div>';
              });
              popup.show(features[0].getGeometry().getFirstCoordinate(),
                '<div style="max-height:350px; max-width:360px; padding:0 4px 0 0; overflow-y:auto">' + popupText + '</div>');
              $('.ol-popup.default>div').css('border', 'none').css('background', 'rgba(0,0,0,0.3)');
              $('.ol-popup.default .anchor').remove();
            }
            clickedFeatures[0]
          } else {
            popup.hide();
          }
        });
      });

      /* Gray map */
      var lmFilter = new ol.filter.Colorize();
      lmMap.addFilter(lmFilter);
      /* Exposure Location Map END*/
    }
    req.send();
  }
  /* Exposure Locations END */

  /* Data Map/Table START */
  if (typeof dataListURL !== 'undefined' && typeof dataListTitle !== 'undefined') {
    var req = new XMLHttpRequest();
    req.open("GET", dataListURL, true);
    var ext = dataListURL.split('?')[0];
    ext = ext.substr(ext.lastIndexOf('.') + 1).toLowerCase();
    if (ext == 'json')
      req.responseType = "json";
    else
      req.responseType = "arraybuffer";
    req.onload = function (e) {
      listData = [];
      headings = [];
      notypes = false;
      types = [];
      filters = [];
      hasFilterRow = false;
      tableColumn = [], tc = 0;
      groups = [];
      GROUP = -1;
      GC = -1;
      LAT = -1;
      LNG = -1;
      modDate = moment();

      var workbook = null, sheet = null;
      var rowOff = 0, rowNum, colNum;

      /* get sheet and last updated date */
      if (ext == 'json') {
        var data = req.response;

        if (!data[0]['DTM']) {
          var lgaTimestamp;
          $.ajax({
            url: "https://www.sahealth.sa.gov.au/wps/themes/html/Portal/js/OBI_DATA/json/Covid_LGA_NewCasesTotalCases_timestamp.json",
            async: false,
            dataType: 'json',
            success: function(data) {
              lgaTimestamp = data.CovidDTM;
            }
          });
          data[0]['DTM'] = moment(lgaTimestamp, "DD/MM/YYYY HH:mm").format("YYYY-MM-DD HH:mm");
        }

        /* Check if date is first row */
        if (Object.keys(data[0]).length == 1) {
          var drow = data.shift();
          var dstr = moment(drow[Object.keys(drow)[0]]);
          if (dstr.format('YYYY-MM-DD') != 'Invalid date') modDate = dstr;
          rowOff = 1;
        }
        else if (data[0]['DTM'] !== undefined) {
          notypes = true;
          var drow = data[0];
          var dstr = moment(drow['DTM']);
          if (dstr.format('YYYY-MM-DD') != 'Invalid date') modDate = dstr;
        }
        sheet = XLSX.utils.json_to_sheet(data);

      } else {
        var data = new Uint8Array(req.response);
        workbook = XLSX.read(data, { type: "array" });
        sheet = workbook.Sheets[workbook.SheetNames[0]];

        var dstr = moment(getT(nextCell));
        if (dstr.format('YYYY-MM-DD') != 'Invalid date') {
          modDate = dstr;
          rowOff = 1;
        } else if (workbook && workbook.Props) {
          dstr = moment(workbook.Props.ModifiedDate.toJSON());
          if (dstr.format('YYYY-MM-DD') != 'Invalid date') modDate = dstr;
        }
      }
      var range = XLSX.utils.decode_range(sheet['!ref']);
      var nextCell = sheet[XLSX.utils.encode_cell({
        r: range.s.r,
        c: range.s.c
      })];



      for (colNum = range.s.c; colNum <= range.e.c; colNum++) {
        nextCell = sheet[XLSX.utils.encode_cell({
          r: range.s.r + rowOff + 0,
          c: colNum
        })];

        if (notypes) {
          var h = getT(nextCell);
          switch (h.toLowerCase()) {
            case "abbname":
              tableColumn[tc] = types.length;
              tc++;
              headings.push('LGA');
              types.push('text');
              break;
            case "new_cases":
              tableColumn[tc] = types.length;
              tc++;
              headings.push('New Cases^');
              types.push('number');
              break;
            case "total_cases":
              tableColumn[tc] = types.length;
              tc++;
              headings.push('Total Cases');
              types.push('number');
              break;
            default:
              headings.push(h);
              types.push('hidden');
          }
        } else {
          headings.push(getT(nextCell));

          nextCell = sheet[XLSX.utils.encode_cell({
            r: range.s.r + rowOff + 1,
            c: colNum
          })];
          var ncv = getT(nextCell).toLowerCase();
          if (ncv.substr(0, 5) == 'group') {
            ncv = ncv.substr(6);
            if (ncv == "colour")
              GC = types.length;
            else {
              GROUP = types.length;
              if (ncv == '') ncv = 'text';
            }
          }
          if (ncv == "lat") LAT = types.length;
          if (ncv == "long") LNG = types.length;
          if (ncv == 'text' || ncv == 'number' || ncv == 'numeric' || ncv == 'currency' || ncv.substr(0, 4) == 'date' || ncv.substr(0, 4) == 'time' || ncv == 'phone' || ncv == 'email' || ncv == 'link') {
            tableColumn[tc] = types.length;
            tc++;
          }
          types.push(ncv);

          nextCell = sheet[XLSX.utils.encode_cell({
            r: range.s.r + rowOff + 2,
            c: colNum
          })];
          var f = getT(nextCell).toLowerCase();
          if (f == 'filter') hasFilterRow = true;
          filters.push(getT(nextCell).toLowerCase());
        }
      }
      if (hasFilterRow) rowOff++;
      if (notypes) rowOff--;

      for (rowNum = range.s.r + rowOff + 2; rowNum <= range.e.r; rowNum++) { // process data rows
        var row = [];
        for (colNum = range.s.c; colNum <= range.e.c; colNum++) {
          var nextCell = sheet[XLSX.utils.encode_cell({
            r: rowNum,
            c: colNum
          })];
          row.push(nextCell);
          if (nextCell === null) inc = false;
        }
        if (row[0] && (!notypes || getT(row[1]))) {
          listData.push(row);
          if (GROUP >= 0) {
            var t = getT(row[GROUP]);
            if (t && !groups[t]) {
              groups[t] = catColours[t] ? catColours[t] : (GC < 0 ? getThemeColour(groups) : getT(row[GC]));
            }
          }
        }
      }

      var optRow = function (obj) {
        return '<option value="' + obj + '">' + obj + '</option>';
      };

      function headRow() {
        var ret = '';
        for (var col in headings) {
          if (types[col] == 'text' || types[col] == 'number' || types[col] == 'numeric' || types[col].substr(0, 4) == 'date' || types[col].substr(0, 4) == 'time' || types[col] == 'phone' || types[col] == 'email' || types[col] == 'link')
            ret += '<th>' + headings[col] + '</th>';
        }
        return ret;
      }
      var dataRow = function (obj) {
        var res = '<tr>';
        for (var col = 0; col < obj.length; col++) {
          if (types[col] == 'text')
            res += '<td data-sort="' + getT(obj[col]).toLowerCase() + '"' + getLinkURL(obj[col]) + '>' + getRT(obj[col], 0) + '</td>';
          else if (types[col] == 'numeric')
            res += '<td data-sort="' + getN(obj[col]) + '">' + getND(obj[col], 2, '') + '</td>';
          else if (types[col] == 'number')
            res += '<td data-sort="' + getN(obj[col]) + '">' + getRT(obj[col], 0) + '</td>';
          else if (types[col] == 'currency')
            res += '<td data-sort="' + getN(obj[col]) + '">' + getND(obj[col], 2, '$') + '</td>';
          else if (types[col] == 'date')
            res += '<td data-sort="' + getDT(obj[col], "YYYY-MM-DD") + '">' + getDT(obj[col], "ddd D MMMM YYYY") + '</td>';
          else if (types[col] == 'datemonthyear')
            res += '<td data-sort="' + getDT(obj[col], "YYYY-MM-DD") + '">' + getDT(obj[col], "MMMM YYYY") + '</td>';
          else if (types[col] == 'datetime')
            res += '<td data-sort="' + getDT(obj[col], "YYYY-MM-DD HH:mm") + '">' + getDT(obj[col], "ddd D MMMM YYYY hh:mma") + '</td>';
          else if (types[col] == 'time')
            res += '<td data-sort="' + getDT(obj[col], "HH:mm") + '">' + getDT(obj[col], "hh:mma") + '</td>';
          else if (types[col] == 'date range' && types[col + 1] == 'rangeend')
            res += '<td data-sort="' + getDR(obj[col], obj[col + 1], "YYYY-MM-DD") + '" data-search="' + getDTA(obj[col], obj[col + 1], "YYYY-MM-DD") + '">' + getDR(obj[col], obj[col + 1], "ddd D MMMM YYYY") + '</td>';
          else if (types[col] == 'datetime range' && types[col + 1] == 'rangeend')
            res += '<td data-sort="' + getDT(obj[col], "YYYY-MM-DD HH:mm") + ' ' + getDT(obj[col + 1], "YYYY-MM-DD HH:mm") + '" data-search="' + getDTA(obj[col], obj[col + 1], "YYYY-MM-DD") + '">' + getDTR(obj[col], obj[col + 1], "ddd D MMMM YYYY", "hh:mma") + '</td>';
          else if (types[col] == 'time range' && types[col + 1] == 'rangeend')
            res += '<td data-sort="' + getDT(obj[col], "HH:mm") + ' ' + getDT(obj[col + 1], "HH:mm") + '">' + getTR(obj[col], obj[col + 1], "hh:mma", ' - ') + '</td>';
          else if (types[col] == 'phone')
            res += '<td data-sort="' + getT(obj[col]).toLowerCase() + '"><a href="tel:' + getT(obj[col]) + '">' + getRT(obj[col], 0) + '</a></td>';
          else if (types[col] == 'email')
            res += '<td data-sort="' + getT(obj[col]).toLowerCase() + '"><a href="mailto:' + getT(obj[col]) + '">' + getRT(obj[col], 0) + '</a></td>';
          else if (types[col] == 'link')
            res += '<td data-sort="' + getT(obj[col]).toLowerCase() + '">' + getH2Link(obj[col]) + '</td>';
        }
        return res + '</tr>';
      };
      var mapRow = function (obj) {
        var res = '';
        for (var col = 0; col < obj.length; col++) {
          if (types[col] == 'text')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getRT(obj[col], 0);
          else if (types[col] == 'numeric')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getND(obj[col], 2, '');
          else if (types[col] == 'number')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getRT(obj[col], 0);
          else if (types[col] == 'currency')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getND(obj[col], 2, '$');
          else if (types[col] == 'date')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getDT(obj[col], "ddd D MMMM YYYY");
          else if (types[col] == 'datemonthyear')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getDT(obj[col], "MMMM YYY");
          else if (types[col] == 'datetime')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getDT(obj[col], "ddd D MMMM YYYY hh:mma");
          else if (types[col] == 'time')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getDT(obj[col], "hh:mma");
          else if (types[col] == 'date range' && types[col + 1] == 'rangeend')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getDR(obj[col], obj[col + 1], "ddd D MMMM YYYY");
          else if (types[col] == 'datetime range' && types[col + 1] == 'rangeend')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getDTR(obj[col], obj[col + 1], "ddd D MMMM YYYY", "hh:mma");
          else if (types[col] == 'time range' && types[col + 1] == 'rangeend')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getTR(obj[col], obj[col + 1], "hh:mma", ' - ');
          else if (types[col] == 'phone')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + '<a href="tel:' + getT(obj[col]) + '">' + getRT(obj[col], 0) + '</a>';
          else if (types[col] == 'email')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + '<a href="mailto:' + getT(obj[col]) + '">' + getRT(obj[col], 0) + '</a>';
          else if (types[col] == 'link')
            res += '<br/><br/><b>' + headings[col] + '</b><br/>' + getH2Link(obj[col]);
        }
        return res.substr(10); // clear first two <br/>'s
      };
      if ($('#contentDataTable').length > 0) {
        var btnTop = '<a href="#maincontent"><button class="repeatable back-to-top-button" role="button" tabindex="0"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 31.5 31.5" style="enable-background:new 0 0 31.5 31.5;" xml:space="preserve"><path class="st1" d="M21.2,5c-0.4-0.4-1.1-0.4-1.6,0c-0.4,0.4-0.4,1.1,0,1.6l8,8H1.1c-0.6,0-1.1,0.5-1.1,1.1c0,0.6,0.5,1.1,1.1,1.1 h26.6l-8,8c-0.4,0.4-0.4,1.2,0,1.6c0.4,0.4,1.2,0.4,1.6,0l10-10c0.4-0.4,0.4-1.1,0-1.6L21.2,5z"></path></svg><span>Back to top</span></button></a>';
        var html = '<div class="media-release-results-header"><div class="datatable-controls"></div></div>';
        html += '<table><thead><tr>' + headRow() + '</tr></thead><tbody>' + listData.map(dataRow).join('') + '</tbody></table>' + btnTop;

        $('#contentDataTable').html(html);
        lt = $('#contentDataTable table').DataTable({
          columnDefs: [{
            targets: 1, type: 'html' 
          }],
          dom: 'Brtip',
          lengthChange: false,
          pageLength: 25,
          responsive: {
            details: {
              display: $.fn.dataTable.Responsive.display.childRowImmediate,
              type: 'none',
              target: ''
            }
          },
          buttons: [{
            extend: 'excelHtml5',
            filename: dataListTitle + '  ' + modDate.format("YYYY-MM-DD HH.mm"),
            title: dataListTitle,
            messageTop: modDate.format("ddd D MMMM YYYY  hh:mma"),
          },
          {
            extend: 'pdfHtml5',
            filename: dataListTitle + '  ' + modDate.format("YYYY-MM-DD HH.mm"),
            title: dataListTitle,
            messageTop: modDate.format("ddd D MMMM YYYY  hh:mma"),

            exportOptions: {
              format: {
                body: function(inner, rowidx, colidx, node) {
                  return inner;
                }
              }
            },

            customize: function(doc) {
              if (dataListTitle){
                var table = doc.content[2].table.body;
              } else {
                var table = doc.content[1].table.body;
              }
              table.forEach(function(row) {
                row.forEach(function(cell) {
                  var tableData = cell.text;
                  if (tableData.includes('href')) {
                    var linkTitle = $(tableData).text();
                    var linkUrl = $(tableData).attr('href');
                    cell.text = linkTitle;
                    cell.link = linkUrl;
                    cell.color = '#3A75D3';
                    cell.decoration = 'underline';
                  }
                });
              });
            }
          }
          ],
        });

        var filterCount = 0;
        var dataTableSearch = $('#dataTableSearch').length;
        
        if(dataTableSearch) {
          $('#dataTableSearch').on( 'keyup', function () {
            lt.search( this.value ).draw();
          });
        }

        lt.columns().flatten().each(function (colIdx) {
          var col = tableColumn[colIdx];
          if (filters[col] == 'filter' && !dataTableSearch || (colIdx == 0 && !hasFilterRow && !dataTableSearch)) {
            filterCount++;
            var p = $('<div class="datatable-control-input"><label>Search by ' + plural(headings[col], true) + '</label></div>').appendTo($('.datatable-controls'));
            /* get column type */
            if ((types[col].substr(0, 4) == 'date' && types[col] !== 'datemonthyear')) {
              var d = $('<input placeholder="All ' + plural(headings[col], false) + '" data-col="' + colIdx + '" class="au-text-input au-text-input--block pac-target-input filter"/>').appendTo(p)
                .on('change', function () {
                  var key = $(this).val();
                  if (key) key = moment(key, "ddd D MMMM YYYY").format("YYYY-MM-DD");
                  lt.column(colIdx).search(key).draw();
                });
              var dt = new DateTime(d[0], {
                format: 'ddd D MMMM YYYY',
                buttons: {
                  today: false,
                  clear: true
                }
              });
            } else {
              var s = $('<select data-col="' + colIdx + '" class="au-select au-select--block category filter"/>').appendTo(p)
                .on('change', function () {
                  var key = $.fn.dataTable.util.escapeRegex($(this).val());
                  if (key) lt.column(colIdx).search('^' + key + '$', true, false).draw();
                  else lt.column(colIdx).search('').draw();
                });
              s.append($('<option value="">All ' + plural(headings[col], false) + '</option>'));
              if ((types[col] == 'datemonthyear')) {
                lt.column(colIdx).cache('search').unique().each(function (d) {
                  s.append($('<option value="' + d + '">' + d + '</option>'));
                });
              }
              else {
                lt.column(colIdx).cache('search').sort().unique().each(function (d) {
                  s.append($('<option value="' + d + '">' + d + '</option>'));
                });
              }
            }
          }
        });

        if (filterCount > 0) {
          var clear = $('<div class="datatable-control-input clear"><a href="#">Show&nbsp;All</a></div>').appendTo($('.datatable-controls')).children('a')
            .on('click', function () {
              $('.datatable-controls .filter').each(function () {
                var colIdx = $(this).data('col');
                lt.column(colIdx).search('').draw();
                $(this).val('');
              });
              return false;
            });
        }

        $.fn.DataTable.ext.pager.numbers_length = 5;

        $('.dt-buttons').append("<div class='dtLastUpdate'>Last updated: " + modDate.format("ddd D MMMM YYYY hh:mma") + "</div>");

        // Handle scrolling on paging
        $(document).scroll(function () {
          dtOff = $('.dataTables_paginate').offset().top - $(document).scrollTop();
        });
        $(document).on('click', '.paginate_button', function () {
          $(document).scrollTop($('.dataTables_paginate').offset().top - dtOff);
        });

        if($('.hide-excel-export').length > 0) {
          $('.buttons-excel').hide();
        }
      }

      /* Data Map START */
      if ($('#contentDataMap').length > 0 && LAT >= 0 && LNG >= 0) {
        lmfeatures = [];
        listData.forEach(function (row, i) {
          if (getT(row[LNG]) !== '' && getN(row[LNG]) != 0 &&
            getT(row[LAT]) !== '' && getN(row[LAT]) != 0) {
            var res = mapRow(row);
            var feature = new ol.Feature({
              geometry: new ol.geom.Point(ol.proj.fromLonLat(getUniqueLngLat(row[LNG], row[LAT]))),
              popup: res,
              color: (GROUP >= 0 && groups[getT(row[GROUP])]) ? groups[getT(row[GROUP])] : defaultColours[0],
            });
            if (res) lmfeatures.push(feature);
          }
        });

        // Popup overlay
        var popup = new ol.Overlay.Popup({
          popupClass: "default",
          closeBox: true,
          positioning: 'auto',
          autoPan: true,
          autoPanAnimation: {
            duration: 250
          }
        });

        // Cluster
        var source = new ol.source.Vector({
          features: lmfeatures,
        });
        var clusterSource = new ol.source.Cluster({
          source: source,
          distance: 50,
          minDistance: 50,
        });
        var styleCache = {};
        var lmSites = new ol.layer.Vector({
          source: clusterSource,
          style: function (feature) {
            var size = feature.get('features').length;
            if (size == 1) {
              var f = feature.get('features')[0];
              return new ol.style.Style({
                image: new ol.style.Icon({
                  anchor: [0.5, 1],
                  src: getMapIcon(f.get('color'), 'FFFFFF')
                })
              });
            }
            var style = styleCache[size];
            if (!style) {
              style = new ol.style.Style({
                image: new ol.style.Circle({
                  radius: 24,
                  stroke: new ol.style.Stroke({
                    color: '#FFFFFF',
                  }),
                  fill: new ol.style.Fill({
                    color: '#' + themePrimary,
                  }),
                }),
                text: new ol.style.Text({
                  text: size.toString(),
                  fill: new ol.style.Fill({
                    color: '#' + themeOnPrimary,
                  }),
                  font: '18px proxima-nova',
                  offsetY: 1,
                  offsetX: 1
                }),
              });
              styleCache[size] = style;
            }
            return style;
          },
        });

        var lmMap = new ol.layer.Tile({
          source: new ol.source.OSM()
        });
        lm = new ol.Map({
          layers: [
            lmMap,
            lmSites
          ],
          target: 'contentDataMap',
          view: new ol.View({
            center: [0, 0],
            zoom: 1
          }),
          overlays: [popup]
        });

        if ($('#contentDataMap.showLegend').length > 0) {
          // Define a new legend
          var legend = new ol.legend.Legend({
            title: GROUP < 0 ? dataListTitle : headings[GROUP],
            style: new ol.style.Style({
              image: new ol.style.Icon({
                anchor: [0.5, 1],
                src: getMapIcon(themePrimary, 'FFFFFF')
              })
            })
          });
          var legendCtrl = new ol.control.Legend({
            legend: legend,
            collapsed: false
          });
          lm.addControl(legendCtrl);
          var otp = []; $('.page-contents-list a').each(function () { otp.push(this.text.trim().toLowerCase()); });
          Object.keys(groups).sort(function (a, b) {
            a = a.toLowerCase(); b = b.toLowerCase();
            var ka = otp.indexOf(a); var kb = otp.indexOf(b);
            if (ka == kb) return a > b ? 1 : -1;
            if (ka < 0) return -1;
            if (kb < 0) return 1;
            return ka > kb ? 1 : -1;
          }).forEach(function (g) {
            legend.addItem({
              title: g,
              typeGeom: 'Point',
              style: new ol.style.Style({
                image: new ol.style.Icon({
                  anchor: [0.5, 1],
                  src: getMapIcon(groups[g], 'FFFFFF')
                })
              })
            });
          });
        }
        var layerExtent = ol.extent.boundingExtent(
          lmfeatures.map(function (r) { return r.getGeometry().getCoordinates() })
        );
        // var layerExtent = lmSites.getSource().getExtent();
        if (layerExtent && lmfeatures.length > 0)
          lm.getView().fit(layerExtent, {
            padding: [60, 40, 50, 60]
          });

        // Control Select 
        var select = new ol.interaction.Select({
          style: null
        });
        lm.addInteraction(select);


        // hover hand
        lm.on('pointermove', function (e) {
          var pixel = lm.getEventPixel(e.originalEvent);
          var hit = lm.hasFeatureAtPixel(pixel);
          lm.getViewport().style.cursor = hit ? 'pointer' : '';
        });

        var maxZoom = 20;
        lm.on('click', function (e) {
          lmSites.getFeatures(e.pixel).then(function (clickedFeatures) {
            if (clickedFeatures.length) {
              // Get clustered Coordinates
              var features = clickedFeatures[0].get('features');
              if (features.length > 1 && lm.getView().getZoom() < maxZoom) {
                var extent = ol.extent.boundingExtent(
                  features.map(function (r) {
                    return r.getGeometry().getCoordinates()
                  })
                );
                lm.getView().fit(extent, {
                  duration: 500,
                  maxZoom: maxZoom,
                  padding: [60, 40, 50, 80]
                });
              } else {
                var popupText = '';
                features.forEach(function (f, index) {
                  popupText += '<div class="note" style="border-color: #' + f.get('color') + '; margin: 4px 0; padding: 12px">';
                  if (features.length > 1) popupText += '<h4 style="margin:-8px -8px 0 0;color:#616161; text-align:right">' + (index + 1) + ' of ' + features.length + '</h4>';
                  popupText += f.get("popup") + '</div>';
                });
                popup.show(features[0].getGeometry().getFirstCoordinate(),
                  '<div style="max-height:350px; max-width:360px; padding:0 4px 0 0; overflow-y:auto">' + popupText + '</div>');
                $('.ol-popup.default>div').css('border', 'none').css('background', 'rgba(0,0,0,0.3)');
                $('.ol-popup.default .anchor').remove();
              }
              clickedFeatures[0]
            } else {
              popup.hide();
            }
          });
        });

        /* Gray map */
        var lmFilter = new ol.filter.Colorize();
        lmMap.addFilter(lmFilter);
        /* Data Map END*/
      }
    }
    req.send();
  }
  /* Data Map/Table END */

  /* Carousel */
  if ($(".intranet .owl-carousel").length > 0) {
    $(".owl-carousel").owlCarousel({
      loop: true,
      dots: true,
      margin: 10,
      nav: true,
      items: 1
    });
  }
  else if ($(".owl-carousel").length > 0) {
    $('.card-carousel .owl-carousel').owlCarousel({
        dots: false,
        loop: false,
        margin: 16,
        items: 1,
        stagePadding: 0,
        rewind: true,
        nav: true,
        navText: ["<div class='owl-prev arrow-right'><i class='fa fa-arrow-left' aria-hidden='true'></i></div>", "<div class='owl-next'><i class='fa fa-arrow-right' aria-hidden='true'></i></div>"],
        responsive:{
            768:{
                items:2,
                loop: ($(this).find('.owl-item').length > 2)
            },
            992:{
                items:3,
                loop: ($(this).find('.owl-item').length > 3)
            }
        }
    });
    $('.video-card-carousel .owl-carousel, .video-content-grid .owl-carousel').owlCarousel({
        dots: false,
        loop: false,
        margin: 24,
        items:1,
        nav: true,
        navText: ["<div class='owl-prev arrow-right'><i class='fa fa-arrow-left' aria-hidden='true'></i></div>", "<div class='owl-next'><i class='fa fa-arrow-right' aria-hidden='true'></i></div>"],
    });
  }
  $('.card-pager').click(function(){
    var p = $(this).parent();
    p.toggleClass('page-2');
  });

  $('.accord h2 button, .accord h3 button, .accord h4 button').click(function(){
    var p = $(this).closest('.accord');
    p.toggleClass('close');
  });
  $('.sidebar-siblings h3 button').click(function(){
    var p = $(this).closest('.sidebar-siblings');
    p.toggleClass('close');
  });
});

/* Picklist search */
function picklistSearch() {
  userInput = $('.picklist .picklist-search').val();
  $('.picklist .content-items a').each(function() {
    if(~$(this).attr('data-title').toLowerCase().indexOf(userInput.toLowerCase())) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
}

/* Sort in this section list */
var thisSectionList = $('.this-section-sort');
thisSectionList.children().sort(function (a, b) {
  return ($(a).text().toLowerCase()) > ($(b).text().toLowerCase()) ? 1 : -1;
}).appendTo(thisSectionList);

/* Scroll to and open accordions */
$(document).on("click", ".accordion-link", function(){
  if (this.hash) {
    event.preventDefault();
    var hash = this.hash;
    $('html, body').animate({
      scrollTop: $(hash).offset().top
    }, 600);
    var accordion = $(hash + '.accord');
    $(accordion).removeClass('close');
    window.location.hash = hash;
  }
});

/* Clickable related list items */
$(".article-list-item--tab").click(function() {
  window.location = $(this).find("a").attr("href");
  return false;
});