WME Show Alt Names

Shows alt names for selected segments

当前为 2015-04-26 提交的版本,查看 最新版本

// ==UserScript==
// @name            WME Show Alt Names
// @description     Shows alt names for selected segments
// @version         0.11
// @author          SAR85
// @copyright       SAR85
// @license         CC BY-NC-ND
// @grant           none
// @include         https://www.waze.com/editor/*
// @include         https://www.waze.com/*/editor/*
// @include         https://editor-beta.waze.com/*
// @namespace       https://greasyfork.org/users/9321
// ==/UserScript==

//OL Popup Patch
/* OL License Info
Copyright 2005-2012 OpenLayers Contributors. All rights reserved. See
authors.txt for full list.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY OPENLAYERS CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of OpenLayers Contributors.
 */
OpenLayers.Popup = OpenLayers.Class({
		events : null,
		id : "",
		lonlat : null,
		div : null,
		contentSize : null,
		size : null,
		contentHTML : null,
		backgroundColor : "",
		opacity : "",
		border : "",
		contentDiv : null,
		groupDiv : null,
		closeDiv : null,
		autoSize : false,
		minSize : null,
		maxSize : null,
		displayClass : "olPopup",
		contentDisplayClass : "olPopupContent",
		padding : 0,
		disableFirefoxOverflowHack : false,
		fixPadding : function () {
			if (typeof this.padding == "number") {
				this.padding = new OpenLayers.Bounds(this.padding, this.padding, this.padding, this.padding);
			}
		},
		panMapIfOutOfView : false,
		keepInMap : false,
		closeOnMove : false,
		map : null,
		initialize : function (id, lonlat, contentSize, contentHTML, closeBox, closeBoxCallback) {
			if (id == null) {
				id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_");
			}
			this.id = id;
			this.lonlat = lonlat;
			this.contentSize = (contentSize != null) ? contentSize : new OpenLayers.Size(OpenLayers.Popup.WIDTH, OpenLayers.Popup.HEIGHT);
			if (contentHTML != null) {
				this.contentHTML = contentHTML;
			}
			this.backgroundColor = OpenLayers.Popup.COLOR;
			this.opacity = OpenLayers.Popup.OPACITY;
			this.border = OpenLayers.Popup.BORDER;
			this.div = OpenLayers.Util.createDiv(this.id, null, null, null, null, null, "hidden");
			this.div.className = this.displayClass;
			var groupDivId = this.id + "_GroupDiv";
			this.groupDiv = OpenLayers.Util.createDiv(groupDivId, null, null, null, "relative", null, "hidden");
			var id = this.div.id + "_contentDiv";
			this.contentDiv = OpenLayers.Util.createDiv(id, null, this.contentSize.clone(), null, "relative");
			this.contentDiv.className = this.contentDisplayClass;
			this.groupDiv.appendChild(this.contentDiv);
			this.div.appendChild(this.groupDiv);
			if (closeBox) {
				this.addCloseBox(closeBoxCallback);
			}
			this.registerEvents();
		},
		destroy : function () {
			this.id = null;
			this.lonlat = null;
			this.size = null;
			this.contentHTML = null;
			this.backgroundColor = null;
			this.opacity = null;
			this.border = null;
			if (this.closeOnMove && this.map) {
				this.map.events.unregister("movestart", this, this.hide);
			}
			this.events.destroy();
			this.events = null;
			if (this.closeDiv) {
				OpenLayers.Event.stopObservingElement(this.closeDiv);
				this.groupDiv.removeChild(this.closeDiv);
			}
			this.closeDiv = null;
			this.div.removeChild(this.groupDiv);
			this.groupDiv = null;
			if (this.map != null) {
				this.map.removePopup(this);
			}
			this.map = null;
			this.div = null;
			this.autoSize = null;
			this.minSize = null;
			this.maxSize = null;
			this.padding = null;
			this.panMapIfOutOfView = null;
		},
		draw : function (px) {
			if (px == null) {
				if ((this.lonlat != null) && (this.map != null)) {
					px = this.map.getLayerPxFromLonLat(this.lonlat);
				}
			}
			if (this.closeOnMove) {
				this.map.events.register("movestart", this, this.hide);
			}
			if (!this.disableFirefoxOverflowHack && OpenLayers.BROWSER_NAME == 'firefox') {
				this.map.events.register("movestart", this, function () {
					var style = document.defaultView.getComputedStyle(this.contentDiv, null);
					var currentOverflow = style.getPropertyValue("overflow");
					if (currentOverflow != "hidden") {
						this.contentDiv._oldOverflow = currentOverflow;
						this.contentDiv.style.overflow = "hidden";
					}
				});
				this.map.events.register("moveend", this, function () {
					var oldOverflow = this.contentDiv._oldOverflow;
					if (oldOverflow) {
						this.contentDiv.style.overflow = oldOverflow;
						this.contentDiv._oldOverflow = null;
					}
				});
			}
			this.moveTo(px);
			if (!this.autoSize && !this.size) {
				this.setSize(this.contentSize);
			}
			this.setBackgroundColor();
			this.setOpacity();
			this.setBorder();
			this.setContentHTML();
			if (this.panMapIfOutOfView) {
				this.panIntoView();
			}
			return this.div;
		},
		updatePosition : function () {
			if ((this.lonlat) && (this.map)) {
				var px = this.map.getLayerPxFromLonLat(this.lonlat);
				if (px) {
					this.moveTo(px);
				}
			}
		},
		moveTo : function (px) {
			if ((px != null) && (this.div != null)) {
				this.div.style.left = px.x + "px";
				this.div.style.top = px.y + "px";
			}
		},
		visible : function () {
			return OpenLayers.Element.visible(this.div);
		},
		toggle : function () {
			if (this.visible()) {
				this.hide();
			} else {
				this.show();
			}
		},
		show : function () {
			this.div.style.display = '';
			if (this.panMapIfOutOfView) {
				this.panIntoView();
			}
		},
		hide : function () {
			this.div.style.display = 'none';
		},
		setSize : function (contentSize) {
			this.size = contentSize.clone();
			var contentDivPadding = this.getContentDivPadding();
			var wPadding = contentDivPadding.left + contentDivPadding.right;
			var hPadding = contentDivPadding.top + contentDivPadding.bottom;
			this.fixPadding();
			wPadding += this.padding.left + this.padding.right;
			hPadding += this.padding.top + this.padding.bottom;
			if (this.closeDiv) {
				var closeDivWidth = parseInt(this.closeDiv.style.width);
				wPadding += closeDivWidth + contentDivPadding.right;
			}
			this.size.w += wPadding;
			this.size.h += hPadding;
			if (OpenLayers.BROWSER_NAME == "msie") {
				this.contentSize.w += contentDivPadding.left + contentDivPadding.right;
				this.contentSize.h += contentDivPadding.bottom + contentDivPadding.top;
			}
			if (this.div != null) {
				this.div.style.width = this.size.w + "px";
				this.div.style.height = this.size.h + "px";
			}
			if (this.contentDiv != null) {
				this.contentDiv.style.width = contentSize.w + "px";
				this.contentDiv.style.height = contentSize.h + "px";
			}
		},
		updateSize : function () {
			var preparedHTML = "<div class='" + this.contentDisplayClass + "'>" +
				this.contentDiv.innerHTML + "</div>";
			var containerElement = (this.map) ? this.map.div : document.body;
			var realSize = OpenLayers.Util.getRenderedDimensions(preparedHTML, null, {
					displayClass : this.displayClass,
					containerElement : containerElement
				});
			var safeSize = this.getSafeContentSize(realSize);
			var newSize = null;
			if (safeSize.equals(realSize)) {
				newSize = realSize;
			} else {
				var fixedSize = {
					w : (safeSize.w < realSize.w) ? safeSize.w : null,
					h : (safeSize.h < realSize.h) ? safeSize.h : null
				};
				if (fixedSize.w && fixedSize.h) {
					newSize = safeSize;
				} else {
					var clippedSize = OpenLayers.Util.getRenderedDimensions(preparedHTML, fixedSize, {
							displayClass : this.contentDisplayClass,
							containerElement : containerElement
						});
					var currentOverflow = OpenLayers.Element.getStyle(this.contentDiv, "overflow");
					if ((currentOverflow != "hidden") && (clippedSize.equals(safeSize))) {
						var scrollBar = OpenLayers.Util.getScrollbarWidth();
						if (fixedSize.w) {
							clippedSize.h += scrollBar;
						} else {
							clippedSize.w += scrollBar;
						}
					}
					newSize = this.getSafeContentSize(clippedSize);
				}
			}
			this.setSize(newSize);
		},
		setBackgroundColor : function (color) {
			if (color != undefined) {
				this.backgroundColor = color;
			}
			if (this.div != null) {
				this.div.style.backgroundColor = this.backgroundColor;
			}
		},
		setOpacity : function (opacity) {
			if (opacity != undefined) {
				this.opacity = opacity;
			}
			if (this.div != null) {
				this.div.style.opacity = this.opacity;
				this.div.style.filter = 'alpha(opacity=' + this.opacity * 100 + ')';
			}
		},
		setBorder : function (border) {
			if (border != undefined) {
				this.border = border;
			}
			if (this.div != null) {
				this.div.style.border = this.border;
			}
		},
		setContentHTML : function (contentHTML) {
			if (contentHTML != null) {
				this.contentHTML = contentHTML;
			}
			if ((this.contentDiv != null) && (this.contentHTML != null) && (this.contentHTML != this.contentDiv.innerHTML)) {
				this.contentDiv.innerHTML = this.contentHTML;
				if (this.autoSize) {
					this.registerImageListeners();
					this.updateSize();
				}
			}
		},
		registerImageListeners : function () {
			var onImgLoad = function () {
				if (this.popup.id === null) {
					return;
				}
				this.popup.updateSize();
				if (this.popup.visible() && this.popup.panMapIfOutOfView) {
					this.popup.panIntoView();
				}
				OpenLayers.Event.stopObserving(this.img, "load", this.img._onImageLoad);
			};
			var images = this.contentDiv.getElementsByTagName("img");
			for (var i = 0, len = images.length; i < len; i++) {
				var img = images[i];
				if (img.width == 0 || img.height == 0) {
					var context = {
						'popup' : this,
						'img' : img
					};
					img._onImgLoad = OpenLayers.Function.bind(onImgLoad, context);
					OpenLayers.Event.observe(img, 'load', img._onImgLoad);
				}
			}
		},
		getSafeContentSize : function (size) {
			var safeContentSize = size.clone();
			var contentDivPadding = this.getContentDivPadding();
			var wPadding = contentDivPadding.left + contentDivPadding.right;
			var hPadding = contentDivPadding.top + contentDivPadding.bottom;
			this.fixPadding();
			wPadding += this.padding.left + this.padding.right;
			hPadding += this.padding.top + this.padding.bottom;
			if (this.closeDiv) {
				var closeDivWidth = parseInt(this.closeDiv.style.width);
				wPadding += closeDivWidth + contentDivPadding.right;
			}
			if (this.minSize) {
				safeContentSize.w = Math.max(safeContentSize.w, (this.minSize.w - wPadding));
				safeContentSize.h = Math.max(safeContentSize.h, (this.minSize.h - hPadding));
			}
			if (this.maxSize) {
				safeContentSize.w = Math.min(safeContentSize.w, (this.maxSize.w - wPadding));
				safeContentSize.h = Math.min(safeContentSize.h, (this.maxSize.h - hPadding));
			}
			if (this.map && this.map.size) {
				var extraX = 0,
				extraY = 0;
				if (this.keepInMap && !this.panMapIfOutOfView) {
					var px = this.map.getPixelFromLonLat(this.lonlat);
					switch (this.relativePosition) {
					case "tr":
						extraX = px.x;
						extraY = this.map.size.h - px.y;
						break;
					case "tl":
						extraX = this.map.size.w - px.x;
						extraY = this.map.size.h - px.y;
						break;
					case "bl":
						extraX = this.map.size.w - px.x;
						extraY = px.y;
						break;
					case "br":
						extraX = px.x;
						extraY = px.y;
						break;
					default:
						extraX = px.x;
						extraY = this.map.size.h - px.y;
						break;
					}
				}
				var maxY = this.map.size.h -
					this.map.paddingForPopups.top -
					this.map.paddingForPopups.bottom -
					hPadding - extraY;
				var maxX = this.map.size.w -
					this.map.paddingForPopups.left -
					this.map.paddingForPopups.right -
					wPadding - extraX;
				safeContentSize.w = Math.min(safeContentSize.w, maxX);
				safeContentSize.h = Math.min(safeContentSize.h, maxY);
			}
			return safeContentSize;
		},
		getContentDivPadding : function () {
			var contentDivPadding = this._contentDivPadding;
			if (!contentDivPadding) {
				if (this.div.parentNode == null) {
					this.div.style.display = "none";
					document.body.appendChild(this.div);
				}
				contentDivPadding = new OpenLayers.Bounds(OpenLayers.Element.getStyle(this.contentDiv, "padding-left"), OpenLayers.Element.getStyle(this.contentDiv, "padding-bottom"), OpenLayers.Element.getStyle(this.contentDiv, "padding-right"), OpenLayers.Element.getStyle(this.contentDiv, "padding-top"));
				this._contentDivPadding = contentDivPadding;
				if (this.div.parentNode == document.body) {
					document.body.removeChild(this.div);
					this.div.style.display = "";
				}
			}
			return contentDivPadding;
		},
		addCloseBox : function (callback) {
			this.closeDiv = OpenLayers.Util.createDiv(this.id + "_close", null, {
					w : 17,
					h : 17
				});
			this.closeDiv.className = "olPopupCloseBox";
			var contentDivPadding = this.getContentDivPadding();
			this.closeDiv.style.right = contentDivPadding.right + "px";
			this.closeDiv.style.top = contentDivPadding.top + "px";
			this.groupDiv.appendChild(this.closeDiv);
			var closePopup = callback || function (e) {
				this.hide();
				OpenLayers.Event.stop(e);
			};
			OpenLayers.Event.observe(this.closeDiv, "touchend", OpenLayers.Function.bindAsEventListener(closePopup, this));
			OpenLayers.Event.observe(this.closeDiv, "click", OpenLayers.Function.bindAsEventListener(closePopup, this));
		},
		panIntoView : function () {
			var mapSize = this.map.getSize();
			var origTL = this.map.getViewPortPxFromLayerPx(new OpenLayers.Pixel(parseInt(this.div.style.left), parseInt(this.div.style.top)));
			var newTL = origTL.clone();
			if (origTL.x < this.map.paddingForPopups.left) {
				newTL.x = this.map.paddingForPopups.left;
			} else
				if ((origTL.x + this.size.w) > (mapSize.w - this.map.paddingForPopups.right)) {
					newTL.x = mapSize.w - this.map.paddingForPopups.right - this.size.w;
				}
			if (origTL.y < this.map.paddingForPopups.top) {
				newTL.y = this.map.paddingForPopups.top;
			} else
				if ((origTL.y + this.size.h) > (mapSize.h - this.map.paddingForPopups.bottom)) {
					newTL.y = mapSize.h - this.map.paddingForPopups.bottom - this.size.h;
				}
			var dx = origTL.x - newTL.x;
			var dy = origTL.y - newTL.y;
			this.map.pan(dx, dy);
		},
		registerEvents : function () {
			this.events = new OpenLayers.Events(this, this.div, null, true);
			function onTouchstart(evt) {
				OpenLayers.Event.stop(evt, true);
			}
			this.events.on({
				"mousedown" : this.onmousedown,
				"mousemove" : this.onmousemove,
				"mouseup" : this.onmouseup,
				"click" : this.onclick,
				"mouseout" : this.onmouseout,
				"dblclick" : this.ondblclick,
				"touchstart" : onTouchstart,
				scope : this
			});
		},
		onmousedown : function (evt) {
			this.mousedown = true;
			OpenLayers.Event.stop(evt, true);
		},
		onmousemove : function (evt) {
			if (this.mousedown) {
				OpenLayers.Event.stop(evt, true);
			}
		},
		onmouseup : function (evt) {
			if (this.mousedown) {
				this.mousedown = false;
				OpenLayers.Event.stop(evt, true);
			}
		},
		onclick : function (evt) {
			OpenLayers.Event.stop(evt, true);
		},
		onmouseout : function (evt) {
			this.mousedown = false;
		},
		ondblclick : function (evt) {
			OpenLayers.Event.stop(evt, true);
		},
		CLASS_NAME : "OpenLayers.Popup"
	});
