MediaWiki:Common.js: Difference between revisions

From Protoball
Jump to navigation Jump to search
(isCommentOrQuery remove edit fixup)
(MediaWiki:Common.js set_ballgame_name undefined fixup)
 
(28 intermediate revisions by the same user not shown)
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
/* Any JavaScript here will be loaded for all users on every page load. */


var google_api_key = "AIzaSyAV9jCvr3k6g750_YPm7hVer9ngTef04oY";
var google_api_key = "AIzaSyCQ-YHMywKy3nlIuZy0M17Xk8yoD8bKlBw";
var gamesAndClubs = []; // from json of all games and clubs
var gamesAndClubs = []; // from json of all games and clubs
var api; // set in formPrep()
wgPageName = mw.config.get('wgPageName')
wgAction = mw.config.get('wgAction')
wgUserName = mw.config.get('wgUserName')
wgUserGroups = mw.config.get('wgUserGroups')


$.getScript( '/js/jquery.cookie.js', onCookieLib );
$.getScript( '/js/jquery.cookie.js', onCookieLib );
Line 220: Line 226:
   var date = get_date_for_title();
   var date = get_date_for_title();


   var game_number = $(".game_number").val();
   var game_number = $(".game_number").val() || '';
   if(game_number) {
   if(game_number) {
     game_number = " " + game_number;
     game_number = " " + game_number;
Line 253: Line 259:
     mapTypeId: 'roadmap',
     mapTypeId: 'roadmap',
     scaleControl: true,
     scaleControl: true,
     scaleControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM }
     scaleControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM },
    zoomControl: true,
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_BOTTOM
    },
   });
   });
   if(isBallgamesAndClubs || isMapSearch) {
   if(isBallgamesAndClubs || isMapSearch) {
Line 362: Line 372:
*/
*/
}
}


