This is a wiki for a reason. Anyone can contribute. If you see something that is inaccurate or can be improved, don't ask that it be fixed--just improve it.
[ Disclaimer, Create new user --- Wiki markup help, Install P99 ]

Difference between revisions of "MediaWiki:LocMaps.js"

From Project 1999 Wiki
Jump to: navigation, search
 
(89 intermediate revisions by one user not shown)
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
+
try {
 +
  (function() {
  
importScript('MediaWiki:Polyfills.js');
+
    var buildImgFromFileName = function(fileName) {
importScript('MediaWiki:Zones.js');
+
      return '<img src="/images/' + fileName.replace(/ /g, '_') + '">'
 +
    };
  
/* p1999wiki.js
+
    // TODO: Add support for cropping maps that have multiple maps.
* written by http://wiki.project1999.com/User:Ravhin
+
    // For instance, the following CSS styles show only one of the three maps for
* last update: 7 January, 2018 by Loramin
+
    // Erudin Palace:
*/
+
    // background-image:url(/images/Erudinpalace.jpg);  
$(function() {
+
    // background-position: 250px 0px; width: 275px; height: 272px
  var hideDelay = 0;
+
    // Figure out how to make the Xs line up with those styles added
  var trigDelay = 250;
+
  var hideTimer = null;
+
  var ajax = null;
+
  
  var currentPosition = { left: '0px', top: '0px' };
+
    var locIsWithinAlternateData = function(loc, alternateData) {
 +
      return loc.x < alternateData.maxX &&
 +
      loc.x > alternateData.minX &&
 +
      loc.y < alternateData.maxY &&
 +
      loc.y > alternateData.minY;
 +
    };
  
  // One instance that's reused to show info for the current person
 
  var container = $('<div id="itemHoverContainer">'
 
    + '<div id="HoverContent"></div>'
 
    + '</div>');
 
  
  $('body').append(container);
+
    /**
 +
    * Determines if the provided name contains any of the provided words
 +
    */
 +
    // TODO: Add a some polyfill to make this a lot simpler
 +
    var containsAny = function(name/* word1, word2, etc. */) {
 +
      for(var arg = 1; arg < arguments.length; ++ arg) {
 +
        var word = arguments[arg];
 +
        if (name.includes(word)) return true;
 +
      }
 +
      return false;
 +
    };
  
/* --- hoverbox for item/mob, currently only used in magelo --- */
+
    var containsAnyNumber = function(name, number, suffix) {
 +
      return containsAny.call(null, name,
 +
      number + suffix,
 +
      'level ' + number,
 +
      'level: ' + number,
 +
      'floor ' + number,
 +
      'floor: ' + number
 +
      );
 +
    };
  
  // Determine which "a" elements should trigger the item stats mouseover
+
    var getZoneLevelData = function(zone, text) {
  var $mouseoverTargets = $('span.ih a');
+
      var levels = zone.levels;
  var isItemCategory = document.title.startsWith('Category:') && document.title.includes('Equipment - Project 1999 Wiki') &&
+
      // Check for part "level" aliases (eg. "1st floor" vs. "Level One")
                      !document.title.includes('Worshiper Equipment');
+
      text = text.toLowerCase();
  if (isItemCategory) {
+
      if(levels['3'&& levels['3'].image.includes('crystal')) {
    // Include the category's item list along with ".ih" links
+
        // Special case for Crystal Caverns
    $mouseoverTargets = $mouseoverTargets.add('.mw-content-ltr a');
+
        if (containsAny(text, 'upper')) return levels[3];
  }
+
        if (containsAny(text, 'lower')) return levels[2];
 +
        if (containsAny(text, 'town', 'coldain')) return levels[0];
 +
      }
  
  $mouseoverTargets = $mouseoverTargets.filter(function(i, a) {
+
      // In most zones "tunnel" = level 0. But in Kurn's there are two level zeroes (tunnels and basement),
    // Don't add hover to links like "next 200"
+
      // so this next line handles the Kurn's case in particular
    return !$(a).attr('href').startsWith('/Special:') &&
+
      if (containsAny(text, 'tunnel') && levels.tunnels) return levels.tunnels;
          !$(a).attr('href').includes('title=Category:')
+
  });
+
  
  $mouseoverTargets.on('mouseover', function()
+
      if (containsAnyNumber(text, 0, 'th') || containsAny(text, 'basement', 'underground', 'tunnel', 'bear pit', 'bear pits', 'cave', 'caves')) return levels[0];
  {
+
      if (containsAnyNumber(text, 1, 'st') || containsAny(text, 'one', 'first', 'ground')) return levels[1];
    var $this = $(this);
+
      if (containsAnyNumber(text, 2, 'nd') || containsAny(text, 'two', 'second')) return levels[2];
    var itemname = $this.attr('title');
+
      if (containsAnyNumber(text, 3, 'rd') || containsAny(text, 'three', 'third')) return levels[3];
 +
      if (containsAnyNumber(text, 4, 'th') || containsAny(text, 'four', 'fourth')) return levels[4];
 +
      if (containsAnyNumber(text, 5, 'th') || containsAny(text, 'five', 'fifth')) return levels[5];
  
    if (itemname == '' || itemname == 'undefined')
+
      // Special case for Tower of Frozen Shadow, which has two level 6 maps
       return;
+
      if (containsAny(text, '6a')) return levels['6A'];
 +
       if (containsAny(text, '6b')) return levels['6B'];
  
    if (hideTimer)
+
      if (containsAnyNumber(text, 6, 'th') || containsAny(text, 'six', 'sixth')) return levels[6];
       clearTimeout(hideTimer);
+
       if (containsAnyNumber(text, 7, 'th') || containsAny(text, 'seven', 'seventh')) return levels[7];
 +
      if (containsAnyNumber(text, 8, 'th') || containsAny(text, 'eight', 'eighth')) return levels[8];
 +
      if (containsAnyNumber(text, 9, 'th') || containsAny(text, 'nine', 'ninth')) return levels[9];
  
    if ($this.parents('div.mw-content-ltr').length) {
+
       var levelKeys = Object.keys(levels);
       var pos = $this.offset();
+
       var keyOfLastLevel = levelKeys[levelKeys.length - 1];
       var width = $this.width();
+
      if (containsAny(text, 'top')) return levels[keyOfLastLevel];
  
       container.css({
+
       // If we still couldn't match, and there is a ground/1st floor, use it
          left: pos.left + 5 + 'px',
+
       return levels[1];
          top: pos.top + 5 + 'px'
+
     };
       });
+
     }
+
  
 +
   
  
 +
    var findZoneData = function(zoneName, locs, nonLocParts) {
 +
      // Convert someZone (East) to East someZone
 +
      if (zoneName.trim().endsWith(')')) {
 +
        try {
 +
          var nameSplit = zoneName.split('(');
 +
          var newName = nameSplit[0].trim();
 +
          var direction = nameSplit[1].split(')')[0].trim();
 +
          if (['east', 'north', 'south', 'west'].includes(direction.toLowerCase())) {
 +
            zoneName = direction + ' ' + newName;
 +
          }
 +
        } catch(err){ /* just use name (it likely won't work, but try) */}
 +
      }
  
    $(this).trigger('mousemove');
+
      var zone = zoneData[zoneName];
  
    $('#itemHoverContent').html('&nbsp;');
+
      // Handle aliases (eg. "North Ro" instead of "Northern Desert of Ro")
 +
      if (typeof(zone) === 'string') zone = zoneData[zone];
  
    //$('#itemHoverContent').html('<div class="itemtopbg"><div class="itemtitle">Loading...</div></div>'
+
      if (!zone) return null;
    //                          + '<div class="itembg" style="min-height:50px;"><div class="itemdata">'
+
    //                          + '<div class="itemicon" style="float:right;"><img alt="" src="/images/Ajax_loader.gif" border="0"></div>'
+
    //                          + '<p></p></div></div><div class="itembotbg"></div>');
+
  
    if (ajax)
+
       // Handle Multi-Level Zones (with different maps for 1st, 2nd, etc. floor)
    {
+
       if (zone.levels) {
       ajax.abort();
+
         var levelOfZone = getZoneLevelData(zone, nonLocParts);
      ajax = null;
+
         return levelOfZone;
    }
+
    ajax = $.ajax({
+
      url: window.location.protocol +
+
          '//wiki.project1999.com/index.php/Special:AjaxHoverHelper/' + itemname,
+
      cacheResponse: true,
+
       success: function(html)
+
      {
+
         var $html = $(html);
+
         $('#itemHoverContent').html($html[2]).prepend($html[0]).prepend($html[1]);
+
 
       }
 
       }
    });
 
  
    container.css('display', 'block');
+
      // Handle Zones with alternate maps on the same level (eg. Kelethin in GFay)
    //container.fadeIn('fast');
+
      if (!zone.alternateMaps) return zone;
  
  }); //on mouseover
+
      for (var i = 0; i < zone.alternateMaps.length; i++) {
 +
        var alternateData = zone.alternateMaps[i];
 +
        var allLocsAreWithin = true;
 +
        // wish I had ES6 [].every
 +
        $.each(locs, function(i, loc) {
 +
          allLocsAreWithin = allLocsAreWithin &&
 +
          locIsWithinAlternateData(loc, alternateData);
 +
        });
 +
        if (allLocsAreWithin) return alternateData;
 +
      };
 +
      return zone;
 +
    };
  
   $('span.ih a').on('mouseout', function()
+
   var addImageUrl = function(zoneData) {
  {
+
     zoneData.imageUrl = '/images/' + zoneData.image;
     if (hideTimer)
+
     return zoneData;
      clearTimeout(hideTimer);
+
   };
    hideTimer = setTimeout(function()
+
    {
+
      container.css('display', 'none');
+
      //container.fadeOut('fast');
+
     }, hideDelay);
+
   });
+
  
   $('span.ih a').mousemove(function(e){
+
   var getZoneData = function(zoneName, locs, nonLocParts) {
     var mousex = e.pageX + 20; //Get X coodrinates
+
     var zoneData = findZoneData(zoneName, locs, nonLocParts);
     var mousey = e.pageY + 20; //Get Y coordinates
+
     if (!zoneData) return null;
     var tipWidth = container.width(); //Find width of tooltip
+
     zoneData.zoneName = zoneName;
     var tipHeight = container.height(); //Find height of tooltip
+
     return addImageUrl(zoneData);
 +
  };
  
    //Distance of element from the right edge of viewport
+
     var build$MapImage = function(zoneData) {
     var tipVisX = $(window).width() - (mousex + tipWidth);
+
      return $(
     //Distance of element from the bottom of viewport
+
        '<img alt="Map of ' + zoneData.zoneName + '" ' +
     var tipVisY = $(window).height() - (mousey + tipHeight);
+
        '     class="thumbborder" ' +
 +
        '     height="'+ zoneData.height + '" ' +
 +
        '    src="' + zoneData.imageUrl + '" ' +
 +
        '    title="Map of ' + zoneData.zoneName + '"' +
 +
        '    width="' + zoneData.width + '" ' +
 +
        '>'
 +
        );
 +
    };``
  
     if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
+
     var build$XContainer = function() {
 +
      return $('<div class="x-container" style="position: relative"></div>');
 +
    }
  
      if( tipWidth > e.pageX - 20 ){
+
   
        mousex = 0;
+
    var build$LightboxFramedMap = function(zoneData) {
       } else {
+
       var $map = build$XContainer().append(build$MapImage(zoneData));
        mousex = e.pageX - tipWidth - 20;
+
       return addFramingStyles($map, zoneData.width, zoneData.height)
       }
+
    };
  
     } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
+
     var addFramingStyles = function($el, width, height) {
       mousey = e.pageY - tipHeight - 20;
+
       return $el.css({
 +
          left: '50%',
 +
          marginLeft: '-' + (width / 2) + 'px', // centering
 +
          marginTop: '-' + (height / 2) + 'px',
 +
          opacity: 1,
 +
          top: '50%'
 +
        });
 
     }
 
     }
  
     container.css({ top: mousey, left: mousex });
+
     var build$AbsolutePositionFrame = function() {
  });
+
      return $('<div style="position: absolute"></div>');
 +
    };
  
  // Allow mouse over of details without hiding details
+
    var removeOpenImage = function(e) {
  $('#itemHoverContainer').mouseover(function()
+
      // Do nothing if there's no open map
  {
+
       if (!window.$openImg) return false;
    if (hideTimer)
+
       clearTimeout(hideTimer);
+
  });
+
  
  // Hide after mouseout
+
      // Do nothing if the user clicked to open a map, then moused out of an area
  $('#itemHoverContainer').mouseout(function()
+
       // (otherwise it can close immediately)
  {
+
      var position = window.$openImg.css('position');
    if (hideTimer)
+
       if (e && e.type === 'mouseleave' && position === 'fixed') return false;
       clearTimeout(hideTimer);
+
    hideTimer = setTimeout(function()
+
    {
+
      container.css('display', 'none');
+
       //container.fadeOut('fast');
+
    }, hideDelay);
+
  });
+
  
  // magelo non-ajax item hover, but move box with mouse
+
      window.$openImg.remove();
  $('.magelohb').mousemove(function(e){
+
      return false;
     var childContainer = $(this).children('span.hb');
+
     }
  
    var tipWidth = childContainer.width(); //Find width of tooltip
 
    var tipHeight = childContainer.height(); //Find height of tooltip
 
  
     var mousex = e.pageX + 20; //Get X coodrinates
+
     var build$FullScreenFrame = function() {
    var mousey = e.pageY + 20; //Get Y coordinates
+
      return build$AbsolutePositionFrame()
 +
        .css({
 +
          background: 'rgba(0,0,0,0.8)',
 +
          height: '100%',
 +
          left: 0,
 +
          position: 'fixed',
 +
          top: 0,
 +
          width: '100%',
 +
          zIndex: 4 // one higher than #p-search's 3
 +
        })
 +
        .click(removeOpenImage);
 +
    }
  
    //Distance of element from the right edge of viewport
+
     var build$FullMap = function(zoneData) {
     var tipVisX = $(window).width() - (mousex + tipWidth - 20);
+
      var $frame = build$FullScreenFrame();
    //Distance of element from the bottom of viewport
+
      if (zoneData) {
    var tipVisY = $(window).height() - (mousey + tipHeight - 20);
+
        $frame.html(build$LightboxFramedMap(zoneData));
 +
        $frame.zoneData = zoneData;
 +
      }
 +
      return $frame;
 +
    };
  
     if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
+
     var build$SmallMap = function(zoneData) {
 +
      return build$AbsolutePositionFrame().append(
 +
        build$XContainer().append(
 +
          build$MapImage(zoneData)));
 +
    }
  
      if( tipWidth > e.pageX - 20){
+
  var baseXFontSizeInEm = 2;
        mousex = 0;
+
      } else {
+
        mousex = e.pageX - tipWidth - 20;
+
      }
+
  
     } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
+
  var buildX = function(left, top, sizeInEm) {
       mousey = e.pageY - tipHeight - 20;
+
     sizeInEm = sizeInEm || baseXFontSizeInEm;
 +
    return $('<div class="x">x</div>')
 +
      .css({
 +
        color: 'red',
 +
        fontSize: sizeInEm + 'em',
 +
        fontWeight: 'bold',
 +
        left: left,
 +
        position: 'absolute',
 +
        top: top
 +
      })
 +
  }
 +
 
 +
  /**
 +
  * Draws a red "X" on the map at the provided coordinate
 +
  */
 +
  var addX = function($xContainer, zoneData, x, y, xSize) {
 +
    var left = (zoneData.zeroX || 0) + x * -1 * (zoneData.zoomX || 0.1);
 +
    var top = (zoneData.zeroY || 0) + y * -1 * (zoneData.zoomY || 0.1);
 +
    $xContainer.append(buildX(left, top, xSize));
 +
  }
 +
 
 +
  var addXs = function($xContainer, zoneData, locs, xSize) {
 +
    $.each(locs, function(i, loc) {
 +
       addX($xContainer, zoneData, loc.x, loc.y, xSize);
 +
    });
 +
  }
 +
 
 +
 
 +
  var parseLoc = function(locText) {
 +
    if (typeof locText !== 'string') return locText;
 +
    try {
 +
        var match = locText.match(/\(? *([\+\-]?\d+\.?\d*)\s*, *([\+\-]?\d+\.?\d*)\)?/);
 +
        return {x: parseFloat(match[2]), y: parseFloat(match[1]) };
 +
    } catch (err) {
 +
        return locText;
 
     }
 
     }
 +
  }
  
    childContainer.css({ top: mousey, left: mousex, 'z-index':'999' });
+
  var isLoc = function(locBit) {
  });
+
      // If we can't split the string by its comma and find a number on either side, it's not a loc
 +
      try {
 +
        return locBit.split(',')[0].match(/\d+/) && locBit.split(',')[1].match(/\d+/);
 +
      } catch (err) {
 +
        return false;
 +
      }
 +
    }
  
  // change to position:fixed on all hover divs if we have JS active
+
    /**
  // otherwise leave as position:absolute so the stationary hovers are near their items
+
    * Helper function to power parseLocs/extractNonLocText, since they both use
  $('.magelohb span.hb').each(function(i) {
+
    * the same logic.
    $(this).css({'position':'fixed'});
+
    *
  });
+
    * SIDE NOTE: If only the wiki didn't have to use 1999 JS, and could
 +
    *            destructure return values with ES2015, the two related functions
 +
    *            wouldn't even need to exist :(
 +
    */
 +
    var parseLocString = function(locString) {
 +
      var nonLocParts = '';
 +
      // Old regex (failed to match Undead Legionaires loc on TT page, but keeping it around unless
 +
      // the new regex has issues
 +
      //var bits = locString.split(/([\+\-]?\d+\.?\d*[^0-9\)]*,\D*[\+\-]?\d+\.?\d*)/g);
 +
      var bits = locString.split(/([\+\-]?\d+\.?\d*\s*,\D*[\+\-]?\d+\.?\d*)/g);
 +
      var relevantBits = bits.filter(function(part) {
 +
        // Filter out the non-loc parts, but save them
 +
        if (isLoc(part)) return true;
 +
        nonLocParts += part; // save as it might be something like "1st floor"
 +
      });
 +
      var locs = relevantBits.map(parseLoc);
 +
      return [locs, nonLocParts];
 +
    };
  
  // Chrome no longer displays alt text when an image is hovered over.  However the wiki only has
+
    /**
   // alt attributes for images, not titles.  This fixes that by converting alt => title
+
    * Extracts all of the locs (objects with x and y properties) from a provided
   $('img[alt]').each(function (i, img) {
+
    * string such as:
    $(img).attr('title', $(img).attr('alt'));
+
    *   "500, 200"
  });
+
    *   "(200, 300), (300, 200)"
 +
    * and returns an array containing any locs found.
 +
    */
 +
    var parseLocs = function(locString) {
 +
      return parseLocString(locString)[0];
 +
    };
 +
   
 +
    /**
 +
    * Extracts the non-loc parts (eg. "Level 1") from a provided string of text
 +
    * (presumably from an NPC's location <td> or somewhere similar). Although not
 +
    * actually a part of the loc, this text may still be useful in determining
 +
    * which map to show for the loc.
 +
    */
 +
    var extractNonLocText = function(locString) {
 +
      return parseLocString(locString)[1];
 +
    };
  
  // Fashion for item pages
+
 
  var extractFashionHtml = function(html) {
+
    var showImage = function($img, $container) {
    return $(html).find('.fashion_show, .primary_secondary_show').map(function(i, el) {
+
      if ($container) {
      var $el = $(el);
+
        $img.css({ marginTop: 40 });
      var data = $el.data();
+
        var isAboveHalf = $container.position().top < ($('body').height() / 2);
      data.race = $el.find('.fashion_race').html();
+
        var isLeftOfHalf = $container.position().left < ($('body').width() / 2);
      if ($el.is('.fashion_show')) {
+
        $container.css('position', 'relative')
         data.armor = $el.find('.fashion_armor').html();
+
                  .prepend($img);
 +
         $img.css({
 +
          [isAboveHalf  ? 'top' : 'bottom']: '1.5em',
 +
          [isLeftOfHalf  ? 'left' : 'right']: '1.5em'
 +
        });
 +
        // TODO: Now, check if the map image is off the page, and if so by how much?
 +
        //      Add/subtract that much from the top/left/bottom/right to make sure
 +
        //      the whole map is shown ... but also make sure the link itself isn't covered
 
       }
 
       }
       return data;
+
       else $('body').append($img);
    }).toArray();
+
  };
+
 
+
  var getFashionShows = function(fashionCategory) {
+
    var url = 'http://wiki.project1999.com/Category:Fashion: ' + fashionCategory;
+
    return $.get(url).then(extractFashionHtml);
+
  };
+
  
  var getItemPageShows = function() {
+
       window.$openImg = $img;
    var fashionCategories =
+
      return $img;
       $('#catlinks li a')
+
    };
        .map(function(i, a) { return $(a).text(); })
+
        .filter(function(i, text) { return text.startsWith('Fashion:'); })
+
        .map(function(i, text) { return text.substr('Fashion: '.length); });
+
    var fashion = fashionCategories[0];
+
    if (!fashion) return $.when();
+
  
     var tint = fashionCategories[1];
+
     /**
    return getFashionShows(fashion).then(function(shows) {
+
    * Adds a loc map image to the page.
       var sameTint = [];
+
    */
       var otherTint = [];
+
    var showMapWithLocs = function(zoneData, locs, $container) {
       shows.forEach(function(show) {
+
       removeOpenImage();
        // Primary/secondary slots have no tint
+
     
        if (show.primaryFashion || show.secondaryFashion) sameTint.push(show);
+
      zoneData = addImageUrl(zoneData);
        else (show.tint === tint ? sameTint : otherTint).push(show);
+
       var $map = $container ? build$SmallMap(zoneData) : build$FullMap(zoneData);
 +
 
 +
       var $xContainer = $map.find('.x-container');
 +
      var xSize = baseXFontSizeInEm;
 +
      if (locs.length > 5) xSize = 0.8 * baseXFontSizeInEm;
 +
      if (locs.length > 15) xSize = 0.5 * baseXFontSizeInEm;
 +
      $map.find('img').load(function() {
 +
        addXs($xContainer, zoneData, locs, xSize);
 
       });
 
       });
       return { matches: sameTint, otherTint: otherTint, fashion: fashion, tint: tint };
+
       return showImage($map, $container);
     });
+
     };
  }
