Greasy Fork is available in English.

WME Show Alt Names

Shows alt names for selected segments

À partir de 2015-05-03. Voir la dernière version.

// ==UserScript==
// @name            WME Show Alt Names
// @description     Shows alt names for selected segments
// @version         0.12
// @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==

// 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 altLayer, $altDiv, nameArray = [];

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 changeHighlightColor(event) {
	var i, n, $this = $(this);
	for (i = 0, n = nameArray.length; i < n; i++) {
		if (nameArray[i].name === $this.text()) {
			nameArray[i].color = randomRgbaColor();
			colorTable();
			$this.trigger('mouseenter', {singleSegment: false});
			break;
		}
	}
}

function getRoadColor(type) {
    var roadTypes = {
            1:{name: 'St', color: '#FFFFFF', expColor: '#FFFFDD'},
            2:{name:'PS', color: '#CBA12E', expColor: '#FDFAA7'},
            3:{name:'Fwy', color: '#387FB8', expColor: '#6870C3'},
            4:{name:'Rmp', color: '#8FB838', expColor: '#B3BFB3'},
            5:{name:'Trl', color: '#E6E6E6', expColor: '#B0A790'},
            6:{name:'MH', color: '#C13040', expColor: '#469FBB'},
            7:{name:'mH', color: '#ECE589', expColor: '#69BF88'},
            8:{name:'Dirt', color: '#E6E6E6', expColor: '#867342'},
            10:{name:'Bdwk', color: '#E6E6E6', expColor: '#9A9A9A'},
            16:{name:'Stwy', color: '#E6E6E6', expColor: '#9A9A9A'},
            17:{name:'PvR', color: '#E6E6E6', expColor: '#BEBA6C'},
            18:{name:'RR', color: '#E6E6E6', expColor: '#B2B6B4'},
            19:{name:'Rwy', color: '#E6E6E6', expColor: '#222222'},
            20:{name:'PLR', 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/>').attr('id', 'altTable').addClass('altTable tablesorter');

	//create header
	$header = $('<thead/>');
	$row = $('<tr/>').attr('id', 'altTable-header');
	$row.append($('<th/>').attr('colspan', '2').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++) {
        currentID = segments[i].segment.attributes.id
        //create row
        $row = $('<tr/>').attr('id', currentID);
		
        //add road type to row
        roadType = getRoadColor(segments[i].segment.attributes.roadType);
        $cell = $('<td/>').css('border-right', 'none')
            .append($('<div/>').addClass('altTable-roadType')
                    .css('background-color', roadType.typeColor)
                    .text(roadType.typeString));
		$row.append($cell);
        
        //add id to row
        $cell = $('<td/>').addClass('altTable-id').css('border-left', 'none');
        $cell.append($('<div/>').text(currentID));
		$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 + 3) {
			for (j = 0, t = segments.maxAltNames - rowLength + 3; 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 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;
        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 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 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 {
		altLayer.removeAllFeatures();
        $altDiv.fadeOut();
	}
}

function updateAlert() {
	var altVersion = "0.12",
	alertOnUpdate = true,
	versionChanges = 'WME Show Alt Names has been updated to ' + altVersion + '.\n';
	versionChanges += 'Changes:\n';
	versionChanges += '[*]Updated display of road type information.\n';
	versionChanges += '[*]Now checks for segments selected via permalink on load.\n';
	versionChanges += '[*]Feature: double-clicking street name changes the highlight color.';
	if (alertOnUpdate && window.localStorage && window.localStorage.altVersion !== altVersion) {
		window.localStorage.altVersion = altVersion;
		alert(versionChanges);
	}
}

function init() {
	var css;

	css = '.altTable {border: 1px solid white; padding: 3px; border-collapse: collapse; -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none;}\n';
    css += '.altTable-id {text-align: center; border-left: none;}\n';
    css += '.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; text-align: center; padding: 0 3px 0 3px; min-width: 32px;}';
    css += 'tr.altTable-selected > .altTable-id {font-weight: bold; background-color: white; color: black;}\n';

	css += '#altDiv {display: none; position: absolute; left: 6px; bottom: 60px; height: auto; width: auto; ';
	css += 'overflow-y: scroll; overflow-x: hidden; white-space: nowrap; background-color: rgba(0,0,0,0.8); color: white; padding: 5px; '; 
	css += 'z-index: 1001; border-radius: 5px; max-height: 50%;}\n';

    //scroll bar CSS
    css += '#altDiv::-webkit-scrollbar {width: 15px; border-radius: 5px;}\n';
    css += '#altDiv::-webkit-scrollbar-track {border-radius: 5px; background: none; width: 10px;}\n';
    css += '#altDiv::-webkit-scrollbar-thumb {background-color: white; border-radius: 5px; border: 2px solid black;}\n';
	css += '#altDiv::-webkit-scrollbar-corner {background: none;}';

	//add css to page
	$('<style/>').html(css).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('dblclick', 'td.altTable-primary, td.altTable-alt', null, changeHighlightColor);
	$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);
	
	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 $ &&
		$('#WazeMap').length !== 0 &&
		undefined !== typeof W.selectionManager.events.register &&
		undefined !== typeof W.loginManager.events.register) {
		window.setTimeout(init, 100);
	} else {
		window.setTimeout(function () {
			bootstrap();
		}, 1000);
	}
}

window.setTimeout(bootstrap, 100);