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:Common.js"

From Project 1999 Wiki
Jump to: navigation, search
Line 74: Line 74:
 
   */
 
   */
 
   var listenForLiClicks = function() {
 
   var listenForLiClicks = function() {
     $('.checkbox-list li span').click(function(e) {
+
     $('.checkbox-list li').click(function(e) {
 
       e.stopPropagation(); // for <li>s nested in other <lis>
 
       e.stopPropagation(); // for <li>s nested in other <lis>
 
       if (e.offsetX > 50) return
 
       if (e.offsetX > 50) return

Revision as of 19:35, 19 November 2018

/* Any JavaScript here will be loaded for all users on every page load. */

/* p1999wiki.js
 * written by http://wiki.project1999.com/User:Ravhin
 * last update: 7 January, 2018 by Loramin
 */


/* --- hoverbox for item/mob, currently only used in magelo --- */

var setupCheckboxes = function() {
  // Determine what page we are on (eg. 'Druid_Epic_Quest')
  var pageName = location.pathname.substr(1);

  var getAllPagesStatus = function() {
    var serializedStatus = localStorage.getItem('checkbox-status') || '{}';
    return JSON.parse(serializedStatus);
  };
  var getPageStatus = function() {
    return getAllPagesStatus()[pageName] || {};
  };

  var checkboxStatus = getPageStatus();
  var $checkboxLis = $('.checkbox-list li');

  /**
 * Sets the status, in local storge, of the checkbox specified by the 
 * provided index, to the providd "isChecked" boolean
 */
  var setCheckedStatus = function(index, isChecked) {
    // Update the page the checkbox/page status
    var status = getPageStatus();
    status[index] = isChecked;
    // Update the page/pages status
    var allPagesStatus = getAllPagesStatus();
    allPagesStatus[pageName] = status;
    // Serialize all of the page's status and store in local storage
    var serializedStatus = JSON.stringify(allPagesStatus);
    localStorage.setItem('checkbox-status', serializedStatus);
  };

  /**
   * Wrap the contents of all checbox LIs in a span so that clicks only work
   * on the text, not on the LI's entire (ie. page) width
   */
  var addWrappingSpans = function() {
    $checkboxLis.each(function(i, li) {
      const html = $(li).html();
      $(li).html('<span>' + html + '</span>');
    })
  };
  /**
   * Both changes the DOM to make the item appear visibly checked, and updates
   * the "checked" status in local storage
   */
  var toggleIsChecked = function($li) {
    var isChecked = !$li.is('.checked'); // Clicks toggle checked status
    $li.toggleClass('checked', isChecked);

    var index = $('.checkbox-list li').index($li);
    setCheckedStatus(index, isChecked);
  };
  /** Attach click handlers to the spans we added */
  var listenForSpanClicks = function() {
    $('.checkbox-list li span').click(function(e) {
      e.stopPropagation(); // for <li>s nested in other <lis>
      var $target = $(e.target);
      toggleIsChecked($target.parent());
    });
  };
  /** 
   * Attach click handlers to the lis also, but only use them if the click was
   * on the left (checkbox) part
   */
  var listenForLiClicks = function() {
    $('.checkbox-list li').click(function(e) {
      e.stopPropagation(); // for <li>s nested in other <lis>
      if (e.offsetX > 50) return
      var $target = $(e.target);
      toggleIsChecked($target);
    });
  };
  /**
   * Set the visible "checked" state of the list items when the page loads
   */
  var initializeCheckboxes = function() {
    Object.keys(checkboxStatus).forEach(function(key) {
      if (!checkboxStatus[key]) return;

      var index = parseInt(key);
      $checkboxLis.eq(index).addClass('checked');
    });
  };

  addWrappingSpans();
  listenForSpanClicks();
  listenForLiClicks();
  initializeCheckboxes();
};

$(function() {
  var hideDelay = 0;
  var trigDelay = 250;
  var hideTimer = null;
  var ajax = null;

  var currentPosition = { left: '0px', top: '0px' };

  // One instance that's reused to show info for the current person
  var container = $('<div id="itemHoverContainer">'
    + '<div id="itemHoverContent"></div>'
    + '</div>');

  $('body').append(container);


  // Determine which "a" elements should trigger the item stats mouseover
  var $mouseoverTargets = $('span.ih a');
  var isItemCategory = document.title.startsWith('Category:') && document.title.includes('Equipment - Project 1999 Wiki');
  if (isItemCategory) {
    // Include the category's item list along with ".ih" links
    $mouseoverTargets = $mouseoverTargets.add('.mw-content-ltr a');
  }

  $mouseoverTargets = $mouseoverTargets.filter(function(i, a) {
    // Don't add hover to links like "next 200"
    return !$(a).attr('href').startsWith('/Special:') &&
           !$(a).attr('href').includes('title=Category:')
  });

  $mouseoverTargets.on('mouseover', function()
  {
    var $this = $(this);
    var itemname = $this.attr('title');

    if (itemname == '' || itemname == 'undefined')
      return;

    if (hideTimer)
      clearTimeout(hideTimer);

    if ($this.parents('div.mw-content-ltr').length) {
      var pos = $this.offset();
      var width = $this.width();

      container.css({
          left: pos.left + 5 + 'px',
          top: pos.top + 5 + 'px'
      });
    }



    $(this).trigger('mousemove');

    $('#itemHoverContent').html('&nbsp;');

    //$('#itemHoverContent').html('<div class="itemtopbg"><div class="itemtitle">Loading...</div></div>'
    //                          + '<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)
    {
      ajax.abort();
      ajax = null;
    }
    ajax = $.ajax({
      url: 'http://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');
    //container.fadeIn('fast');

  }); //on mouseover

  $('span.ih a').on('mouseout', function()
  {
    if (hideTimer)
      clearTimeout(hideTimer);
    hideTimer = setTimeout(function()
    {
      container.css('display', 'none');
      //container.fadeOut('fast');
    }, hideDelay);
  });

  $('span.ih a').mousemove(function(e){
    var mousex = e.pageX + 20; //Get X coodrinates
    var mousey = e.pageY + 20; //Get Y coordinates
    var tipWidth = container.width(); //Find width of tooltip
    var tipHeight = container.height(); //Find height of tooltip

    //Distance of element from the right edge of viewport
    var tipVisX = $(window).width() - (mousex + tipWidth);
    //Distance of element from the bottom of viewport
    var tipVisY = $(window).height() - (mousey + tipHeight);

    if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport

      if( tipWidth > e.pageX - 20 ){
        mousex = 0;
      } else {
        mousex = e.pageX - tipWidth - 20;
      }

    } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
      mousey = e.pageY - tipHeight - 20;
    }

    container.css({  top: mousey, left: mousex });
  });

  // Allow mouse over of details without hiding details
  $('#itemHoverContainer').mouseover(function()
  {
    if (hideTimer)
      clearTimeout(hideTimer);
  });

  // Hide after mouseout
  $('#itemHoverContainer').mouseout(function()
  {
    if (hideTimer)
      clearTimeout(hideTimer);
    hideTimer = setTimeout(function()
    {
      container.css('display', 'none');
      //container.fadeOut('fast');
    }, hideDelay);
  });

  // magelo non-ajax item hover, but move box with mouse
  $('.magelohb').mousemove(function(e){
    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 mousey = e.pageY + 20; //Get Y coordinates

    //Distance of element from the right edge of viewport
    var tipVisX = $(window).width() - (mousex + tipWidth - 20);
    //Distance of element from the bottom of viewport
    var tipVisY = $(window).height() - (mousey + tipHeight - 20);

    if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport

      if( tipWidth > e.pageX - 20){
        mousex = 0;
      } else {
        mousex = e.pageX - tipWidth - 20;
      }

    } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
      mousey = e.pageY - tipHeight - 20;
    }

    childContainer.css({ top: mousey, left: mousex, 'z-index':'999' });
  });

  // 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
  $('.magelohb span.hb').each(function(i) {
    $(this).css({'position':'fixed'});
  });

  // 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
  $('img[alt]').each(function (i, img) {
    $(img).attr('title', $(img).attr('alt'));
  });

  setupCheckboxes();


  // Give the Per-Level Hunting Guide Page its own JS
  if ($('title').text() === 'Per-Level Hunting Guide - Project 1999 Wiki') {
    importScript('MediaWiki:HuntingGuide.js');
  // The item category search also needs special JS
  } else if ($('title').text() === 'Item Category Search - Project 1999 Wiki') {
    importScript('MediaWiki:ItemCategorySearch.js');
  // So does the Solo Artist Challenge
  } else if ($('title').text() === 'Solo Artist Challenge - Project 1999 Wiki') {
    importScript('MediaWiki:SoloArtistChallenge.js');
  } else if ($('title').text() === 'Treasure Hunting Guide - Project 1999 Wiki') {
    importScript('MediaWiki:TreasureHuntingGuide.js');
  }

  // Warn users who accidentally try to edit a templated section
  if ((window.location + '').includes('title=Template:Namedmobpage&action=edit')) {
    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.');
  }

});