+
 
  var addFashionSection = function() {
+
    var mapIconHtml = '<img ' +
    getItemPageShows().then(function(pageShows) {
+
      'alt="Map Icon.png" ' +
    if(!pageShows || !pageShows.matches) return;
+
      'height="12" ' +
    // Build fashion section
+
      'src="/images/thumb/Map_Icon.png/12px-Map_Icon.png" ' +
      var lis = pageShows.matches.map(function(show) {
+
      'width="12">';
         return '<li class="fashion-link" data-file="' + show.file +'">' +
+
    var addLocLinksToTable = function($table, sharedZone, zoneColumnIndex) {
                '<a href="#">' + show.gender + ' ' + show.race + '</a></li>';
+
      var areaColumnIndex = $table.find('th:contains("Area"), th:contains("Location")').index();
 +
      var locationColumnIndex =
 +
        $table.find('th:contains("Location"), th:contains("Loc")').index();
 +
     
 +
 
 +
      $table.find('tr').each(function(i, tr) {
 +
        var $tr = $(tr);
 +
        var $loc = $tr.find('td:eq(' + locationColumnIndex + ')');
 +
        var loc = $loc.text().trim();
 +
        if (!isLoc(loc)) return; // Non-loc text (eg. "Various") in loc column
 +
       
 +
        // Include the area in case it contains relevant non-loc location info
 +
        // (such as a floor number)
 +
        var nonLoc = $tr.find('td:eq(' + areaColumnIndex + ')').text().trim();
 +
         var zone = sharedZone ||
 +
                  $tr.find('td:eq(' + zoneColumnIndex + ')').text().trim();
 +
                  var $locLink = $('<a class="loc-link" href="' + zone + '" ' +
 +
                  '  data-loc="' + nonLoc + ', ' + loc + '" ' +
 +
                  '   data-zone="' + zone + '"' +
 +
                  '>' + loc + '</a>');
 +
        $loc.html($locLink);
 +
        // If we actually have zone data, add the map icon
 +
        if (getZoneData(zone, loc, nonLoc)) $loc.append(mapIconHtml);
 
       });
 
       });
      var $ul = $('<ul>').append(lis);
 
      var $div = $('<div><h2>Fashion/Appearance</h2></div>').append($ul);
 
      // Not sure why we have two IDs: two different item templates?
 
      $('#Drop_looted_from, #Drops_From').parent().before($div);
 
    });
 
  };
 
  addFashionSection();
 
 
 
 
 
  //*****************************************
 
  // Add class-based filtering to item tables
 
  //*****************************************w
 
 
 
  // Determine whether or not a provided row should be shown for the provided
 
  // class abbreviation (eg. "BRD")
 
  var isRowShown = function($tr, classAbbrev) {
 
    // Extract classes (and races)
 
    var  classText = $tr.find('td').eq(3).text().split('Class:')[1];
 
    if (!classText) return true;  // Ignore (don't filter) rows without class text
 
 
 
    // remove "Race: " part (if any) and upper-case text
 
    classText = classText.split('Race:')[0] || classText;
 
    classText = classText.toUpperCase();
 
 
 
    // determine matching text
 
    var isMatch = classText.includes(classAbbrev);
 
    var isAllMatch = classText.includes('ALL');
 
    var isExcept = classText.includes('ALL EXCEPT');
 
 
 
    // determine matches
 
    if (isMatch && !isExcept) return true; // (eg. BRD in "BRD")
 
    if (!isMatch && isExcept) return true;  // (eg. BRD in "ALL EXCEPT WIZ")
 
    if (!isExcept && isAllMatch) return true; // (eg. BRD in "ALL")
 
    return false;
 
  };
 
 
 
  var scrollToTable = function($table) {
 
    window.setTimeout(function() {
 
      $('html, body').animate({ scrollTop: ($table.offset().top) }, 200);
 
    }, 100);
 
  };
 
 
 
  // Filter the provided table to only display rows for the provided class
 
  // abbreviation
 
  var filterTable = function($table, classAbbrev) {
 
    $table.find('tr').each(function (i, tr) {
 
      var $tr = $(tr);
 
      var rowIsShown = isRowShown($tr, classAbbrev);
 
      $tr.toggle(rowIsShown);
 
    });
 
    scrollToTable($table);
 
 
 
    addFilterLink($table, false);
 
    $('.itemsUnfilterLink').click(function() {
 
      unfilterTable($table);
 
    });
 
 
 
    alert('Filtered to only show rows containing ' + classAbbrev + ' gear.');
 
  };
 
 
 
  // Restore a table to its previous, un-filtered state
 
  var unfilterTable = function($table) {
 
    $table.find('tr').show();
 
    addFilterLink($table, true);
 
    scrollToTable($table);
 
  };
 
 
 
  // When a user clicks on a table class filter link, handle it by asking them
 
  // which class (and then filtering the table for that class)
 
  var handleItemFilterLinkClick = function(e) {
 
    var promptMessage = 'Please enter the three-letter abbreviation for the ' +
 
        'class you want to filter by (eg. "brd" for "Bard").';
 
 
 
    var $table = $(e.target).closest('table');
 
    var classAbbrev = prompt(promptMessage).toUpperCase();
 
    if (!classAbbrev || classAbbrev.length !== 3 || classAbbrev === 'ALL') {
 
      alert('A 3-digit abbreviation wasn\'t entered (or "All" was entered); ' +
 
          'filtering disabled');
 
      unfilterTable($table);
 
      return false;
 
 
     }
 
     }
     filterTable($table, classAbbrev);
+
      
  };
