MediaWiki:Common.js

From Protoball
Revision as of 19:31, 20 September 2014 by Dave (talk | contribs) (bounds fix attempt)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* 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() + "'";
		//filter_string += "[[" + filter.property + "::" + filter_input.val() + "]]";
	}
	//filter_string += additional_filter;
	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),
		//source: parse_list(data.parse.text["*"])
		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;
	}

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

/* Maps... */

function toggle_marker_spread() {
	var map = $("#map")[0];
	map.spread_markers = this.checked;
	map.infoWindow.close(map.map);
	map.infoWindow.marker = null;
	filter_map_years();
}

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();
	var coords = lat_long? new google.maps.LatLng(parseFloat(lat_long.split(", ")[0]), parseFloat(lat_long.split(", ")[1])) : elysian_fields;
	var map = $("#map")[0];
	map.infoWindow = new google.maps.InfoWindow();
	map.map = new google.maps.Map(map, {
		center: coords,
		zoom: 12,
		mapTypeId: 'roadmap',
		scaleControl: true,
		scaleControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM }
	});
	if($(map).hasClass("map_ballgames")) {
		map.spread_markers = false;
		var marker_option_div = $('<div class="google_map_inlay"><input type="checkbox" name="spread_markers" id="spread_markers" /><label for="spread_markers">Spread Markers Each Location</label></div>')[0];
		map.map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(marker_option_div);
		$(marker_option_div).children("input").change(toggle_marker_spread);

		var marker_pin_legend = $('<div class="google_map_inlay" id="club_game_legend"><img height="25px" src="' + marker_image_url("c", "FFCC00") + '" /> = Club, <img height="25px" src="' + marker_image_url("•", "FF867C") + '" /> = Game</div>')[0];
		map.map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(marker_pin_legend);
		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());
			}
		});
		set_map_layer();
	} else if($(map).hasClass("map_picker")) {
		if(!lat_long) { set_map_marker(); }
		set_map_picker();
	}
}

//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 ballgames_info(marker) {
	var map = $("#map")[0];
	var city = "", state = "", country = "", address = "", borough = "";
	var domain = "http://" + document.domain + "/";
	if(marker.city) {
		address = marker.city + (marker.state ? ", " + marker.state : "") + (marker.country && marker.country != "United States" ? ", " + marker.country : "");
		city = '<a href="' + domain + address.replace(/ /g, "_") + '">' + marker.city + '</a>';
	}
	if(marker.borough) {
		address = marker.borough;
		borough = '<a href="' + domain + address.replace(/ /g, "_") + '">' + marker.borough + '</a>';
	}
	if(marker.state) {
		address = marker.state + (marker.country && marker.country != "United States" ? ", " + marker.country : "");
		state = '<a href="' + domain + address.replace(/ /g, "_") + '">' + marker.state + '</a>';
	}
	if(marker.country) {
		country = '<a href="' + domain + marker.country.replace(/ /g, "_") + '">' + marker.country + '</a>';
	}
	address = ((city ? ", " + city : "") + (state ? ", " + state : "") + (country ? ", " + country : "")).replace(/^, /, "");
	var infoHtml = "";
	if(map.spread_markers || !marker.markers || marker.markers.length == 1) {
		infoHtml = '<strong><a 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(borough) {
			infoHtml += borough + "<br>";
		}
		if(marker.source_type != "Club") {
			infoHtml += marker.info + "<br>";
		}
		if(marker.digger) {
			infoHtml += "Found by " + '<a href="' + domain + marker.digger.replace(/ /g, "_") + '">' + marker.digger + "</a><br>";
		}
		return infoHtml;
	} else {
		infoHtml = '<strong>' + address + '</strong><br>';
		infoHtml += marker.clubAndGamesText;
		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 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 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]) 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) {
			marker.setMap(map.map);
		}
		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);
}

var _bounds_ = null;
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);
}

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)) {
			marker.setMap(map.map);
		} 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 = [];
			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.predecessors;
				thing.push(marker.markers[i]);
			}
			marker.clubAndGamesText = "";
			if(marker.clubs.length > 0) {
				marker.clubAndGamesText += 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.clubAndGamesText) { marker.clubAndGamesText += (show_predecessor_games && marker.predecessors.length > 0) ? ", " : " and "; }
				marker.clubAndGamesText += 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.clubAndGamesText) { marker.clubAndGamesText += marker.clubAndGamesText.indexOf(",") > -1 ? ", and " : " and " }
				marker.clubAndGamesText += marker.predecessors.length + " predecessor game" + (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.clubAndGamesText; }
		} 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 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], "")}).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 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: '/' } );
}

var show_predecessor_games = $.cookie('show_predecessor_games') == "true";
$(".map_header").prepend($('<div class="show_predecessor_games"><input id="show_predecessor_games" type="checkbox"' + (show_predecessor_games ? ' checked="checked"' : '') + '><label for="show_predecessor_games">' + (show_predecessor_games ? 'Showing' : '&nbsp;&nbsp;&nbsp;Show')  + ' Predecessor Games</label></div>'));
$(".show_predecessor_games input").click(function() { show_predecessor_games = this.checked; $.cookie('show_predecessor_games', this.checked); $(this).next().text((this.checked ? 'Showing' : '&nbsp;&nbsp;&nbsp;Show') + " Predecessor Games"); set_map_layer(); });

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;
if(is_admin) {
	$(".admin, .editsection").show();
} else {
	$(".new a").each(function() { this.href += "&namespace=new" });
}
if(is_admin || wgUserName == "JKittel") {
	$(".gloss_admin").show();
}
if(is_admin || wgUserName == "Bsallardice") {
	$(".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;
}
addOnloadHook(formPrep);
addOnloadHook(changeEditLinksToTopLinks);