MediaWiki:Common.js: Difference between revisions

From Protoball
Jump to navigation Jump to search
(map search)
(chron debug)
Line 4: Line 4:


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


function set_autocomplete(target_info, filter_info_list, additional_filter) {
function set_autocomplete(target_info, filter_info_list, additional_filter) {
var filter_string = "";
  var filter_string = "";
for(var i in filter_info_list) {
  for(var i in filter_info_list) {
var filter = filter_info_list[i];
    var filter = filter_info_list[i];
var filter_input = $("." + filter.css_class);
    var filter_input = $("." + filter.css_class);
if(filter_input.val() == "") { continue; }
    if(filter_input.val() == "") { continue; }
filter_string += filter.property + "='" + filter_input.val() + "'";
    filter_string += filter.property + "='" + filter_input.val() + "'";
}
  }
if(additional_filter) {
  if(additional_filter) {
filter_string = filter_string +
    filter_string = filter_string +
(filter_string? " AND " : "") +  
      (filter_string? " AND " : "") +  
additional_filter;
      additional_filter;
}
  }
var target_input = $("." + target_info.css_class);
  var target_input = $("." + target_info.css_class);
get_fusion_column(target_info.property, filter_string, function(data) { target_input.autocomplete({
  get_fusion_column(target_info.property, filter_string, function(data) { target_input.autocomplete({
source: parse_fusion_rows(data.rows),
    source: parse_fusion_rows(data.rows),
select: function(event, ui) { event.preventDefault(); $(this).val(ui.item.value); $(this).change(); }  
    select: function(event, ui) { event.preventDefault(); $(this).val(ui.item.value); $(this).change(); }  
})});
  })});
}
}


function get_fusion_column(column, filter, handler) {
function get_fusion_column(column, filter, handler) {
fusion_request(fusion_tables.ballgames.id, column, filter, handler, true);
  fusion_request(fusion_tables.ballgames.id, column, filter, handler, true);
}
}


function parse_fusion_rows(rows) {
function parse_fusion_rows(rows) {
if(!rows) {
  if(!rows) {
return [];
    return [];
}
  }
var info = [];
  var info = [];
for(var i = 0; i < rows.length; i++) {
  for(var i = 0; i < rows.length; i++) {
if(rows[i][0]) {
    if(rows[i][0]) {
info.push(rows[i][0]);
      info.push(rows[i][0]);
}
    }
}
  }
return function(request, response) {
  return function(request, response) {
         var results = $.ui.autocomplete.filter(info, request.term);
         var results = $.ui.autocomplete.filter(info, request.term);


Line 50: Line 50:


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


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


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


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


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


function add_new_input() {
function add_new_input() {
var span = this;
  var span = this;
var input = $(this).children('input').first();
  var input = $(this).children('input').first();
var name = input.attr('name');
  var name = input.attr('name');
var index =  "" + $(this).find('input').length - 1;
  var index =  "" + $(this).find('input').length - 1;
name = name.replace("[is_list]", "[" + index + "]");
  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>');
  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).append(new_item);
$(this).find(".new_multi_property_link").click(function(){ $(this).parent().parent().children('span').toggle(); return false; });
  $(this).find(".new_multi_property_link").click(function(){ $(this).parent().parent().children('span').toggle(); return false; });
}
}


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


function populate_chron_year_number() {
function populate_chron_year_number() {
var year = $('[name="Chronology Entry[Year]"]').val();
  var year = $('[name="Chronology Entry[Year]"]').val();
if(!year) return;
  if(!year) return;
var defaultYear = $('[name="Chronology Entry[Year]"]').prop("defaultValue");
  var defaultYear = $('[name="Chronology Entry[Year]"]').prop("defaultValue");
if(year == defaultYear) {
  if(year == defaultYear) {
var defaultVal = $('[name="Chronology Entry[Year Number]"]').prop("defaultValue");
    var defaultVal = $('[name="Chronology Entry[Year Number]"]').prop("defaultValue");
$('[name="Chronology Entry[Year Number]"]').val(defaultVal);
    $('[name="Chronology Entry[Year Number]"]').val(defaultVal);
return;
    return;
}
  }
var ask = "/Special:Ask/-5B-5BYear::" + year + "-5D-5D";
  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";
  ask += "/-3FYear-20Number/mainlabel%3D-2D/limit%3D1/order%3DDESC/sort%3DYear_Number/searchlabel%3D/format%3Djson";
var data = {};
  var data = {};
$.getJSON(ask, data, function (data) {
  $.getJSON(ask, data, function (data) {
$('[name="Chronology Entry[Year Number]"]').val(data.items.length ? parseInt(data.items[0].year_number, 10) + 1 : 1);
    $('[name="Chronology Entry[Year Number]"]').val(data.items.length ? parseInt(data.items[0].year_number, 10) + 1 : 1);
});
  });
}
}


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


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


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


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


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


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


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;
}
  }


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


Line 222: Line 222:


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


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


if(isBallgamesAndClubs) {
  if(isBallgamesAndClubs) {
map.spread_markers = spread_markers;
    map.spread_markers = spread_markers;


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




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


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


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


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


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


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


Line 380: Line 380:


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


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


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


Line 404: Line 404:
         infoWindow.setContent(info_function(marker));
         infoWindow.setContent(info_function(marker));
         infoWindow.open(map, marker);
         infoWindow.open(map, marker);
infoWindow.marker = marker;
  infoWindow.marker = marker;
     };
     };
}
}


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


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