+
    // Handle "Where to obtain" rows for spells
 
+
    var handleWhereToObtainRows = function() {
  // Adds either a filter or unfilter link (as determined by showFilter) to the
+
      $('table'+
  // provided table
+
        ':has(th:contains("Area"))' +
  var addFilterLink = function($table, showFilter) {
+
        ':has(th:contains("Location"))'+
    var $statsHeaderCells = $table.find('th:contains("Stats")');
+
         ':has(th:contains("Loc"))' +
    var filterType = showFilter ? 'Filter' : 'Unfilter';
+
        ':has(th:contains("Zone"))'+
    $statsHeaderCells.html('Stats <span style="float:right">' +
+
         ':not(.zoneTopTable)' +
         '<a style="text-decoration: underline" class="items' + filterType + 'Link" href="#">' +
+
        ':not(:has(th:contains("Zone Spawn Timer:")))'
         filterType + (showFilter ? ' by Class' : '') + '</a></span>');
+
      )
 
+
        .each(function(i, table) {
    var $link = $statsHeaderCells.find('.items' + filterType + 'Link');
+
          var $table = $(table);
    if (showFilter) $link.click(handleItemFilterLinkClick);
+
          var zoneColumnIndex = $table.find('th:contains("Zone")').index();
    else $link.click(function() { unfilterTable($table); })
+
          addLocLinksToTable($table, null, zoneColumnIndex);
  };
+
        });
 
+
    };
  // Add class filtering links to all item tables