OpenLayers.Popup.WIDTH = 200;
OpenLayers.Popup.HEIGHT = 200;
OpenLayers.Popup.COLOR = "white";
OpenLayers.Popup.OPACITY = 1;
OpenLayers.Popup.BORDER = "0px";
//End OL Popup Patch

// tablesorter plugin
/* The MIT License (MIT)

Copyright (c) 2007 Christian Bach

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
(function($){$.extend({tablesorter:new
function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
//End tablesorter plugin

var altPopups = [], altLayer, $altDiv, nameArray = [];

function isLonLatInMapExtent(lonlat) {
	'use strict';
	return lonlat && W.map.getExtent().containsLonLat(lonlat);
}

function Popup(id, html, anchorObj) {
	this.id = id;
	this.html = html;
	this.anchorObj = anchorObj;
	this.lonlat = this.anchorObj.geometry.getBounds().getCenterLonLat();
	this.initialLonLat = this.lonlat.clone();
	this.popup = new OL.Popup(this.id, this.lonlat, new OL.Size(100, 100), this.html, true);
	this.$masterDiv = $(this.popup.div);
	this.$groupDiv = $(this.popup.groupDiv);
	this.$contentDiv = $(this.popup.contentDiv);
	this.$closeDiv = $(this.popup.closeDiv),

	//Set popup options
	this.popup.relativePosition = 'br';
	//this.popup.panMapIfOutOfView = true;
	this.popup.autoSize = true;

	//Style the close div
	this.$closeDiv.css('text-align', 'center');
	this.$closeDiv.html('X');

	//Add popup to map
	this.calculatePosition();
	this.add();

	//Remove z-index from main div (allows stylesheet to set it)
	//Done after add() because the map.addPopup sets z-index
	this.$masterDiv.css({
		'z-index' : '',
		'background-color' : '',
		'color' : ''
	});

	//push to array of popups
	altPopups.push(this);
}
Popup.prototype = {
	add : function () {
		W.map.addPopup(this.popup);
	},
	calculatePosition : function () {
		var i,
		n;
		var bounds = this.anchorObj.geometry.getBounds();
		if (!isLonLatInMapExtent(this.initialLonLat)) {
			for (i = 0, n = this.anchorObj.geometry.components.length; i < n; i++) {
				component = this.anchorObj.geometry.components[i];
				if (isLonLatInMapExtent(component.toLonLat())) {
					this.popup.lonlat = component.toLonLat().clone();
					break;
				}
			}
		} else {
			this.popup.lonlat = this.initialLonLat.clone();
		}
		//prevent overlapping with segment
		if (bounds.getWidth() > bounds.getHeight()) {
			this.popup.lonlat.lat -= 10;
		} else {
			this.popup.lonlat.lon += 10;
		}
		this.popup.updatePosition();
	},
	hide : function () {
		this.popup.hide();
	},
	show : function () {
		this.calculatePosition();
		this.popup.show();
	},
};

function getSegmentInfo(segments) {
	'use strict';
	var i,
	n,
	j,
    t,
	item,
	primaryName,
	primaryCity,
	altName,
	altCity,
	segmentInfo,
	feature,
    maxAltNames = 0,
	segmentInfoArray = [];
    
    if (!segments) {
        if (!W.selectionManager.hasSelectedItems()) {
		  return;
        } else {
            segments = W.selectionManager.selectedItems;
        }
    }
	
	for (i = 0, n = segments.length; i < n; i++) {
		feature = W.selectionManager.selectedItems[i];
		item = feature.model;
		if (item.type === 'segment') {
			primaryName = W.model.streets.get(item.attributes.primaryStreetID);
			primaryCity = W.model.cities.get(primaryName.cityID);
			segmentInfo = {
				segment : item,
				feature : feature,
				primary : {
					name : primaryName.name || 'No name',
					city : primaryCity.name || 'No city',
				},
                alt: []
			};
			for (j = 0, t = item.attributes.streetIDs.length; j < t; j++) {
				altName = W.model.streets.get(item.attributes.streetIDs[j]);
				altCity = W.model.cities.get(altName.cityID);
				segmentInfo.alt.push({
					name : altName.name || 'No name',
					city : altCity.name || 'No city'
				});
			}
			if (t > maxAltNames) {
				maxAltNames = t;
			}
			segmentInfoArray.push(segmentInfo);
		}
	}
	segmentInfoArray.maxAltNames = maxAltNames;
	return segmentInfoArray;
}

function randomRgbaColor(opacity) {
	opacity = opacity || 0.8;
	function random255() {
		return Math.floor(Math.random()*255);
	}
	return 'rgba(' + random255() + ',' + random255() + ',' + random255() + ',' + opacity + ')';
}

function colorTable() {
	'use strict';
    var i,
	n,
    $table = $('#altTable');
	
    $table.find('.altTable-primary, .altTable-alt').each(function(index1) {
		var $this = $(this),
			text = $this.text(),
			match = false,
			color;
		
		for (i = 0, n = nameArray.length; i < n; i++) {
			if (nameArray[i].name === text) {
				$this.css('background-color', nameArray[i].color);
				match = true;
				break;
			}
		}
		if (match === false) {
			color = randomRgbaColor();
			$this.css('background-color', color);
			nameArray.push({name: text, color: color});
		}
		match = false;
	});
}

function getRoadColor(type) {
    var roadTypes = {
            1:{name: 'street', color: '#FFFFFF', expColor: '#FFFFDD'},
            2:{name:'primary', color: '#CBA12E', expColor: '#FDFAA7'},
            3:{name:'freeway', color: '#387FB8', expColor: '#6870C3'},
            4:{name:'ramp', color: '#8FB838', expColor: '#B3BFB3'},
            5:{name:'trail', color: '#E6E6E6', expColor: '#B0A790'},
            6:{name:'major', color: '#C13040', expColor: '#469FBB'},
            7:{name:'minor', color: '#ECE589', expColor: '#69BF88'},
            8:{name:'dirt', color: '#E6E6E6', expColor: '#867342'},
            10:{name:'boardwalk', color: '#E6E6E6', expColor: '#9A9A9A'},
            16:{name:'stairway', color: '#E6E6E6', expColor: '#9A9A9A'},
            17:{name:'prvt', color: '#E6E6E6', expColor: '#BEBA6C'},
            18:{name:'railroad', color: '#E6E6E6', expColor: '#B2B6B4'},
            19:{name:'runway', color: '#E6E6E6', expColor: '#222222'},
            20:{name:'parking', color: '#E6E6E6', expColor: '#ABABAB'}
            //add ferry
        },
        roadsExpLayerVisible = W.map.getLayersByName("Roads experimental")[0].getVisibility();
    if (type && undefined !== typeof roadTypes[type]) {
        return {
            typeString: roadTypes[type].name,
            typeColor: roadsExpLayerVisible ? roadTypes[type].expColor : roadTypes[type].color
            };
    } else {
        return {typeString: 'error', typeColor: roadTypes[1]};
    }
}

function createTable(segments) {
	'use strict';
	var i,
	n,
	p,
	j,
	t,
    e,
    l,
    currentID,
	rowLength,
    roadType,
	$table,
	$header,
	$row,
	$cell;
	
	if (!segments) {
		return;
	}
	
	//create table
	$table = $('<table/>');
	$table.attr('id', 'altTable');
	$table.addClass('altTable tablesorter');

	//create header
	$header = $('<thead/>');
	$row = $('<tr/>').attr('id', 'altTable-header');
	$row.append($('<th/>').text('Segment ID'));
	$row.append($('<th/>').text('Primary'));
	for (i = 0, n = segments.maxAltNames; i < n; i++) {
		$row.append($('<th/>').text('Alt ' + (i + 1)));
	}
	$header.append($row);
	$table.append($header);

	//create rows for each segment
	for (i = 0, n = segments.length; i < n; i++) {
		//add id to row
        currentID = segments[i].segment.attributes.id
        roadType = getRoadColor(segments[i].segment.attributes.roadType);
		$row = $('<tr/>').attr('id', currentID);
		$cell = $('<td/>').addClass('altTable-id');
        $cell.append($('<div/>').text(currentID));
        $cell.append($('<div/>').addClass('altTable-roadType')
                     .css('background-color', roadType.typeColor)
                     .text(roadType.typeString));
		$row.append($cell);
		
		//add primary name and city to row
		$cell = $('<td/>').addClass('altTable-primary');
		$cell.append($('<div/>').addClass('altTable-primary-name').text(segments[i].primary.name));
		$cell.append($('<div/>').addClass('altTable-primary-city').text(segments[i].primary.city));
		$row.append($cell);
		
		//add alt names and cities to row
		for (e = 0, l = segments[i].alt.length; e < l; e++) {
			$cell = $('<td/>').addClass('altTable-alt altTable-alt' + e)
			$cell.append($('<div/>').addClass('altTable-alt' + e + '-name').text(segments[i].alt[e].name));
			$cell.append($('<div/>').addClass('altTable-alt' + e + '-city').text(segments[i].alt[e].city));
			$row.append($cell);
		}
		
		//add additional cells to row to match maxAltNames
		rowLength = $row.find('td').length;
		if (rowLength < segments.maxAltNames + 2) {
			for (j = 0, t = segments.maxAltNames - rowLength + 2; j < t; j++) {
				$row.append($('<td/>').addClass('altTable-placeholder'));
			}
		}
		$table.append($row);
	}
	$table.find('tr, th, td').addClass('altTable');
	$table.tablesorter();
	return $altDiv.append($table), colorTable();
}

function drawAltNames(segments) {
	'use strict';
	var i,
	n,
	p,
	html,
	popup;
	if (!segments) {
		return;
	}
	for (i = 0, n = segments.length; i < n; i++) {
		html = '<div style="font-size:0.5em"><p><strong>Segment ID: </strong>' +
			segments[i].segment.attributes.id + '</p>';
		html += '<table class="popupTable"><thead><tr><th></th><th>Name</th><th>City</th></tr></thead><tbody>';
		html += '<tr><td><strong>Primary</strong></td>' +
		'<td>' + segments[i].primary.name + '</td>' +
		'<td>' + segments[i].primary.city + '</td></tr>';
		for (p in segments[i]) {
			if (!segments[i].hasOwnProperty(p) || p === 'primary' || p === 'segment'
				 || p === 'feature') {
				continue;
			}
			html += '<tr><td><strong>' + p + '</strong></td>' +
			'<td>' + segments[i][p].name + '</td>' +
			'<td>' + segments[i][p].city + '</td></tr>';
		}
		html += '</tbody></table></div>';
		console.log(html);

		popup = new Popup(
				segments[i].segment.attributes.id,
				html,
				segments[i].segment);
		segments[i].feature.popup = popup;
	}
}

function preventCollision() {
	var i,
	j,
	l;
	if (altPopups.length < 1) {
		return;
	}
	altPopups.sort(function (a, b) {
		console.log(a.$masterDiv.position().left, b.$masterDiv.position().left);
		return a.$masterDiv.position().left - b.$masterDiv.position().left;
	})
	for (j = 0, n = altPopups.length; j < n; j++) {
		var $div1 = altPopups[j].$masterDiv;
		var x1 = $div1.position().left;
		var y1 = $div1.position().top;
		var h1 = $div1.outerHeight(true);
		var w1 = $div1.outerWidth(true);
		var b1 = y1 + h1;
		var r1 = x1 + w1;
		for (i = j + 1; i < n; i++) {
			$div2 = altPopups[i].$masterDiv;
			if (!$div2.is(':visible')) {
				continue;
			}
			var x2 = $div2.position().left;
			var y2 = $div2.position().top;
			var h2 = $div2.outerHeight(true);
			var w2 = $div2.outerWidth(true);
			var b2 = y2 + h2;
			var r2 = x2 + w2;
			if (!(b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2)) {
				//$div2.css('top', b1 + 5);
				pixel = new OL.Pixel(x2, b1 + 5);
				altPopups[i].popup.moveTo(pixel);
			}
		}
	}
}

function resetRenderIntent(intent) {
    var i, n;
    intent = intent || 'default';
    for (i = 0, n = altLayer.features.length; i < n; i++) {
        altLayer.features[i].renderIntent = intent;
    }
}

function colorFeatures(nameToMatch, color) {
    'use strict';
    var i, 
    n, 
    j, 
    t,
    colorValues,
    feature, 
    names, 
    nameCityCombined;
    
    //remove opacity from color so it can be controlled by layer style
    colorValues = color.match(/\d+/g);
    color = 'rgb(' + colorValues[0] + ',' + colorValues[1] + ',' + colorValues[2] + ')';
    
    for (i = 0, n = altLayer.features.length; i < n; i++) {
        feature = altLayer.features[i];
        //combine primary and alt names in one array
        names = feature.attributes.alt.clone();
        names.push(feature.attributes.primary);
        //test names for match
        for (j = 0, t = names.length; j < t; j++) {
            //combine street and city name (as in text of table cell)
            nameCityCombined = names[j].name + names[j].city;
            if (nameCityCombined === nameToMatch) {
                feature.attributes.bgColor = color;
                feature.renderIntent = 'highlight';
            }
        }
    }
}

function colorSegment(id, color) {
    'use strict';
    var i, n, feature;
    color = color || 'rgba(0, 0, 0, 0.8)';
    for (i = 0, n = altLayer.features.length; i < n; i++) {
        feature = altLayer.features[i];
        if (feature.attributes.segment.attributes.id == id) {
            feature.attributes.bgColor = color;
            feature.renderIntent = 'highlight';
            break;
        }
    }
}

function createFeatures(segments) {
    var segment,
        attributes,
        featureArray = [];
    for (i = 0, n = segments.length; i < n; i++) {
        segment = segments[i]
        featureArray.push(new OL.Feature.Vector(segment.segment.geometry.clone(), segment))
    }
    altLayer.addFeatures(featureArray);
}

function checkSelection() {
	var i,
	n,
	segments;
	if (W.selectionManager.hasSelectedItems() && W.map.zoom >= 3 && altLayer.getVisibility()) {
		selectedSegments = getSegmentInfo();
		if (selectedSegments.length > 0) {
            createFeatures(selectedSegments);
			$altDiv.html('');
			createTable(selectedSegments);
			$altDiv.fadeIn();
		}
	} else {
		for (i = 0, n = W.map.popups.length; i < n; i++) {
			W.map.popups[i].hide();
		}
		altLayer.removeAllFeatures();
        $altDiv.fadeOut();
	}
}

function updateAlert() {
	var altVersion = "0.11",
	alertOnUpdate = true,
	versionChanges = 'WME Show Alt Names has been updated to ' + altVersion + '.\n';
	versionChanges += 'Changes:\n';
	versionChanges += '[*]Selected segments with the same name can be highlighted ';
	versionChanges += 'on the map by hovering over a name in the table.\n';
	if (alertOnUpdate && window.localStorage && window.localStorage.altVersion !== altVersion) {
		window.localStorage.altVersion = altVersion;
		alert(versionChanges);
	}
}

function applyHighlighting(event) {
    var $this1;
    switch (event.type) {
        case 'mouseenter':
            $this1 = $(this);
            if (event.data.singleSegment) {
                colorSegment($this1.parent().attr('id'));
            } else {
                colorFeatures($this1.text(), $this1.css('background-color'));
            }
            $('#altTable tbody td').each(function (index) {
               var $this2 = $(this);
               if ($this1.text() === $this2.text()) {
                   $this2.parent().addClass('altTable-selected');
               }
            });
            break;
        case 'mouseleave':
            resetRenderIntent();
            $('#altTable tr').each(function (index) {
                $(this).removeClass('altTable-selected');
            });
            break;
    }
    altLayer.redraw();
}

function init() {
	var olPopupCss,
	altTableCss,
	altDivCss,
    altStyleMap;
	
	olPopupCss = '.olPopup {border-radius: 5px; z-index: 1000; background-color: rgba(0,0,0,0.8); ';
	olPopupCss += 'color: white}\n';
	olPopupCss += 'table.popupTable {border: 1px solid white}\n';
	olPopupCss += 'table.popupTable tr {border: 1px solid white; padding: 3px}\n';
	olPopupCss += 'table.popupTable td {border: 1px solid white; padding: 3px}\n';
	olPopupCss += 'table.popupTable th {border: 1px solid white; padding: 3px}\n';
	
	altTableCss = '.altTable {border: 1px solid white; padding: 3px; border-collapse: collapse}\n';
    altTableCss += '.altTable-id {text-align: center}\n';
    altTableCss += '.altTable-roadType {border-radius: 10px; color: black; text-shadow: 1px 1px 0 #fff,-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,0px 1px 0 #fff,1px 0px 0 #fff,0px -1px 0 #fff,-1px 0px 0 #fff; border: 1px solid white; font-size: 0.8em;}';
    altTableCss += 'tr.altTable-selected > .altTable-id {font-weight: bold; background-color: white; color: black;}'
	
	altDivCss = '#altDiv {display: none; position: absolute; left: 6px; bottom: 60px; height: auto; width: auto; ';
	altDivCss += 'overflow-y: scroll; overflow-x: hidden; white-space: nowrap; background-color: rgba(0,0,0,0.8); color: white; padding: 5px; '; 
	altDivCss += 'z-index: 1001; border-radius: 5px; max-height: 550px;}';
    altDivCss += '#altDiv::-webkit-scrollbar {width: 15px; border-radius: 5px;}';
    altDivCss += '#altDiv::-webkit-scrollbar-track {border-radius: 5px; background: none; width: 10px;}';
    altDivCss += '#altDiv::-webkit-scrollbar-thumb {background-color: white; border-radius: 5px; border: 2px solid black;}';
	altDivCss += '#altDiv::-webkit-scrollbar-corner {background: none;}';
    
	//add css to page
	$('<style/>').html(olPopupCss + altTableCss + altDivCss).appendTo($(document.head));
	
	updateAlert();
	
	//div
	$altDiv = $('<div/>').attr('id', 'altDiv');
	$altDiv.appendTo($('#WazeMap'));
    $altDiv.on('mouseenter mouseleave', 'td.altTable-primary, td.altTable-alt', {singleSegment: false}, applyHighlighting);
    $altDiv.on('mouseenter mouseleave', 'td.altTable-id', {singleSegment: true}, applyHighlighting);
	
	//map layer
    altStyleMap = new OL.StyleMap({
        default: new OL.Style({
            stroke: false
        }),
        highlight: new OL.Style({
        	stroke: true,
            strokeWidth: 20,
            strokeColor: '${bgColor}',
            strokeOpacity: 1,
            strokeLinecap: 'round'
        })
    });
	altLayer = new OL.Layer.Vector('WME Show Alt Names', {styleMap: altStyleMap});
    altLayer.events.register("visibilitychanged", null, checkSelection);
    W.map.addLayer(altLayer);
	
	//register WME event listeners
	W.loginManager.events.register('afterloginchanged', null, init);
	W.selectionManager.events.register('selectionchanged', null, checkSelection);
}

function bootstrap() {
	var bGreasemonkeyServiceDefined = false;
	try {
		if ("object" === typeof Components.interfaces.gmIGreasemonkeyService) {
			bGreasemonkeyServiceDefined = true;
		}
	} catch (err) {
		/* Ignore. */
	}
	if (undefined === typeof unsafeWindow || !bGreasemonkeyServiceDefined) {
		unsafeWindow = (function () {
			var dummyElem = document.createElement('p');
			dummyElem.setAttribute('onclick', 'return window;');
			return dummyElem.onclick();
		})();
	}
	/* begin running the code! */
	if (undefined !== typeof W.loginManager.events.register) {
		window.setTimeout(init, 100);
	} else {
		window.setTimeout(function () {
			bootstrap();
		}, 1000);
	}
}

window.setTimeout(bootstrap, 100);