Line 476: Line 476:


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


Line 493: Line 493:


function set_map_layer(additional_filter_dict) {
function set_map_layer(additional_filter_dict) {
if(!additional_filter_dict) { additional_filter_dict = {}; }
  if(!additional_filter_dict) { additional_filter_dict = {}; }
var map = $("#map")[0];
  var map = $("#map")[0];
var classes = $(map).attr("class").split(" ");
  var classes = $(map).attr("class").split(" ");
var map_types = [];
  var map_types = [];
for(var i in classes) {
  for(var i in classes) {
if(classes[i].indexOf("map") == 0) {
    if(classes[i].indexOf("map") == 0) {
map_types[map_types.length] = classes[i].substring("map_".length);
      map_types[map_types.length] = classes[i].substring("map_".length);
}
    }
}
  }
var filter = '';
  var filter = '';
map.filters = {};
  map.filters = {};
map.marker_in_filter = function(marker) {  
  map.marker_in_filter = function(marker) {  
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] == '+'))) {
return false;
        return false;
}
      }
}
    }
return true;
    return true;
};
  };
var radius = $("#radius").text();
  var radius = $("#radius").text();
if(radius) {
  if(radius) {
filter = "ST_INTERSECTS(Location, CIRCLE(LATLNG(" + map.map.center.lat() + ", " + map.map.center.lng() + "), " + radius + "))";
    filter = "ST_INTERSECTS(Location, CIRCLE(LATLNG(" + map.map.center.lat() + ", " + map.map.center.lng() + "), " + radius + "))";
} else {
  } else {
var filters = ['Country', 'State', 'Borough', 'City'];
    var filters = ['Country', 'State', 'Borough', 'City'];
for(var i in filters) {
    for(var i in filters) {
var text = $("#" + filters[i]).text();
      var text = $("#" + filters[i]).text();
if (!text) { continue; }
      if (!text) { continue; }
map.filters[filters[i].toLowerCase()] = text;
      map.filters[filters[i].toLowerCase()] = text;
}
    }
}
  }
var additional_filter = additional_filter_dict[map_type];
  var additional_filter = additional_filter_dict[map_type];
if(filter && additional_filter) {  
  if(filter && additional_filter) {  
filter += " AND " + additional_filter;
    filter += " AND " + additional_filter;
} else if(additional_filter) {
  } else if(additional_filter) {
filter = additional_filter;
    filter = additional_filter;
}
  }