+
   
  var addItemFilteringLinks = function() {
+
    // Handle Zone NPC Locs
    var $tables = $('table th:contains("Item Name")').closest('table');
+
    var handleZoneNPCRows = function() {
    $tables.each(function(i, table) {
+
      var $npcsInZone = $('i:contains("NPCs that spawn in")');
      var $table = $(table);
+
      if ($npcsInZone.length) {
      // Make sure it has both "Item Name" and "Stats" columns
+
        var match = $npcsInZone.text().match(/\d+ NPCs that spawn in (.*):/);
      if (!$table.has('th:contains("Stats")')) return;
+
        if (!match) return;
 
+
      addFilterLink($table, true);
+
    });
+
  };
+
  addItemFilteringLinks();
+
 
+
  //*****************************************
+
  // End class-based filtering to item tables
+
  //*****************************************
+
  
  // Add No-Drop-Based filtering to the class equipment pages
+
        var zone = match[1];
  if (window.location.pathname.includes('Special:ClassSlotEquip')) {
+
        var $table = $npcsInZone.parent().next()
    // Add checkboxes UI to the page
+
        addLocLinksToTable($table, zone);
    $('table')
+
       }
       .before('<label><input id="showNoDrop" type="checkbox" checked/> Show No Drop</label> ' +
+
    };
              '<label><input id="showDroppable" type="checkbox" checked/> Show Droppable</label>');
+
  
     // Handle when either box is checked
+
     var getZoneName = function() {
    $('#showNoDrop, #showDroppable').change(function() {
+
       try {
       var showNoDrop = $('#showNoDrop').is(':checked');
+
        return $('b:contains("Zone:")').parents('tr:first').text().split('Zone:')[1].trim();
      var showDroppable = $('#showDroppable').is(':checked');
+
      } catch (err) {
      // NOTE: Some tables are weird and don't keep their TRs in THEAD
+
         return null;
      //      .... but those rows do have an old bgcolor="#cccccc" attribute
+
       };
      //      that we can use to identify (and not hide) them
+
     };
      $('tbody tr[bgcolor!=#cccccc]').each(function(i, el) {
+
        var text = $(el).find('td:eq(0) .itemdata').text();
+
        var isNoDrop = text.includes('NO DROP');
+
         $(el).toggle((showNoDrop && isNoDrop) || (showDroppable && !isNoDrop));
+
       });
+
     });
+
  }
+
  
 +
    /**
 +
    * Determines whether the page has a "Location" <td> (as all NPC pages do)
 +
    * with parsable locs inside it (as only some do).  Also checks that
 +
    * "loc-mapped" zone data exists for the NPC's zone.
 +
    */
 +
    var getZoneDataIfThereIsALocBox = function($locTd, zoneName) {
 +
      if (!$locTd.length) return false; // page isn't an NPC page (no loc box)
 +
     
 +
      var locs = parseLocs($locTd.text());
 +
      if (!locs.length) return false; // no locs existed (or could be parsed)
  
  // Generic Table Filtering (for Template:TableFilterCheckbox)
+
      var nonLocParts = extractNonLocText($locTd.text());
  $('.table-filter-checkbox-container').each(function(i, el) {
+
      return !!getZoneData(zoneName, locs, nonLocParts); // does zone data exist?
    var $container = $(el);
+
    };
    var matchSelector = $container.data('match');
+
    var text = $container.text();
+
    $container.html('<label><input class="table-filter-checkbox" type="checkbox" ' +
+
                      'value="' + matchSelector + '" checked />' + text + '</label>');
+
  });