function set_map_marker() {
function set_map_marker() {
   var fields = $(".country, .state, .city, .modern_address");
   var fields = $(".country, .state, .city, .modern_address");
  set_map_marker_for_fields(fields);
}
function set_map_marker_for_pics_location() {
  var fields = $(".pics-location");
  set_map_marker_for_fields(fields);
}
function set_map_marker_for_fields(fields) {
   var address = "";
   var address = "";
   fields.each(function() { if($(this).val()) { address = $(this).val() + ", " + address; } });
   fields.each(function() { if($(this).val()) { address = $(this).val() + ", " + address; } });
   if(address) {
   if(address) {
     address = address.substring(0, address.length - 2);  
     if (fields.length > 1) {
      address = address.substring(0, address.length - 2);
    }
     var map = $("#map")[0];
     var map = $("#map")[0];
     if(!map.geocoder) {
     if(!map.geocoder) {
Line 512: Line 534:
   map.filters = {};
   map.filters = {};
   map.marker_in_filter = function(marker) {  
   map.marker_in_filter = function(marker) {  
    var pos = marker.getPosition();
    if(isNaN(pos.lat()) || isNaN(pos.lng())) {
      console.log('bad lat or lng', marker);
      return false;
    }
     for(var filter in map.filters) {
     for(var filter in map.filters) {
       if(!(map.filters[filter] == marker[filter] || (marker[filter] && map.filters[filter] == '+'))) {
       if(!(map.filters[filter] == marker[filter] || (marker[filter] && map.filters[filter] == '+'))) {
Line 1,058: Line 1,085:


   //$(".city").change(function(){set_autocomplete(field, [city, state], "[[Category:" + "Fields]]")}).change();
   //$(".city").change(function(){set_autocomplete(field, [city, state], "[[Category:" + "Fields]]")}).change();
}
function titleExistsCheck(title, callback) {
  api.get({action: "query", titles: [title]}).then(
  function(result) {
    callback(!result.query.pages[-1]);
  });
}
function notifyOnDupTitle(namespace, elem) {
  elem = elem || this;
  if(!$("#dupTitleNotification").length) {
    $(elem).closest("td").append("<div id='dupTitleNotification' style='display: none'>Title already exists!</div>");
    return;
  }
  if(elem.defaultValue == elem.value) {
    $("#dupTitleNotification").hide();
    return;
  }
  namespace = namespace || '';
  titleExistsCheck(namespace + elem.value, function(exists) {
    if (exists) {
      $("#dupTitleNotification").show();
    } else {
      $("#dupTitleNotification").hide();
    }
  });
}
function notifyOnProtoPixDupTitle() {
  notifyOnDupTitle('ProtoPix:', this);
}
function getProtoPixTitleFromImageUpload() {
  var titleField = $(".proto_pix_title");
  if (!titleField || titleField.val()) {
    return;
  }
  var fileName = $(".proto_pix_image").val();
  var extIndex = fileName.lastIndexOf(".");
  fileName = fileName.substring(0, extIndex);
  fileName = fileName.replace(/(_|\-|\.)/g, ' ');
  titleField.val(fileName);
}
}


function formPrep() {
function formPrep() {
api = new mw.Api();
  if(wgPageName.indexOf("Special:FormEdit") > -1 || wgAction.indexOf("formedit") > -1) {
  if(wgPageName.indexOf("Special:FormEdit") > -1 || wgAction.indexOf("formedit") > -1) {
   $('.allow_new .checkboxesSpan').each(add_new_input);
   $('.allow_new .checkboxesSpan').each(add_new_input);
Line 1,079: Line 1,151:
   $(".type_of_date").change(set_date_by_type_of_date).change();
   $(".type_of_date").change(set_date_by_type_of_date).change();
   $(".ballgame_name").parents("form").submit(set_ballgame_name);
   $(".ballgame_name").parents("form").submit(set_ballgame_name);
   $('.image-upload').each(function(i) { if(i && !$(this).val()) {$(this).closest('tr').hide();} else { $(this).change() }});
   $($('.image-upload').get().reverse()).each(function(i) { if(i && !$(this).val()) {$(this).closest('tr').hide();} else { $(this).change() }});
   $('.image-upload').change(function() { if($(this).val()) { $(this).closest('tr').next().find('.image-upload').closest('tr').show(); } });
   $('.image-upload').change(function() { if($(this).val()) { $(this).closest('tr').next().find('.image-upload').closest('tr').show(); } });


Line 1,085: Line 1,157:
   $(".country, .state, .city, .modern_address").change(set_map_marker);
   $(".country, .state, .city, .modern_address").change(set_map_marker);
   /* ...Ballgames */
   /* ...Ballgames */
  /* ProtoPix */
  $(".pics-location").change(set_map_marker_for_pics_location);
  $(".notify_on_proto_pix_dup_title").change(notifyOnProtoPixDupTitle).change();
  $(".proto_pix_image").change(getProtoPixTitleFromImageUpload);
  /* ...ProtoPix */


   /* Editors... */
   /* Editors... */
Line 1,211: Line 1,289:
     }  
     }  
     inner.find(".hidden").remove();
     inner.find(".hidden").remove();
     inner.find("i").filter(function(i, e) {console.log(e); return e.text().substr(0,4) == "Edit";}).remove();
     inner.find("i").filter(function(i, e) {return $(e).text().substr(0,4) == "Edit";}).remove();
   }
   }
   setTimeout(merge, 500);  
   setTimeout(merge, 500);  

Latest revision as of 13:58, 27 February 2024

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

var google_api_key = "AIzaSyCQ-YHMywKy3nlIuZy0M17Xk8yoD8bKlBw";
var gamesAndClubs = []; // from json of all games and clubs
var api; // set in formPrep()

wgPageName = mw.config.get('wgPageName')
wgAction = mw.config.get('wgAction')
wgUserName = mw.config.get('wgUserName')
wgUserGroups = mw.config.get('wgUserGroups')

$.getScript( '/js/jquery.cookie.js', onCookieLib );
function onCookieLib() {
  show_predecessor_games = $.cookie('show_predecessor_games') == "true";
  show_additional_markers = $.cookie('show_additional_markers') == "true";
  spread_markers = $.cookie('spread_markers') == "true";
  set_map_trigger('cookies');
}

function ClassProp(css_class, property) {
  this.css_class = css_class;
  this.property = property;
}

function set_autocomplete(target_info, filter) {
  var values = get_autocomplete_values(target_info.property, filter);
  var target_input = $("." + target_info.css_class);
  target_input.autocomplete({
    source: get_autocomplete_source_function(values),
    select: function(event, ui) { event.preventDefault(); $(this).val(ui.item.value); $(this).change(); } 
  });
}

function get_autocomplete_values(property, filter) {
  valueDict = {}
  for(var i = 0; i < gamesAndClubs.length; i++) {
    var thing = gamesAndClubs[i];
    if (filter && !filter(thing)) {
      continue;
    }
    valueDict[thing[property]] = true;
  }
  var values = Object.keys(valueDict);
  values.sort();
  return values;
}

function get_autocomplete_source_function(values) {
  return function(request, response) {
    var results = $.ui.autocomplete.filter(values, request.term);
    response(results.slice(0, 100));
  };
}

function parse_list(text) {
  if(text[0] == '\n') { return []; }
  return text.split("\n")[0].substring("<p>".length).split(",");
}

function api_parse(text, callback) {
  var data = {action: "parse", prop: "text", format: "json", text: text };
  $.getJSON("/api.php", data, callback);
}

function get_property_values(property, filter, callback) {
  var ask = "{{#arraydefine:array|{{#ask:" + filter + "|?" + property + "|link=none|mainlabel=-|headers=hide|limit=10000|sep=@}}|@|unique}}{{#arrayprint:array|,}}";
  api_parse(ask, callback);
}

function default_to_one_and_hide() {
  if(!$(this).val()) {
    $(this).val("1");
  }
  $(this).hide();
}

function modify_selected_values() {
  var input = $(this).parent().prev('span').children('input');
  var chk_value = this.value;
  var selected_values = input.val() ? input.val().split(/ *, */) : [];
  if(this.checked) {
    selected_values.push(this.value);
    selected_values.sort();
  } else {
    selected_values = $.grep(selected_values, function(value) { return value != chk_value; });
  }
  input.val(selected_values.join(", "));
}

function add_new_input() {
  var span = this;
  var input = $(this).children('input').first();
  var name = input.attr('name');
  var index =  "" + $(this).find('input').length - 1;
  name = name.replace("[is_list]", "[" + index + "]");
  var new_item = $('<span class="checkboxSpan"><span>&nbsp;<a href="" class="new_multi_property_link">new</a>&nbsp;</span><span style="display:none;">&nbsp;new&nbsp;<input name="' + name + '" /></span></span>');
  $(this).append(new_item);
  $(this).find(".new_multi_property_link").click(function(){ $(this).parent().parent().children('span').toggle(); return false; });
}

function set_salience_names() {
  var names = { 1: "Prominent", 2: "Noteworthy", 3: "Peripheral", 4: "Incomplete" };
  var inputs = $(this).find('input');
  for(var i = 1; i < 5; i++) {
    inputs[i].nextSibling.nodeValue = " " + names[i];
  }
}

function populate_chron_year_number() {
  var year = $('[name="Chronology Entry[Year]"]').val();
  if(!year) return;
  var defaultYear = $('[name="Chronology Entry[Year]"]').prop("defaultValue");
  if(year == defaultYear) {
    var defaultVal = $('[name="Chronology Entry[Year Number]"]').prop("defaultValue");
    $('[name="Chronology Entry[Year Number]"]').val(defaultVal);
    return;
  }
  var ask = "/Special:Ask/-5B-5BYear::" + year + "-5D-5D";
  ask += "/-3FYear-20Number/mainlabel%3D-2D/limit%3D1/order%3DDESC/sort%3DYear_Number/searchlabel%3D/format%3Djson";
  var data = {};
  var year_input = $('[name="Chronology Entry[Year Number]"]');
  $.getJSON(ask, data).done(function (data) {
    var num = 1;
    for(var r in data.results) {
       var year_num = data.results[r].printouts["Year Number"][0];
       if (year_num > num) {
           num = year_num + 1;
       }
    }
    year_input.val(num);
  }).fail(function() {year_input.val(1)});
}

function sort_eras_chronologically() {
  var spans = $(this).children('span');
  /* 1700s 1800s Contemporary Derivative Post-1900 Pre-1700 Predecessor */
  $(this).append(spans[6]);
  $(this).append(spans[3]);
  $(this).append(spans[5]);
  $(this).append(spans[0]);
  $(this).append(spans[1]);
  $(this).append(spans[4]);
  $(this).append(spans[2]);
  $(spans[3]).after("<br />");
}

function set_none_to_unknown_for_enumerated_radio_buttons() {
  var input = $(this).find('input')[0];
  input.nextSibling.nodeValue="Unknown";
}

function set_none_value_for_enumerated_radio_buttons() {
  var input = $(this).find('input')[0];
  input.value = "";
}

function set_date_by_type_of_date() {
  var type_of_date = $(this).val();
  if(type_of_date == "") { $(this).val("Day"); type_of_date = "Day"; }
  var day = $(this).parents("tr").find(".dayInput");
  var month = $(this).parents("tr").find(".monthInput");
  if(type_of_date == "Day") {
    day.show();
    month.show();
  } else {
    day.val("1");
    day.hide();
    if (type_of_date == "Month") {
      month.show();
    } else {
      month.hide();
      month.val("01");
    }
  }
}


function get_date_for_title() {
  var type_of_date = $(".type_of_date").val();
  var day = $(".dayInput").val();
  var month = $(".monthInput option:selected").text();
  var year = $(".yearInput").val();
  var date = "";
  if(type_of_date == "Day") {
    date = "on " + day + " " + month + " " + year;
  } else if(type_of_date == "Month") {
    date = "in " + month + " " + year;
  } else if(type_of_date == "Year") {
    date = "in " + year;
  } else if(type_of_date == "Circa") {
    date = "Circa " + year;
  }
  return date;
}


function set_ballgame_name() {
  var championship = $(".championship").val();
  var year = $(".yearInput").val();
  if(championship) {
    $(".ballgame_name").val(championship + " " + year);
    return;
  }
  var home_team = $(".home_team").val();
  var away_team = $(".away_team").val();
  var country = $(".country").val();
  var state = $(".state").val();
  var city = $(".city").val();
  var event = "";
  if(home_team != "") {
    event = home_team;
    if(away_team != "") {
      event += " v " + away_team;
    }
  } 
  if(home_team.indexOf(" ") == -1) {
    var places = [city, state, country];
    for(var i in places) {
      if(places[i] != "") {
        event += (event.length > 0 ? " " : "") + "in " + places[i];
        break;
      }
    }
  }

  var date = get_date_for_title();

  var game_number = $(".game_number").val() || '';
  if(game_number) {
    game_number = " " + game_number;
  }

  $(".ballgame_name").val(event + " " + date + game_number);
}

/* Maps... */
var show_predecessor_games = false;
var show_additional_markers = false;
var spread_markers = false;
var load_search_markers = function() {};

function set_map() {
  var elysian_fields = new google.maps.LatLng(40.749885, -74.027172);
  var lat_long = $('#lat_long').text();
  lat_long = lat_long? lat_long: $('[name$="[Coordinates]"]').val();
  if(lat_long && lat_long.indexOf("error") == -1) {
    lat_long = lat_long.split(", ");
  } else {
    lat_long = null;
  }
  var coords = lat_long? new google.maps.LatLng(parseFloat(lat_long[0]), parseFloat(lat_long[1])) : elysian_fields;
  var map = $("#map")[0];
  map.infoWindow = new google.maps.InfoWindow();
  var isBallgamesAndClubs = $(map).hasClass("map_ballgames");
  var isMapSearch = $(map).hasClass("map_search");
  map.map = new google.maps.Map(map, {
    center: isBallgamesAndClubs || isMapSearch ? null: coords,
    zoom: isBallgamesAndClubs || isMapSearch ? null : 11, // zoom bug for boroughs
    mapTypeId: 'roadmap',
    scaleControl: true,
    scaleControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM },
    zoomControl: true,
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_BOTTOM
    },
  });
  if(isBallgamesAndClubs || isMapSearch) {
    google.maps.event.addListener(map.infoWindow,'closeclick',function(){
      map.infoWindow.marker = null;
    });

    google.maps.event.addListener(map.map, 'zoom_changed', function(event) {
      if(map.infoWindow.marker) {
        map.map.setCenter(map.infoWindow.marker.getPosition());
      }
    });
  }

  if(isBallgamesAndClubs) {
    map.spread_markers = spread_markers;

    createOverlay("Spread Markers Each Location", function() {
      var map = $("#map")[0];
      $.cookie('spread_markers', this.checked);
      map.spread_markers = this.checked;
      map.infoWindow.close(map.map);
      map.infoWindow.marker = null;
      filter_map_years();
    }, spread_markers);


    createOverlay("Show Predecessor Games", function() { 
      show_predecessor_games = this.checked;
      $.cookie('show_predecessor_games', this.checked);
      set_map_layer();
    }, show_predecessor_games);

    createOverlay("Show Additional Markers", function() {
      var map = $("#map")[0];
      $.cookie('show_additional_markers', this.checked);
      var set = this.checked ? map.map : null;
      for(i = 0; i < map.markers.length; i++) { if(!map.marker_in_filter(map.markers[i])) { map.markers[i].setMap(set); } }
    }, show_additional_markers);

    createOverlay('<img height="25px" src="' + marker_image_url("c", "FFCC00") + '" /> = Clubs, <img height="25px" src="' + marker_image_url("•", "FF867C") + '" /> = +Games');

    set_map_layer();
  } else if($(map).hasClass("map_picker")) {
    if(!lat_long) { set_map_marker(); }
    set_map_picker();
  } else if($(map).hasClass("map_search")) {
    map.marker_in_filter = function(marker) { 
      return true;
    };
    load_search_markers();
  }
}

function createOverlay(label, callback, checked) {
  this.overlayCount = (this.overlayCount ? this.overlayCount: 0) + 1;
  var name = "overlay" + this.overlayCount;
  if(callback) {
    checked = checked ? 'checked="checked"' : "";
    label = '<input type="checkbox" ' + checked + ' name="' + name + '" id="' + name + '" /><label for="' + name + '">' + label + '</label>';
  }
  var overlay = $('<div class="google_map_inlay '+ name +'" id="' + name + '">' + label + '</div>')[0];
  if(callback) {
    $(overlay).children("input").change(callback);
  }
  map.map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(overlay);
}
//var off_save_form_for_marker_change;
function set_map_picker() {
  var map = $("#map")[0];
  map.marker = new google.maps.Marker({
    map:map.map,
    //draggable:true,
    //animation: google.maps.Animation.DROP,
    position: map.map.center
  });
  if(!map.geocoder) {
    map.geocoder = new google.maps.Geocoder();
  }
/*
  setTimeout(function(){
    var map = $("#map")[0];
    map.infoWindow.setContent("<strong>Movable marker.</strong></br >" + (map.marker_not_set_by_default?"Type address to set.":"Move to change coordinates."));
    map.infoWindow.open(map.map, map.marker);
  }, 500);
  setTimeout(function(){
    var map = $("#map")[0];
    map.infoWindow.close(map.map);
    map.map.setCenter(map.marker.getPosition());
  }, 7000);
  google.maps.event.addListener(map.map, 'zoom_changed', function(event) {
     map.map.setCenter(map.marker.getPosition());
  });
  google.maps.event.addListener(map.marker, 'mouseup', function(event) {
    $('[name$="[Coordinates]"]').val(map.marker.position.lat() + ", " + map.marker.position.lng());
    if(off_save_form_for_marker_change) { clearTimeout(off_save_form_for_marker_change); }
    setTimeout(function(){
      var map = $("#map")[0];
      map.infoWindow.close(map.map);
      map.infoWindow.setContent("<strong>Coordinates changed.</strong></br >Save the whole form to save.");
      map.infoWindow.open(map.map, map.marker);
    }, 500);
    off_save_form_for_marker_change = setTimeout(function(){
      var map = $("#map")[0];
      map.infoWindow.close(map.map);
    }, 4500);
  });
*/
}


function set_map_marker() {
  var fields = $(".country, .state, .city, .modern_address");
  set_map_marker_for_fields(fields);
}

function set_map_marker_for_pics_location() {
  var fields = $(".pics-location");
  set_map_marker_for_fields(fields);
}

function set_map_marker_for_fields(fields) {
  var address = "";
  fields.each(function() { if($(this).val()) { address = $(this).val() + ", " + address; } });
  if(address) {
    if (fields.length > 1) {
      address = address.substring(0, address.length - 2);
    }
    var map = $("#map")[0];
    if(!map.geocoder) {
      map.geocoder = new google.maps.Geocoder();
    }
    map.geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if(map.marker) {
          map.marker.position = results[0].geometry.location;
          map.marker.setMap(map.map);
          $('[name$="[Coordinates]"]').val(map.marker.position.lat() + ", " + map.marker.position.lng());
        } else {
          map.marker_not_set_by_default = true; 
        }
        var spots = results[0].address_components.length;
        map.map.setZoom(spots > 2 ? 12 : spots == 2 ? 6 : 3);
        map.map.setCenter(results[0].geometry.location);
      }
    });
  }
}

/* Maps > Markers... */

function marker_image_url(letter, color) {
  return "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=" + encodeURI(letter + "|" + color);
}

function custom_marker_and_shadow(letter, color) {
  var pinImage = new google.maps.MarkerImage(marker_image_url(letter, color),
    new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34));
  var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    new google.maps.Size(40, 37), new google.maps.Point(0, 0), new google.maps.Point(12, 35));
  return [pinImage, pinShadow];
}

var _orange_bullet_marker_and_shadow;
function orange_bullet_marker_and_shadow() {
  if (!_orange_bullet_marker_and_shadow) {
    _orange_bullet_marker_and_shadow = custom_marker_and_shadow("c", "FFCC00");
  }
  return _orange_bullet_marker_and_shadow;
}

function marker_click_function(map, marker, infoWindow, info_function) {
    return function() {
        infoWindow.close(map)
        infoWindow.setContent(info_function(marker));
        infoWindow.open(map, marker);
  infoWindow.marker = marker;
    };
}

function get_address_info_from_marker(marker, domain) {
  var city = "", state = "", country = "", address = "", borough = "";
  if(marker.city) {
    address = marker.city + (marker.state ? ", " + marker.state : "") + (marker.country && marker.country != "United States" ? ", " + marker.country : "");
    city = '<a target="_blank" href="' + domain + address.replace(/ /g, "_") + '">' + marker.city + '</a>';
  }
  if(marker.borough) {
    address = marker.borough;
    borough = '<a target="_blank" href="' + domain + address.replace(/ /g, "_") + '">' + marker.borough + '</a>';
  }
  if(marker.state) {
    address = marker.state + (marker.country && marker.country != "United States" ? ", " + marker.country : "");
    state = '<a target="_blank" href="' + domain + address.replace(/ /g, "_") + '">' + marker.state + '</a>';
  }
  if(marker.country) {
    country = '<a target="_blank" href="' + domain + marker.country.replace(/ /g, "_") + '">' + marker.country + '</a>';
  }
  return ((city ? ", " + city : "") + (state ? ", " + state : "") + (country ? ", " + country : "")).replace(/^, /, "");
}

function ballgames_info(marker, domain) {
  var map = $("#map")[0];
  var domain = "https://" + document.domain + "/";
  var address = get_address_info_from_marker(marker, domain);
  var infoHtml = "";
  if(map.spread_markers || !marker.markers || marker.markers.length == 1) {
    infoHtml = '<strong><a target="_blank" href="' + domain + marker.title.replace(/ /g, "_") + '">' + marker.title + '</a></strong><br>';
    if(marker.source_type == "Club") {
      infoHtml += marker.date + "<br>";
    }
    infoHtml += address + "<br>";
    if(marker.modern_address) {
      infoHtml += marker.modern_address + "<br>";
    }
    if(marker.borough) {
      infoHtml += marker.borough + "<br>";
    }
    if(marker.source_type != "Club") {
      infoHtml += marker.info + "<br>";
    }
    if(marker.digger) {
      infoHtml += "Found by " + '<a target="_blank" href="' + domain + marker.digger.replace(/ /g, "_") + '">' + marker.digger + "</a><br>";
    }
    return infoHtml;
  } else {
    infoHtml = '<strong>' + address + '</strong><br>';
    infoHtml += marker.thingsTitle;
    infoHtml += "<br>";
    var things = [marker.clubs, marker.games];
    if(show_predecessor_games) { things.push(marker.predecessors) }
    for(var i in things) {
      for(var j in things[i]) {
        var thing = things[i][j];
        infoHtml += '<a target="_blank" href="' + domain + thing.title.replace(/ /g, "_") + '">' + thing.title + '</a>'
        infoHtml += (things[i] == marker.clubs) ? " est. " + thing.year : "";
        infoHtml += '<br>';
        if(thing.digger) {
          infoHtml += "&nbsp;Found by " + '<a target="_blank" href="' + domain + thing.digger.replace(/ /g, "_") + '">' + thing.digger + "</a><br>";
        }
      }
    }
    return infoHtml;
  }
}

/* ...Maps > Markers */

function spiral_coords(lat_long, i, zoom) {
  if(i <= 1) return lat_long;
    var angle = Math.sqrt(i);
  var a = 0;
  var b = 500;
  var r = 0.000002;
    var x = lat_long[1] + (r * (a + (b * angle)) * Math.cos(angle * 3));
    var y = lat_long[0] + (r * .8 * (a + (b * angle)) * Math.sin(angle * 3));
  return [y, x];
}


function set_map_layer() {
  var map = $("#map")[0];
  var classes = $(map).attr("class").split(" ");
  var map_types = [];
  for(var i in classes) {
    if(classes[i].indexOf("map") == 0) {
      map_types[map_types.length] = classes[i].substring("map_".length);
    }
  }
  var filter = '';
  map.filters = {};
  map.marker_in_filter = function(marker) { 
    var pos = marker.getPosition();
    if(isNaN(pos.lat()) || isNaN(pos.lng())) {
      console.log('bad lat or lng', marker);
      return false;
    }
    for(var filter in map.filters) {
      if(!(map.filters[filter] == marker[filter] || (marker[filter] && map.filters[filter] == '+'))) {
        return false;
      }
    }
    var isPred = marker.source_type == "Predecessor Game";
    if(show_predecessor_games && !isPred) {
      return false;
    }
    if(!show_predecessor_games && isPred) {
      return false;
    }
    return true;
  };

  var filters = ['Country', 'State', 'Borough', 'City'];
  for(var i in filters) {
    var text = $("#" + filters[i]).text();
    if (!text) { continue; }
    map.filters[filters[i].toLowerCase()] = text;
  }
  ballgamesDataHandler(gamesAndClubs);
}



function ballgamesDataHandler(d) {
  var map = $("#map")[0];
  var zoom = map.map.getZoom();
  var reset = !!map.markers;
  if(reset) {
    for(var i in map.markers) {
      map.markers[i].setMap(null);
    }
    map.years = null;
  }
  if(map.infoWindow) map.infoWindow.marker = null;
  map.markers = [];

  var location_markers = {};

  for (var i = 0; i < d.length; i++) {
    var row = d[i];
    var location = row["Location"];
    var lat_long = location.split(" ");
    lat_long[0] = parseFloat(lat_long[0]);
    lat_long[1] = parseFloat(lat_long[1]);
    if(!(location in location_markers)) {
      location_markers[location] = [];
    }
    var spiral_number = location_markers[location].length + 1;
    var spiral_lat_long = spiral_coords(lat_long, spiral_number, zoom);
    var date = row["Date"];
    var year = parseInt(date.substring(date.length - 5))
    var marker = new google.maps.Marker({
      lat_long: lat_long,
      location: location,
      spiral_number: spiral_number,
      spiral_zoom: zoom,
      position: new google.maps.LatLng(spiral_lat_long[0], spiral_lat_long[1]),
      title: row["Title"],
      date: date,
      year: year,
      city: row["City"],
      borough: row["Borough"],
      state: row["State"],
      country: row["Country"],
      info: row["Info"],
      source_type: row["Type"],
      modern_address: row["Modern Address"],
      digger: row["Digger"],
    });
    if(marker.source_type == "Club") {
      marker.set('icon', orange_bullet_marker_and_shadow()[0]);
      marker.set('shadow', orange_bullet_marker_and_shadow()[1]);
    }
    location_markers[location].push(marker);
    if(map.spread_markers || location_markers[location].length == 1) {
      var set = show_additional_markers || map.marker_in_filter(marker) ? map.map : null; 
      marker.setMap(set);
    }
    if(map.marker_in_filter(marker)) {
      if(!map.years) {
        map.years = [year, year];
      } else {
        map.years = [Math.min(map.years[0], year), Math.max(map.years[1], year)];
      }
    }
    map.markers.push(marker);
    var click_function = marker_click_function(map.map, marker, map.infoWindow, ballgames_info);
    google.maps.event.addListener(marker, 'click', click_function);
  }
  if(map.years) {
    map.base_years = [map.years[0], map.years[1]];
    map.filter_years = [map.years[0], map.years[1]];
    set_map_boundries();
    if(reset && $("#slider")[0].is_setup) { slider_reset(); } else { slider_setup(); }
    set_marker_markers(location_markers);
  }
}

function set_map_boundries() {
  var map = $("#map")[0];
  var bounds = new google.maps.LatLngBounds();
  var some_bounds = false;
  for(var i in map.markers) {
    if(!map.marker_in_filter(map.markers[i])) continue;
    bounds.extend(map.markers[i].getPosition());
    some_bounds = true;
  }
  if (some_bounds) fitBounds(map.map, bounds);
}

function fitBounds(map, bounds) {
  if(!map.zoomListenerSet) {
    map.zoomListenerSet = true;
    google.maps.event.addListener(map, 'bounds_changed', function(event) {
      if (this.getZoom() > 13 && this.fitBoundsCall == true) {
            this.setZoom(13);
            this.fitBoundsCall = false;
      }
    });
  }
  map.fitBoundsCall = true;
  map.fitBounds(bounds);
}

function search_entries_data_handler(entries) {
  var map = $("#map")[0];
  var zoom = map.map.getZoom();
  map.markers = [];

  var location_markers = {};
  $.each(entries, function(index, entry) {
    var location = entry.coordinates;
    if(!location) {
      return;
    }
    var lat_long = location.split(" ");
    lat_long[0] = parseFloat(lat_long[0]);
    lat_long[1] = parseFloat(lat_long[1]);
    if(!(location in location_markers)) {
      location_markers[location] = [];
    }
    var spiral_number = location_markers[location].length + 1;
    var spiral_lat_long = spiral_coords(lat_long, spiral_number, zoom);
    var date = entry.date;
    var year = date ? parseInt(date.substring(0, 4)): null;
    var marker = new google.maps.Marker({
      lat_long: lat_long,
      location: location,
      spiral_number: spiral_number,
      spiral_zoom: zoom,
      position: new google.maps.LatLng(spiral_lat_long[0], spiral_lat_long[1])
    });
    if(year) {
      marker.year = year;
      marker.date = date;
    }
    marker.info_keys = [];
    $.each(entry, function(key, value) {
      marker[key] = entry[key];
      marker.info_keys.push(key);
    });
    location_markers[location].push(marker);
    if(map.spread_markers || location_markers[location].length == 1) {
      marker.setMap(map.map);
    }
    if(year) {
      if(!map.years) {
        map.years = [year, year];
      } else {
        map.years = [Math.min(map.years[0], year), Math.max(map.years[1], year)];
      }
    }
    map.markers.push(marker);
    var click_function = marker_click_function(map.map, marker, map.infoWindow, search_entry_info);
    google.maps.event.addListener(marker, 'click', click_function);
  });
  if(map.years) {
    map.base_years = [map.years[0], map.years[1]];
    map.filter_years = [map.years[0], map.years[1]];
    set_map_boundries();
    slider_setup(); 
    set_marker_markers(location_markers);
  }
}

function search_entry_info(marker) {
  var map = $("#map")[0];
  var domain = "https://" + document.domain + "/";
  var address = get_address_info_from_marker(marker, domain);
  var infoHtml = "";
  if(map.spread_markers || !marker.markers || marker.markers.length == 1) {
    infoHtml = '<strong><a target="_blank" href="' + domain + marker.title.replace(/ /g, "_") + '">' + (marker.title_text || marker.title) + '</a></strong><br>';
    if(marker.source_type == "Club") {
      infoHtml += marker.date + "<br>";
    }
    infoHtml += address + "<br>";
    if(marker.modern_address) {
      infoHtml += marker.modern_address + "<br>";
    }
    if(marker.borough) {
      infoHtml += marker.borough + "<br>";
    }
    $.each(marker.info_keys, function(index, key) {
      if(['title', 'city', 'borough', 'state', 'country', 'name', 'coordinates', 'source_type'].indexOf(key) == -1) {
        infoHtml += key + ": " + marker[key].substring(0,40) + (marker[key].length > 40 ? "..." : "") + "<br>";
      }
    })
    if(marker.digger) {
      infoHtml += "Found by " + '<a target="_blank" href="' + domain + marker.digger.replace(/ /g, "_") + '">' + marker.digger + "</a><br>";
    }
    return infoHtml;
  } else {
    infoHtml = '<strong>' + address + '</strong><br>';
    infoHtml += marker.thingsTitle;
    infoHtml += "<br>";
    var things = [marker.clubs, marker.games, marker.others];
    for(var i in things) {
      for(var j in things[i]) {
        var thing = things[i][j];
        infoHtml += '<a target="_blank" href="' + domain + thing.title.replace(/ /g, "_") + '">' + (thing.title_text || thing.title) + '</a>'
        infoHtml += (things[i] == marker.clubs) ? " est. " + thing.year : "";
        infoHtml += '<br>';
        if(thing.digger) {
          infoHtml += "&nbsp;Found by " + '<a target="_blank" href="' + domain + thing.digger.replace(/ /g, "_") + '">' + thing.digger + "</a><br>";
        }
      }
    }
    return infoHtml;
  }
}

function set_map_trigger(script) {
  this.scripts = this.scripts || {};
  this.scripts[script] = true;
  if (Object.keys(this.scripts).length == 3) {
    set_map();
  }
}

if($('#map').length > 0) {
  $.getScript('https://maps.googleapis.com/maps/api/js?sensor=false&async=2&key=' + google_api_key, function() {
    set_map_trigger('googleapis');
  });
  $.ajax({
    dataType: "json",
    url: '/games_and_clubs.json',
    cache: true,
    beforeSend: function(xhr) {
      xhr.setRequestHeader('Cache-Control', 'private');
      xhr.setRequestHeader('Pragma', 'cache=yes');
    },
    success: function(data) {
      gamesAndClubs = data;
      set_map_trigger('json');
    }
  });
}

/* Maps > UI slider... */

if($('.slider, .tabs').length > 0) {
  $.getScript('/jquery-ui/js/jquery-ui-1.8.23.custom.min.js', ui_setup);
}

function ui_setup() {
  $('.tabs').each(function() { $(this).tabs(); $(this).removeClass("ui-widget ui-widget-content"); $(this).find(".scrollable").removeClass("ui-widget-content"); });
  slider_setup();
}

function slider_setup() {
  if($("#map").length > 0 && $("#map")[0].years && $("#slider").slider && $("#slider").length > 0 && !$("#slider")[0].is_setup) {
    var map = $("#map")[0];
    $('<div id="slider-one-year" class="slider" style="display: none"></div>').insertAfter("#slider");
    $("#slider").slider({
      range: true,
      min: map.years[0],
      max: map.years[1],
      values: map.years,
      change: function( event, ui ) {
        map.years = [parseInt(ui.values[0]), parseInt(ui.values[1])];
      },
      slide: function( event, ui ) {
        var slider = $("#slider")[0];
        if(event) {
          var old_values = map.years;
          map.years = [parseInt(ui.values[0]), parseInt(ui.values[1])];
          if(slider.mode && slider.mode == "freeze_ranges") {
            var old_diff = old_values[1] - old_values[0];
            var new_diff = map.years[1] - map.years[0];
            if(old_diff != new_diff) {
              var index = (old_values[0] == map.years[0]) ? 0 : 1;
              var value = index == 0 ? Math.max(map.years[1] - old_diff, map.base_years[0]) : Math.min(map.years[0] + old_diff, map.base_years[1]);
              map.years[index] = value;
              $(slider).slider("values", index, value);
            }
          }
        } else if (slider.mode && slider.mode == "freeze_ranges") {
          if(map.years[0] == map.base_years[0] && map.years[1] == map.base_years[1]) {
            map.years[1] = Math.min(map.years[1], map.years[0] + 1);
            $(slider).slider("values", 1, map.years[1]);
          }
        }
        set_slider_text(map.years);
        map.filter_years = map.years;
        filter_map_years();
      }
    });
    $("#slider-one-year").slider({
      min: map.years[0],
      max: map.years[1],
      value: map.years[0],
      slide: function( event, ui ) {
        if(event) {
          map.year = parseInt(ui.value);
        } else if(!map.year) {
          map.year = map.years[0];
          $("#slider-one-year").slider("value", map.year);
        }
        set_slider_text([map.year]);
        map.filter_years = [map.year, map.year];
        filter_map_years();
      }
    });
    $("#slider")[0].is_setup = true;
    set_slider_text(map.years);
    $('<div class="slider_opts"><input type="radio" name="slider_group" value="standard" id="standard_slide" checked="checked" /> Standard  <input type="radio" name="slider_group" value="freeze_ranges" id="freeze_slide" /> Freeze Range <input type="radio" name="slider_group" value="one_year" id="one_year_slide" /> One Year At a Time</div>').insertBefore("#slider-values");
    $("#standard_slide, #freeze_slide").click(function() { var slider = $("#slider"); slider[0].mode = $(this).val(); $("#slider-one-year").hide(); slider.show(); slider.slider('option', 'slide').call(slider); });
    $("#one_year_slide").click(function() { var slider = $("#slider-one-year"); $("#slider").hide(); slider.show(); slider.slider('option', 'slide').call(slider); });
  }
}

function slider_reset() {
  var map = $("#map")[0];
  map.year = map.years[0];
  $("#slider, #slider-one-year").slider("option", "min", map.years[0] );
  $("#slider, #slider-one-year").slider("option", "max", map.years[1] );
  map.years = map.prev_years ? map.prev_years : map.years;
  map.year = map.prev_year ? map.prev_year : map.year;
  map.prev_years = $("#slider").slider("option", "values");
  map.prev_year = $("#slider-one-year").slider("option", "value");
  $("#slider").slider("option", "values", map.years);
  $("#slider-one-year").slider("option", "value", map.year);
  set_slider_text($("#one_year_slide")[0].checked ? [map.years[0]] : map.years);
}

function year_link(year, back_or_forwards, displayed, left_or_right) {
  back_or_forwards = displayed ? back_or_forwards : "nowhere";
  return '<a href="#" id="move_map_' + year + '_' + back_or_forwards + '" class="move_map_year"' + (displayed?'':' style="color:white;"') + '><i class="icon-chevron-' + left_or_right + '"></i></a>';
}

function set_slider_text(years) {
  var map = $("#map")[0];
  var label = years.length > 1 ? "Years: " : "Year: ";
  var link = "";
  var range_mode = years.length == 2;
  var frozen_range_mode = range_mode && $("#slider")[0].mode == "freeze_ranges";
  for(var i in years) {
    var handle = years.length == 1 ? "year" : "year" + i;
    var show_left_link = years[i] > map.base_years[0] && (!range_mode || !(i == 1 && years[0] == years[1])) && (!frozen_range_mode || i == 0);
    var show_right_link = years[i] < map.base_years[1] && (!range_mode || !(i == 0 && years[0] == years[1])) && (!frozen_range_mode || i == 1);
    if(i == 1) {
      link += " - ";
    }
    link += year_link(handle, "back", show_left_link, "left");
    link += ' ' + years[i] + ' ';
    link += year_link(handle, "forward", show_right_link, "right");
  }
  $("#slider-values").html(label + link);
  $(".move_map_year").click(adjust_map_by_one);
}

function adjust_map_by_one() {
  var map = $("#map")[0];
  var info = this.id.split("_");
  var handle = info[2];
  var move = info[3];
  if(move == "nowhere") return false;
  var slider;
  if(handle == "year") {
    map.year += move == "forward" ? 1: -1;
    slider = $("#slider-one-year");
    slider.slider("value", map.year);
  } else {
    slider = $("#slider");
    if(slider[0].mode == "freeze_ranges") {
      map.years[0] += move == "forward" ? 1: -1;
      map.years[1] += move == "forward" ? 1: -1;
    } else {
      var i = parseInt(handle.substr(4));
      map.years[i] += move == "forward" ? 1: -1;
    }
    slider.slider("values", map.years);
  }
  slider.slider('option', 'slide').call(slider);
  return false;
}

function filter_map_years() {
  var map = $("#map")[0];
  var zoom = map.map.getZoom();
  var location_markers = {};
  for(var i in map.markers) {
    var marker = map.markers[i];
    var on = false;
    var reset = false;
    if(marker.year) {
      // allow for markers beyond filter years to show when the range is at the extreme points
      if((map.base_years[0] == map.filter_years[0] || marker.year >= map.filter_years[0]) && (map.base_years[1] == map.filter_years[1] || marker.year <= map.filter_years[1])) {
        var location = marker.location;
        if(!(location in location_markers)) {
          location_markers[location] = [];
        }
        location_markers[location].push(marker);
        var location_count = location_markers[location].length;
        if(map.spread_markers || location_count == 1) {
          on = true;
          if(marker.spiral_number != location_markers[location].length || marker.spiral_zoom != zoom) {
            var spiral_lat_long = spiral_coords(marker.lat_long, location_count, zoom);
            marker.position = new google.maps.LatLng(spiral_lat_long[0], spiral_lat_long[1]);
            marker.spiral_number = location_count;
            marker.spiral_zoom = zoom;
            reset = true;
            if(marker.source_type == "Club") {
              marker.set('icon', orange_bullet_marker_and_shadow()[0]);
              marker.set('shadow', orange_bullet_marker_and_shadow()[1]);
            }
          }
        }
      }
    }
    if(on && (!marker.map || reset)) {
      var set = show_additional_markers || map.marker_in_filter(marker) ? map.map : null; 
      marker.setMap(set);
    } else if(!on) {
      marker.setMap(null);
    }
  }
  set_marker_markers(location_markers);
}

function set_marker_markers(location_markers) {
  for(var location in location_markers) {
    var marker = location_markers[location][0];
    marker.markers = location_markers[location];
    if(marker.markers.length > 1) {
      marker.clubs = [];
      marker.games = [];
      marker.predecessors = [];
      marker.others = [];
      for(var i in marker.markers) {
        var thing = (marker.markers[i].source_type == "Club") ? marker.clubs 
        : (marker.markers[i].source_type == "Ballgame") ? marker.games
        : (marker.markers[i].source_type == "Predecessor Game") ? marker.predecessors
        : marker.others;
        thing.push(marker.markers[i]);
      }
      marker.thingsTitle = "";
      if(marker.clubs.length > 0) {
        marker.thingsTitle += marker.clubs.length + " club" + (marker.clubs.length > 1?"s":"");
        if(marker.games.length == 0) {
          marker.set('icon', orange_bullet_marker_and_shadow()[0]);
          marker.set('shadow', orange_bullet_marker_and_shadow()[1]);
        }
      }
      if(marker.games.length > 0) {
        if(marker.thingsTitle) { marker.thingsTitle += (show_predecessor_games && marker.predecessors.length > 0) ? ", " : " and "; }
        marker.thingsTitle += marker.games.length + " ballgame" + (marker.games.length > 1?"s":"");
        marker.set('icon', null);
        marker.set('shadow', null);   
      }
      if(show_predecessor_games && marker.predecessors.length > 0) {
        if(marker.thingsTitle) { marker.thingsTitle += marker.thingsTitle.indexOf(",") > -1 ? ", and " : " and " }
        marker.thingsTitle += marker.predecessors.length + " predecessor game" + (marker.predecessors.length > 1?"s":"");
      }
      if(marker.others.length > 0) {
        if(marker.thingsTitle) { marker.thingsTitle += marker.thingsTitle.indexOf(",") > -1 ? ", and " : " and " }
        marker.thingsTitle += marker.others.length + " other" + (marker.others.length > 1?"s":"");
      }
      var address = marker.city + (marker.state ? ", " + marker.state : "") + (marker.country && marker.country != "United States" ? ", " + marker.country : "");
      if(marker.ee) { marker.ee.title = address + ": " + marker.thingsTitle; }
    } else {
      if(marker.ee) { marker.ee.title = marker.title; }
    }
    if(map.infoWindow.marker == marker) {
      map.infoWindow.close();
      map.infoWindow.marker = null;
    }
  }
}

/* ...Maps > slider UI */

/* ...Maps */

function tinymce_loaded() {
  if(!(is_admin || is_block_editor)) {
    setTimeout(function() {
        $("[name=Block\\[Title\\]").parents("form").find("textarea:not([name*=Comment]):not([name*=Query])").each(function() { var body = tinyMCE.get($(this).attr("id")).getBody();
   body.setAttribute('contenteditable', false);
   body.style.backgroundColor = "#eee";
});
        }, 100);
  }
}
var tinymce_changed_func = function(inst) {}
function tinymce_changed(inst) { tinymce_changed_func(inst); }
function listen_for_free_text() {
  var has = $('[name="Chronology Entry[Has Supplemental Text][value]"], [name="Game[Has Supplemental Text][value]"], [name="Club[Has Supplemental Text][value]"]')[0];
  tinymce_changed_func = function(inst) {
    if(inst.id == "sf_free_text") {
      var body = inst.getBody();
      text = tinymce.trim(body.innerText || body.textContent);
      has.checked = text.length > 0;
    }
  }
}
function setAutocompleteUsingMapValues() {
  if (!gamesAndClubs.length || !$ || !$.ui || !$.ui.autocomplete) {
    setTimeout(function() {
      setAutocompleteUsingMapValues();
    }, 100);
    return;
  }
  var city = new ClassProp("city", "City");
  var borough = new ClassProp("borough", "Borough");
  var state = new ClassProp("state", "State");
  var home_away = new ClassProp("home_team, .away_team", "Title");
  var field = new ClassProp("field", "Title");
  set_autocomplete(state);
  $(".state").change(function() {
    var stateInput = $(".state");
    var stateVal = stateInput.val();
    var stateFilter = !stateVal ? null : function(thing) {
      return thing["State"] == stateVal;
    }
    set_autocomplete(city, stateFilter);
    set_autocomplete(borough, stateFilter);
  }).change();
  set_autocomplete(home_away, function(thing) {
    return thing["Type"] == "Club";
  });

  //$(".city").change(function(){set_autocomplete(field, [city, state], "[[Category:" + "Fields]]")}).change();
}

function titleExistsCheck(title, callback) {
  api.get({action: "query", titles: [title]}).then(
  function(result) { 
    callback(!result.query.pages[-1]);
  });
}

function notifyOnDupTitle(namespace, elem) {
  elem = elem || this;
  if(!$("#dupTitleNotification").length) {
    $(elem).closest("td").append("<div id='dupTitleNotification' style='display: none'>Title already exists!</div>");
    return;
  }
  if(elem.defaultValue == elem.value) {
    $("#dupTitleNotification").hide();
    return;
  }
  namespace = namespace || '';
  titleExistsCheck(namespace + elem.value, function(exists) {
    if (exists) {
      $("#dupTitleNotification").show();
    } else {
      $("#dupTitleNotification").hide();
    }
  });
}

function notifyOnProtoPixDupTitle() {
  notifyOnDupTitle('ProtoPix:', this);
}

function getProtoPixTitleFromImageUpload() {
  var titleField = $(".proto_pix_title");
  if (!titleField || titleField.val()) {
    return;
  }
  var fileName = $(".proto_pix_image").val();
  var extIndex = fileName.lastIndexOf(".");
  fileName = fileName.substring(0, extIndex);
  fileName = fileName.replace(/(_|\-|\.)/g, ' ');
  titleField.val(fileName); 
}

function formPrep() {
 api = new mw.Api();

 if(wgPageName.indexOf("Special:FormEdit") > -1 || wgAction.indexOf("formedit") > -1) {
  $('.allow_new .checkboxesSpan').each(add_new_input);
  $('.set_none_to_unknown_for_enumerated_radio_buttons .radioButtonSpan').each(set_none_to_unknown_for_enumerated_radio_buttons);
  $('.set_none_value_for_enumerated_radio_buttons .radioButtonSpan').each(set_none_value_for_enumerated_radio_buttons);

  /* for Chronology */
  $('.salience').each(set_salience_names);
  $('[name="Chronology Entry[Year]"]').change(populate_chron_year_number);

  /* for Games */
  $('.sort_eras_chronologically .checkboxesSpan').each(sort_eras_chronologically);

  /* for Diggers */
  $('[name="Digger Activity[Digger Activity Date][day]"]').each(default_to_one_and_hide);

  /* for Ballgames... */
  $(".type_of_date").change(set_date_by_type_of_date).change();
  $(".ballgame_name").parents("form").submit(set_ballgame_name);
  $($('.image-upload').get().reverse()).each(function(i) { if(i && !$(this).val()) {$(this).closest('tr').hide();} else { $(this).change() }});
  $('.image-upload').change(function() { if($(this).val()) { $(this).closest('tr').next().find('.image-upload').closest('tr').show(); } });

  setAutocompleteUsingMapValues();
  $(".country, .state, .city, .modern_address").change(set_map_marker);
  /* ...Ballgames */

  /* ProtoPix */
  $(".pics-location").change(set_map_marker_for_pics_location);
  $(".notify_on_proto_pix_dup_title").change(notifyOnProtoPixDupTitle).change();
  $(".proto_pix_image").change(getProtoPixTitleFromImageUpload);
  /* ...ProtoPix */

  /* Editors... */
  if(wgAction.indexOf("formedit") > -1) {
     $('textarea.wikiEditor_on_edit').attr('class','wikiEditor');
  }

  if($('textarea.wikiEditor').length > 0) {
    $(function(){mw.loader.using("ext.semanticforms.wikieditor",function(){$('textarea.wikiEditor').SemanticForms_registerInputInit(window.ext.wikieditor.init, null);});});
  }

  $('[name="Chronology Entry[Has Supplemental Text][value]"], [name="Game[Has Supplemental Text][value]"], [name="Club[Has Supplemental Text][value]"]').each(listen_for_free_text);

  if($('textarea.tinymce').length == 0) return;
  $.getScript("/tinymce/jscripts/tiny_mce/jquery.tinymce.js", function() { 
    $('textarea.tinymce').each(function() { 
      var id = this.id;
      var opts = {
        // Location of TinyMCE script
        script_url : '/tinymce/jscripts/tiny_mce/tiny_mce.js',

        // General options
        theme : "advanced",
        plugins : "pagebreak,style,layer,save,advhr,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,table,spellchecker,heading",

        // Theme options
        theme_advanced_buttons1 : "spellchecker,|,tablecontrols" + ($(this).hasClass("with_headings") ? ",|,h2,h3,h4" : ""),
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,hr,nonbreaking,removeformat,visualaid,|,sub,sup,|,charmap,iespell,advhr,|,fullscreen",
        theme_advanced_buttons3 : "bold,italic,underline,strikethrough,|,bullist,numlist,|,link,unlink,|,outdent,indent,blockquote,|justifyleft,justifycenter,justifyright,justifyfull,|,cleanup,help,code" ,

        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
        theme_advanced_path : false,
        spellchecker_languages : "+English=en",
        heading_clear_tag : "p",
        extended_valid_elements: "ref,references",

        content_css : "/tinymce/css/custom_content.css",
        theme_advanced_font_sizes: "10px,12px,13px,14px,16px,18px,20px",
        font_size_style_values : "10px,12px,13px,14px,16px,18px,20px",

        width: "600",
        oninit : "tinymce_loaded",
        onchange_callback : "tinymce_changed",
        gecko_spellcheck : true
      };
      if($(this).hasClass("simple")) {
        delete opts["theme_advanced_buttons2"];
        delete opts["theme_advanced_buttons3"];
        opts["theme_advanced_buttons1"] = "bold,italic,underline,|,sub,sup,|,link,unlink,|,spellchecker,|,cleanup,help,code";
      }

      $(this).tinymce(opts);
    });
  });
  /* ...Editors */
 }
}

$('.field_me').replaceWith(function(){ return '<input type="hidden" name="' + $(this).data('name') + '" value="' + $(this).data('value') + '" />'; });

$(".subnav_list_box a").each(function() { if(!this.href){ $(this).attr("href", "#"); $(this).click(function() { $(".subnav_list_items").toggle();  $(".subnav_add_items").hide(); return false; }) } });
$(".subnav_add_box a").each(function() { if(!this.href){ $(this).attr("href", "#"); $(this).click(function() { $(".subnav_add_items").toggle(); $(".subnav_list_items").hide(); return false; }) } });

function changeEditLinksToTopLinks() {
 if(wgPageName.indexOf("List_of_Diggers") > -1) {
  $(".editsection a").attr("href", "#top").text("↑ top");
 }
}

// have searches use a get so the url can be shared
$('#sfForm[action="/Special:RunQuery/Chronology_Search"]').each(function(){this.method = "get";});

// runquery results don't use parser functions except for within the ask call
// so, we hide the header listings
// then reveal only the lines with any values
$(".hide_unless_span_content").each(function() {
  var text = $(this).children('span').text()
  if(text.length > 0 && text != "No") {
    $(this).show();
    if(text == "Yes") {
      $(this).children('span').hide();
    }
  }
});

var scroll_height = 0;
$(".scrollable").each(function() {
  if(!scroll_height) {
    scroll_height = $(window).height() - $(this).offset().top - 60;
  }
  $(this).css('height', scroll_height);
  $(this).css('overflow', "auto");
});

$('#searchform').append($("<input type='button' id='enhancedSearchButton' value='Enhanced'>").click(function() {window.location="/Special:EnhancedSearch?text=" + $('#searchInput').val(); return false;}))

$('.tip_link a').attr("target","_blank");

$('.stats').each(function() { $(this).find("td:not(:hidden):last").addClass("table_turner_container").append('<a href="" class="table_turner"><i class="icon-cut"></i></a>'); });
$(".table_turner").click(function() { turn_table($(this).parents(".stats")); return false; })
var chron_re = /^\d+.?\.\d+$/;
turn_table = function(table) { 
  var offset = table.offset(); 
  var div = $('<div id="turned" style="position: absolute; z-index: 10; top: ' + Math.round(offset.top) + 'px; width: 400px; left: ' + (offset.left + Math.round(table.width()/2) - 200) + 'px"><a id="close_entry" href="#" style="font-size: 30px; display: block; text-align: right; position: relative; left: 1em;"><i class="icon-remove-circle"></i></a><iframe id="turned_list" style="height: 300px; width: 380px; background-color: white;" src="about:blank"></iframe></div>'); 
  $("body").append(div); 
  var merge = function() {
    var inner = div.children("iframe").contents().find('body'); 
    var title = $("#firstHeading").text(); 
    inner.append($('<a target="_blank" href="' + window.location.href + '">' + window.location.href + '</a><br /><br />'));
    inner.append($('<b><a target="_blank" href="/' + title + '">' + (chron_re.test(title) ? "Protoball Chronology #" : "") + title + '</a></b><br /><br />'));
    var subtitle = $(".subtitle").text(); 
    if(subtitle) { inner.append($('<b>' + $(".subtitle").text() + '</b><br /><br />')); } 
    var rows = table.find("tr:not(:hidden)"); 
    for(var i = 0; i < rows.length; i++) { 
      var td = $(rows[i]).find("td");
      var text = td.html();
      var isPara = td.find("p").length > 0;
      var isCommentOrQuery = td.children().eq(0).prop("tagName") == "I";
      if(isCommentOrQuery) {
        continue;
      }
      inner.append($('<b>' + $(rows[i]).find("th").html()  + '</b>' + (isPara ? "" : '<br />') + text +  (isPara ? "" : '<br /><br />')));
    } 
    inner.find(".hidden").remove();
    inner.find("i").filter(function(i, e) {return $(e).text().substr(0,4) == "Edit";}).remove();
  }
  setTimeout(merge, 500); 
  div.find(".admin").remove();  
  $("#close_entry").click(function() { $("#turned").remove(); return false; }); return false; 
}
var pull_toggle_a = $("<a href='#' id='pull_toggle'>show</a>");
pull_toggle_a.click(function() { var text = $(this).text(); text = text == "show" ? "hide" : "show"; $(this).text(text); $(".pull_list").toggle(); if(text == "hide") {$("#pull_entry").empty();} return false; });
$(".pull_list_container span").append("[", pull_toggle_a, "]").addClass("toctoggle");
$(".pull_list").after('<div style="position:absolute; margin: 1em auto;" id="pull_entry"></div>');
$(".pull_list a").each(function() { this.entry_title = this.title; this.title ="Click to see entry"; $(this).click(function() { var entry = $(".chron_entry_side_text a[title='" + this.entry_title + "']").parents(".chron_entry_wrapper_outer").get(0); entry = $(entry).clone(); var x = $("<div style='position:absolute; right: 0; z-index: 10;'><a id='close_entry' href='#' style='font-size: 30px;'><i class='icon-remove-circle'></i></a></div>"); $("#pull_entry").empty().append(x, entry); $("#close_entry").click(function() { $("#pull_entry").empty(); return false; }); return false;}); });

if($(".sup_text").length) {
  $("#catlinks").before('<div class="chron_back_link"></div>');
}
var chron_back_links = $(".chron_back_link");
if(chron_back_links.length) {
  var referrer = document.referrer;
  if(referrer && (referrer.indexOf("Chronology:") > -1 || referrer.indexOf("Prominent") > -1)) {
    if(referrer.indexOf("#") == -1) {
      referrer += "#" + escape(chron_back_links.text().replace(/ /g, "_")).replace(/%/g, ".").replace(/\.3A/g, ":").replace(/\.22$/, "");
    }
    chron_back_links.html('<a href="' + referrer + '">Back to Chronology Listing</a>');
  }
}
var infobox_t = $('<div class="infobox_toggle"><a href="#">Toggle Subnav</a></div>');
infobox_t.click(function() { $('.infobox').toggle(); return false; });
$('.infobox').first().parent().append(infobox_t);


var add_pages = $(".nice .icon-plus-sign");
if(add_pages.length) {
  $("#mw-panel").append($('<div class="portal"><h5>Legend</h5><div class="body"><ul><li><a href="#"><i class="icon-plus-sign" style="font-size:200%; line-height: 1.5"></i></a></li><li>Click the item&#8217;s <i class="icon-plus-sign"></i> icon to add a new page of information for the item.</li></div>'));
}

$("#discussion_below").each(function() {
  $("#mw-content-text").append($(this));
  $(this).show();
});

$('.reveal').each(function() { var $this = $(this); $this.before($('<a href="#">' + ($this.data("title") || 'Reveal') + '</a>').click(function() { $this.show(); $(this).hide(); return false; }) ) });

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
$('.pick_random').each(function() { var $this = $(this); var lis = $this.find("li"); lis.hide(); var limit = $this.data("number"); for(var i = 0; i < limit; ) { var index = getRandomInt(0,lis.length -1);  var li = $(lis[index]); if(li.css('display') == 'none') { li.show(); i++; } } }).show();

var is_admin = isAdmin();
var is_editor = isEditor();
var is_super_editor = isSuperEditor();
var is_block_editor = isBlockEditor();
if(is_admin || is_super_editor) {
  $(".admin, .editsection").show();
} else {
  $(".new a").each(function() { this.href += "&namespace=new" });
}
if(is_admin || wgUserName == "JKittel") {
  $(".gloss_admin").show();
}
if(is_admin || is_super_editor) {
  $(".prepro_admin").show();
}
if(is_admin || is_block_editor) {
  $(".block_admin").show();
}
var is_editor = isEditor();
if(is_admin || is_editor) {
  $(".admin").show();
} else {
  $(".editsection").hide();
}
if(!(is_admin || is_block_editor)) {
  $("[name=Block\\[Title\\]").parents("form").find("input").attr('readonly', 'readonly');
  // see also tiny_mce_loaded
}
$('table.sortable').before("<div class='sortable_table_marquee'><div>Sortable</div></div>")
function appendBallgameStats() {
	var table = $('table.ballgame-table');
	if (!table.length) {
		return;
	}
	var gamesWithScores = 0;
	var runs = 0;
	var winningRuns = 0;
	var losingRuns = 0;
	var rows = table.find('tbody tr');
	for(var i = 0; i < rows.length; i++) {
		var score = rows.eq(i).find("td").eq(7).text();
		var scores = score.split(' - ');
		if (scores.length < 2) {
			continue;
		}
		gamesWithScores++;
		var run1 = +scores[0];
		var run2 = +scores[1];
		runs += run1 + run2;
		if (run1 > run2) {
			winningRuns += run1;
			losingRuns += run2;
		} else {
			winningRuns += run2;
			losingRuns += run1;
		}
	}
	if (!gamesWithScores) {
		return;
	}
	var runsAvg100 = Math.round(100 * runs/(gamesWithScores * 2));
	var winningRunsAvg100 = Math.round(100 * winningRuns/gamesWithScores);
	var losingRunsAvg100 = Math.round(100 * losingRuns/gamesWithScores);
	var text = " Ballgames with Scores: " + gamesWithScores;
	text += ", Average Runs: " + format100(runsAvg100);
	text += ", Average Winning Runs: " + format100(winningRunsAvg100);
	text += ", Average Losing Runs: " + format100(losingRunsAvg100);
	table.after('<div class="ballgame-table-stats">' + text + ' </div>')
}
function format100(x) {
	var modulo = x % 100;
	if (modulo < 10) {
		modulo = '0' + modulo
	}
	return "" + Math.floor(x / 100) + '.' + modulo
}
appendBallgameStats();

function isRole(role) {
for(var i in wgUserGroups) { if(wgUserGroups[i] == role) return true; };
return false;
}
function isEditor() {
return isRole("editor");
}
function isSuperEditor() {
return isRole("supereditor");
}
function isAdmin() {
return isRole("sysop");
}
function isBlockEditor() {
return isRole("blockeditor");
}
$(function() {
  formPrep();
  changeEditLinksToTopLinks();
});

function embedPdf(url, id) {
  var embed = function() {
      var myPDF = new PDFObject({ 
      url: url,
      pdfOpenParams: { view: 'FitH' }
    }).embed(id); 
  };
  if(window.PDFObject) {
    embed();
  } else {
    $.getScript('/js/pdfobject.js', embed);
  }
}

(function boroughColumnAdjust() {
  var boroughTables = $(".borough_header").parents("table");
  boroughTables.each(function() {
    var pos = $(this).find(".borough_header").parent().index();
    if(pos == -1) return;
    var cellsWithInfo = $(this).find("td").filter( function() { return $(this).index() == pos && $.trim($(this).text()); }).length;
    if(!cellsWithInfo) {
      $(this).find("th, td").filter( function() { return $(this).index() == pos }).hide();
    }
  });
}());