for(var i in map_types) {
  for(var i in map_types) {
var map_type = map_types[i];
    var map_type = map_types[i];
var fusion_table = fusion_tables[map_type];
    var fusion_table = fusion_tables[map_type];
if(map_type == "ballgames") {
    if(map_type == "ballgames") {
if(filter) { filter += " AND "; }
      if(filter) { filter += " AND "; }
filter += 'Type ' + (show_predecessor_games ? '=' : 'NOT EQUAL TO') + " 'Predecessor Game'";  
      filter += 'Type ' + (show_predecessor_games ? '=' : 'NOT EQUAL TO') + " 'Predecessor Game'";  
}
    }
fusion_request(fusion_table.id, "*", filter, fusion_table.data_handler)
    fusion_request(fusion_table.id, "*", filter, fusion_table.data_handler)
}
  }
}
}


function fusion_request(fusion_table_id, column_list, filter, handler, group_by_column) {
function fusion_request(fusion_table_id, column_list, filter, handler, group_by_column) {
var request_url = "https://www.googleapis.com/fusiontables/v1/query?key=" + google_api_key + "&sql=SELECT+" + column_list + "+FROM+" + fusion_table_id;
  var request_url = "https://www.googleapis.com/fusiontables/v1/query?key=" + google_api_key + "&sql=SELECT+" + column_list + "+FROM+" + fusion_table_id;
if(filter) {
  if(filter) {
request_url += encodeURI(" WHERE " + filter);
    request_url += encodeURI(" WHERE " + filter);
}
  }
if(group_by_column) {
  if(group_by_column) {
request_url += encodeURI(" GROUP BY " + column_list + " ORDER BY " + column_list);
    request_url += encodeURI(" GROUP BY " + column_list + " ORDER BY " + column_list);
}
  }
$.get(request_url, handler, "jsonp");
  $.get(request_url, handler, "jsonp");
}
}