+
  
  var shouldRowBeShown = function(tr) {
+
    var handleLocBoxes = function() {
    var $tr = $(tr);
+
      var zoneName = getZoneName();
    // Check all the checkboxes to see if any given row should appear
+
       var $bold = $('b:contains("Location:"), b:contains("Loc:")').not('.zoneTopTable b, .toc b');
    // TODO: Instead of checking *every* checkbox, check ones in the same .filter-group
+
       if(!$bold.length) return;
    return $('.table-filter-checkbox')
+
       .toArray()
+
      .reduce(function(isShown, checkbox) {
+
        var matchSelector = $(checkbox).val();
+
        var matches = $tr.is(matchSelector) ||
+
                      !!$tr.has(matchSelector).length;
+
        var isChecked = $(checkbox).attr('checked');
+
        return isShown && !!(isChecked || (!isChecked && !matches));
+
      }, true);
+
  }
+
  $('body').on('change', '.table-filter-checkbox', function(e) {
+
    $('table').show();
+
    $('table:not(.toc) tbody tr:not([bgcolor="#cccccc"])').each(function(i, tr) {
+
       $(tr).toggle(shouldRowBeShown(tr));
+
    });
+
    // If all of a table's non-header rows are hidden, hide it
+
    $('table').filter(function(i, table) {
+
      return !$(table).has('tr:visible:not([bgcolor="#cccccc"])').length;
+
    }).hide();
+
  });
+
  
 +
      var label = $bold.text().trim();
 +
      var labelNoColon = label.substr(0, label.length - 1);
  
  importScript('MediaWiki:CheckboxLists.js');
+
      var $locTd = $bold.parent();
  importScript('MediaWiki:LocMaps.js');
+
      // The TD can either have the label and the locs, or there could
 +
      // be one TD for the label, and a sibling for the loc
 +
      var isLabelTd = $locTd.text().trim().endsWith(':');
 +
      if (isLabelTd) $locTd = $locTd.closest('tr').children('td:last');
  
  var fullTitle = $('title').text();
+
      var zoneData = getZoneDataIfThereIsALocBox($locTd, zoneName);
  var title = fullTitle.substr(0, fullTitle.length - ' - Project 1999 Wiki'.length);
+
       if (!zoneData) return;
  switch(title) {
+
        
    // Give the Per-Level Hunting Guide Page its own JS
+
       // Get the mob's loc(s)
    case 'Per-Level Hunting Guide':
+
       var locs = parseLocs($locTd.text());
       importScript('MediaWiki:HuntingGuide.js');
+
       var nonLocParts = extractNonLocText($locTd.text());
       break;
+
        
    // The item category search also needs special JS
+
       // Do we have data for that zone's map?
    case 'Item Category Search':
+
       var zoneData = getZoneData(zoneName, locs, nonLocParts);
       importScript('MediaWiki:ItemCategorySearch.js');
+
      if (!zoneData) return; // If not, stop here
      break;
+
    // So does the Solo Artist Challenge
+
    case 'Solo Artist Challenge':
+
      importScript('MediaWiki:SoloArtistChallenge.js');
+
       break;
+
    case 'Treasure Hunting Guide':
+
      importScript('MediaWiki:TreasureHuntingGuide.js');
+
       break;
+
    case 'Buff Lines':
+
      importScript('MediaWiki:BuffLines.js');
+
      break;
+
    case 'FashionQuest Finder':
+
      importScript('MediaWiki:FashionQuest.js');
+
       break;
+
    case 'Mobs By Level':
+
       // Basic DOM manipulation (since the wiki won't let us add <input> tags in the wiki text
+
       $('#placeholder')
+
        .replaceWith(
+
          '<form id="form">' +
+
            'Class: <input id="class" style="width: 8em" value="Warrior" /> ' +
+
            'Level: <input id="level" style="width: 4em" /> ' +
+
            '<input type="submit"/>' +
+
          '</form>'
+
        );
+
      $('#form').submit(function() {
+
        var clazz = $('#class').val();  
+
        var level = $('#level').val();  
+
        window.location = 'https://wiki.project1999.com/index.php?title=Special:Search&limit=500&offset=0&redirs=0&profile=default&search=%22Level%5C%3A%5C+' +
+
        level + '%22+-%22Shopkeeper%22+-%22Merchant%22+%22Class%5C%3A%5C+'+ clazz + '%22+-"startMageloProfile"';
+
        return false;
+
      });
+
      break;
+
  }
+
  
  // Warn users who accidentally try to edit a templated section
+
      // Add the mouse-enter link
  if ((window.location + '').includes('title=Template:Namedmobpage&action=edit')) {
+
      var $link = $(' <a href="#">(Map)</a>')
    alert('Warning: You are attempting you edit the template for all named mobs.  You probably didn\'t mean to do that: you probably clicked on an edit link somewhere in the page and wound up here. To avoid this simply go back and use the edit *tab* at the top of the page instead.');
+
        // When it's moused-over, show the map nearby
  }
+
        .on('mouseenter', function(e) {
 +
          // If there is already a map "open" (because of a click), do nothing
 +
          if (window.$openImg && window.$openImg.parent().length) return false;
  
  // Warn uses who try to edit a mostly-transcluded section (and offer to take them to the transcluded page)
+
          var $map = showMapWithLocs(zoneData, locs, $locTd);
  var text = $('#wpTextbox1').val();
+
          $map.parent().one('mouseleave', removeOpenImage);
  var match = text && text.match(/\{\{\#lsth\:(.*?)\|\[\[(.*?)\]\]\}\}/);
+
        })
  if (match) {
+
        // When it's clicked, show the map full-screen/lightbox style
    var pageName = match[1];
+
        .on('click', function(e) {
    var section = match[2];
+
          showMapWithLocs(zoneData, locs);
    var isEdit = (window.location + '').includes('action=edit');
+
        });
    var isUnderTenLines = $('#wpTextbox1').val().split('\n').length < 10;
+
    var url = '/' + pageName + '#' + section;
+
    var message = 'This page uses "transclusion" to show part of another page, specifically the code:\n\n    {{#lsth:' + pageName +
+
                  '|[[' + section + ']]}}\n\nIf you want to edit the transcluded section, click "Ok": you will be taken to that page.' +
+
                  '  If you want to stay on this page, click "Cancel".';
+
    if (isEdit && isUnderTenLines && confirm(message)) location = url;
+
  }
+
  
  // Add links to search the forum for items to their auction tracker
+
      $bold
  const forumSearchUrl = 'https://www.project1999.com/forums/search.php?do=process&forumchoice[]=27&query=%22' +
+
        .html($('<span>' + labelNoColon + ' </span>')
                        $('#firstHeading').text() + '%22';
+
        .append($link)
  $('.auctrackerbox span span:contains("Project 1999 Auction Tracker")')
+
        .append('<span>:</span>'));
    .append(
+
    };
      '<a ' +
+
        'style="font-size: 0.5em; float: right" '+
+
        'target="_new" ' +
+
        'href="' + forumSearchUrl + '"' +
+
      '>Search Forum</a>');
+
  
});
+
    // Setup event listeners (code "starts" here)
 +
    var startLocFunctionality = function() {
 +
      handleWhereToObtainRows();
 +
      handleZoneNPCRows();
 +
      handleLocBoxes();
 +
    };
 +
 
 +
    // Sometimes zoneData isn't ready when this code is, so retry for 10 secs in hope that it becomes available
 +
    var tries = 10;
 +
    var timeBetweenTries = 1000; // 1 second
 +
    var interval = window.setInterval(function() {
 +
      if (window.zoneData) {
 +
        window.clearInterval(interval);
 +
        startLocFunctionality();
 +
      } else {
 +
        tries -= 1;
 +
        if (!tries) window.clearInterval(interval); // Failure :(
 +
      }
 +
    }, timeBetweenTries);
 +
 
 +
    var showMapForData = function(data, $target) {
 +
      if (!data.loc || ! data.zone) return;
 +
 
 +
      var locs = parseLocString(data.loc)[0];
 +
      var nonLocParts = parseLocString(data.loc)[1];
 +
      var zoneData = getZoneData(data.zone, locs, nonLocParts);
 +
      if (!zoneData) {
 +
        // If it was a click and not a mouseover
 +
        if ($target) return false;
 +
 
 +
        return confirm('We\'re sorry, but ' + data.zone + ' has not been loc mapped yet ... ' +
 +
          'please see "/Loc_Maps" for more information.  You can now click "OK" to be taken ' +
 +
          'to the zone\'s page instead, where you can use its map as a guide, or "Cancel" to stay here.');
 +
      }
 +
      showMapWithLocs(zoneData, locs, $target);
 +
    };
 +
  // TODO: Add a new class/event handler/template to trigger this
 +
  var addCharacterToMap = function(data, $target) {
 +
      if (!data.loc || ! data.zone) return;
 +
 
 +
      var locs = parseLocString(data.loc)[0];
 +
      var nonLocParts = parseLocString(data.loc)[1];
 +
      var zoneData = getZoneData(data.zone, locs, nonLocParts);
 +
      if (!zoneData) {
 +
        // If it was a click and not a mouseover
 +
        if ($target) return false;
 +
 
 +
        alertNoData(data.zone);
 +
        return true;
 +
      }
 +
      // TODO: do next line, but replace $target with a query for the existing map on the page
 +
      // Also, instead of making an X, make a number that's provided (via link's data attr)
 +
      // showMapWithLocs(zoneData, locs, $target);
 +
    };
 +
 
 +
    // TODO: this is in here because fashion links and loc links share global
 +
    // event watchers, but this file needs to be renamed now
 +
 
 +
    /**
 +
    * Shows an image (triggered by clicking on a link, such
 +
    * as a thumbnail or a fashion show link, which contains
 +
    * data about the file's URL).
 +
    */
 +
    var showImageFromData = function(data, $container) {
 +
      if (!data.file) return;
 +
      var $img = $(buildImgFromFileName(data.file));
 +
      var $div = $('<div class="framed-image"></div>')
 +
                    .html($img)
 +
      var $framedImage;
 +
      if ($container) {
 +
        var $outerFrame = build$AbsolutePositionFrame();
 +
        var $innerFrame = $('<div style="position:relative"></div>');
 +
        $framedImage = $outerFrame.append($innerFrame.append($div));
 +
      } else {
 +
        $framedImage = build$FullScreenFrame().html($div);
 +
      }
 +
      showImage($framedImage, $container);
 +
    };
 +
 
 +
    // Hook up loc-link events
 +
    $('body')
 +
      .on('click', '.loc-link, .fashion-link, .thumbnail-link', function() {
 +
        removeOpenImage(); // get rid of any mouseover images first
 +
        var data = $(this).data();
 +
        var theClickedLinkShouldRedirect = showMapForData(data) || showImageFromData(data);
 +
        return theClickedLinkShouldRedirect || false;
 +
      })
 +
      // Temporarily (?) disable mouseover showing of images
 +
      //.on('mouseenter', '.loc-link, .fashion-link, .thumbnail-link', function(e) {
 +
      //  var $this = $(e.target).on('mouseleave', removeOpenImage);
 +
      //  var data = $(this).data();
 +
      //  showMapForData(data, $this);
 +
      //  showFashionForData(data, $this);
 +
      //});
 +
 
 +
     
 +
    // *** HELPER FUNCTIONS ***
 +
    // Define two helper functions for building new zone definitions
 +
 
 +
    // 1) Use this function to find the correct 0,0 point
 +
    window.testZero = window.testZeroZero = function(zoneData) {
 +
      removeOpenImage(); // test functions don't clean up properly
 +
      var locs = [{ x: 0, y: 0 }];
 +
      showMapWithLocs(zoneData, locs);
 +
    };
 +
 
 +
 
 +
    // 2) Use this function to generate a grid of alignment of X's
 +
    window.testGrid = function(zoneData) {
 +
      removeOpenImage(); // test functions don't clean up properly
 +
      var $locTd = $('b:contains("Location:")').parent();
 +
      var locs = [];
 +
      for (var x = zoneData.maxX; x >= zoneData.minX; x -= zoneData.interval) {
 +
        for (var y = zoneData.maxY; y >= zoneData.minY; y -= zoneData.interval) {
 +
          locs.push({ x: x, y: y });
 +
        }
 +
      };
 +
      showMapWithLocs(zoneData, locs);
 +
    };
 +
 
 +
  })();
 +
  } catch (err) {
 +
    console.error(err); // If anything goes wrong, move on but log the error
 +
  }