function ballgames_data_handler(d) {
function ballgames_data_handler(d) {
var map = $("#map")[0];
  var map = $("#map")[0];
var zoom = map.map.getZoom();
  var zoom = map.map.getZoom();
var reset = !!map.markers;
  var reset = !!map.markers;
if(reset) {
  if(reset) {
for(var i in map.markers) {
    for(var i in map.markers) {
map.markers[i].setMap(null);
      map.markers[i].setMap(null);
}
    }
map.years = null;
    map.years = null;
}
  }
if(map.infoWindow) map.infoWindow.marker = null;
  if(map.infoWindow) map.infoWindow.marker = null;
map.markers = [];
  map.markers = [];
if(!d.rows) return;
  if(!d.rows) return;
var rows = d.rows;
  var rows = d.rows;
var fields = d.columns;
  var fields = d.columns;
var index = {};
  var index = {};
for (var i in fields) {
  for (var i in fields) {
index[fields[i]] = i;
    index[fields[i]] = i;
}
  }
var location_markers = {};
  var location_markers = {};


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


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


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


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


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


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


if($('#map').length > 0) {
if($('#map').length > 0) {
$.getScript('http://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=set_map');
  $.getScript('http://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=set_map');
}
}


Line 772: Line 773:


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


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


function slider_setup() {
function slider_setup() {
if($("#map").length > 0 && $("#map")[0].years && $("#slider").slider && $("#slider").length > 0 && !$("#slider")[0].is_setup) {
  if($("#map").length > 0 && $("#map")[0].years && $("#slider").slider && $("#slider").length > 0 && !$("#slider")[0].is_setup) {
var map = $("#map")[0];
    var map = $("#map")[0];
$('<div id="slider-one-year" class="slider" style="display: none"></div>').insertAfter("#slider");
    $('<div id="slider-one-year" class="slider" style="display: none"></div>').insertAfter("#slider");
$("#slider").slider({
    $("#slider").slider({
range: true,
      range: true,
min: map.years[0],
      min: map.years[0],
max: map.years[1],
      max: map.years[1],
values: map.years,
      values: map.years,
change: function( event, ui ) {
      change: function( event, ui ) {
map.years = [parseInt(ui.values[0]), parseInt(ui.values[1])];
        map.years = [parseInt(ui.values[0]), parseInt(ui.values[1])];
},
      },
slide: function( event, ui ) {
      slide: function( event, ui ) {
var slider = $("#slider")[0];
        var slider = $("#slider")[0];
if(event) {
        if(event) {
var old_values = map.years;
          var old_values = map.years;
map.years = [parseInt(ui.values[0]), parseInt(ui.values[1])];
          map.years = [parseInt(ui.values[0]), parseInt(ui.values[1])];
if(slider.mode && slider.mode == "freeze_ranges") {
          if(slider.mode && slider.mode == "freeze_ranges") {
var old_diff = old_values[1] - old_values[0];
            var old_diff = old_values[1] - old_values[0];
var new_diff = map.years[1] - map.years[0];
            var new_diff = map.years[1] - map.years[0];
if(old_diff != new_diff) {
            if(old_diff != new_diff) {
var index = (old_values[0] == map.years[0]) ? 0 : 1;
              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]);
              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;
              map.years[index] = value;
$(slider).slider("values", index, value);
              $(slider).slider("values", index, value);
}
            }
}
          }
} else if (slider.mode && slider.mode == "freeze_ranges") {
        } else if (slider.mode && slider.mode == "freeze_ranges") {
if(map.years[0] == map.base_years[0] && map.years[1] == map.base_years[1]) {
          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);
            map.years[1] = Math.min(map.years[1], map.years[0] + 1);
$(slider).slider("values", 1, map.years[1]);
            $(slider).slider("values", 1, map.years[1]);
}
          }
}
        }
set_slider_text(map.years);
        set_slider_text(map.years);
map.filter_years = map.years;
        map.filter_years = map.years;
filter_map_years();
        filter_map_years();
}
      }
});
    });
$("#slider-one-year").slider({
    $("#slider-one-year").slider({
min: map.years[0],
      min: map.years[0],
max: map.years[1],
      max: map.years[1],
value: map.years[0],
      value: map.years[0],
slide: function( event, ui ) {
      slide: function( event, ui ) {
if(event) {
        if(event) {
map.year = parseInt(ui.value);
          map.year = parseInt(ui.value);
} else if(!map.year) {
        } else if(!map.year) {
map.year = map.years[0];
          map.year = map.years[0];
$("#slider-one-year").slider("value", map.year);
          $("#slider-one-year").slider("value", map.year);
}
        }
set_slider_text([map.year]);
        set_slider_text([map.year]);
map.filter_years = [map.year, map.year];
        map.filter_years = [map.year, map.year];
filter_map_years();
        filter_map_years();
}
      }
});
    });
$("#slider")[0].is_setup = true;
    $("#slider")[0].is_setup = true;
set_slider_text(map.years);
    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");
    $('<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); });
    $("#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); });
    $("#one_year_slide").click(function() { var slider = $("#slider-one-year"); $("#slider").hide(); slider.show(); slider.slider('option', 'slide').call(slider); });
}
  }
}
}


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


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


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


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


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


Line 1,009: Line 1,010:
function tinymce_changed(inst) { tinymce_changed_func(inst); }
function tinymce_changed(inst) { tinymce_changed_func(inst); }
function listen_for_free_text() {
function listen_for_free_text() {
var has = $('[name="Chronology Entry[Has Supplemental Text][value]"], [name="Game[Has Supplemental Text][value]"]')[0];
  var has = $('[name="Chronology Entry[Has Supplemental Text][value]"], [name="Game[Has Supplemental Text][value]"]')[0];
tinymce_changed_func = function(inst) {
  tinymce_changed_func = function(inst) {
if(inst.id == "sf_free_text") {
    if(inst.id == "sf_free_text") {
var body = inst.getBody();
      var body = inst.getBody();
text = tinymce.trim(body.innerText || body.textContent);
      text = tinymce.trim(body.innerText || body.textContent);
has.checked = text.length > 0;
      has.checked = text.length > 0;
}
    }
}
  }
}
}
function formPrep() {
function formPrep() {
  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);
$('.set_none_to_unknown_for_enumerated_radio_buttons .radioButtonSpan').each(set_none_to_unknown_for_enumerated_radio_buttons);
  $('.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);
  $('.set_none_value_for_enumerated_radio_buttons .radioButtonSpan').each(set_none_value_for_enumerated_radio_buttons);


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


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


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


/* for Ballgames... */
  /* for Ballgames... */
$(".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);


var city = new ClassProp("city", "City");
  var city = new ClassProp("city", "City");
var borough = new ClassProp("borough", "Borough");
  var borough = new ClassProp("borough", "Borough");
var state = new ClassProp("state", "State");
  var state = new ClassProp("state", "State");
var home_away = new ClassProp("home_team, .away_team", "Title");
  var home_away = new ClassProp("home_team, .away_team", "Title");
var field = new ClassProp("field", "Title");
  var field = new ClassProp("field", "Title");
set_autocomplete(state, [], "");
  set_autocomplete(state, [], "");
$(".state").change(function(){
  $(".state").change(function(){
set_autocomplete(city, [state], "");
    set_autocomplete(city, [state], "");
set_autocomplete(borough, [state], "");
    set_autocomplete(borough, [state], "");
}).change();
  }).change();
set_autocomplete(home_away, [], "Type = 'Club'");
  set_autocomplete(home_away, [], "Type = 'Club'");
//$(".city").change(function(){set_autocomplete(field, [city, state], "[[Category:" + "Fields]]")}).change();
  //$(".city").change(function(){set_autocomplete(field, [city, state], "[[Category:" + "Fields]]")}).change();
$(".country, .state, .city, .modern_address").change(set_map_marker);
  $(".country, .state, .city, .modern_address").change(set_map_marker);
/* ...Ballgames */
  /* ...Ballgames */


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


if($('textarea.wikiEditor').length > 0) {
  if($('textarea.wikiEditor').length > 0) {
$(function(){mw.loader.using("ext.semanticforms.wikieditor",function(){$('textarea.wikiEditor').SemanticForms_registerInputInit(window.ext.wikieditor.init, null);});});
    $(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]"]').each(listen_for_free_text);
  $('[name="Chronology Entry[Has Supplemental Text][value]"], [name="Game[Has Supplemental Text][value]"]').each(listen_for_free_text);


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


// General options
        // General options
theme : "advanced",
        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",
        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 options
theme_advanced_buttons1 : "spellchecker,|,tablecontrols" + ($(this).hasClass("with_headings") ? ",|,h2,h3,h4" : ""),
        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_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_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_location : "top",
theme_advanced_toolbar_align : "left",
        theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
        theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
        theme_advanced_resizing : true,
theme_advanced_path : false,
        theme_advanced_path : false,
spellchecker_languages : "+English=en",
        spellchecker_languages : "+English=en",
heading_clear_tag : "p",
        heading_clear_tag : "p",
extended_valid_elements: "ref,references",
        extended_valid_elements: "ref,references",


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


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


$(this).tinymce(opts);
      $(this).tinymce(opts);
});
    });
});
  });
/* ...Editors */
  /* ...Editors */
  }
  }
}
}
Line 1,129: Line 1,130:
// then reveal only the lines with any values
// then reveal only the lines with any values
$(".hide_unless_span_content").each(function() {
$(".hide_unless_span_content").each(function() {
var text = $(this).children('span').text()
  var text = $(this).children('span').text()
if(text.length > 0 && text != "No") {
  if(text.length > 0 && text != "No") {
$(this).show();
    $(this).show();
if(text == "Yes") {
    if(text == "Yes") {
$(this).children('span').hide();
      $(this).children('span').hide();
}
    }
}
  }
});
});


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