Latest revision as of 20:01, 30 November 2025

try {
  (function() {

    var buildImgFromFileName = function(fileName) {
      return '<img src="/images/' + fileName.replace(/ /g, '_') + '">'
    };

    // TODO: Add support for cropping maps that have multiple maps.
    // For instance, the following CSS styles show only one of the three maps for 
    // Erudin Palace:
    // background-image:url(/images/Erudinpalace.jpg); 
    // background-position: 250px 0px; width: 275px; height: 272px
    // Figure out how to make the Xs line up with those styles added

    var locIsWithinAlternateData = function(loc, alternateData) {
      return loc.x < alternateData.maxX &&
      loc.x > alternateData.minX &&
      loc.y < alternateData.maxY &&
      loc.y > alternateData.minY;
    };


    /**
     * Determines if the provided name contains any of the provided words
     */
    // TODO: Add a some polyfill to make this a lot simpler
    var containsAny = function(name/* word1, word2, etc. */) {
      for(var arg = 1; arg < arguments.length; ++ arg) {
        var word = arguments[arg];
        if (name.includes(word)) return true;
      }
      return false;
    };

    var containsAnyNumber = function(name, number, suffix) {
      return containsAny.call(null, name, 
       number + suffix,
       'level ' + number,
       'level: ' + number,
       'floor ' + number,
       'floor: ' + number
       );
    };

    var getZoneLevelData = function(zone, text) {
      var levels = zone.levels;
      // Check for part "level" aliases (eg. "1st floor" vs. "Level One")
      text = text.toLowerCase();
      if(levels['3']  && levels['3'].image.includes('crystal')) {
        // Special case for Crystal Caverns
        if (containsAny(text, 'upper')) return levels[3];
        if (containsAny(text, 'lower')) return levels[2];
        if (containsAny(text, 'town', 'coldain')) return levels[0];
      }

      // In most zones "tunnel" = level 0.  But in Kurn's there are two level zeroes (tunnels and basement),
      // so this next line handles the Kurn's case in particular
      if (containsAny(text, 'tunnel') && levels.tunnels) return levels.tunnels;

      if (containsAnyNumber(text, 0, 'th') || containsAny(text, 'basement', 'underground', 'tunnel', 'bear pit', 'bear pits', 'cave', 'caves')) return levels[0];
      if (containsAnyNumber(text, 1, 'st') || containsAny(text, 'one', 'first', 'ground')) return levels[1];
      if (containsAnyNumber(text, 2, 'nd') || containsAny(text, 'two', 'second')) return levels[2];
      if (containsAnyNumber(text, 3, 'rd') || containsAny(text, 'three', 'third')) return levels[3];
      if (containsAnyNumber(text, 4, 'th') || containsAny(text, 'four', 'fourth')) return levels[4];
      if (containsAnyNumber(text, 5, 'th') || containsAny(text, 'five', 'fifth')) return levels[5];

      // Special case for Tower of Frozen Shadow, which has two level 6 maps
      if (containsAny(text, '6a')) return levels['6A'];
      if (containsAny(text, '6b')) return levels['6B'];

      if (containsAnyNumber(text, 6, 'th') || containsAny(text, 'six', 'sixth')) return levels[6];
      if (containsAnyNumber(text, 7, 'th') || containsAny(text, 'seven', 'seventh')) return levels[7];
      if (containsAnyNumber(text, 8, 'th') || containsAny(text, 'eight', 'eighth')) return levels[8];
      if (containsAnyNumber(text, 9, 'th') || containsAny(text, 'nine', 'ninth')) return levels[9];

      var levelKeys = Object.keys(levels);
      var keyOfLastLevel = levelKeys[levelKeys.length - 1];
      if (containsAny(text, 'top')) return levels[keyOfLastLevel];

      // If we still couldn't match, and there is a ground/1st floor, use it
      return levels[1];
    };

    

    var findZoneData = function(zoneName, locs, nonLocParts) {
      // Convert someZone (East) to East someZone
      if (zoneName.trim().endsWith(')')) {
        try {
          var nameSplit = zoneName.split('(');
          var newName = nameSplit[0].trim();
          var direction = nameSplit[1].split(')')[0].trim();
          if (['east', 'north', 'south', 'west'].includes(direction.toLowerCase())) {
            zoneName = direction + ' ' + newName;
          }
        } catch(err){ /* just use name (it likely won't work, but try) */}
      }

      var zone = zoneData[zoneName];

      // Handle aliases (eg. "North Ro" instead of "Northern Desert of Ro")
      if (typeof(zone) === 'string') zone = zoneData[zone];

      if (!zone) return null;

      // Handle Multi-Level Zones (with different maps for 1st, 2nd, etc. floor)
      if (zone.levels) {
        var levelOfZone = getZoneLevelData(zone, nonLocParts);
        return levelOfZone;
      }

      // Handle Zones with alternate maps on the same level (eg. Kelethin in GFay)
      if (!zone.alternateMaps) return zone;

      for (var i = 0; i < zone.alternateMaps.length; i++) {
        var alternateData = zone.alternateMaps[i];
        var allLocsAreWithin = true;
        // wish I had ES6 [].every
        $.each(locs, function(i, loc) {
          allLocsAreWithin = allLocsAreWithin && 
          locIsWithinAlternateData(loc, alternateData);
        });
        if (allLocsAreWithin) return alternateData;
      };
      return zone;
    };

  var addImageUrl = function(zoneData) {
    zoneData.imageUrl = '/images/' + zoneData.image;
    return zoneData;
  };

  var getZoneData = function(zoneName, locs, nonLocParts) {
    var zoneData = findZoneData(zoneName, locs, nonLocParts);
    if (!zoneData) return null;
    zoneData.zoneName = zoneName;
    return addImageUrl(zoneData);
  };

    var build$MapImage = function(zoneData) {
      return $(
        '<img alt="Map of ' + zoneData.zoneName + '" ' +
        '     class="thumbborder" ' +
        '     height="'+ zoneData.height + '" ' +
        '     src="' + zoneData.imageUrl + '" ' +
        '     title="Map of ' + zoneData.zoneName + '"' +
        '     width="' + zoneData.width + '" ' +
        '>'
        );
    };``

    var build$XContainer = function() {
      return $('<div class="x-container" style="position: relative"></div>');
    }

    
    var build$LightboxFramedMap = function(zoneData) {
      var $map = build$XContainer().append(build$MapImage(zoneData));
      return addFramingStyles($map, zoneData.width, zoneData.height)
    };

    var addFramingStyles = function($el, width, height) {
      return $el.css({
          left: '50%',
          marginLeft: '-' + (width / 2) + 'px', // centering
          marginTop: '-' + (height / 2) + 'px',
          opacity: 1,
          top: '50%'
        });
    }

    var build$AbsolutePositionFrame = function() {
      return $('<div style="position: absolute"></div>');
    };

    var removeOpenImage = function(e) {
      // Do nothing if there's no open map
      if (!window.$openImg) return false;

      // Do nothing if the user clicked to open a map, then moused out of an area
      // (otherwise it can close immediately)
      var position = window.$openImg.css('position');
      if (e && e.type === 'mouseleave' && position === 'fixed') return false;

      window.$openImg.remove();
      return false;
    }


    var build$FullScreenFrame = function() {
      return build$AbsolutePositionFrame()
        .css({
          background: 'rgba(0,0,0,0.8)',
          height: '100%',
          left: 0,
          position: 'fixed',
          top: 0,
          width: '100%',
          zIndex: 4 // one higher than #p-search's 3
        })
        .click(removeOpenImage);
    }

    var build$FullMap = function(zoneData) {
      var $frame = build$FullScreenFrame();
      if (zoneData) {
        $frame.html(build$LightboxFramedMap(zoneData));
        $frame.zoneData = zoneData;
      }
      return $frame;
    };

    var build$SmallMap = function(zoneData) {
      return build$AbsolutePositionFrame().append(
        build$XContainer().append(
          build$MapImage(zoneData)));
    }

  var baseXFontSizeInEm = 2;

  var buildX = function(left, top, sizeInEm) {
    sizeInEm = sizeInEm || baseXFontSizeInEm;
    return $('<div class="x">x</div>')
      .css({
        color: 'red',
        fontSize: sizeInEm + 'em',
        fontWeight: 'bold',
        left: left,
        position: 'absolute',
        top: top
      })
  }

  /**
   * Draws a red "X" on the map at the provided coordinate
   */
  var addX = function($xContainer, zoneData, x, y, xSize) {
    var left = (zoneData.zeroX || 0) + x * -1 * (zoneData.zoomX || 0.1);
    var top = (zoneData.zeroY || 0) + y * -1 * (zoneData.zoomY || 0.1);
    $xContainer.append(buildX(left, top, xSize));
  }

  var addXs = function($xContainer, zoneData, locs, xSize) {
    $.each(locs, function(i, loc) {
      addX($xContainer, zoneData, loc.x, loc.y, xSize);
    });
  }


  var parseLoc = function(locText) {
    if (typeof locText !== 'string') return locText;
    try {
        var match = locText.match(/\(? *([\+\-]?\d+\.?\d*)\s*, *([\+\-]?\d+\.?\d*)\)?/);
        return {x: parseFloat(match[2]), y: parseFloat(match[1]) };
    } catch (err) {
        return locText;
    }
  }

  var isLoc = function(locBit) {
      // If we can't split the string by its comma and find a number on either side, it's not a loc
      try {
        return locBit.split(',')[0].match(/\d+/) && locBit.split(',')[1].match(/\d+/);
      } catch (err) {
        return false;
      }
    }

    /**
     * Helper function to power parseLocs/extractNonLocText, since they both use
     * the same logic.
     *
     * SIDE NOTE: If only the wiki didn't have to use 1999 JS, and could
     *            destructure return values with ES2015, the two related functions
     *            wouldn't even need to exist :(
     */
    var parseLocString = function(locString) {
      var nonLocParts = '';
      // Old regex (failed to match Undead Legionaires loc on TT page, but keeping it around unless
      // the new regex has issues
      //var bits = locString.split(/([\+\-]?\d+\.?\d*[^0-9\)]*,\D*[\+\-]?\d+\.?\d*)/g);
      var bits = locString.split(/([\+\-]?\d+\.?\d*\s*,\D*[\+\-]?\d+\.?\d*)/g);
      var relevantBits = bits.filter(function(part) {
        // Filter out the non-loc parts, but save them
        if (isLoc(part)) return true;
        nonLocParts += part; // save as it might be something like "1st floor"
      });
      var locs = relevantBits.map(parseLoc);
      return [locs, nonLocParts];
    };

    /**
     * Extracts all of the locs (objects with x and y properties) from a provided
     * string such as:
     *   "500, 200"
     *   "(200, 300), (300, 200)"
     * and returns an array containing any locs found.
     */
     var parseLocs = function(locString) {
      return parseLocString(locString)[0];
    };
    
    /**
     * Extracts the non-loc parts (eg. "Level 1") from a provided string of text
     * (presumably from an NPC's location <td> or somewhere similar). Although not
     * actually a part of the loc, this text may still be useful in determining
     * which map to show for the loc.
     */
    var extractNonLocText = function(locString) {
      return parseLocString(locString)[1];
    };


    var showImage = function($img, $container) {
      if ($container) {
        $img.css({ marginTop: 40 });
        var isAboveHalf = $container.position().top < ($('body').height() / 2);
        var isLeftOfHalf = $container.position().left < ($('body').width() / 2);
        $container.css('position', 'relative')
                  .prepend($img);
        $img.css({ 
          [isAboveHalf  ? 'top' : 'bottom']: '1.5em', 
          [isLeftOfHalf  ? 'left' : 'right']: '1.5em' 
        });
        // TODO: Now, check if the map image is off the page, and if so by how much?
        //       Add/subtract that much from the top/left/bottom/right to make sure 
        //       the whole map is shown ... but also make sure the link itself isn't covered
      }
      else $('body').append($img);

      window.$openImg = $img;
      return $img;
    };

    /**
     * Adds a loc map image to the page.
     */
    var showMapWithLocs = function(zoneData, locs, $container) {
      removeOpenImage();
      
      zoneData = addImageUrl(zoneData);
      var $map = $container ? build$SmallMap(zoneData) : build$FullMap(zoneData);

      var $xContainer = $map.find('.x-container');
      var xSize = baseXFontSizeInEm;
      if (locs.length > 5) xSize = 0.8 * baseXFontSizeInEm;
      if (locs.length > 15) xSize = 0.5 * baseXFontSizeInEm;
      $map.find('img').load(function() {
        addXs($xContainer, zoneData, locs, xSize);
      });
      return showImage($map, $container);
    };

    var mapIconHtml = '<img ' +
      'alt="Map Icon.png" ' +
      'height="12" ' +
      'src="/images/thumb/Map_Icon.png/12px-Map_Icon.png" ' +
      'width="12">';
    var addLocLinksToTable = function($table, sharedZone, zoneColumnIndex) {
      var areaColumnIndex = $table.find('th:contains("Area"), th:contains("Location")').index();
      var locationColumnIndex =
        $table.find('th:contains("Location"), th:contains("Loc")').index();
      

      $table.find('tr').each(function(i, tr) {
        var $tr = $(tr);
        var $loc = $tr.find('td:eq(' + locationColumnIndex + ')');
        var loc = $loc.text().trim();
        if (!isLoc(loc)) return; // Non-loc text (eg. "Various") in loc column
        
        // Include the area in case it contains relevant non-loc location info
        // (such as a floor number)
        var nonLoc = $tr.find('td:eq(' + areaColumnIndex + ')').text().trim();
        var zone = sharedZone ||
                   $tr.find('td:eq(' + zoneColumnIndex + ')').text().trim();
                   var $locLink = $('<a class="loc-link" href="' + zone + '" ' +
                   '   data-loc="' + nonLoc + ', ' + loc + '" ' +
                   '   data-zone="' + zone + '"' +
                   '>' + loc + '</a>');
        $loc.html($locLink);
        // If we actually have zone data, add the map icon
        if (getZoneData(zone, loc, nonLoc)) $loc.append(mapIconHtml);
      });
    }
    
    // Handle "Where to obtain" rows for spells
    var handleWhereToObtainRows = function() {
      $('table'+
        ':has(th:contains("Area"))' +
        ':has(th:contains("Location"))'+
        ':has(th:contains("Loc"))' +
        ':has(th:contains("Zone"))'+
        ':not(.zoneTopTable)' +
        ':not(:has(th:contains("Zone Spawn Timer:")))'
      )
        .each(function(i, table) {
          var $table = $(table);
          var zoneColumnIndex = $table.find('th:contains("Zone")').index();
          addLocLinksToTable($table, null, zoneColumnIndex);
        });
    };
    
    // Handle Zone NPC Locs
    var handleZoneNPCRows = function() {
      var $npcsInZone = $('i:contains("NPCs that spawn in")');
      if ($npcsInZone.length) {
        var match = $npcsInZone.text().match(/\d+ NPCs that spawn in (.*):/);
        if (!match) return;

        var zone = match[1];
        var $table = $npcsInZone.parent().next()
        addLocLinksToTable($table, zone);
      }
    };

    var getZoneName = function() {
      try {
        return $('b:contains("Zone:")').parents('tr:first').text().split('Zone:')[1].trim();
      } catch (err) {
        return null;
      };
    };

    /**
     * Determines whether the page has a "Location" <td> (as all NPC pages do)
     * with parsable locs inside it (as only some do).  Also checks that
     * "loc-mapped" zone data exists for the NPC's zone.
     */
    var getZoneDataIfThereIsALocBox = function($locTd, zoneName) {
      if (!$locTd.length) return false; // page isn't an NPC page (no loc box)
      
      var locs = parseLocs($locTd.text());
      if (!locs.length) return false; // no locs existed (or could be parsed)

      var nonLocParts = extractNonLocText($locTd.text());
      return !!getZoneData(zoneName, locs, nonLocParts); // does zone data exist?
    };

    var handleLocBoxes = function() {
      var zoneName = getZoneName();
      var $bold = $('b:contains("Location:"), b:contains("Loc:")').not('.zoneTopTable b, .toc b');
      if(!$bold.length) return;

      var label = $bold.text().trim();
      var labelNoColon = label.substr(0, label.length - 1);

      var $locTd = $bold.parent();
      // The TD can either have the label and the locs, or there could
      // be one TD for the label, and a sibling for the loc
      var isLabelTd = $locTd.text().trim().endsWith(':');
      if (isLabelTd) $locTd = $locTd.closest('tr').children('td:last');

      var zoneData = getZoneDataIfThereIsALocBox($locTd, zoneName);
      if (!zoneData) return;
      
      // Get the mob's loc(s)
      var locs = parseLocs($locTd.text());
      var nonLocParts = extractNonLocText($locTd.text());
      
      // Do we have data for that zone's map?
      var zoneData = getZoneData(zoneName, locs, nonLocParts);
      if (!zoneData) return;  // If not, stop here

      // Add the mouse-enter link
      var $link = $(' <a href="#">(Map)</a>')
        // When it's moused-over, show the map nearby
        .on('mouseenter', function(e) {
          // If there is already a map "open" (because of a click), do nothing
          if (window.$openImg && window.$openImg.parent().length) return false;

          var $map = showMapWithLocs(zoneData, locs, $locTd);
          $map.parent().one('mouseleave', removeOpenImage);
        })
        // When it's clicked, show the map full-screen/lightbox style
        .on('click', function(e) {
          showMapWithLocs(zoneData, locs);
        });

      $bold
        .html($('<span>' + labelNoColon + ' </span>')
        .append($link)
        .append('<span>:</span>'));
    };

    // Setup event listeners (code "starts" here)
    var startLocFunctionality = function() {
      handleWhereToObtainRows();
      handleZoneNPCRows();
      handleLocBoxes();
    };

    // Sometimes zoneData isn't ready when this code is, so retry for 10 secs in hope that it becomes available
    var tries = 10;
    var timeBetweenTries = 1000; // 1 second
    var interval = window.setInterval(function() {
      if (window.zoneData) {
         window.clearInterval(interval);
         startLocFunctionality();
      } else {
        tries -= 1;
        if (!tries) window.clearInterval(interval); // Failure :(
      }
    }, timeBetweenTries);

    var showMapForData = function(data, $target) {
      if (!data.loc || ! data.zone) return;

      var locs = parseLocString(data.loc)[0];
      var nonLocParts = parseLocString(data.loc)[1];
      var zoneData = getZoneData(data.zone, locs, nonLocParts);
      if (!zoneData) {
        // If it was a click and not a mouseover
        if ($target) return false;

        return confirm('We\'re sorry, but ' + data.zone + ' has not been loc mapped yet ... ' +
          'please see "/Loc_Maps" for more information.  You can now click "OK" to be taken ' +
          'to the zone\'s page instead, where you can use its map as a guide, or "Cancel" to stay here.'); 
      }
      showMapWithLocs(zoneData, locs, $target);
    };
   // TODO: Add a new class/event handler/template to trigger this
   var addCharacterToMap = function(data, $target) {
      if (!data.loc || ! data.zone) return;

      var locs = parseLocString(data.loc)[0];
      var nonLocParts = parseLocString(data.loc)[1];
      var zoneData = getZoneData(data.zone, locs, nonLocParts);
      if (!zoneData) {
        // If it was a click and not a mouseover
        if ($target) return false;

        alertNoData(data.zone);
        return true;
      }
      // TODO: do next line, but replace $target with a query for the existing map on the page
      // Also, instead of making an X, make a number that's provided (via link's data attr)
      // showMapWithLocs(zoneData, locs, $target);
    };

    // TODO: this is in here because fashion links and loc links share global
    // event watchers, but this file needs to be renamed now

    /**
     * Shows an image (triggered by clicking on a link, such
     * as a thumbnail or a fashion show link, which contains
     * data about the file's URL).
     */
    var showImageFromData = function(data, $container) {
       if (!data.file) return;
       var $img = $(buildImgFromFileName(data.file));
       var $div = $('<div class="framed-image"></div>')
                    .html($img)
       var $framedImage;
       if ($container) {
        var $outerFrame = build$AbsolutePositionFrame();
        var $innerFrame = $('<div style="position:relative"></div>');
         $framedImage = $outerFrame.append($innerFrame.append($div));
       } else {
         $framedImage = build$FullScreenFrame().html($div);
       }
       showImage($framedImage, $container);
    };

    // Hook up loc-link events
    $('body')
      .on('click', '.loc-link, .fashion-link, .thumbnail-link', function() {
        removeOpenImage(); // get rid of any mouseover images first
        var data = $(this).data();
        var theClickedLinkShouldRedirect = showMapForData(data) || showImageFromData(data);
        return theClickedLinkShouldRedirect || false;
      })
      // Temporarily (?) disable mouseover showing of images
      //.on('mouseenter', '.loc-link, .fashion-link, .thumbnail-link', function(e) {
      //  var $this = $(e.target).on('mouseleave', removeOpenImage);
      //  var data = $(this).data();
      //  showMapForData(data, $this);
      //  showFashionForData(data, $this);
      //});

      
    // *** HELPER FUNCTIONS ***
    // Define two helper functions for building new zone definitions

    // 1) Use this function to find the correct 0,0 point
    window.testZero = window.testZeroZero = function(zoneData) {
      removeOpenImage(); // test functions don't clean up properly
      var locs = [{ x: 0, y: 0 }];
      showMapWithLocs(zoneData, locs);
    };


    // 2) Use this function to generate a grid of alignment of X's
    window.testGrid = function(zoneData) {
      removeOpenImage(); // test functions don't clean up properly
      var $locTd = $('b:contains("Location:")').parent();
      var locs = [];
      for (var x = zoneData.maxX; x >= zoneData.minX; x -= zoneData.interval) {
        for (var y = zoneData.maxY; y >= zoneData.minY; y -= zoneData.interval) {
          locs.push({ x: x, y: y });
        }
      };
      showMapWithLocs(zoneData, locs);
    };

  })();
  } catch (err) {
    console.error(err); // If anything goes wrong, move on but log the error
  }