Line 1,156: Line 1,157:
var chron_re = /^\d+.?\.\d+$/;
var chron_re = /^\d+.?\.\d+$/;
turn_table = function(table) {  
turn_table = function(table) {  
var offset = table.offset();  
  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>');  
  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);  
  $("body").append(div);  
var merge = function() {
  var merge = function() {
var inner = div.children("iframe").contents().find('body');  
    var inner = div.children("iframe").contents().find('body');  
var title = $("#firstHeading span").text();  
    var title = $("#firstHeading span").text();  
inner.append($('<b><a target="_blank" href="/' + title + '">' + (chron_re.test(title) ? "Protoball Chronology #" : "") + title + '</a></b><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();  
    var subtitle = $(".subtitle").text();  
if(subtitle) { inner.append($('<b>' + $(".subtitle").text() + '</b><br /><br />')); }  
    if(subtitle) { inner.append($('<b>' + $(".subtitle").text() + '</b><br /><br />')); }  
var rows = table.find("tr:not(:hidden)");  
    var rows = table.find("tr:not(:hidden)");  
for(var i = 0; i < rows.length; i++) {  
    for(var i = 0; i < rows.length; i++) {  
var td = $(rows[i]).find("td");
      var td = $(rows[i]).find("td");
var text = td.html();
      var text = td.html();
var isPara = td.find("p").length > 0;
      var isPara = td.find("p").length > 0;
inner.append($('<b>' + $(rows[i]).find("th").html()  + '</b>' + (isPara ? "" : '<br />') + text +  (isPara ? "" : '<br /><br />')));
      inner.append($('<b>' + $(rows[i]).find("th").html()  + '</b>' + (isPara ? "" : '<br />') + text +  (isPara ? "" : '<br /><br />')));
}  
    }  
inner.find(".hidden").remove();
    inner.find(".hidden").remove();
}
  }
setTimeout(merge, 500);  
  setTimeout(merge, 500);  
div.find(".admin").remove();   
  div.find(".admin").remove();   
$("#close_entry").click(function() { $("#turned").remove(); return false; }); return false;  
  $("#close_entry").click(function() { $("#turned").remove(); return false; }); return false;  
}
}
var pull_toggle_a = $("<a href='#' id='pull_toggle'>show</a>");
var pull_toggle_a = $("<a href='#' id='pull_toggle'>show</a>");
Line 1,187: Line 1,188:
var toc_default_set = $.cookie('mw_hidetoc_default_set');
var toc_default_set = $.cookie('mw_hidetoc_default_set');
if(!toc_default_set) {
if(!toc_default_set) {
$.cookie('mw_hidetoc_default_set', true, { expires: 30, path: '/' } );
  $.cookie('mw_hidetoc_default_set', true, { expires: 30, path: '/' } );
$.cookie('mw_hidetoc', '1', { expires: 30, path: '/' } );
  $.cookie('mw_hidetoc', '1', { expires: 30, path: '/' } );
}
}


if($(".sup_text").length) {
if($(".sup_text").length) {
$("#catlinks").before('<div class="chron_back_link"></div>');
  $("#catlinks").before('<div class="chron_back_link"></div>');
}
}
var chron_back_links = $(".chron_back_link");
var chron_back_links = $(".chron_back_link");
if(chron_back_links.length) {
if(chron_back_links.length) {
var referrer = document.referrer;
  var referrer = document.referrer;
if(referrer && (referrer.indexOf("Chronology:") > -1 || referrer.indexOf("Prominent") > -1)) {
  if(referrer && (referrer.indexOf("Chronology:") > -1 || referrer.indexOf("Prominent") > -1)) {
if(referrer.indexOf("#") == -1) {
    if(referrer.indexOf("#") == -1) {
referrer += "#" + escape(chron_back_links.text().replace(/ /g, "_")).replace(/%/g, ".").replace(/\.3A/g, ":").replace(/\.22$/, "");
      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>');
    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>');
var infobox_t = $('<div class="infobox_toggle"><a href="#">Toggle Subnav</a></div>');
Line 1,211: Line 1,212:
var add_pages = $(".nice .icon-plus-sign");
var add_pages = $(".nice .icon-plus-sign");
if(add_pages.length) {
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>'));
  $("#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() {
$("#discussion_below").each(function() {
$("#mw-content-text").append($(this));
  $("#mw-content-text").append($(this));
$(this).show();
  $(this).show();
});
});


Line 1,230: Line 1,231:
var is_super_editor = isSuperEditor();
var is_super_editor = isSuperEditor();
if(is_admin || is_super_editor) {
if(is_admin || is_super_editor) {
$(".admin, .editsection").show();
  $(".admin, .editsection").show();
} else {
} else {
$(".new a").each(function() { this.href += "&namespace=new" });
  $(".new a").each(function() { this.href += "&namespace=new" });
}
}
if(is_admin || wgUserName == "JKittel") {
if(is_admin || wgUserName == "JKittel") {
$(".gloss_admin").show();
  $(".gloss_admin").show();
}
}
if(is_admin || is_super_editor) {
if(is_admin || is_super_editor) {
$(".prepro_admin").show();
  $(".prepro_admin").show();
}
}
var is_editor = isEditor();
var is_editor = isEditor();
if(is_admin || is_editor) {
if(is_admin || is_editor) {
$(".admin").show();
  $(".admin").show();
} else {
} else {
$(".editsection").hide();
  $(".editsection").hide();
}
}
$('table.sortable').before("<div class='sortable_table_marquee'><div>Sortable</div></div>")
$('table.sortable').before("<div class='sortable_table_marquee'><div>Sortable</div></div>")
Line 1,259: Line 1,260:


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


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

Revision as of 08:46, 10 May 2015

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

var google_api_key = "AIzaSyB2c94sMGn9J8MOrpvT1UhzBdH5I81heKE";

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

function set_autocomplete(target_info, filter_info_list, additional_filter) {
  var filter_string = "";
  for(var i in filter_info_list) {
    var filter = filter_info_list[i];
    var filter_input = $("." + filter.css_class);
    if(filter_input.val() == "") { continue; }
    filter_string += filter.property + "='" + filter_input.val() + "'";
  }
  if(additional_filter) {
    filter_string = filter_string +
      (filter_string? " AND " : "") + 
      additional_filter;
  }
  var target_input = $("." + target_info.css_class);
  get_fusion_column(target_info.property, filter_string, function(data) { target_input.autocomplete({
    source: parse_fusion_rows(data.rows),
    select: function(event, ui) { event.preventDefault(); $(this).val(ui.item.value); $(this).change(); } 
  })});
}

function get_fusion_column(column, filter, handler) {
  fusion_request(fusion_tables.ballgames.id, column, filter, handler, true);
}

function parse_fusion_rows(rows) {
  if(!rows) {
    return [];
  }
  var info = [];
  for(var i = 0; i < rows.length; i++) {
    if(rows[i][0]) {
      info.push(rows[i][0]);
    }
  }
  return function(request, response) {
        var results = $.ui.autocomplete.filter(info, 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 = {};
  $.getJSON(ask, data, function (data) {
    $('[name="Chronology Entry[Year Number]"]').val(data.items.length ? parseInt(data.items[0].year_number, 10) + 1 : 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 span = $(this).children('span')[0];
  var input = $(span).children('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();
    }
  }
}

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 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;
  }

  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 = $.cookie('show_predecessor_games') == "true";
var show_additional_markers = $.cookie('show_additional_markers') == "true";
var spread_markers = $.cookie('spread_markers') == "true";
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 }
  });
  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");
  var address = "";
  fields.each(function() { if($(this).val()) { address = $(this).val() + ", " + address; } });
  if(address) {
    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 "http://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("http://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 = "http://" + 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];
}

var fusion_tables = {};
fusion_tables.ballgames = {};
fusion_tables.ballgames.id = (document.URL.indexOf("http://beta.protoball.org") != 0) ? "1UNz5h2AVTr1z5xPaz-wUnTgJTuA8pxv1A095IVU" : "1DHie9n7OhZX-bCgSwzQWzI14Eemq0Oae-BbJtwA";
//fusion_tables.ballgames.id = (document.URL.indexOf("http://protoball.org") == 0) ? "1WLxLX5DbfGEYvPePLbLi3n0vmk2n8IdSstdpxI4" : "1LqWjLWfO5pC--B3Nx8g7HQP2AYSQqe4hUdxhB5E";
fusion_tables.ballgames.data_handler = ballgames_data_handler;

function set_map_layer(additional_filter_dict) {
  if(!additional_filter_dict) { additional_filter_dict = {}; }
  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) { 
    for(var filter in map.filters) {
      if(!(map.filters[filter] == marker[filter] || (marker[filter] && map.filters[filter] == '+'))) {
        return false;
      }
    }
    return true;
  };
  var radius = $("#radius").text();
  if(radius) {
    filter = "ST_INTERSECTS(Location, CIRCLE(LATLNG(" + map.map.center.lat() + ", " + map.map.center.lng() + "), " + radius + "))";
  } else {
    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;
    }
  }
  var additional_filter = additional_filter_dict[map_type];
  if(filter && additional_filter) { 
    filter += " AND " + additional_filter;
  } else if(additional_filter) {
    filter = additional_filter;
  }
  for(var i in map_types) {
    var map_type = map_types[i];
    var fusion_table = fusion_tables[map_type];
    if(map_type == "ballgames") {
      if(filter) { filter += " AND "; }
      filter += 'Type ' + (show_predecessor_games ? '=' : 'NOT EQUAL TO') + " 'Predecessor Game'"; 
    }
    fusion_request(fusion_table.id, "*", filter, fusion_table.data_handler)
  }
}

function fusion_request(fusion_table_id, column_list, filter, handler, group_by_column) {
  var request_url = "https://www.googleapis.com/fusiontables/v1/query?key=" + google_api_key + "&sql=SELECT+" + column_list + "+FROM+" + fusion_table_id;
  if(filter) {
    request_url += encodeURI(" WHERE " + filter);
  }
  if(group_by_column) {
    request_url += encodeURI(" GROUP BY " + column_list + " ORDER BY " + column_list);
  }
  $.get(request_url, handler, "jsonp");
}

function ballgames_data_handler(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 = [];
  if(!d.rows) return;
  var rows = d.rows;
  var fields = d.columns;
  var index = {};
  for (var i in fields) {
    index[fields[i]] = i;
  }
  var location_markers = {};

  for (var i in rows) {
    var row = rows[i];
    var location = row[index["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[index["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[index["Title"]],
      date: date,
      year: year,
      city: row[index["City"]],
      borough: row[index["Borough"]],
      state: row[index["State"]],
      country: row[index["Country"]],
      info: row[index["Info"]],
      source_type: row[index["Type"]],
      modern_address: row[index["Modern Address"]],
      digger: row[index["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);
      console.log(marker);
    }
    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 = "http://" + 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>";
    }
    $.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 + '</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;
  }
}

if($('#map').length > 0) {
  $.getScript('http://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=set_map');
}

/* 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.predecessors.length + " other" + (marker.predecessors.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 */


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]"]')[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 formPrep() {
 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);

  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(){
    set_autocomplete(city, [state], "");
    set_autocomplete(borough, [state], "");
  }).change();
  set_autocomplete(home_away, [], "Type = 'Club'");
  //$(".city").change(function(){set_autocomplete(field, [city, state], "[[Category:" + "Fields]]")}).change();
  $(".country, .state, .city, .modern_address").change(set_map_marker);
  /* ...Ballgames */

  /* 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]"]').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",
        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");
});

$("#searchGoButton").click(function() { $(this).parent().children()[0].name="text"; $(this).parent().children(":last").remove(); this.form.method = "get"; this.form.action="/Special:EnhancedSearch"; });
$("#searchGoButton").insertAfter("#mw-searchButton").val("Enhanced").show();

$('.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 span").text(); 
    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;
      inner.append($('<b>' + $(rows[i]).find("th").html()  + '</b>' + (isPara ? "" : '<br />') + text +  (isPara ? "" : '<br /><br />')));
    } 
    inner.find(".hidden").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;}); });


var toc_default_set = $.cookie('mw_hidetoc_default_set');
if(!toc_default_set) {
  $.cookie('mw_hidetoc_default_set', true, { expires: 30, path: '/' } );
  $.cookie('mw_hidetoc', '1', { expires: 30, path: '/' } );
}

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 = $("#pt-adminlinks").length > 0;
var is_editor = isEditor();
var is_super_editor = isSuperEditor();
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();
}
var is_editor = isEditor();
if(is_admin || is_editor) {
  $(".admin").show();
} else {
  $(".editsection").hide();
}
$('table.sortable').before("<div class='sortable_table_marquee'><div>Sortable</div></div>")
function isEditor() {
for(var i in wgUserGroups) { if(wgUserGroups[i] == "editor") return true; };
return false;
}
function isSuperEditor() {
for(var i in wgUserGroups) { if(wgUserGroups[i] == "supereditor") return true; };
return false;
}
addOnloadHook(formPrep);
addOnloadHook(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();
    }
  });
}());