var $_insertAddressMunicipality,mapObj,mapMeter,mapDrawing,$_extEventHandler=null,$_extPickTip=null,$_extPickOptions=null,$_DisableMyObjects=!1,$_LineColor="red",$_LineWidth=2,$_LineType="solid",$_FillColor="blue",$_FillOpacity="0.5",window_type=null,$_UserPositionTimeOut=5e3,$_mouseMoveUseTimer=!0,$_mouseMoveTimerInterval=300,subsite=null,positionTarget="",toolMode="pan",toolModePrevious="pan",_imageSize=256,_tileOriginOffsetX=void 0;function get_Center(visible){var center=window.teklaMap.getCenter(),ret={n:center.lat,e:center.lng};return Tekla.SideBar&&Tekla.SideBar.isVisible()&&(ret.e=center.lng+200*currentWupp()),ret}var $_infoTimer,$_SelectedDBIndex,$_SelectedId,fillDrawing=!1,distanceStartOffsetX=16,distanceStartOffsetY=16,$_queryTargetUrl=null,$_queryTargetTimeout=100,$_queryCookieName="userquery0801";function TXWSetAttributes(){var i,key,ret=!0,a=TXWSetAttributes.arguments;for(i=0;i<a.length;i+=2)key=a[i],i+1<a.length&&1!=TXWSetAttribute(key,a[i+1])&&(ret=!1);return ret}function TXWSetAttribute(key,value){if("tileSize"==key)_imageSize=value;else if("tileOriginOffsetX"==key)_tileOriginOffsetX=value;else if("userquery-url"==key)$_queryTargetUrl=value;else if("userquery-timeout"==key)$_queryTargetTimeout=value;else if("mmove-timer"==key)$_mouseMoveUseTimer=value;else if("mmove-timer-intv"==key)$_mouseMoveTimerInterval=value;else{if("disable-myobjects"!=key)return!1;$_DisableMyObjects=value}return!0}function __getPinImage(nameonly){var name="/Images/pointer.png";return nameonly?name:options.appPath+name}function __getLineImage(){return options.appPath+"/Images/polypoint.gif"}function __getPolygonImage(){return options.appPath+"/Images/areapoint.gif"}function __getMeasImage(){return options.appPath+"/Images/measure-pin.png"}function $_EnsureColors(){if(options&&"function"==typeof options._getCurrentPresentation){var pres=options._getCurrentPresentation();pres&&($_LineColor=pres.LineColor,$_LineOpacity=pres.LineOpacity,$_LineWidth=pres.LineWidth,$_LineType=pres.LineType,$_FillColor=pres.FillColor,$_FillOpacity=pres.FillOpacity)}$_LineColor||($_LineColor="red"),$_LineWidth||($_LineWidth=2),$_LineType||($_LineType="solid"),$_FillColor||($_FillColor="blue"),$_FillOpacity||($_FillOpacity="0.5")}function $_AdjustRange(val,min,max,def){return val<min||val>max?def:val}function $_SetActiveObject(DBindex,Id){$_SelectedDBIndex=DBindex,$_SelectedId=Id}function CheckBrowser(isprint,pw,ph){return!0}var $_Crd_timer,$_CrdLatLng=null;function $_showCoordinates_enable(){if(document.getElementById("coordinatediv")){var center=window.teklaMap.getCenter();$_showCoordinates_common([center.lat,center.lng]),$_mouseMoveUseTimer?window.teklaMap.AddMapMoveListener($_showCoordinates_timer):window.teklaMap.AddMapMoveListener($_showCoordinates)}}function $_showCoordinates_disable(){$_mouseMoveUseTimer?(window.teklaMap.RemoveMapMoveListener($_showCoordinates_timer),$_Crd_timer&&(clearTimeout($_Crd_timer),$_Crd_timer=null)):window.teklaMap.RemoveMapMoveListener($_showCoordinates)}function $_showCoordinates_timer(pt){pt&&($_Crd_timer?$_CrdLatLng=[pt.latlng.lat,pt.latlng.lng]:$_Crd_timer=setTimeout("shC();",$_mouseMoveTimerInterval))}function shC(){$_Crd_timer=null,$_CrdLatLng&&$_showCoordinates_common($_CrdLatLng)}function $_showCoordinates(pt){$_showCoordinates_common([pt.latlng.lng,pt.latlng.lat])}function $_showCoordinates_common(pt){var res=$_getCoordinateString(pt[0],pt[1]),distance=document.getElementById("coordinatediv");distance&&(distance.innerHTML=res)}function $_queryOnMouseup(){var map=window.teklaMap;$_updateCategoryMove(),map.NeedLayerRedraw(),map.EndGuiTrans()}var $_wheelListenerActive=!1,$_wheelListenerTimer=null;function sWLT(){!1!==$_wheelListenerActive||$_wheelListenerTimer||(options.wheelTimeOut>0?$_wheelListenerTimer=setTimeout((function(){sWL(!0)}),options.wheelTimeOut):sWL(!0))}function handleMouseDown(event,id,resizeid){}function drawLine(event){}function drawZoom(event){}function doPan(event,moveX,moveY){}function stopPan(event){setHandCursor(mapObj)}var linkresult=null;function initlink(s){linkresult=s}function $_GetLocation(linkresult){Tekla.MapBubble.hideAll(),window.teklaMap.BeginGuiTrans();var title=String.get_Safe(linkresult.query.title),obj=new SR_Point(title,title,null,null,linkresult.query.north,linkresult.query.east);obj.tpid=linkresult.query.tpid,obj.returnurl=linkresult.query.returnurl,obj.set_EditType("ext"),obj.Editable=!0,linkresult.query.conv&&(obj.Conv=linkresult.query.conv);var Id=SearchDB.Insert(obj),html='<div class="mysites">   <h3 class="mysites">'+String.format(GetText("cl_getLocationTitle")||"",title)+'</h3>   <div class="actionhelp">'+GetText("cl_getLocationHelp")+"</div></div>",$html=jQuery(html);Id>0&&($html.append(jQuery('<div><a class="getlocationrow" href="#">'+title+"</a></div>").find("a").click((function(){return searchClick(OBJ_SEARCH,obj.__id),!1})).end()),jQuery.each(Tekla.MapBubble.getObjectActions("ext",OBJ_SEARCH,obj),(function(){$this=this,$html.append(jQuery('<div><a class="bubblelink" href="#">'+$this.name+"</a></div>").find("a").click((function(event){return $this.action(event),!1})).end())}))),$_showSiteResultWnd($html);var map=window.teklaMap;map.NeedLayerRedraw(),map.EndGuiTrans();var content=map._PrepareBubble(OBJ_SEARCH,obj);if(null!=content){var cnt=obj.get_CenterPoint();map.ShowBubble([cnt.y,cnt.x],content,__PopupAnchor(obj))}}function createSite(tiptxt){hideInfo(),clearToolstate(),window.teklaMap._HandleRemove(),toolMode="createsite",jQuery("body").addClass(toolMode),setStatus(GetText("cl_selectNewObjectPosition")),window.teklaMap.AddMapMoveListener(updateTooltip),enableTooltip(tiptxt),jQuery(".leaflet-container").css("cursor","crosshair")}function updateSites(){window.teklaMap.RedrawLayers()}function deleteDrawing(){_clearLayers(L_TEMPLAYER),mapDrawing.points=null}function showSite(DBIndex,Id,noZoom){document.getElementById("mapsites");var obj=$_DBSelect(DBIndex,Id);obj&&(noZoom||$_ZoomToObject(obj),showInfo(DBIndex,Id,null,null))}function $_generateLayerCommand(){var selectedKeys=Tekla.Layers.getselected(!1,!0),layerScript="";if(selectedKeys&&selectedKeys.length>0)for(var i=0;i<selectedKeys.length;i++)i>0&&(layerScript+="|"),layerScript+=$_ENCODE(selectedKeys[i]);return"&Layerkey="+layerScript}function changeArea(){$_changeAreaBySelect("areaselect")}function $_ZoomToObject(obj){if(obj){if(window.teklaMap._getIsThreeDMode()){if(window.teklaMap3&&window.Tekla.ThreeD){var BB=obj.get_BB();window.Tekla.ThreeD.updateCamera({north:BB.northmin+(BB.northmax-BB.northmin)/2,east:BB.eastmin+(BB.eastmax-BB.eastmin)/2}),window.Tekla.ThreeD.setViewAngle("north")}return}if(!1!==$_CallEventHandler(tekla.Map.EVENT.ZOOMINGTOOBJECT,obj))if((BB=obj.get_BB())&&BB.Valid){options&&options.zoomMarginal>.1&&BB.Extend(options.zoomMarginal);BB.eastmax,BB.eastmin,BB.northmax,BB.northmin;var bounds=[[BB.northmin,BB.eastmin],[BB.northmax,BB.eastmax]];window.teklaMap._FitBounds(bounds),window.teklaMap._UpdateMapPosition(!0)}}}function __ZoomToBB(BB){if(BB&&BB.Valid){options&&options.zoomMarginal>.1&&BB.Extend(options.zoomMarginal);var bounds=[[BB.northmin,BB.eastmin],[BB.northmax,BB.eastmax]];window.teklaMap._FitBounds(bounds),window.teklaMap._UpdateMapPosition(!0)}}function showDrawing(DBIndex,Id){var obj=$_DBSelect(DBIndex,Id);if(obj){window.Tekla.MobileSetTab&&window.Tekla.MobileSetTab("map"),$_ZoomToObject(obj);var map=window.teklaMap,content=map._PrepareBubble(DBIndex,obj);if(null!=content){var cnt=obj.get_CenterPoint();map.ShowBubble([cnt.y,cnt.x],content,__PopupAnchor(obj))}}}function _updateCopyright(text,update){layersobj=document.getElementById("copy2"),layersobj&&text&&(layersobj.innerHTML=text)}function clearAllSites(){$_ClearElementInnetHTML("searchresults"),window.teklaMap._ClearVisualizations(!1)}function $_setCookie(name,value){var date=new Date;date.setTime(date.getTime()+31536e6),document.cookie=name+"="+value+"; expires="+date.toGMTString()}function $_getCookie(name){var buffer=""+document.cookie,prefix=name+"=",start=buffer.indexOf(prefix);if(-1!=start){var end=buffer.indexOf(";",start);return buffer.substring(start+prefix.length,-1!=end?end:buffer.length)}return null}function $_eSiteLink(result){if(result.ResultArray||result.geoJSON){if($_beginResultSet(OBJ_SEARCH),result.ResultArray)for(var i=0;i<result.ResultArray.length;i++){var rset=result.ResultArray[i][0];rset.geoJSON&&$_layerGeoJSONDisplayResults(SearchDB,rset.geoJSON)}else $_layerGeoJSONDisplayResults(SearchDB,result.geoJSON);$_endResultSet(OBJ_SEARCH)}result.objectdata&&$_publishObjectData(result.objectdata)}var curPrSet=null;function showPrintPage(json){curPrSet=json,json&&json.layout?window.teklaMap.printPage(null,null,json.layout):window.teklaMap.printPage()}function $_redrawDrawing(){$_EnsureColors(),mapDrawing.linecolor=$_LineColor,mapDrawing.lineweight=$_LineWidth,mapDrawing.dashtype=$_LineType,mapDrawing.fillcolor=$_FillColor,mapDrawing.fillopacity=$_FillOpacity;var linestring=L.polyline(mapDrawing.points,{color:$_LineColor,weight:__GetWeight($_LineWidth),fill:!1,identity:"drawing"});if(linestring.on({contextmenu:function(e){}}),container=new L.FeatureGroup,container.addLayer(linestring),(rectangle=L_inserthandle(mapDrawing.points[0][0],mapDrawing.points[0][1])).on({click:function a(e){showSiteProperties(e.latlng),e.preventDefault&&e.preventDefault()}}),rectangle.on({doubleclick:function a(e){cancelEventPropagation(event)}}),container.addLayer(rectangle),mapDrawing.points.length>2){var rectangle,l=mapDrawing.points.length-1;(rectangle=L_inserthandle(mapDrawing.points[l][0],mapDrawing.points[l][1])).on({click:function a(e){showSiteProperties(e.latlng),e.preventDefault&&e.preventDefault()}}),rectangle.on({doubleclick:function a(e){cancelEventPropagation(event)}}),container.addLayer(rectangle)}L_TEMPLAYER&&window.teklaMap.removeLayer(L_TEMPLAYER),L_TEMPLAYER=container,L_TEMPLAYER&&window.teklaMap.addLayer(container)}function actionUrl(controller,action,skiplang){return options.appPath+(skiplang?"":"/"+options.lang)+"/"+controller+(action?"/"+action:"")}function currentWupp(){var map=window.teklaMap;return map.options.crs.zoom2Wupp(map.getZoom())}function meters2LatLon(x,y){var OS=20037508.342789,lat=y/OS*180;return{lon:x/OS*180,lat:lat=180/Math.PI*(2*Math.atan(Math.exp(lat*Math.PI/180))-Math.PI/2)}}function $_isValidUrl(url,strict){return!!url&&(strict?/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(url)&&url.indexOf(" ")<0:url&&null!=url&&"null"!=url&&"undefined"!=url&&null!=url)}function $_tryGetValidUrl(url,strict){return url?strict?/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(url)?url.indexOf(" ")<0?url:null:/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(url)?"http://"+url:null:url&&null!=url&&"null"!=url&&"undefined"!=url&&null!=url?url:null:null}
var $_GeoUtil=new GeoUtil,$_CoordDef=null,$_CoordLabelDistanceKey=null,$_CoordLabelStatusRowKey=null;function $_coordinatesInit(iniString,iniDistanceLabelKey,iniStatusRowLabelKey){$_CoordDef=$_ParseIniString(iniString,iniDistanceLabelKey,iniStatusRowLabelKey)}function $_getCoordinateString(north,east,target){var format=GetText("cl_distanceCoordinates");return target&&"distance"==target?String.IsPrintable($_CoordLabelDistanceKey)&&(format=GetText("cl_"+$_CoordLabelDistanceKey)):String.IsPrintable($_CoordLabelStatusRowKey)&&(format=GetText("cl_"+$_CoordLabelStatusRowKey)),$_coordinateFormat(format,north,east)}function $_coordinateFormat(format,north,east){return $_CoordDef?$_CoordDef.wgs?$_CoordDef.wgs.ConvertFormatXY(format,east,north):$_CoordDef.zoneshift?$_CoordDef.zoneshift.ConvertFormatXY(format,east,north):$_CoordDef.affine?$_CoordDef.affine.ConvertFormatXY(format,east,north):String.format(format,Math.round(north),Math.round(east)):String.format(format,Math.round(north),Math.round(east))}function $_splitAction(actionString){var ret={name:"",params:""},a1=actionString.indexOf("["),a2=actionString.indexOf("]");return a1>=0&&a2>=0&&(ret.name=actionString.slice(0,a1),ret.params=actionString.slice(a1+1,a2)),ret}function $_splitAffine(actionString){var ret={name:null,a:null,b:null,c:null,d:null,e:null,f:null},affineParams=actionString.split(",");if(affineParams.length>1)for(var i=0;i<affineParams.length;i++){var n=$_splitNameValue(affineParams[i],"=");ret[n.name]=parseFloat(n.value)}else ret.name=affineParams[0];return ret}function $_splitZoneShift(actionString){for(var ret={source:-1,target:3},params=actionString.split(","),i=0;i<params.length;i++){var n=$_splitNameValue(params[i],"=");ret[n.name]="auto"==n.value?-1:parseInt(n.value,10)}return ret}function $_ParseIniString(iniString,iniDistanceLabelKey,iniStatusRowLabelKey){var ret={affine:null,zoneshift:null,wgs:null},parts=null;if(String.IsPrintable(iniDistanceLabelKey)&&($_CoordLabelDistanceKey=iniDistanceLabelKey),String.IsPrintable(iniStatusRowLabelKey)&&($_CoordLabelStatusRowKey=iniStatusRowLabelKey),String.IsPrintable(iniString)&&(parts=iniString.stripSpaces().split(";")),parts&&parts.length>0)for(var i=0;i<parts.length;i++){var a=$_splitAction(parts[i]);if("affine"==a.name){var affine=$_splitAffine(a.params);ret.affine="turku"==affine.name||"turkuwithzone"==affine.name?new CCHelmert(affine.name):new CCHelmert("param",affine.a,affine.b,affine.c,affine.d,affine.e,affine.f)}else if("kkjzoneshift"==a.name){var zonekkj=$_splitZoneShift(a.params);ret.zoneshift=new CCKKJZoneShift(ret.affine,zonekkj.source,zonekkj.target)}else if("kkj2wgs"==a.name){var p=$_splitNameValue(a.params,"=");ret.wgs=new CCWGS84(ret.affine,"source"==p.name?"auto"==p.value?-1:parseInt(p.value,10):-1)}else setStatus("Transform "+a.name+" not supported")}return ret}function CCHelmert(conversionType,a,b,c,d,e,f){this.Type=conversionType,this.aff_a=a,this.aff_b=b,this.aff_c=c,this.aff_d=d,this.aff_e=e,this.aff_f=f}function CCKKJZoneShift(PreHelmert,S,T){this.Helmert=PreHelmert,this.SourceZone=S,this.TargetZone=T}function CCWGS84(PreHelmert,Zone){this.Helmert=PreHelmert,this.ResultZone=Zone}function GeoUtil(){}function LatLon(){this.DoubleValue=0}function $_Fmt_3(inp){var ret="";if((inp+="")&&inp.length>3)for(var l=inp.length,i=0;i<l;i++)i>0&&(l-i)%3==0&&(ret+=" "),ret+=inp.charAt(i);else ret=inp;return ret}CCHelmert.prototype.ConvertXY=function(InNorth,InEast){var North,East,xk,yk,xv,yv,xtku,ytku;if("turku"==this.Type||"turkuwithzone"==this.Type)yv=(ytku=InNorth)+5e5+((yk=ytku/1e3)*yk*yk-343e3-((xk=(xtku=InEast)/1e3)-105)*(xk-105)*(yk+140))/244900,North=1.000005371*(xk=(xv=xtku+66e5+(xk-105)*(2*yk*yk+140*yk-4900)/244900)>1e6?xv-1e6*Math.floor(xv/1e6):xv)+49e-9*(yk=yv>1e5?yv-1e5*Math.floor(yv/1e5):yv)-5.782-xk+xv,East=1.000005371*yk-49e-9*xk+.924-yk+yv,"turkuwithzone"==this.Type&&East<1e6&&(East+=1e6);else if("param"==this.Type){var NewInNorth=InEast,NewInEast=InNorth;North=this.aff_a+this.aff_c*NewInNorth+this.aff_d*NewInEast,East=this.aff_b+this.aff_e*NewInNorth+this.aff_f*NewInEast}else North=InNorth,East=InEast;return[North,East]},CCHelmert.prototype.ConvertFormatXY=function(format,InNorth,InEast){var a=this.ConvertXY(InNorth,InEast),n=$_Fmt_3(Math.round(a[0])),e=$_Fmt_3(Math.round(a[1]));return String.format(format,n,e)},CCKKJZoneShift.prototype.ConvertXY=function(InNorth,InEast){var North=InNorth,East=InEast,Zone=this.SourceZone;if(null!=this.Helmert){var coordsh=this.Helmert.ConvertXY(InNorth,InEast);North=coordsh[0],East=coordsh[1]}Zone<0&&(Zone=$_GeoUtil.KKJ_DetectZone(East));var coords=$_GeoUtil.KKJ_xy2gk(East,North,Zone),Lat=coords[0],Lon=coords[1];return $_GeoUtil.KKJ_gk2xy(Lat,Lon,this.TargetZone)},CCKKJZoneShift.prototype.ConvertFormatXY=function(format,InNorth,InEast){var a=this.ConvertXY(InNorth,InEast);return String.format(format,Math.round(a[1]),Math.round(a[0]))},CCWGS84.prototype.ConvertFormatXY=function(format,InNorth,InEast){var coords=this.ConvertXY_MML(InNorth,InEast),Lat=coords[0],Lon=coords[1],ll=new LatLon;return ll.set_DoubleDec(Lat),Lat=ll.ToString(),ll.set_DoubleDec(Lon),Lon=ll.ToString(),String.format(format,Lat,Lon)},CCWGS84.prototype.ConvertXY_MML=function(InNorth,InEast){var P,I,North=InNorth,East=InEast,Zone=this.ResultZone;if(null!=this.Helmert){var coordsh=this.Helmert.ConvertXY(InNorth,InEast);North=coordsh[0],East=coordsh[1]}if(Zone<0&&(Zone=$_GeoUtil.KKJ_DetectZone(East)),3!=Zone){var coords=$_GeoUtil.KKJ_xy2gk(East,North,Zone),Lat=coords[0],Lon=coords[1],coords2=$_GeoUtil.KKJ_gk2xy(Lat,Lon,3);East=coords2[0],North=coords2[1]}return North<=72e5?(P=.9999955294*North-125.056+68348e-10*East,I=.9999955294*East-107.85-68348e-10*North):(P=1.0000006841*North-132.881-15179e-10*East,I=1.0000006841*East-185.993+15179e-10*North),$_GeoUtil.WGS_xy2gk(I,P,3)},GeoUtil.prototype.atanh=function(x){return Math.log((1+x)/(1-x))/2},GeoUtil.prototype.asinh=function(x){return Math.log(x+Math.sqrt(x*x+1))},GeoUtil.prototype.cosh=function(x){var Result=Math.exp(x);return(Result+1/Result)/2},GeoUtil.prototype.sinh=function(x){var Result=Math.exp(x);return(Result-1/Result)/2},GeoUtil.prototype.tanh=function(x){var Result=Math.exp(x);return(Result-1/Result)/(Result+1/Result)},GeoUtil.prototype.KKJ_DetectZone=function(I){return I>=1e6&&I<2e6?1:I>=2e6&&I<3e6?2:I>=3e6&&I<4e6?3:I>=4e6&&I<5e6?4:I>=5e6&&I<6e6?5:I>=6e6&&I<7e6?6:I>=7e6&&I<8e6?7:0},GeoUtil.prototype.KKJ_DetectGeoZone=function(Longitude){return Longitude>16.5&&Longitude<=19.5?0:Longitude>19.5&&Longitude<=22.5?1:Longitude>22.5&&Longitude<=25.5?2:Longitude>25.5&&Longitude<=28.5?3:Longitude>28.5&&Longitude<=31.5?4:Longitude>31.5&&Longitude<=34.5?5:Longitude>34.5&&Longitude<=37.5?6:Longitude>37.5&&Longitude<=40.5?7:0},GeoUtil.prototype.KKJ_xy2gk=function(x,y,zone){var lat,lon,ksi,ksi1,eta,eta1,q,q1,q2,beta,i,aa=6367654.500057584,e=.08199188997902919,hh=[.0008412763388185882,5.956192977992e-8,1.6948520876e-10,2204739e-19];for(ksi1=ksi=y/aa,eta1=eta=(x=x-5e5-1e6*zone)/aa,i=1;i<5;i++)ksi1-=hh[i-1]*Math.sin(2*i*ksi)*this.cosh(2*i*eta),eta1-=hh[i-1]*Math.cos(2*i*ksi)*this.sinh(2*i*eta);beta=Math.asin(1/this.cosh(eta1)*Math.sin(ksi1)),q2=q=this.asinh(Math.tan(beta)),q1=q,i=0;do{i++,q1=q2,q2=q+e*this.atanh(e*this.tanh(q2))}while((q1-q2>1e-12||q1-q2<-1e-12)&&i<20);return lat=180*Math.atan(this.sinh(q2))/Math.PI,lon=180*Math.asin(this.tanh(eta1)/Math.cos(beta))/Math.PI,[lat,lon+=18+3*zone]},GeoUtil.prototype.KKJ_gk2xy=function(lat,lon,zone){var q,beta,eta,eta1,ksi,ksi1,aa=6367654.500057584,e=.08199188997902919,hh=[.0008412759910095592,7.6730668628408e-7,1.21291229577e-9,248508228e-20];lat=lat/180*Math.PI,lon=lon/180*Math.PI,lon-=(18+3*zone)/180*Math.PI,q=this.asinh(Math.tan(lat))-e*this.atanh(e*Math.sin(lat)),beta=Math.atan(this.sinh(q)),eta1=this.atanh(Math.cos(beta)*Math.sin(lon)),ksi=ksi1=Math.asin(Math.sin(beta)*this.cosh(eta1)),eta=eta1;for(var i=1;i<5;i++)ksi+=hh[i-1]*Math.sin(2*i*ksi1)*this.cosh(2*i*eta1),eta+=hh[i-1]*Math.cos(2*i*ksi1)*this.sinh(2*i*eta1);return[aa*eta+5e5+1e6*zone,aa*ksi]},GeoUtil.prototype.WGS_xy2gk=function(x,y,zone){var lat,lon,ksi,ksi1,eta,eta1,q,q1,q2,beta,i,aa=6367449.145823415,e=.08181919084262149,hh=[.0008377321640600652,5.9058695679340996e-8,1.6734888803548956e-10,21677377630221183e-29];for(ksi1=ksi=y/aa,eta1=eta=(x=x-5e5-1e6*zone)/aa,i=1;i<5;i++)ksi1-=hh[i-1]*Math.sin(2*i*ksi)*this.cosh(2*i*eta),eta1-=hh[i-1]*Math.cos(2*i*ksi)*this.sinh(2*i*eta);beta=Math.asin(1/this.cosh(eta1)*Math.sin(ksi1)),q2=q=this.asinh(Math.tan(beta)),q1=q,i=0;do{i++,q1=q2,q2=q+e*this.atanh(e*this.tanh(q2))}while((q1-q2>1e-12||q1-q2<-1e-12)&&i<20);return lat=180*Math.atan(this.sinh(q2))/Math.PI,lon=180*Math.asin(this.tanh(eta1)/Math.cos(beta))/Math.PI,[lat,lon+=18+3*zone]},LatLon.prototype.set_DoubleDec=function(dec){this.DoubleValue=dec},LatLon.prototype.get_DoubleDec=function(){return this.DoubleValue},LatLon.prototype.ConvertDouble2Deg=function(){this.Degrees=Math.floor(this.DoubleValue);var f=60*(this.DoubleValue-this.Degrees);return this.Minutes=Math.floor(f),this.Seconds=60*(f-this.Minutes),!0},LatLon.prototype.ToString=function(){this.ConvertDouble2Deg();var resultSeconds=Math.round(100*this.Seconds)/100;return this.Degrees+"º "+this.Minutes+"' "+resultSeconds+"''"},function(window){window.Tekla||(window.Tekla={}),window.Tekla.CoordinateTransformation||(window.Tekla.CoordinateTransformation={}),window.Tekla.CoordinateTransformation.transform=function(north,east,onReady,options){var data={north:north,east:east};options&&options.sourceSystem&&(data.sourceSystem=options.sourceSystem),options&&options.targetSystem&&(data.targetSystem=options.targetSystem),options&&options.decimalCount&&(data.decimalCount=options.decimalCount);var url=actionUrl("Transform");jQuery.ajax({type:"GET",url:url,data:data,dataType:tekla.utility.isSameOrigin(url)?"json":"jsonp",success:function(data){onReady(data)}})}}(window);
var $_defaultPresentation=null,$_defaultTexts=null;function $_deleteGuideLines(){}function $_GetSVGSource(isStatic){}function $_GetVMLDiv(isStatic){}function $_GetSVGDiv(isStatic){}function $_guiDrawObjectVisible(isStatic,accept){return!1}function $_DrawModeOn(){return"drawpolygon"===toolMode||"drawrectangle"===toolMode||"drawpolyline"===toolMode||"createaddress"===toolMode||"createsearchobject"===toolMode||"createsite"===toolMode||"movesite"===toolMode||"selectposition"===toolMode||"distance"===toolMode||"moveLine"===toolMode||"zoom"===toolMode}function $_GetSVGDashArray(dashtype){return"solid"==dashtype?"1":"dot"==dashtype?"3,8":"dash"==dashtype?"8,8":"longdash"==dashtype?"18,8":"1"}function $_SVGObjectVisible(isStatic,accept){var source=$_GetSVGSource(isStatic);if(source)for(var i=0;i<source.childNodes.length;i++)if(!accept||source.childNodes[i].linename==accept)return!0;return!1}function $_deleteChildNodes(sourcediv,accept,deny){if(sourcediv.childNodes)for(var i=0;i<sourcediv.childNodes.length;i++){var childNode=sourcediv.childNodes[i];accept&&childNode.linename!=accept||deny&&$_matchDynTarget(deny,childNode.linename)||(sourcediv.removeChild(childNode),i-=1)}}function refreshDraw(obj){if(obj.Geometry){for(var cnt=obj.Geometry.members?obj.Geometry.members.length:1,removeArray=[],m=0;m<cnt;m++)for(var o in L_MYSITESLAYER._layers){var lr=L_MYSITESLAYER._layers[o];lr&&lr.options.obj.__id==obj.__id&&removeArray.push(lr)}for(var i=0;i<removeArray.length;i++)L_MYSITESLAYER.removeLayer(removeArray[i])}window.teklaMap._HandleRemoveAll(),$_CreatePolylinePolygonHTML(!0,OBJ_MYSITES,obj,L_MYSITESLAYER)}function removeNode(handle){var obj=$_DBSelect(OBJ_MYSITES,handle.Id);obj&&($_DBSetDirty(OBJ_MYSITES,!0),obj.RemoveNode(handle.NodeId,handle.MemberId,handle.RingId),refreshDraw(obj,OBJ_MYSITES+$_nameSeparator+handle.Id))}function $_endPolygon(event){handleDoubleClick(event),cancelEventPropagation(event)}var $_MouseMoved=!1,$_nameSeparator="_";
var L_CATLAYER,L_SEARCHLAYER,L_MYSITESLAYER,L_TEMPLAYER,L_HANDLESLAYER,L_MEASURELAYER,L_USERPOSITIONLAYER,L_MAPOBJECTPOSITIONLAYER,OBJ_CATLAYER=0,OBJ_SEARCH=1,OBJ_MYSITES=2,OBJ_NAMEDAREAS=3;function _clearLayers(layer){layer&&layer.clearLayers()}var LIST_NO=0,LIST_COLLECTION=2,LIST_NO_CC=3,LIST_CB=4,TXWConst={EDITSTATE_PROPERTIES:1,EDITSTATE_GEOMETRY:2,EDITSTATE_PRESENTATION:4,EDITSTATE_ALL:3,CATEGORY:0,SEARCH:1,MYSITES:2},LayerDB=new DataBase(!0),SearchDB=new DataBase(!1),MySitesDB=new DataBase(!1),StreetNameDB=new StreetNameDataBase(!1),NamedAreasDB=new DataBase(!1),HLDB=new HLSelection(!1),LoadBB=null,$_defaultLineColor="Red",$_defaultFillColor="Green",$_defaultLineType="solid",$_defaultLineWidth=4,$_defaultFillOpacity=.7,$_defaultLineOpacity=.8,$_GlobalLayerLevelsHash=new Object;function $_GlobalLayerLevels_Find(layer){return $_GlobalLayerLevelsHash[layer]}function $_GlobalLayerLevels_Add(layer,max){$_GlobalLayerLevelsHash[layer]=max}function $_GlobalLayerLevels_Remove(layer){$_GlobalLayerLevelsHash[layer]=null}function $_CategoryLoadable(level){var catLayerMax=options.mapData.settings.CatLayerMax;return!(catLayerMax&&level>catLayerMax)}function $_DBIsPolylineOrArea(obj){return obj&&obj.PointArray}function $_DBIsValidObject(obj,DB){var ret=obj&&(obj.Name||obj.FmtText||obj.AttrList);if(!ret)return ret;var filter=DB?DB.LayerFilter(obj.Category):null;return filter&&!filter(obj)&&(ret=!1),ret}function $_DBObjectOverlap(obj,BB){return!BB||BB.BBOverlap(obj.get_BB())}function $_DBSelect(DBIndex,Id){return $_GetDBByIndex(DBIndex).Select(Id)}function $_DBSetDirty(DBIndex,dirty){var DB=$_GetDBByIndex(DBIndex);DB&&DB.set_Dirty(dirty)}function $_DBDelete(DBIndex,Id){var DB=$_GetDBByIndex(DBIndex),obj=DB.Select(Id);return!!obj&&(DB.DeleteObj(obj),DBIndex==OBJ_MYSITES&&window.teklaMap._HandleRemoveIf(Id),!0)}function $_GetDBByIndex(index){return index==OBJ_CATLAYER?LayerDB:index==OBJ_SEARCH?SearchDB:index===OBJ_NAMEDAREAS?NamedAreasDB:MySitesDB}function $_GetIndexByDB(DB){return DB==LayerDB?OBJ_CATLAYER:DB==SearchDB?OBJ_SEARCH:OBJ_MYSITES}function TXWPoint(n,e){this.south=n,this.east=e}function $_ConvertPointsToPoint(n,e){return[e,n]}function $_ConvertPointsToPolygon(points){for(var mainarea=[],a=0;a<points.length;a++)mainarea.push([points[a][1],points[a][0]]);return[mainarea]}function _TXWConvertPointsToPolygon(points){for(var mainarea=[],a=0;a<points.length;a++)mainarea.push([points[a].east,points[a].south]);return[mainarea]}function _TXWConvertPointsToLineString(points){var coordinates=[];if(points)for(var a=0;a<points.length;a++)coordinates.push([points[a].east,points[a].south]);return coordinates}function $_ConvertPointsToLineString(points){var coordinates=[];if(points)for(var a=0;a<points.length;a++)coordinates.push([points[a][1],points[a][0]]);return coordinates}function $_ConvertToPointArray(northArray,eastArray){for(var routePoints=[],a=0;a<northArray.length&&a<eastArray.length;a++)routePoints.push(new TXWPoint(northArray[a],eastArray[a]));return routePoints}function _isThreeD(array){return array&&array.length>2}function _geoIsThreeD(geo){return"LineString"===geo.type&&_isThreeD(geo.coordinates[0])}function $_objectVisible(DBIndex,Id,obj){return!1}function $_DBFindObjectByName(DB,name){return null!=$_DBFindObjectByAttribute(DB,"Name",name)}function $_DBFindObjectByAttribute(DB,key,value){for(var Id=0;Id<DB.items.length;Id++){var obj=DB.items[Id];if(obj&&obj[key]==value)return obj}return null}function DataBase(nc){this.__id=1,this.items=[],this.idindex=[],nc&&(this.__visibleLayers=[],this.__visibleCategories=[],this.__loadedCategories=[],this.__wupp=null,this.LoadedBB=new BBox)}function SR_Geo(name,explanation){this.Name=name,this.Explanation=explanation}function SR_Point(name,explanation,url,image,north,east){this.Name=name,this.Explanation=explanation,this.Url=url,this.Image=image,this.North=north,this.East=east}function SR_Path(name,explanation,url,image,pointarray){this.Name=name,this.Explanation=explanation,this.Url=url,this.Image=image||__getLineImage(),this.PointArray=pointarray}function __ensureVisibleCategories(level){var needLoad=!1;if(level===LayerDB.__wupp)return!1;var ret=[],needRefresh=!1;LayerDB.__wupp=level;for(var i=0;i<LayerDB.__visibleLayers.length;i++){var layerName=LayerDB.__visibleLayers[i],status=Tekla.Layers.visiblebyinfo(layerName,layerName,level);if(!0===status)ret.push(layerName);else if(status&&status.isvec&&status.info)for(var a=0;a<status.info.length;a++)ret.push(status.info[a])}if(ret.length>0)for(i=0;i<ret.length;i++){var info=ret[i];LayerDB.__visibleCategories.Find(info)||(LayerDB.AddCategory(info,!1),needLoad=!0)}if(LayerDB.__visibleCategories.length>0){var remove=[];for(i=0;i<LayerDB.__visibleCategories.length;i++){info=LayerDB.__visibleCategories[i];ret.Find(info)||remove.push(info)}for(i=0;i<remove.length;i++)LayerDB.RemoveCategory(remove[i]),needRefresh=!0}return!needLoad&&needRefresh&&window.teklaMap.RedrawLayersImmediate(),needLoad}function $_updateCategoryMove(force){var needLoad=!1,needLoadAll=!1,level=currentWupp();if($_CategoryLoadable(level)){__ensureVisibleCategories(level)&&(needLoad=!0);var visibleCount=LayerDB.__visibleCategories.length;if(visibleCount>0&&(force||LayerDB.$_NeedLoad_Area())&&(needLoadAll=!0),!needLoad)for(var i=0;i<visibleCount;i++)if(!LayerDB.$_LayerLoaded(LayerDB.__visibleCategories[i])){needLoad=!0;break}if(needLoad||needLoadAll){visibleCount=LayerDB.__visibleCategories.length;var cids="";for(i=0;i<visibleCount;i++)!needLoadAll&&LayerDB.$_LayerLoaded(LayerDB.__visibleCategories[i])||(cids+="&cidname="+$_ENCODE(LayerDB.__visibleCategories[i]));if(cids.length>0){var url=actionUrl("Search")+"?Op=catinarea&noadmchk=true"+cids;url+=(LoadBB=$_getAreaBB(null)).ToAreaString(),$_CallEventHandler(tekla.Map.EVENT.LOADSTARTED),jQuery.ajax({async:!0,type:"GET",url:url,dataType:tekla.utility.isSameOrigin(url)?"text":"jsonp",success:function(data){onReadyStateLayerDataAsync(data)},complete:function(xhr,statusText){$_CallEventHandler(tekla.Map.EVENT.LOADREADY)}})}else force&&window.teklaMap.RedrawLayersImmediate();$_VectorVisibilityHandler(!1)}else force&&window.teklaMap.RedrawLayersImmediate()}else force&&window.teklaMap.RedrawLayersImmediate()}function $_updateCategory_Cached(categoryName,newState){return 1==newState?LayerDB.AddCategory(categoryName):LayerDB.RemoveCategory(categoryName)}function $_updateCategory($_Array,newState){for(var l=$_Array.length,i=0;i<l;i++)!0===newState?LayerDB.AddLayer($_Array[i].layer):LayerDB.RemoveLayer($_Array[i].layer);LayerDB.__wupp=null,$_updateCategoryMove()}function $_prepareCategoryLayer(categories){if(categories)for(var i=0;i<categories.length;i++)LayerDB.RemoveCategory(categories[i]),Tekla.Layers.iscategoryselected(categories[i])&&LayerDB.AddCategory(categories[i],!0)}async function onReadyStateLayerDataAsync(data){var result="string"==typeof data?$_EVALJSON(data):data;result&&(result.categories&&$_prepareCategoryLayer(result.categories),result.ResultArray&&result.ResultArray.length>0&&(rset=result.ResultArray[0][0]).categories&&$_prepareCategoryLayer(rset.categories));if(result.ResultArray||result.geoJSON){if($_beginResultSet(OBJ_CATLAYER),LayerDB.CatChecked_Bg(),result.ResultArray)for(var i=0;i<result.ResultArray.length;i++){var rset;(rset=result.ResultArray[i][0]).geoJSON?await $_layerGeoJSONDisplayResults(LayerDB,rset.geoJSON):rset&&await $_layerGeoJSONDisplayResults(LayerDB,rset.results)}else await $_layerGeoJSONDisplayResults(LayerDB,result.geoJSON);return $_restoreHighlights(LayerDB),$_endResultSet(OBJ_CATLAYER),void LayerDB.set_LoadedArea(LoadBB)}LayerDB.CatChecked_Bg(),$_layerDisplayResults(LayerDB,result,LIST_NO_CC),LayerDB.set_LoadedArea(LoadBB)}function get_EncTypeText(text,encType){return encType&&"decode"==encType?String.unescapeHTML(text):text}function $_layerDisplayResults(DB,result,tolist,encType){var html="",sb=null,model=null,DBIndex=$_GetIndexByDB(DB);if(window.teklaMap.BeginGuiTrans(),model=tolist==LIST_CB?{msg:null,items:[]}:null,tolist==LIST_COLLECTION&&(html="<span class='mysites'><h3 class='mysites'>"+String.get_Safe(result.CollName)+"</h3>"+(result.CollExp?"<p class='mysites'>"+result.CollExp+"</p>":"")+(result.Creator?"<p class='mysites'>"+GetText("cl_performer")+":&nbsp;"+result.Creator+"</p>":""),sb=new StringBuilder(html)),result.count<1)tolist==LIST_CB?model.msg=GetText("cl_noObjectsFound"):tolist==LIST_COLLECTION&&(String.IsPrintable(result.CollName)||String.IsPrintable(result.CollExp)||String.IsPrintable(result.Creator))&&$_showSiteResultWnd(html);else{var Id;if(tolist==LIST_CB?model.msg=String.format(GetText(result.truncated?"cl_searchTooManyObjectsFoundDisplayingN":"cl_searchNObjectsFound"),result.count):tolist==LIST_COLLECTION&&sb.Append("<table class='mysites' style='width: 100%; display: block; cursor: auto;'>"),!result.results)return;for(var i=0;i<result.results.length;i++){var item=result.results[i];if(item&&item.name){var obj;if(tolist==LIST_NO_CC&&0==DB.CatChecked(item.category))continue;if(item.geometry)(obj=new SR_Geo(item.name,item.tip)).set_Geometry(item.geometry),obj.set_Presentation(item.presentation),item.url&&(obj.Url=item.url),obj.set_Image(item.image),tolist==LIST_COLLECTION&&obj.set_AV(!0);else if(item.northarray){var pointsArray=$_ConvertToPointArray(item.northarray,item.eastarray);obj=new SR_Path(get_EncTypeText(item.name,encType),item.tip,item.url,item.image,pointsArray),item.north&&obj.set_Point(item.north,item.east),obj.set_Presentation(item.linecolor,item.linetype,item.linewidth,item.fillcolor?item.fillcolor:null,item.fillopacity?item.fillopacity:null),item.fill&&obj.set_Filled(item.fill),tolist==LIST_COLLECTION&&obj.set_AV(!0)}else obj=new SR_Point(get_EncTypeText(item.name,encType),item.tip,item.url,item.image,item.north,item.east);if(item.category&&obj.set_Category(item.category),item.editable&&(item.edittype?(obj.EditType=item.edittype,obj.Municipality=item.municipality,obj.Editable=!0,obj.CategoryId=item.categoryid,obj.ReferenceId=item.referenceid):obj.set_EditableAddress(item.streetname,item.addressnumber,item.municipality)),item.pe&&(obj.PX=item.pe),item.pn&&(obj.PY=item.pn),item.refid&&(obj.RefId=item.refid),item.nocluster&&(obj.NoCluster=item.nocluster),item.extdocs)for(var doccount=item.extdocs.length,doc=0;doc<doccount;doc++)obj.AddDocument(item.extdocs[doc].url,item.extdocs[doc].exp);if(item.addattrs){var attrcount=item.addattrs.length;obj.AttrList=[];for(var attr=0;attr<attrcount;attr++){var a=new Object;a.n=item.addattrs[attr].n,a.v=item.addattrs[attr].v,obj.AttrList.push(a)}}Id=DB.Insert(obj),item.urltype&&(obj.set_UrlType(item.urltype),"SF"==item.urltype&&(obj.Url="JavaScript:showFeedbackById("+DBIndex+","+Id+");")),tolist==LIST_CB?model.items.push({name:item.name,subtitle:item.subtitle,category:item.displaycategory,id:Id}):tolist==LIST_COLLECTION&&(html="<tr class='mysites'><td width='30px' class='mysites'><img src='"+(item.image?item.image:obj&&obj.Image?obj.Image:__getPinImage())+"' border='0'></td><td class='mysites'><h4 class='mysites'><a style=\"cursor:pointer\" onmouseover=\"doHover(this)\" onmouseout=\"removeHover(this)\" onmousedown=\"searchClick("+DBIndex+","+Id+');">'+String.escapeHTML(obj.Name)+"</a></h4><p class='mysites'>"+(item.tip?String.escapeHTML(item.tip):"&nbsp;")+"</p></td></tr>",sb.Append(html))}}tolist==LIST_COLLECTION&&(sb.Append("</table></span>"),html=sb.ToString()),1==result.results.length&&(result.setarea||(tolist!=LIST_NO&&tolist!=LIST_NO_CC||options.showBubbleInExactSearch&&DB==SearchDB)&&searchClick(DBIndex,Id,!0)),result.setarea&&(window.teklaMap._FitBounds([[result.mnorth-result.height/2,result.meast-result.width/2],[result.mnorth+result.height/2,result.meast+result.width/2]]),window.teklaMap._UpdateMapPosition(),1==result.results.length&&options.showBubbleInExactSearch&&searchClick(DBIndex,Id)),tolist!=LIST_NO&&tolist!=LIST_NO_CC&&$_showSiteResultWnd(html),window.teklaMap.NeedLayerRedraw()}return window.teklaMap.EndGuiTrans(),model}function $_CreatePointHTML(DBIndex,Id,obj){}function $_CreatePolylinePolygonHTML(isStatic,DBIndex,obj,container){obj.ToL(DBIndex,container),DBIndex==OBJ_MYSITES&&obj.__id==window.teklaMap._HandleGetActive()&&(L_HANDLESLAYER?(L_HANDLESLAYER.clearLayers(),L_drawHandles(L_HANDLESLAYER,obj,!0)):(L_HANDLESLAYER=new L.FeatureGroup,L_drawHandles(L_HANDLESLAYER,obj,!0),window.teklaMap.addLayer(L_HANDLESLAYER)))}function __isInsideSVGRange(level){var sets=options.mapData.settings,min=sets.SVGRMin?sets.SVGRMin:.01;return!sets.SVGRMax||!(level<min||level>sets.SVGRMax)}function $_internalUpdateDatabaseTypes(isStatic){var layer=void 0,mysitesLayer=void 0,catlayer=void 0;if(L_SEARCHLAYER&&(L_SEARCHLAYER.clearLayers(),window.teklaMap.removeLayer(L_SEARCHLAYER)),L_MYSITESLAYER)try{L_MYSITESLAYER.clearLayers(),window.teklaMap.removeLayer(L_MYSITESLAYER)}catch(e){}L_CATLAYER&&(L_CATLAYER.clearLayers(),window.teklaMap.removeLayer(L_CATLAYER));try{currentWupp()<=options.mapData.settings.ClusteringLevelMin-.01?(catlayer=L_updateLayersDatabase(),layer=L_updateSingleDatabase(SearchDB,OBJ_SEARCH),mysitesLayer=L_updateSingleDatabase(MySitesDB,OBJ_MYSITES)):options.mySitesClustered?layer=L_updateSingleClustered([{db:MySitesDB,dbi:OBJ_MYSITES},{db:LayerDB,dbi:OBJ_CATLAYER},{db:SearchDB,dbi:OBJ_SEARCH}]):(layer=L_updateSingleClustered([{db:LayerDB,dbi:OBJ_CATLAYER},{db:SearchDB,dbi:OBJ_SEARCH}]),mysitesLayer=L_updateSingleDatabase(MySitesDB,OBJ_MYSITES)),(L_MYSITESLAYER=mysitesLayer)&&window.teklaMap.addLayer(L_MYSITESLAYER),(L_CATLAYER=catlayer)&&window.teklaMap.addLayer(L_CATLAYER),(L_SEARCHLAYER=layer)&&window.teklaMap.addLayer(L_SEARCHLAYER)}catch(e){console.log(e)}}function $_dynPointImgOrSpan(hlon,pres,imgsrc,imgid){return pres&&pres.className?"<span class='"+pres.className+" normal"+(hlon?" highlight":"")+"' style='background-image: url("+imgsrc+")' id='"+imgid+"' ":"<img border='0'"+(pres&&pres.imgClass?" class='"+pres.imgClass+"'":"")+" src='"+imgsrc+"' id='"+imgid+"' "}function $_dynPointImgOrSpan2(pres,imgsrc,close,altText){return pres&&pres.className?"<span class='"+pres.className+" normal' style='background-image: url("+imgsrc+")' "+(close?"></span>":""):"<img border='0' src='"+imgsrc+"' "+(altText?" alt='"+altText+"'":"")+(close?"></img>":"")}function BBox(northmin,eastmin,northmax,eastmax){northmin?(this.eastmax=eastmax,this.eastmin=eastmin,this.northmax=northmax,this.northmin=northmin,this.Valid=!0):this.Valid=!1}function $_updateRefId(aid,refid){var obj=$_DBSelect(OBJ_SEARCH,aid);obj&&(obj.ReferenceId=refid)}function $_deleteExternalObject(aid){var obj=$_DBSelect(OBJ_SEARCH,aid);obj&&(obj.set_Editable(!1),$_GetDBByIndex(OBJ_SEARCH).DeleteObj(obj),window.teklaMap.RedrawLayersImmediate())}function $_onReadyUpdateAddress_Data(data){var result=$_EVALJSON(data);result.status&&setStatus("OK"),result.op&&result.type&&("ea"===result.type?!result.status&&result.aid&&"update"!==result.op&&$_deleteExternalObject(result.aid):"eso"===result.type&&(result.status&&result.aid&&result.newrefid?$_updateRefId(result.aid,result.newrefid):!result.status&&result.aid&&$_deleteExternalObject(result.aid))),String.IsPrintable(result.msg)&&alert(result.msg)}function $_updateNearestAddress(str,onready){}function $_updateAddress(str){jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?"+str,success:function(data){$_onReadyUpdateAddress_Data(data)}})}function $_loadStreetNames(municipality){jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=getstreetnames&municipality="+municipality,success:function(data){var result=$_EVALJSON(data);result&&result.municipality&&result.streetnames&&(StreetNameDB.Insert(result.municipality,result.streetnames),$_openAddressPropertiesWindow_cb(result.municipality))}})}function StreetNameDataBase(){this.hashtable=[]}function CollectionIdentity(mapid,name){this.MapId=mapid,this.Name=name}function CollectionDataBase(){this.hashtable=[]}function _isSelectedRid(rid){return window.teklaMap.__selectedRefIds&&window.teklaMap.__selectedRefIds[rid]==rid}TXWPoint.prototype.North=function(){return this.south},TXWPoint.prototype.East=function(){return this.east},DataBase.prototype.GetAt=function(i){return this.items[i]},DataBase.prototype.$_NeedLoad_Area=function(){return!this.LoadedBB.Valid||!this.LoadedBB.BBInside($_getAreaBB(.01))},DataBase.prototype.$_LayerLoaded=function(catname){return!!this.__loadedCategories.Find(catname)},DataBase.prototype.Clear=function(clearAll){var newitems=[],newidindex=[];if(!clearAll)for(var Id=0;Id<this.items.length;Id++){var obj=this.items[Id];obj&&obj.Permanent&&(newitems.push(obj),newidindex[obj.__id]=newitems.length-1)}this.items=newitems,this.idindex=newidindex,this.Dirty=!1},DataBase.prototype.GetPermanentItems=function(){for(var newitems=[],Id=0;Id<this.items.length;Id++){var obj=this.items[Id];obj&&obj.Permanent&&newitems.push(obj)}return newitems},DataBase.prototype.ClearFiltered=function(filter){for(var newitems=[],newidindex=[],Id=0;Id<this.items.length;Id++){var obj=this.items[Id],keep=obj&&obj.Permanent;keep||(keep=filter(obj)),keep&&(newitems.push(obj),newidindex[obj.__id]=newitems.length-1)}this.items=newitems,this.idindex=newidindex,this.Dirty=!1,window.teklaMap._UpdateMapPosition()},DataBase.prototype.Count=function(skippermanent){for(var count=0,Id=0;Id<this.items.length;Id++){var obj=this.items[Id];!$_DBIsValidObject(obj)||skippermanent&&obj.Permanent||count++}return count},DataBase.prototype.CopyObjectsToDB=function(db,count){var nCount=count||1;if((db=db||MySitesDB)&&nCount>0)for(var Id=0;Id<this.items.length;Id++){var obj=this.items[Id];if($_DBIsValidObject(obj)&&!obj.Permanent){var newObj=db.InsertClone(obj,!0);if(newObj.Editable=!0,newObj.set_Dirty(TXWConst.EDITSTATE_ALL),$_CallEventHandler(tekla.Map.EVENT.DRAWINGREADY,newObj),0==(nCount-=1))return}}},DataBase.prototype.set_LoadedArea=function(BB){this.LoadedBB=BB},DataBase.prototype.CatChecked=function(categoryName){return categoryName!==this.lastc&&(this.laststate=this.__visibleCategories.Find(categoryName),this.lastc=categoryName),this.laststate},DataBase.prototype.CatChecked_Bg=function(){this.lastc=null,this.laststate=!1},DataBase.prototype.LayerFilter=function(categoryName){return categoryName?window.Tekla.Layers.getFilter(categoryName):null},DataBase.prototype.AddLayer=function(layerName){this.__visibleLayers.Find(layerName)||this.__visibleLayers.push(layerName)},DataBase.prototype.__addCategory=function(categoryName,isloaded){var mod=!1;return 0==this.__visibleCategories.Find(categoryName)&&(this.__visibleCategories.push(categoryName),mod=!0),isloaded&&0==this.__loadedCategories.Find(categoryName)&&(this.__loadedCategories.push(categoryName),mod=!0),mod},DataBase.prototype.AddCategory=function(categoryName,isloaded){var mod=!1,self=this;return Tekla.Layers.__enumInfo(categoryName,(function(info){self.__addCategory(info,isloaded)&&(mod=!0)})),mod},DataBase.prototype.UnloadCategory=function(categoryName){var mod=!1;this.__loadedCategories.Find(categoryName)&&(this.__loadedCategories.remove(categoryName),mod=!0),this.LoadedBB.Valid=!1;for(var Id=0;Id<this.items.length;Id++){var obj=this.items[Id];null!=obj&&obj.Category==categoryName&&(this.items[Id]=null)}return mod},DataBase.prototype.RemoveLayer=function(layerName){this.__visibleLayers.Find(layerName)&&this.__visibleLayers.remove(layerName)},DataBase.prototype.RemoveCategory=function(categoryName){var changed=!1;1==this.__visibleCategories.Find(categoryName)&&(this.__visibleCategories.remove(categoryName),changed=!0),1==this.__loadedCategories.Find(categoryName)&&(this.__loadedCategories.remove(categoryName),changed=!0);for(var Id=0;Id<this.items.length;Id++){var obj=this.items[Id];null!=obj&&obj.Category==categoryName&&(this.items[Id]=null)}return changed},DataBase.prototype.DeleteObj=function(obj){if(obj){if(obj.Editable){var Op="ea"==obj.get_EditType()?"Op=update&Type=delete&streetname="+$_ENCODE(obj.StreetName)+"&addressnumber="+$_ENCODE(obj.AddressNumber)+"&municipality="+$_ENCODE(obj.Municipality):"eso"==obj.get_EditType()?"Op=updatesearchobject&Type=delete&categoryid="+obj.CategoryId+"&referenceid="+obj.ReferenceId+"&municipality="+$_ENCODE(obj.Municipality):null;Op&&($_updateAddress(Op),obj.Editable=!1)}obj.Name=null,obj.FmtText=null,obj.IsDeleted=!0,this.Dirty=!0}},DataBase.prototype.Insert=function(item){if(this.__id++,null==item)throw"NullPointerException {"+this.__id+"},{"+item+"}";if(item.ReferenceId&&this._newItems&&this._newItems.Find(item.ReferenceId)){this._newItems.remove(item.ReferenceId);var oldItem=this.FindByReferenceId(item.ReferenceId);oldItem&&this.DeleteObj(oldItem)}return item.__id=this.__id,this.items.push(item),this.idindex[item.__id]=this.items.length-1,this.Dirty=!0,item.__id},DataBase.prototype.InsertNew=function(item){var ret=this.Insert(item);return item.ReferenceId&&(this._newItems||(this._newItems=[]),this._newItems.push(item.ReferenceId)),ret},DataBase.prototype.InsertRange=function(items){for(var i=0;i<items.length;i++)this.Insert(items[i])},DataBase.prototype.InsertClone=function(obj,upgrade){var newobj;return this.__id++,upgrade&&!obj.Geometry?(function _upgradeGeometry(target,source){var g,p={};target.Geometry||(source.PointArray&&source.get_Filled()?(g={type:"Polygon",coordinates:_TXWConvertPointsToPolygon(source.PointArray)},p={LineColor:source.LineColor,LineType:source.LineType,LineWidth:source.LineWidth,FillColor:source.FillColor,FillOpacity:source.FillOpacity,Image:source.Image}):obj.PointArray?(g={type:"LineString",coordinates:_TXWConvertPointsToLineString(source.PointArray)},p={LineColor:source.LineColor,LineType:source.LineType,LineWidth:source.LineWidth,Image:source.Image}):(g={type:"Point",coordinates:$_ConvertPointsToPoint(source.North,source.East)},p={Image:source.Image}),target.set_Geometry(g)),target.Presentation||target.set_Presentation(p)}(newobj=new SR_Geo(obj.Name,obj.Explanation),obj),newobj.Url=obj.Url,newobj.ReferenceId=obj.ReferenceId):newobj=$_CloneObject(obj,!0),newobj.__id=this.__id,this.items.push(newobj),this.idindex[this.__id]=this.items.length-1,this.Dirty=!0,newobj},DataBase.prototype.ReIndex=function(){for(var i=0;i<this.items.length;i++)this.idindex[this.items[i].__id]=i},DataBase.prototype.Select=function(id){return this.items[this.idindex[id]]},DataBase.prototype.FindByReferenceId=function(referenceId){for(var Id in this.items){var obj=this.items[Id];if($_DBIsValidObject(obj)&&obj.ReferenceId&&obj.ReferenceId==referenceId)return obj}return null},DataBase.prototype.FindByAttribute=function(key,value){for(var Id=0;Id<this.items.length;Id++){var obj=this.items[Id];if($_DBIsValidObject(obj)&&obj[key]==value)return obj}return null},DataBase.prototype.GetObjectsWithGeometry=function(){for(var obj,retVal=[],id=0;id<this.items.length;id++)$_DBIsValidObject(obj=this.items[id])&&!obj.Permanent&&(obj.Geometry?retVal.push(obj):obj.PointArray&&obj.PointArray.length>1?retVal.push(Object.assign(obj.Filled?{__proto__:obj.__proto__,Geometry:{type:"Polygon",coordinates:[obj.PointArray.map((function(pa){return[pa.East(),pa.North()]}))]}}:{__proto__:obj.__proto__,Geometry:{type:"LineString",coordinates:obj.PointArray.map((function(pa){return[pa.East(),pa.North()]}))}},obj)):obj.North&&obj.East&&retVal.push(Object.assign({__proto__:obj.__proto__,Geometry:{type:"Point",coordinates:[obj.East,obj.North]}},obj)));return retVal},DataBase.prototype.GetThreeDItems=function(){for(var obj,retVal=[],id=0;id<this.items.length;id++)if($_DBIsValidObject(obj=this.items[id])&&!obj.Permanent&&obj.Geometry){var geo=obj.Geometry;if(_geoIsThreeD(geo)){var start=geo.coordinates[0],end=geo.coordinates[1];retVal.push({text:obj.Explanation,start:{x:start[0],y:start[1],z:start[2]},end:{x:end[0],y:end[1],z:end[2]},id:obj.__id})}}return retVal},DataBase.prototype.SetThreeDItemEditability=function(editable){for(var id=0;id<this.items.length;id++){var obj=this.items[id];if($_DBIsValidObject(obj)&&!obj.Permanent&&obj.Geometry)_geoIsThreeD(obj.Geometry)&&(obj.Editable&&obj.setCanDelete(!0),obj.Editable=editable)}},DataBase.prototype.set_Dirty=function(dirty){this.Dirty=dirty},DataBase.prototype.get_Dirty=function(){return this.Dirty},SR_Geo.prototype.getCanDelete=function(){return this.CanDelete},SR_Geo.prototype.setCanDelete=function(v){this.CanDelete=v},SR_Geo.prototype.GetType=function(getFirstGeom){if(getFirstGeom&&this.Geometry){var geom=this.Geometry;return"MultiPolygon"===geom.type?"Polygon":"GeometryCollection"===geom.type&&geom.members&&geom.members.length>0&&geom.members[0].geometry?geom.members[0].geometry.type:geom.type}return"Geo"},SR_Geo.prototype.set_Selected=function(i,clear,noflush){this.CustomClass=!0,clear&&(window.teklaMap._SetSelectMode(!1),window.teklaMap._SetSelectMode(!0)),this.set_SelectedState(i,!0)},SR_Geo.prototype.set_SelectedState=function(i,sel){var LR=i==OBJ_MYSITES?L_MYSITESLAYER:null;if(LR)for(var o in LR._layers){var layer=LR._layers[o];if(layer&&layer.options&&layer.options.obj)if(layer.options.obj.__id==this.__id){sel?__setStyleSelected(layer):__setStyleUnselected(layer),layer.options.isselected=sel;break}}window.teklaMap.__selectedRefIds=window.teklaMap._GetSelectedRefIds()},SR_Geo.prototype.set_Geometry=function(g){g&&"empty"!==g.type&&(this.Geometry=g)},SR_Geo.prototype.set_Presentation=function(p){this.Presentation=p},SR_Geo.prototype.IsSVGPresentation=function(){return this.Presentation&&this.Presentation.svg},SR_Geo.prototype.set_Offsets=function(sdir,sdx,sdy){this.Presentation=this.Presentation||{},this.Presentation.sdir=gonsToRadians(+sdir,!0),this.Presentation.sdx=+sdx,this.Presentation.sdy=+sdy,this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),this.__bbox&&(this.__bbox=null)},SR_Geo.prototype.set_SvgAsync=async function(svg,size,bg){this.set_Svg(svg,size,bg),svg&&await window.Tekla.BitmapManager.getBitmapAsync(svg)},SR_Geo.prototype.set_Svg=function(svg,size,bg){this.Presentation=this.Presentation||{},this.Presentation.svg=svg,isNaN(size)||(this.Presentation.size=+size),svg&&bg&&(this.Presentation.bg=bg),this.__bbox&&(this.__bbox=null)},SR_Geo.prototype.HasChanges=function(svg,size,bg){return!this.Presentation||this.Presentation.svg!=svg||this.Presentation.size!=+size},SR_Geo.prototype.set_Bg=function(bg){this.Presentation=this.Presentation||{},this.Presentation.bg=bg},SR_Geo.prototype.get_Presentation=function(gethl){var retVal=null;function getHLPresentation(HLPres,Pres){return HLPres&&(HLPres.svg||Pres.svg)&&(HLPres.sdir=Pres.sdir,HLPres.sdx=Pres.sdx,HLPres.sdy=Pres.sdy,HLPres.svg=Pres.svg,HLPres.size=Pres.size,HLPres.hl=!0),HLPres}var useClass=this.Presentation&&this.Presentation.className;!0===gethl?retVal=useClass?getHLPresentation(this.HLPresentation,this.Presentation)||this.Presentation:getHLPresentation(this.HLPresentation,this.Presentation)||TGMap.Style.highlight:!1===gethl&&(retVal=this.Presentation);var pres=this.Presentation||{};if($_CallEventHandler(tekla.Map.EVENT.DRAWINGPRESENTATION,this,pres)&&(this.Presentation=pres),retVal=useClass?this.HLOn&&getHLPresentation(this.HLPresentation,this.Presentation)||this.Presentation:this.HLOn?getHLPresentation(this.HLPresentation,this.Presentation):this.Presentation,this.Width>0){retVal||(retVal={}),retVal.OrigLineWidth||(retVal.OrigLineWidth=retVal.LineWidth);var newLineWidth=Math.round(this.Width/currentWupp());retVal.LineWidth=newLineWidth>1?newLineWidth:1}else retVal&&retVal.OrigLineWidth&&(retVal.LineWidth=retVal.OrigLineWidth,delete retVal.OrigLineWidth);return retVal},SR_Geo.prototype.set_Image=function(img){this.Presentation&&void 0!==img&&!this.Presentation.Image&&(this.Presentation.Image=img)},SR_Geo.prototype.set_Category=function(c){this.Category=c},SR_Geo.prototype.get_Category=function(){return this.Category},SR_Geo.prototype.set_FmtText=function(text){this.FmtText=text},SR_Geo.prototype.get_FmtText=function(){return this.FmtText},SR_Geo.prototype.set_Explanation=function(e){return this.Explanation=e},SR_Geo.prototype.set_ThreedDLine=function(crd){this.Geometry={type:"LineString",coordinates:crd}},SR_Geo.prototype.$_get_FirstGeomemtryMember=function(index){var geom=this.Geometry;return!geom||"GeometryCollection"!==geom.type&&"MultiPolygon"!==geom.type?geom:this.Geometry.members[index||0].geometry},SR_Geo.prototype.get_Type=function(){var geom=this.$_get_FirstGeomemtryMember();return geom?_geoIsThreeD(geom)?"Point":geom.type:"Point"},SR_Geo.prototype.get_DrawPointForPolygon=function(){return options.showImageForPolygon&&!this.get_HasPoint()},SR_Geo.prototype.get_HasPoint=function(){var g=this.Geometry;if(g)for(var cnt=g.members?g.members.length:1,m=0;m<cnt;m++){var geo=g.members?g.members[m].geometry:g;if("Point"===geo.type)return geo}return null},SR_Geo.prototype.get_IsPoly=function(){var g=this.Geometry;if(g)for(var cnt=g.members?g.members.length:1,m=0;m<cnt;m++){var geo=g.members?g.members[m].geometry:g;if("LineString"===geo.type||"Polyline"===geo.type||"Polygon"===geo.type)return!0}return!1},SR_Geo.prototype.get_PresTypes=function(){var ret=[],g=this.Geometry;if(null!=g)for(var cnt=g.members?g.members.length:1,m=0;m<cnt;m++){var geo=g.members?g.members[m].geometry:g;ret.push(geo.type)}else ret.push("Point");return ret},SR_Geo.prototype.get_Measures=function(){var g=this.Geometry,len=0;if(g)for(var cnt=g.members?g.members.length:1,m=0;m<cnt;m++){var geo=g.members?g.members[m].geometry:g;if("LineString"===geo.type&&!_geoIsThreeD(geo))for(var i=1;i<geo.coordinates.length;i++){var pair=geo.coordinates[i],pair1=geo.coordinates[i-1];len+=TGMap.Measure.distanceBetweenPoints(pair[1],pair[0],pair1[1],pair1[0])}}return{length:len,area:0}},SR_Geo.prototype.get_CenterPoint=function(){var east=null,north=null;if(this.Geometry)if(this.isMarkupThreeDLine())north=this.Geometry.coordinates[0][1],east=this.Geometry.coordinates[0][0];else if(geo=this.get_HasPoint())east=geo.coordinates[0],north=geo.coordinates[1];else{var geom=this.$_get_FirstGeomemtryMember();if("Point"===geom.type)east=geom.coordinates[0],north=geom.coordinates[1];else if("LineString"===geom.type){var index=geom.coordinates.length>0?Math.floor(geom.coordinates.length/2):0;east=(pair=geom.coordinates[index])[0],north=pair[1]}else if("Polygon"===geom.type){var geo,pair;if(geom.coordinates.length>0)east=(pair=(geo=geom.coordinates[0])[index=geo.length>0?Math.floor(geo.length/2):0])[0],north=pair[1]}}return isNaN(east)||isNaN(north)?null:{x:east,y:north}},SR_Geo.prototype.$_IsComplex=function(){if(this.Geometry){var g=this.Geometry;if(g.members&&g.members.length>1)return!0;var geo=g.members?g.members[0].geometry:g;if("Polygon"===geo.type&&geo.coordinates.length>1)return!0}return!1},SR_Geo.prototype.$_IsPointAndPolyObj=function(){if(this.Geometry){var g=this.Geometry,cnt=g.members?g.members.length:1;if(cnt>1)for(var ispoint=!1,ispoly=!1,m=0;m<cnt;m++){if("Point"===(g.members?g.members[m].geometry:g).type?ispoint=!0:ispoly=!0,ispoint&&ispoly)return!0}}return!1},SR_Geo.prototype.RegisterBB=function(BB){if(this.Geometry)for(var g=this.Geometry,cnt=g.members?g.members.length:1,m=0;m<cnt;m++){var geo=g.members?g.members[m].geometry:g;if("Point"===geo.type)BB.RegisterPoint(geo.coordinates[1],geo.coordinates[0]);else if("LineString"===geo.type)for(var i=0;i<geo.coordinates.length;i++){var pair=geo.coordinates[i];BB.RegisterPoint(pair[1],pair[0])}else if("Polygon"===geo.type)for(var ring=0;ring<geo.coordinates.length;ring++){var carray=geo.coordinates[ring];for(i=0;i<carray.length;i++){pair=carray[i];BB.RegisterPoint(pair[1],pair[0])}}else if("Circle"===geo.type){var r=geo.radius;BB.RegisterPoint(geo.coordinates[1]-r,geo.coordinates[0]-r),BB.RegisterPoint(geo.coordinates[1]+r,geo.coordinates[0]+r)}}},SR_Geo.prototype.set_EditType=function(edittype){this.EditType=edittype},SR_Geo.prototype.get_EditType=function(){return this.EditType},SR_Geo.prototype.AddDocument=function(url,exp){this.DocList||(this.DocList=[]),this.DocList.push({Url:url,Exp:exp})},SR_Geo.prototype.get_EditType=function(){return this.EditType},SR_Geo.prototype.get_UrlType=function(){return this.UrlType},SR_Geo.prototype.get_Image=function(){return this.Presentation?this.Presentation.Image:null},SR_Geo.prototype.get_AV=function(){return this.AV},SR_Geo.prototype.set_AV=function(value){this.AV=value},SR_Geo.prototype.Move=function(north,east,id){var geom=this.$_get_FirstGeomemtryMember();geom&&"Point"===geom.type&&(geom.coordinates[1]=north,geom.coordinates[0]=east,this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"move",this),this.__bbox&&(this.__bbox=null))},SR_Geo.prototype.MoveLine=function(north,east,north2,east2){var geom=this.$_get_FirstGeomemtryMember();geom&&"LineString"===geom.type&&(geom.coordinates[0][1]=north,geom.coordinates[0][0]=east,geom.coordinates[1][1]=north2,geom.coordinates[1][0]=east2,this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"move",this),this.__bbox&&(this.__bbox=null))},SR_Geo.prototype.MoveNode=function(nodeid,north,east,memberid,ringid){try{var geom=this.$_get_FirstGeomemtryMember(memberid);"LineString"===geom.type?(geom.coordinates[nodeid][1]=north,geom.coordinates[nodeid][0]=east,this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"move",this)):"Polygon"===geom.type&&(ringid||(ringid=0),geom.coordinates[ringid][nodeid][1]=north,geom.coordinates[ringid][nodeid][0]=east,this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"move",this))}catch(e){}this.__bbox&&(this.__bbox=null)},SR_Geo.prototype.CalculateRectNodes=function(nodeid,north,east,memberid,ringid){var geom=this.$_get_FirstGeomemtryMember(memberid);ringid||(ringid=0);var oldNorth=geom.coordinates[ringid][nodeid][1],oldEast=geom.coordinates[ringid][nodeid][0];geom.coordinates[ringid].forEach((function(lngLat){lngLat[0]===oldEast&&(lngLat[0]=east),lngLat[1]===oldNorth&&(lngLat[1]=north)}))},SR_Geo.prototype.MoveRectangleNode=function(nodeid,north,east,memberid,ringid){try{this.CalculateRectNodes(nodeid,north,east,memberid,ringid),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"move",this)}catch(e){console.error("An error occurred:",e)}this.__bbox&&(this.__bbox=null)},SR_Geo.prototype.RemoveNode=function(nodeid,memberid,ringid){var geom=this.$_get_FirstGeomemtryMember(memberid);"LineString"===geom.type?(geom.coordinates.length>2&&geom.coordinates.splice(nodeid,1),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"removenode",this)):"Polygon"===geom.type&&(ringid||(ringid=0),0==ringid?geom.coordinates[ringid].length>3&&geom.coordinates[ringid].splice(nodeid,1):(geom.coordinates[ringid].length>0&&geom.coordinates[ringid].splice(nodeid,1),geom.coordinates[ringid].length<2&&geom.coordinates.splice(ringid,1)),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"removenode",this)),this.__bbox&&(this.__bbox=null)},SR_Geo.prototype.InsertNode=function(nodeidafter,north,east,memberid,ringid){var geom=this.$_get_FirstGeomemtryMember(memberid),node=[east,north];"LineString"===geom.type?(geom.coordinates.splice(nodeidafter,0,node),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"insertnode",this)):"Polygon"===geom.type&&(ringid||(ringid=0),geom.coordinates[ringid].splice(nodeidafter,0,node),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"insertnode",this)),this.__bbox&&(this.__bbox=null)},SR_Geo.prototype.InsertRing=function(north,east,memberid){var geom=this.$_get_FirstGeomemtryMember(memberid);"Polygon"===geom.type&&(geom.coordinates.push([[east,north],[east,north]]),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY)),this.__bbox&&(this.__bbox=null)},SR_Geo.prototype.IsLineArea=function(){return"Point"!==this.get_Type()},SR_Geo.prototype.get_BB=function(){var ret=null;if(this.__bbox)return this.__bbox;var geom=this.$_get_FirstGeomemtryMember();if("Point"===geom.type)ret=new BBox(geom.coordinates[1],geom.coordinates[0],geom.coordinates[1],geom.coordinates[0]);else if("LineString"===geom.type){ret=new BBox;for(var i=0;i<geom.coordinates.length;i++)ret.RegisterPoint(geom.coordinates[i][1],geom.coordinates[i][0])}else if("Polygon"===geom.type){ret=new BBox;for(i=0;i<geom.coordinates[0].length;i++)ret.RegisterPoint(geom.coordinates[0][i][1],geom.coordinates[0][i][0])}else if("Circle"===geom.type){var r=geom.radius;ret=new BBox(geom.coordinates[1]-r,geom.coordinates[0]-r,geom.coordinates[1]+r,geom.coordinates[0]+r)}return this.__bbox=ret,ret},SR_Geo.prototype.get_Editable=function(){return this.Editable},SR_Geo.prototype.set_UrlType=function(urlType){this.UrlType=urlType},SR_Geo.prototype.get_UrlType=function(){return this.UrlType},SR_Geo.prototype.set_Dirty=function(mask){this.EditState?this.EditState|=mask:this.EditState=mask},SR_Geo.prototype.get_Dirty=function(){return this.EditState},SR_Geo.prototype.HighLight=function(dbi,pres){if(pres)this.HLPresentation=this.Presentation?jQuery.extend({},this.Presentation,pres):pres;else if(!this.Presentation||!this.Presentation.className){var hlpres=pres||TGMap.Style.highlight;this.HLPresentation=this.Presentation?jQuery.extend({},this.Presentation,hlpres):pres}this.HLOn=!0,HLDB.Add(dbi,this.__id,this.ReferenceId),$_refreshObject(dbi,this.__id,this)},SR_Geo.prototype.UnhighLight=function(dbi){this.HLOn=!1,$_refreshObject(dbi,this.__id,this),HLDB.Remove(dbi,this.__id)},SR_Geo.prototype.PinToPoly=function(DBIndex,obj,image,container){var coords=obj.get_CenterPoint(),icon=L.icon({iconUrl:image,iconAnchor:__PinOffset(this)}),marker=L.marker([coords.y,coords.x],{icon:icon,obj:obj});_attachEvents(marker,DBIndex,!0),container&&marker&&container.addLayer(marker)},SR_Geo.prototype.isMarkupThreeDLine=function(){return"LineString"===this.Geometry.type&&2===this.Geometry.coordinates.length&&_isThreeD(this.Geometry.coordinates[0])},SR_Geo.prototype.ToL=function(DBIndex,container){function handleOffsets(obj,pres){obj&&pres&&pres.PointSymbol&&(isNaN(obj.PX)&&!isNaN(pres.PointSymbol.OffsetE)&&(obj.PX=pres.PointSymbol.OffsetE),isNaN(obj.PY)&&!isNaN(pres.PointSymbol.OffsetN)&&(obj.PY=pres.PointSymbol.OffsetN))}function pointImage(){var img=pres&&pres.PointSymbol?pres.PointSymbol.Image:pres&&pres.Image;return img||options.appPath+"/images/pointer.png"}var fillColor,color,weight,opacity,fillOpacity,defImage,layer=null,isSelected=!(!this.CustomClass&&!this.CustomSelectable||!_isSelectedRid(this.ReferenceId)),pres=this.get_Presentation();if(pres?(fillColor=pres.FillColor||"red",color=pres.LineColor||"blue",weight=__GetWeight(pres.LineWidth)||2,dash=pres.LineType||"solid",opacity=pres.LineOpacity||.8,fillOpacity=pres.FillOpacity||.5,defImage=pres.Image):(fillColor=this.FillColor||"red",color=this.LineColor||"blue",weight=__GetWeight(this.LineWidth)||2,dash=this.LineType||"solid",opacity=this.LineOpacity||.8,fillOpacity=this.FillOpacity||.5,defImage=this.Image),"GeometryCollection"===this.Geometry.type)for(var r=0;r<this.Geometry.members.length;r++){var sub=this.Geometry.members[r];if("Polygon"===sub.geometry.type||"LineString"===sub.geometry.type){var polygon,modGeo=null;if("LineString"===sub.geometry.type){modGeo=[];for(var q=0;q<sub.geometry.coordinates.length;q++)modGeo.push([sub.geometry.coordinates[q][1],sub.geometry.coordinates[q][0]])}else{var multi=sub.geometry.coordinates.length>1;for(q=0;q<sub.geometry.coordinates.length;q++){for(var ring=sub.geometry.coordinates[q],modRing=[],w=0;w<ring.length;w++)modRing.push([ring[w][1],ring[w][0]]);multi?(modGeo||(modGeo=[]),modGeo.push(modRing)):modGeo=modRing}}if("Polygon"===sub.geometry.type){var opts={color:color,opacity:opacity,weight:weight,fill:!0,fillColor:fillColor,fillOpacity:fillOpacity,dashArray:__LineType2Dash(dash),obj:this};isSelected&&__applySelectedAttributes(opts,!0),polygon=L.polygon(modGeo,opts),isSelected&&(polygon.ofillColor=fillColor,polygon.ofillOpacity=fillOpacity,polygon.ocolor=color,polygon.oweight=weight)}else{opts={color:color,opacity:opacity,weight:weight,fill:!1,dashArray:__LineType2Dash(dash),obj:this,offset:pres&&pres.LineOffset,symbolOptions:pres&&pres.LineSymbol};isSelected&&__applySelectedAttributes(opts,!0),polygon=L.polyline(modGeo,opts),isSelected&&(polygon.ocolor=color,polygon.oweight=weight)}_attachEvents(polygon,DBIndex),container&&polygon&&container.addLayer(polygon),defImage&&this.get_DrawPointForPolygon()&&this.PinToPoly(DBIndex,this,defImage,container)}else if("Point"===sub.geometry.type){if(pres&&pres.className)var classes=pres.className+" normal"+(this.HLOn?" highlight":""),icon=new L.DivIcon({className:classes,html:'<div class="'+classes+'" style="background-image: url('+(pres.Image?pres.Image:options.appPath+"/images/pointer.png")+')" aria-label="Marker"</div>',iconSize:[32,32]});else handleOffsets(this,pres),icon=L.icon({iconUrl:pointImage(),iconAnchor:__PinOffset(this),className:__GetExtraClasses(pres,isSelected,this.HLOn)});var cnt=[sub.geometry.coordinates[1],sub.geometry.coordinates[0]];opts={icon:icon,obj:this,zIndexOffset:this.HLOn?300:0};isSelected&&(opts.isselected=!0);var marker=L.marker(cnt,opts);_attachEvents(marker,DBIndex,!0),container&&marker&&container.addLayer(marker)}}else if("Polygon"===this.Geometry.type||"LineString"===this.Geometry.type)if(this.isMarkupThreeDLine()){icon=L.icon({iconUrl:pres&&pres.Image?pres.Image:options.appPath+"/images/pointer.png",iconAnchor:__PinOffset(this),className:__GetExtraClasses(pres,isSelected,this.HLOn)}),cnt=[this.Geometry.coordinates[0][1],this.Geometry.coordinates[0][0]],opts={icon:icon,obj:this,zIndexOffset:this.HLOn?300:0};isSelected&&(opts.isselected=!0);marker=L.marker(cnt,opts);_attachEvents(marker,DBIndex,!0),container&&marker&&container.addLayer(marker)}else{modGeo=null;if("LineString"===this.Geometry.type){modGeo=[];for(q=0;q<this.Geometry.coordinates.length;q++)modGeo.push([this.Geometry.coordinates[q][1],this.Geometry.coordinates[q][0]])}else for(multi=this.Geometry.coordinates.length>1,q=0;q<this.Geometry.coordinates.length;q++){for(ring=this.Geometry.coordinates[q],modRing=[],w=0;w<ring.length;w++)modRing.push([ring[w][1],ring[w][0]]);multi?(modGeo||(modGeo=[]),modGeo.push(modRing)):modGeo=modRing}opts={color:color,opacity:opacity,weight:weight,fill:!1,dashArray:__LineType2Dash(dash),obj:this,offset:pres&&pres.LineOffset,symbolOptions:pres&&pres.LineSymbol};"Polygon"===this.Geometry.type?(opts.fill=!0,opts.fillColor=fillColor,opts.fillOpacity=fillOpacity,isSelected&&__applySelectedAttributes(opts,!0),layer=L.polygon(modGeo,opts),isSelected&&(layer.ofillColor=fillColor,layer.ofillOpacity=fillOpacity,layer.ocolor=color,layer.oweight=weight)):(isSelected&&__applySelectedAttributes(opts,!0),layer=L.polyline(modGeo,opts),isSelected&&(layer.ocolor=color,layer.oweight=weight)),_attachEvents(layer,DBIndex),container&&layer&&container.addLayer(layer),defImage&&this.get_DrawPointForPolygon()&&this.PinToPoly(DBIndex,this,defImage,container)}else if("Point"===this.Geometry.type){handleOffsets(this,pres);icon=L.icon({iconUrl:pointImage(),iconAnchor:__PinOffset(this),className:__GetExtraClasses(pres,isSelected,this.HLOn)}),cnt=[this.Geometry.coordinates[1],this.Geometry.coordinates[0]];if(isSelected&&(opts.isselected=!0),pres&&pres.svg){opts={obj:this,svgpres:pres,zIndexOffset:this.HLOn?300:0};layer=new SVGMarker(cnt,opts)}else{opts={icon:icon,obj:this,zIndexOffset:this.HLOn?300:0};layer=L.marker(cnt,opts)}_attachEvents(layer,DBIndex,!0),container&&layer&&container.addLayer(layer)}},SR_Point.prototype.get_IsPoly=function(){return!1},SR_Point.prototype.$_IsComplex=function(){return!1},SR_Point.prototype.IsLineArea=function(){return!1},SR_Point.prototype.Point=function(){return new TXWPoint(this.North,this.East)},SR_Point.prototype.GetType=function(){return"Point"},SR_Point.prototype.get_CenterPoint=function(){var coords=new Object;return coords.x=this.East,coords.y=this.North,coords},SR_Point.prototype.set_EncType=function(encType){this.EncType=encType},SR_Point.prototype.get_EncType=function(){return this.EncType},SR_Point.prototype.set_UrlType=function(urlType){this.UrlType=urlType},SR_Point.prototype.get_UrlType=function(){return this.UrlType},SR_Point.prototype.get_BB=function(){return new BBox(this.North,this.East,this.North,this.East)},SR_Point.prototype.RegisterBB=function(BB){BB.RegisterPoint(this.North,this.East)},SR_Point.prototype.set_Category=function(Category){this.Category=Category},SR_Point.prototype.get_Category=function(){return this.Category},SR_Point.prototype.set_FmtText=function(text){this.FmtText=text},SR_Point.prototype.get_FmtText=function(){return this.FmtText},SR_Point.prototype.set_AV=function(value){this.AV=value},SR_Point.prototype.get_AV=function(){return this.AV},SR_Point.prototype.SetAddress=function(aid,municipality,streetname,addressnumber,north,east){this.set_Editable(!0),this.set_EditType("ea"),this.Editable&&"ea"==this.get_EditType()&&$_updateAddress("Op=update&Type=insert&streetname="+$_ENCODE(streetname)+"&addressnumber="+$_ENCODE(addressnumber)+"&municipality="+$_ENCODE(municipality)+"&n="+north+"&e="+east+"&aid="+aid),this.Municipality=municipality,this.StreetName=streetname,this.AddressNumber=addressnumber,this.Name=this.StreetName+" "+this.AddressNumber,this.North=north,this.East=east},SR_Point.prototype.UpdateAddress=function(aid,streetname,addressnumber){!this.Editable||"ea"!=this.get_EditType()||this.StreetName===streetname&&this.AddressNumber===addressnumber||$_updateAddress("Op=update&Type=update&o_streetname="+$_ENCODE(this.StreetName)+"&o_addressnumber="+$_ENCODE(this.AddressNumber)+"&streetname="+$_ENCODE(streetname)+"&addressnumber="+$_ENCODE(addressnumber)+"&municipality="+$_ENCODE(this.Municipality)+"&o_n="+this.North+"&o_e="+this.East+"&aid="+aid),this.StreetName=streetname,this.AddressNumber=addressnumber,this.Name=this.StreetName+" "+this.AddressNumber},SR_Point.prototype.SetSearchObject=function(aid,municipality,categoryid,name,explanation,url,image,north,east){this.set_Editable(!0),this.set_EditType("eso"),this.Editable&&"eso"==this.get_EditType()&&$_updateAddress("Op=updatesearchobject&Type=insert&categoryid="+categoryid+"&name="+$_ENCODE(name)+"&explanation="+$_ENCODE(explanation)+"&url="+$_ENCODE(url)+"&image="+$_ENCODE(image)+"&municipality="+$_ENCODE(municipality)+"&n="+north+"&e="+east+"&aid="+aid),this.Municipality=municipality,this.Name=name,this.Explanation=explanation,this.Url=url,this.Image=image,this.CategoryId=categoryid,this.North=north,this.East=east},SR_Point.prototype.UpdateSearchObject=function(aid,categoryid,name,explanation,url,image){this.Editable&&"eso"==this.get_EditType()&&$_updateAddress("Op=updatesearchobject&Type=update&referenceid="+this.ReferenceId+"&categoryid="+categoryid+"&name="+$_ENCODE(name)+"&explanation="+$_ENCODE(explanation)+"&url="+$_ENCODE(url)+"&municipality="+$_ENCODE(this.Municipality)+"&n="+this.North+"&e="+this.East+"&aid="+aid),this.Name=name,this.Explanation=explanation,this.Image=image,this.Url=url,this.CategoryId=categoryid},SR_Point.prototype.Move=function(north,east,id){if(this.Editable){var Op="ea"==this.get_EditType()?"Op=update&Type=move&streetname="+$_ENCODE(this.StreetName)+"&addressnumber="+$_ENCODE(this.AddressNumber)+"&municipality="+$_ENCODE(this.Municipality)+"&n="+north+"&e="+east:"eso"==this.get_EditType()?"Op=updatesearchobject&Type=move&referenceid="+this.ReferenceId+"&categoryid="+this.CategoryId+"&municipality="+$_ENCODE(this.Municipality)+"&n="+north+"&e="+east:null;Op&&$_updateAddress(Op),this.North=north,this.East=east,this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"move",this)}else this.North=north,this.East=east},SR_Point.prototype.set_EditableAddress=function(streetname,addressnumber,municipality){this.Editable=!0,this.StreetName=streetname,this.AddressNumber=addressnumber,this.Municipality=municipality,this.EditType="ea"},SR_Point.prototype.set_Editable=function(editable){this.Editable=editable},SR_Point.prototype.get_Editable=function(){return this.Editable},SR_Point.prototype.set_EditType=function(edittype){this.EditType=edittype},SR_Point.prototype.get_EditType=function(){return this.EditType},SR_Point.prototype.AddDocument=function(url,exp){this.DocList||(this.DocList=[]);var doc=new Object;doc.Url=url,doc.Exp=exp,this.DocList.push(doc)},SR_Point.prototype.set_Dirty=function(mask){this.EditState?this.EditState|=mask:this.EditState=mask},SR_Point.prototype.get_Dirty=function(){return this.EditState},SR_Point.prototype.ToL=function(DBIndex,container){var marker=L.marker([this.North,this.East],{icon:L.icon({iconUrl:this.Image||options.appPath+"/images/pointer.png",iconAnchor:__PinOffset(this)}),obj:this});_attachEvents(marker,DBIndex,!0),container&&marker&&container.addLayer(marker)},SR_Path.prototype.IsLineArea=function(){return!!this.PointArray},SR_Path.prototype.get_IsPoly=function(){return!!this.PointArray},SR_Path.prototype.AddDocument=function(url,exp){this.DocList||(this.DocList=[]);var doc=new Object;doc.Url=url,doc.Exp=exp,this.DocList.push(doc)},SR_Path.prototype.$_IsComplex=function(){return!1},SR_Path.prototype.GetType=function(){return this.Filled?"Polygon":"Polyline"},SR_Path.prototype.get_CenterPoint=function(){var coords=null,east=null,north=null;if(this.North&&this.East)east=this.East,north=this.North;else{var index=this.PointArray.length>0?Math.floor(this.PointArray.length/2):0;0==index&&this.PointArray.length>0?(east=this.PointArray[0].east,north=this.PointArray[0].south):index>0&&(east=Math.round((this.PointArray[index].east+this.PointArray[index-1].east)/2),north=Math.round((this.PointArray[index].south+this.PointArray[index-1].south)/2))}return east&&north&&((coords=new Object).x=east,coords.y=north),coords},SR_Path.prototype.Point=function(){return new TXWPoint(this.North,this.East)},SR_Path.prototype.set_Point=function(north,east){this.North=north,this.East=east},SR_Path.prototype.get_FirstPoint=function(){if(!this.PointArray)return null;var coords=new Object;return coords.x=this.PointArray[0].east,coords.y=this.PointArray[0].south,coords},SR_Path.prototype.get_LastPoint=function(){if(!this.PointArray)return null;var index=this.PointArray.length>0?this.PointArray.length-1:0,coords=new Object;return coords.x=this.PointArray[index].east,coords.y=this.PointArray[index].south,coords},SR_Path.prototype.set_EncType=function(encType){this.EncType=encType},SR_Path.prototype.get_EncType=function(){return this.EncType},SR_Path.prototype.set_UrlType=function(urlType){this.UrlType=urlType},SR_Path.prototype.get_UrlType=function(){return this.UrlType},SR_Path.prototype.get_BB=function(){if(this.__bbox)return this.__bbox;var ret=new BBox;return this.RegisterBB(ret),this.__bbox=ret,ret},SR_Path.prototype.RegisterBB=function(BB){if(this.PointArray)for(var i=0;i<this.PointArray.length;i++)BB.RegisterPoint(this.PointArray[i].south,this.PointArray[i].east)},SR_Path.prototype.PathToString=function(){for(var sb=new StringBuilder(""),a=0;a<this.PointArray.length;a++)sb.Append((a>0?"~":"")+Math.round(this.PointArray[a].south)+"~"+Math.round(this.PointArray[a].east));return sb.ToString()},SR_Path.prototype.set_Filled=function(fill){fill||(this.FillColor=null),fill?(this.Image||(this.Image=__getPolygonImage()),this.FillColor||(this.FillColor=$_defaultFillColor)):this.Image||(this.Image=__getLineImage()),this.Filled=fill},SR_Path.prototype.get_Filled=function(){return this.Filled},SR_Path.prototype.set_Category=function(Category){this.Category=Category},SR_Path.prototype.get_Category=function(){return this.Category},SR_Path.prototype.get_FmtText=function(){return null},SR_Path.prototype.set_AV=function(value){this.AV=value},SR_Path.prototype.get_AV=function(){return this.AV},SR_Path.prototype.set_Editable=function(editable,editid){this.Editable=editable,this.EditId=editable?editid:null},SR_Path.prototype.get_Editable=function(){return this.EditId},SR_Path.prototype.set_EditType=function(edittype){this.EditType=edittype},SR_Path.prototype.get_EditType=function(){return this.EditType},SR_Path.prototype.MoveNode=function(nodeid,north,east){this.PointArray[nodeid].south=north,this.PointArray[nodeid].east=east,this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"move",this)},SR_Path.prototype.RemoveNode=function(nodeid){this.PointArray.length>1&&this.PointArray.splice(nodeid,1),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"removenode",this)},SR_Path.prototype.InsertNode=function(nodeidafter,north,east){var node={south:north,east:east};this.PointArray.splice(nodeidafter,0,node),this.set_Dirty(TXWConst.EDITSTATE_GEOMETRY),$_CallEventHandler(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,"insertnode",this)},SR_Path.prototype.set_Presentation=function(linecolor,linetype,linewidth,fillcolor,fillopacity){var defaultColor=TGMap.Style.default;this.LineColor=linecolor||defaultColor.LineColor,this.LineType=linetype||defaultColor.LineType,this.LineWidth=linewidth||defaultColor.LineWidth,fillcolor&&(this.FillColor=fillcolor),fillopacity&&(this.FillOpacity=fillopacity)},SR_Path.prototype.set_Dirty=function(mask){this.EditState?this.EditState|=mask:this.EditState=mask},SR_Path.prototype.get_Dirty=function(){return this.EditState},SR_Path.prototype.get_Presentation=function(){return{LineColor:this.LineColor,FillColor:this.FillColor}},SR_Path.prototype.get_DrawPointForPolygon=function(){return options.showImageForPolygon&&this.East&&this.North},SR_Path.prototype.ToL=function(DBIndex,container){for(var routePoints=[],a=0;a<this.PointArray.length;a++)routePoints.push([this.PointArray[a].south,this.PointArray[a].east]);var opts={color:this.LineColor||"blue",weight:__GetWeight(this.LineWidth)||2,opacity:this.LineOpacity||.8,obj:this,dashArray:__LineType2Dash(this.LineType||"solid")};this.Filled&&(opts.fillColor=this.FillColor||"red",opts.fillOpacity=this.FillOpacity||.5);var polygon=this.Filled?L.polygon(routePoints,opts):L.polyline(routePoints,opts);if(_attachEvents(polygon,DBIndex),container&&polygon&&container.addLayer(polygon),this.Image&&this.get_DrawPointForPolygon()){var icon=L.icon({iconUrl:this.Image||options.appPath+"/images/pointer.png",iconAnchor:__PinOffset(this)}),marker=L.marker([this.North,this.East],{icon:icon,obj:this});_attachEvents(marker,DBIndex,!0),container&&marker&&container.addLayer(marker)}},BBox.prototype.Clear=function(){this.Valid=!1},BBox.prototype.Extend=function(marginal){this.Valid&&(this.eastmax+=marginal,this.northmax+=marginal,this.eastmin-=marginal,this.northmin-=marginal)},BBox.prototype.RegisterPoint=function(north,east){this.Valid?(this.eastmax=Math.max(this.eastmax,east),this.eastmin=Math.min(this.eastmin,east),this.northmax=Math.max(this.northmax,north),this.northmin=Math.min(this.northmin,north)):(this.eastmax=east,this.eastmin=east,this.northmax=north,this.northmin=north,this.Valid=!0)},BBox.prototype.PointInside=function(north,east){return this.Valid&&north>=this.northmin&&north<=this.northmax&&east>=this.eastmin&&east<=this.eastmax},BBox.prototype.BBOverlap=function(BB){return!(this.eastmax<BB.eastmin||this.eastmin>BB.eastmax||this.northmax<BB.northmin||this.northmin>BB.northmax)},BBox.prototype.BBInside=function(BB){return this.PointInside(BB.northmin,BB.eastmin)&&this.PointInside(BB.northmax,BB.eastmax)},BBox.prototype.ToAreaString=function(){return this.Valid?"&south="+this.northmin+"&west="+this.eastmin+"&north="+this.northmax+"&east="+this.eastmax:null},StreetNameDataBase.prototype.Load=function(municipality,readyCB){jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=getstreetnames&municipality="+municipality,success:function(data){var result=$_EVALJSON(data);result&&result.municipality&&result.streetnames&&(StreetNameDB.Insert(result.municipality,result.streetnames),readyCB())}})},StreetNameDataBase.prototype.Insert=function(municipality,names){this.hashtable[municipality]=names},StreetNameDataBase.prototype.ExistMunicipality=function(municipality){return!!this.hashtable[municipality]},StreetNameDataBase.prototype.get_StreetNames=function(municipality){return this.hashtable[municipality]},CollectionDataBase.prototype.Insert=function(mapid,name){var newObj=new CollectionIdentity(mapid,name);return this.hashtable[mapid]=newObj,newObj},CollectionDataBase.prototype.Update=function(mapid,name){var newObj=new CollectionIdentity(mapid,name);return this.hashtable[mapid]=newObj,newObj},CollectionDataBase.prototype.Delete=function(mapid){this.hashtable[mapid]=null},CollectionDataBase.prototype.Clear=function(){this.hashtable=[]};var $_EventHandler=null,$_VisibilityTipDisplayed=!1;function hideVisibilityInfo(){$_VectorVisibilityHandler(!1)}function $_VectorVisibilityHandler(allnotvisible){var a=document.getElementById("TXWObjVisControl");if(a){var mode="hidden";allnotvisible&&0==$_VisibilityTipDisplayed&&0==$_isVisible_Handle(a)&&(mode="visible",$_VisibilityTipDisplayed=!0,setTimeout("hideVisibilityInfo()",2e3)),a.style.visibility=mode}}function $_CallEventHandler(){return $_EventHandler?$_EventHandler.apply(this,arguments):null}function $_GetSelection(){return $_ActiveHandleId}function gonsToRadians(gangle,dir){let rangle=gangle*Math.PI/200;return dir?-1*rangle:rangle}async function $_layerGeoJSONDisplayResults(DB,geoJSON,category,encType){if(geoJSON.length>0){for(var DBIndex=$_GetIndexByDB(DB),svgs=new Set,i=0;i<geoJSON.length;i++){if((item=geoJSON[i])instanceof SR_Geo)DB.Insert(item);else if(item&&item.name){var obj,filter=void 0;if(item.category&&(0==DB.CatChecked(item.category)||filter&&!filter(item)))continue;if(item.geometry){var sp;if((obj=new SR_Geo(item.name,item.explanation)).set_Geometry(item.geometry),obj.set_Presentation(item.presentation),obj.set_Image(item.image),item.CustomClass&&item.CustomClassId)if(sp=window.Tekla.BitmapManager.getPresentation(item.CustomClassId,item.CustomClass))sp.sdir=gonsToRadians(+item.SymbolDir||0,!0),sp.sdx=+item.SymbolDx||0,sp.sdy=+item.SymbolDy||0,obj.set_Presentation(sp),svgs.add(sp.svg);else(sp={svg:item.presentation.Image,size:10}).sdir=gonsToRadians(+item.SymbolDir||0,!0),sp.sdx=+item.SymbolDx||0,sp.sdy=+item.SymbolDy||0,obj.set_Presentation(sp),svgs.add(sp.svg);item.__bbox&&item.__bbox.Valid&&(obj.__bbox=item.__bbox)}else if(item.northarray){var pointsArray=$_ConvertToPointArray(item.northarray,item.eastarray);obj=new SR_Path(get_EncTypeText(item.name,encType),item.tip,item.url,item.image,pointsArray),item.north&&obj.set_Point(item.north,item.east),obj.set_Presentation(item.linecolor,item.linetype,item.linewidth,item.fillcolor?item.fillcolor:null,item.fillopacity?item.fillopacity:null),item.fill&&obj.set_Filled(item.fill)}else obj=new SR_Point(get_EncTypeText(item.name,encType),item.tip,item.url,item.image,item.north,item.east);if(item.category&&obj.set_Category(item.category),obj.Editable=!!item.Editable&&item.Editable,item.Id&&(obj.Id=item.Id),item.PartyInCharge&&(obj.PartyInCharge=item.PartyInCharge),item.url&&(obj.Url=item.url),item.referenceid&&(obj.ReferenceId=item.referenceid),void 0!==item.width&&(obj.Width=item.width),item.myotype&&(obj.MyOType=item.myotype),item.IsRectangle&&(obj.IsRectangle=item.IsRectangle),item.TextContent&&(obj.TextContent=item.TextContent),item.drawMeasurements&&(obj.drawMeasurements=item.drawMeasurements),item.CanDelete&&obj.setCanDelete(item.CanDelete),item.skipBubble&&(obj.skipBubble=item.skipBubble),item.streetaddress&&(obj.StreetAddress=item.streetaddress),item.oninfo&&(obj.oninfo=item.oninfo),item.urltype&&(obj.set_UrlType(item.urltype),"SF"==item.urltype&&(obj.Url="JavaScript:showFeedbackById("+DBIndex+","+Id+");")),item.urltarget&&(obj.UrlTarget=item.urltarget),item.permanent&&(obj.Permanent=item.permanent),item.htmldescription&&(obj.htmldescription=item.htmldescription),item.imageurl&&(obj.imageurl=item.imageurl),item.pe&&(obj.PX=item.pe),item.pn&&(obj.PY=item.pn),item.refid&&(obj.RefId=item.refid),item.nocluster&&(obj.NoCluster=item.nocluster),item.extdocs&&item.extdocs.length)for(var doc=0;doc<item.extdocs.length;doc++)obj.AddDocument(item.extdocs[doc].url,item.extdocs[doc].exp);if(item.addattrs&&item.addattrs.length){obj.AttrList=[];for(var attr=0;attr<item.addattrs.length;attr++)obj.AttrList.push({n:item.addattrs[attr].n,v:item.addattrs[attr].v})}for(var prop in item)item.hasOwnProperty(prop)&&0===prop.indexOf("Custom")&&(obj[prop]=item[prop]);DB.Insert(obj)}}for(var item of svgs)await window.Tekla.BitmapManager.getBitmapAsync(item);DBIndex==OBJ_MYSITES&&$_CallEventHandler(tekla.Map.EVENT.DRAWINGREADY,null)}}function $_restoreHighlights(DB){if(DB&&HLDB){var highlights=HLDB.GetReferenceIds(),DBIndex=$_GetIndexByDB(DB);highlights.forEach((function(hl){var item=DB.FindByReferenceId(hl);item&&(HLDB.RemoveByReferenceId(hl),item.HighLight(DBIndex))}))}}function $_beginResultSet(DBIndex){Tekla.MapBubble.hideAll(!1,DBIndex),window.teklaMap.BeginGuiTrans()}function $_endResultSet(DBIndex){window.teklaMap.NeedLayerRedraw(),window.teklaMap.EndGuiTrans()}function HLSelection(){}function RemoveHighlights(){HLDB.RemoveAll()}HLSelection.prototype.Add=function(dbi,id,referenceId){this.$HL||(this.$HL=[]),this.$HL.push({DB:dbi,Id:id,ReferenceId:referenceId})},HLSelection.prototype.Remove=function(dbi,id){this.$HL&&(this.$HL=this.$HL.filter((function(item){return item.DB!==dbi&&item.Id!==id})))},HLSelection.prototype.RemoveByReferenceId=function(referenceId){this.$HL&&referenceId&&(this.$HL=this.$HL.filter((function(item){return item.ReferenceId!==referenceId.toString()})))},HLSelection.prototype.GetReferenceIds=function(){var highlighted=[];if(this.$HL)for(var l=this.$HL.length,i=0;i<l;i++){var item=this.$HL[i];item&&item.ReferenceId&&highlighted.push(item.ReferenceId)}return highlighted},HLSelection.prototype.RemoveAll=function(){if(this.$HL){for(var l=this.$HL.length,i=0;i<l;i++){var item=this.$HL[i];if(item){var obj=$_DBSelect(item.DB,item.Id);obj&&obj.UnhighLight(item.DB)}}this.$HL=null}};var Cluster=function(dbi,obj,xp,yp){this.center={x:xp,y:yp},this.length=1,this.__dbi=dbi,this.__obj=obj};function __GetExtraClasses(pres,isSelected,highlight){var className=(pres&&pres.imgClass?pres.imgClass:"")+(isSelected?" map-selected":"")+(highlight?" highlight":"");return""!==className?className:null}Cluster.prototype={add:function(){this.length+=1},inside:function(x,y,delta){return null!=this.center&&x>=this.center.x-delta&&x<=this.center.x+delta&&y>=this.center.y-delta&&y<=this.center.y+delta},distance:function(x,y){var dx=x-this.center.x,dy=y-this.center.y;return dx*dx+dy*dy}},window.Tekla.BitmapManager||(window.Tekla.BitmapManager={_nativePresentation:void 0,_cachedBitmaps:new Map,_baseUri:"",loadBitmap(id,url){var img=new Image;img.onload=()=>{var bitmap={id:id,width:img.width,height:img.height,img:img,url:url};window.Tekla.BitmapManager._cachedBitmaps.set(bitmap.id,bitmap)},img.src=url},loadBitmapAsync:(id,url)=>new Promise(((resolve,reject)=>{const img=new Image;img.onload=()=>{const bitmap={id:id,width:img.width,height:img.height,img:img,url:url};window.Tekla.BitmapManager._cachedBitmaps.set(bitmap.id,bitmap),resolve(bitmap)},img.onerror=reject,img.src=url})),getBitmap:id=>window.Tekla.BitmapManager._cachedBitmaps.get(id),async getBitmapAsync(fname){var result=window.Tekla.BitmapManager._cachedBitmaps.get(fname);return result||(result=await this.loadBitmapAsync(fname,0==fname.indexOf("/")?fname:options.appPath+"/Image/Get/"+fname)),result},setPresentation(np){window.Tekla.BitmapManager._nativePresentation=np},getPresentation(classId,eclass){var np=window.Tekla.BitmapManager._nativePresentation,match=np&&np.NativePresentationList&&np.NativePresentationList.find((n=>n.ClassId==classId));if(match){var image=match.ImageList.find((i=>i.Value==eclass));if(image)return{svg:image.SVG,size:image.Size}}}});
var _hilighted=[];function _addHilighted(obj){_hilighted.push(obj)}function _resetHilighted(){if(_hilighted&&_hilighted.length>0){for(var i=0;i<_hilighted.length;i++){var layer=_hilighted[i];layer.setStyle({fillColor:layer.ofillColor,fillOpacity:layer.ofillOpacity,color:layer.ocolor,weight:__GetWeight(layer.oweight)})}_hilighted.length=0}}function _attachEvents(obj,DBIndex,isicon){obj.on({click:function(e){var layer=e.target,ctrl=e.originalEvent&&e.originalEvent.ctrlKey;e.originalEvent&&e.originalEvent.altKey;if((window.teklaMap.__isSelectMode||ctrl&&DBIndex==OBJ_MYSITES&&window.teklaMap.__allowSelection)&&layer.options.obj&&layer.options.obj.CustomSelectable)if(isicon){layer._icon?(sel=jQuery(layer._icon).hasClass("map-selected"),$_CallEventHandler(tekla.Map.EVENT.SELECTIONCHANGED,layer.options.obj,!sel),layer.options.isselected=!sel,jQuery(layer._icon).toggleClass("map-selected")):(sel=layer.options.isselected,$_CallEventHandler(tekla.Map.EVENT.SELECTIONCHANGED,layer.options.obj,!sel),layer.options.isselected=!sel,layer instanceof SVGMarker&&layer.redraw()),sel&&window.teklaMap.__allowSelection&&ctrl&&window.teklaMap._HandleRemove()}else{var sel=layer.options.isselected;$_CallEventHandler(tekla.Map.EVENT.SELECTIONCHANGED,layer.options.obj,!sel),layer.options.isselected=!sel,sel?(window.teklaMap.__allowSelection&&e.ctrlKey&&window.teklaMap._HandleRemove(),__setStyleUnselected(layer)):(_hilighted.length=0,__setStyleSelected(layer))}else if("pan"===toolMode){var map=window.teklaMap,content=map._PrepareBubble(DBIndex,layer.options.obj,e.latlng);null!=content&&map.ShowBubble(e.latlng,content,isicon?__PopupAnchor(layer.options.obj):new L.Point(0,0))}}}),isicon||obj.on({mouseover:function highlightFeature(e){if("pan"===toolMode){var layer=highlight=e.target,lo=layer.options;if(!(lo.isselected||lo.obj.Editable&&lo.obj.__id==window.teklaMap._HandleGetActive())){_resetHilighted(),layer.ofillColor=lo.fillColor,layer.ofillOpacity=lo.fillOpacity,layer.ocolor=lo.color,layer.oweight=__GetWeight(lo.weight);var fillOpacity=lo.fillOpacity>.5?lo.fillOpacity+.05:lo.fillOpacity;fillOpacity>1&&(fillOpacity=1),layer.setStyle({fillColor:"#fff00d",fillOpacity:fillOpacity,color:"#fff00d",weight:__GetWeight(lo.weight<4?4:lo.weight)}),_addHilighted(layer)}}},mouseout:function(e){var layer=e.target;layer.options.isselected||layer.options.obj.Editable&&layer.options.obj.__id==window.teklaMap._HandleGetActive()?_hilighted.length=0:_resetHilighted()},contextmenu:function(e){}})}function L_updateSingleDatabase(DB,DBIndex){new StringBuilder("");var arrayListPointDraw=!0,clipBB=null,container=new L.FeatureGroup;if(DBIndex==OBJ_CATLAYER||DBIndex==OBJ_SEARCH){var level=currentWupp();__isInsideSVGRange(level)||!1,DBIndex==OBJ_CATLAYER&&(arrayListPointDraw=$_CategoryLoadable(level)),clipBB=$_getAreaBB()}if(!arrayListPointDraw)return null;for(var i=0;i<DB.items.length;i++){var obj=DB.items[i];obj&&("function"!=typeof obj.isVisible||obj.isVisible())&&$_DBIsValidObject(obj)&&$_DBObjectOverlap(obj,clipBB)&&obj.ToL(DBIndex,container)}return container}function L_updateLayersDatabase(){var clipBB,DBIndex=OBJ_CATLAYER,DB=LayerDB,container=new L.FeatureGroup,level=currentWupp();if(__isInsideSVGRange(level)||!1,!$_CategoryLoadable(level))return null;var layerHash=Tekla.Layers._getselectedCategoriesOrdered(2);clipBB=$_getAreaBB();for(var orderedList=[],i=0;i<DB.items.length;i++){var obj=DB.items[i];if(obj&&("function"!=typeof obj.isVisible||obj.isVisible())&&$_DBIsValidObject(obj,LayerDB)&&$_DBObjectOverlap(obj,clipBB))if(layerHash){var o=layerHash[obj.Category];obj._o=o||0,orderedList.push(obj)}else obj.ToL(DBIndex,container)}return orderedList&&__renderOrderedList(container,orderedList),container}function __renderOrderedList(container,orderedList){var DBIndex=OBJ_CATLAYER;if(orderedList){orderedList.sort((function(a,b){return b._o-a._o}));for(var i=0;i<orderedList.length;i++){orderedList[i].ToL(DBIndex,container)}}}function L_updateSingleClustered(dbs){for(var __gridS=60*currentWupp(),currentBB=$_getAreaBB(.01,!1),_clusters=[],orderedList=void 0,dontClusterPO=!options.clusterPolyobjects,container=new L.FeatureGroup,d=0;d<dbs.length;d++){var DB=dbs[d].db,DBIndex=dbs[d].dbi,layerHash=void 0;DBIndex==OBJ_CATLAYER?(layerHash=Tekla.Layers._getselectedCategoriesOrdered(2),orderedList=[]):orderedList=void 0;for(var Id=0;Id<DB.items.length;Id++){var obj=DB.items[Id];if($_DBIsValidObject(obj,DB===LayerDB?DB:void 0))if(obj.NoCluster||dontClusterPO&&obj.get_IsPoly()){if($_DBObjectOverlap(obj,currentBB))if(layerHash){var o=layerHash[obj.Category];obj._o=o||0,orderedList.push(obj)}else obj.ToL(DBIndex,container)}else{var latLong=obj.get_CenterPoint(!1);if(currentBB.PointInside(latLong.y,latLong.x)){for(var distance=0,clusterToAdd=null,c=0;c<_clusters.length;c++){var idistance=_clusters[c].distance(latLong.x,latLong.y);(0===c||idistance<distance)&&(distance=idistance,clusterToAdd=_clusters[c])}null!=clusterToAdd&&clusterToAdd.inside(latLong.x,latLong.y,__gridS)?clusterToAdd.add():_clusters.push(new Cluster(DBIndex,obj,latLong.x,latLong.y))}}}orderedList&&orderedList.length>0&&__renderOrderedList(container,orderedList)}__isInsideSVGRange(currentWupp());L.icon({iconUrl:options.appPath+"/images/cluster-32.png",iconAnchor:[14,32]});for(var key=0;key<_clusters.length;key++){var Length=_clusters[key].length;if(1==Length){obj=_clusters[key].__obj;var dbi=_clusters[key].__dbi;obj.ToL(dbi,container)}else if(Length>1){String.format(GetText("clusterTip"),Length);var cnt=[_clusters[key].center.y,_clusters[key].center.x],cIcon=new L.DivIcon({className:"cluster-image",html:'<div class="cluster-count">'+Length+"</div>",iconSize:[32,32]}),marker=L.marker(cnt,{icon:cIcon});container.addLayer(marker)}}return _clusters=void 0,container}function _handlePoint2Rectangle(n,e,d){return[[n-(d=d||5),e-d],[n+d,e+d]]}function L_singlehandle(n,e,addnode,id,nodeid,member,ring,allowRemove){var _endPosition,_activeHandle,globj;_handlePoint2Rectangle(n,e,addnode?3:5);var size=addnode?18:22,anchor=size/2+2,vertexIcon=new L.DivIcon({className:addnode?"handle-middle":"handle-vertex",html:"<div></div>",iconSize:[size,size],iconAnchor:[anchor,anchor]}),drMarker=L.marker([n,e],{icon:vertexIcon,id:id,nodeId:nodeid,memberId:member,ringId:ring,type:addnode?"addnode":"node",draggable:!0,contextmenu:!addnode,contextmenuItems:!0===allowRemove?[{text:GetText("removePoint"),index:0,callback:function(e){var o=e.relatedTarget.options,obj=$_DBSelect(OBJ_MYSITES,o.id);obj&&($_DBSetDirty(OBJ_MYSITES,!0),obj.RemoveNode(o.nodeId,o.memberId,o.ringId),refreshDraw(obj))}},{separator:!0,index:1}]:[]});return drMarker.on("dragstart",(function _dragstart(e){_endPosition=e,"moveLine"!=toolModePrevious&&(toolModePrevious=toolMode),toolMode="moveLine",$_setCursor("crosshair"),_activeHandle=this,_resetHilighted(),globj=$_DBSelect(OBJ_MYSITES,_activeHandle.options.id)})),drMarker.on("drag",(function _markerMove(e){_endPosition=e,globj&&globj.IsRectangle&&(globj.CalculateRectNodes(_activeHandle.options.nodeId,e.latlng.lat,e.latlng.lng,_activeHandle.options.memberId,_activeHandle.options.ringId),window.teklaMap.RedrawLayersImmediate())})),drMarker.on("dragend",(function _markerDragEnd(ee){if(_activeHandle){var e=_endPosition;toolMode=toolModePrevious,$_restoreCursor(),globj&&($_DBSetDirty(OBJ_MYSITES,!0),globj.IsRectangle?globj.MoveRectangleNode(_activeHandle.options.nodeId,e.latlng.lat,e.latlng.lng,_activeHandle.options.memberId,_activeHandle.options.ringId):"addnode"===_activeHandle.options.type?globj.InsertNode(_activeHandle.options.nodeId,e.latlng.lat,e.latlng.lng,_activeHandle.options.memberId,_activeHandle.options.ringId):globj.MoveNode(_activeHandle.options.nodeId,e.latlng.lat,e.latlng.lng,_activeHandle.options.memberId,_activeHandle.options.ringId),refreshDraw(globj)),_activeHandle=null}})),drMarker}function L_inserthandle(n,e){var vertexIcon=new L.DivIcon({className:"handle-vertex",html:"<div></div>",iconSize:[22,22],iconAnchor:[13,13]});return L.marker([n,e],{icon:vertexIcon})}function _centerPoint(x1,y1,x2,y2){return[x1+(x2-x1)/2,y1+(y2-y1)/2,Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2,2))]}function L_drawHandles(container,obj,insertnodehandles){if(obj.Geometry)for(var handle,g=obj.Geometry,cnt=g.members?g.members.length:1,m=0;m<cnt;m++){var geo=g.members?g.members[m].geometry:g;if("LineString"===geo.type)for(var i=0;i<geo.coordinates.length;i++){if(handle=L_singlehandle((pair=geo.coordinates[i])[1],pair[0],!1,obj.__id,i,m),container.addLayer(handle),i<geo.coordinates.length-1)(a=_centerPoint(geo.coordinates[i][0],geo.coordinates[i][1],geo.coordinates[i+1][0],geo.coordinates[i+1][1]))[2]>.4&&(handle=L_singlehandle(a[1],a[0],!0,obj.__id,i+1,m),container.addLayer(handle))}else if("Polygon"===geo.type)if(obj.IsRectangle)for(var ring=0;ring<geo.coordinates.length;ring++){var carray=geo.coordinates[ring];for(i=0;i<carray.length;i++){handle=L_singlehandle((pair=carray[i])[1],pair[0],!1,obj.__id,i,m,ring,!1),container.addLayer(handle)}}else for(ring=0;ring<geo.coordinates.length;ring++)for(carray=geo.coordinates[ring],i=0;i<carray.length;i++){var pair=carray[i];(i!==carray.length-1||pair[0]!==carray[0][0]&&pair[1]!==carray[0][1])&&(handle=L_singlehandle(pair[1],pair[0],!1,obj.__id,i,m,ring),container.addLayer(handle)),(a=_centerPoint(carray[i][0],carray[i][1],carray[i>=carray.length-1?0:i+1][0],carray[i>=carray.length-1?0:i+1][1]))[2]>.4&&(handle=L_singlehandle(a[1],a[0],!0,obj.__id,i+1,m,ring),container.addLayer(handle))}}else if(obj.PointArray)for(i=0;i<obj.PointArray.length;i++){var a;if(handle=L_singlehandle(obj.PointArray[i].south,obj.PointArray[i].east,!1,obj.__id,i),container.addLayer(handle),i>0)handle=L_singlehandle((a=_centerPoint(obj.PointArray[i-1].east,obj.PointArray[i-1].south,obj.PointArray[i].east,obj.PointArray[i].south))[0],a[1],!0,obj.__id,i),container.addLayer(handle)}}function __applySelectedAttributes(opts,fill){fill&&(opts.fillColor="#FFBE00",opts.fillOpacity=.9),opts.color="##FFBE00",opts.weight=4,opts.isselected=!0}function __setStyleSelected(layer){layer.ocolor||(layer.ofillColor=layer.options.fillColor,layer.ofillOpacity=layer.options.fillOpacity,layer.ocolor=layer.options.color,layer.oweight=__GetWeight(layer.options.weight)),layer.setStyle({fillColor:"#FFBE00",fillOpacity:.9,color:"##FFBE00",weight:4})}function __setStyleUnselected(layer){layer.setStyle({fillColor:layer.ofillColor,fillOpacity:layer.ofillOpacity,color:layer.ocolor,weight:__GetWeight(layer.oweight)})}function __LineType2Dash(dashtype){return"solid"===dashtype?null:"dot"===dashtype?"3,8":"dash"===dashtype?"8,8":"longdash"===dashtype?"18,8":null}function __GetWeight(w){return w&&"number"!=typeof w?parseInt(w):w}function __PopupAnchor(obj){var n;return n=-(__PinOffset(obj)[1]-4),new L.Point(0,n)}function __PinOffset(obj){var e=obj.PX?obj.PX:options.pinOffsetE?options.pinOffsetE:14,n=obj.PY?obj.PY:options.pinOffsetN?options.pinOffsetN:32;return obj.HLOn&&(e+=2,n+=2),[e,n]}
var $_OverrideTipText=null,$_Cursor;function startPan(){toolMode="pan",setHandCursor()}function startZoom(){toolMode="zoom",jQuery(".leaflet-container").css("cursor","")}function startMeter(fromTab){if(window.teklaMap._getIsThreeDMode())window.Tekla.ThreeD&&("distance"===toolMode?(window.Tekla.ThreeD.setActiveTool("selection"),endMeter()):(window.Tekla.ThreeD.setActiveTool("measurement"),toolMode="distance",jQuery("body").addClass(toolMode)));else{var start=!0;fromTab&&"distance"==toolMode&&(start=!1),"distance"==toolMode?endMeter():start&&(toolMode="distance",jQuery("body").addClass(toolMode),options.istouch||(setStatus(GetText("cl_measureDistance")),enableTooltip()),jQuery(".leaflet-container").css("cursor","crosshair"))}}function endMeter(){clearToolstate(),startPan()}function createDraw(fill,tiptxt){fillDrawing=fill,clearToolstate(),toolMode=fill?"drawpolygon":"drawpolyline",initDraw(tiptxt)}function initDraw(tiptxt){window.teklaMap._HandleRemove(),jQuery("body").addClass(toolMode),setStatus(GetText("cl_drawPolylineTip")),tiptxt&&enableTooltip(tiptxt),jQuery(".leaflet-container").css("cursor","crosshair")}function createDrawRectangle(tiptxt){fillDrawing=!0,clearToolstate(),toolMode="drawrectangle",initDraw(tiptxt)}function $_removeDrawingVisuals(){mapDrawing.points=null,L_TEMPLAYER&&(window.teklaMap.removeLayer(L_TEMPLAYER),L_TEMPLAYER=null)}function cancelDrawing(){$_removeDrawingVisuals(),clearToolstate(),startPan()}function removeLastPoint(){if("drawpolygon"===toolMode||"drawpolyline"===toolMode){var minCount="drawpolygon"===toolMode?3:2;if(null==mapDrawing.points||mapDrawing.points.length<minCount)return;mapDrawing.points.length=mapDrawing.points.length-1,$_redrawDrawing()}}function showSiteProperties(pt){if("drawpolygon"===toolMode||"drawpolyline"===toolMode||"drawrectangle"===toolMode){var minCount="drawpolygon"===toolMode?3:2;if(null==mapDrawing.points||mapDrawing.points.length<minCount)return clearToolstate(),deleteDrawing(),void startPan()}Tekla.MapBubble.insert(toolMode,pt,null)}function startPositionSelect(target){document.getElementById("positionselect");"positionselect"!=toolMode&&(toolModePrevious=toolMode),toolMode="selectposition",enableTooltip(),jQuery(".leaflet-container").css("cursor","crosshair"),target&&(positionTarget=target)}function cancelEventPropagation(event){event&&(event.preventDefault&&event.preventDefault(),event.stopPropagation&&event.stopPropagation())}function openUrl(url,event,target){if("distance"!=toolMode){if(null==url||"undefined"==url)return;-1!=url.indexOf("cript:")?eval(url):window.open(url,target||"txwwin"),event&&cancelEventPropagation(event)}}function openUrlId(DBIndex,Id,event){try{var obj=$_DBSelect(DBIndex,Id);obj&&($_isValidUrl(obj.Url,!0)||DBIndex!=OBJ_MYSITES?openUrl(obj.Url,event):"/"==obj.Url.charAt(0)&&openUrl(obj.Url,event,obj.UrlTarget))}catch(e){}}function openObjectSelectionMenu(lat,lng){openObjectSelectionWithLatLng(new L.LatLng(lat,lng))}function openObjectSelectionWithLatLng(latLng){window.Tekla.mapObjectSelection.selectMapObjects(latLng,(function(obj){if(!map.__isSelectMode&&obj&&obj.ReferenceId&&obj.DocList&&1===obj.DocList.length)openUrl(obj.DocList[0].Url);else if(obj){var layer=$_findLayer(L_CATLAYER,obj),cnt=obj.get_CenterPoint(),eventLatLng="Point"===obj.GetType(!0)&&cnt?[cnt.y,cnt.x]:latLng;if(layer)layer.fire("click",{latlng:eventLatLng});else{var content=map._PrepareBubble(OBJ_CATLAYER,obj,latLng);null!=content&&map.ShowBubble(eventLatLng,content,__PopupAnchor(obj))}}}),!1)}function $_isVisible_Handle(obj){return!!obj&&"visible"==obj.style.visibility}function $_isVisible(objname){return $_isVisible_Handle(document.getElementById(objname))}function enableTooltip(tiptxt){$_OverrideTipText=tiptxt,window.teklaMap.AddMapMoveListener(updateTooltip)}function $_cancelTooltip(){$_OverrideTipText=null,window.teklaMap.RemoveMapMoveListener(updateTooltip)}function showTooltip(event){showObj("tooltipdiv")}function cancelDrawLine(){}function updateDistance(){var i,distancediv=document.getElementById("distancediv"),lastmeterpoint=document.getElementById("lastmeterpoint"),meterDistance=0;if(mapMeter.points&&mapMeter.points.length>0){for(i=1;i<mapMeter.points.length;i++)meterDistance+=TGMap.Measure.distanceBetweenPoints(mapMeter.points[i].south,mapMeter.points[i].east,mapMeter.points[i-1].south,mapMeter.points[i-1].east);lastmeterpoint&&(lastmeterpoint.innerHTML=String.format(GetText("cl_lastPointLocation"),$_getCoordinateString(mapMeter.points[mapMeter.points.length-1].south,mapMeter.points[mapMeter.points.length-1].east,"distance")))}else lastmeterpoint&&(lastmeterpoint.innerHTML="");distancediv&&(distancediv.innerHTML=String.format(GetText("cl_totalDistance"),TGMap.Measure.formatDistance(Math.round(meterDistance))))}function updateTooltip(latlng){if(latlng&&latlng.containerPoint){var mousePoint=latlng.containerPoint,x=mousePoint.x,y=mousePoint.y,worldPoint=latlng.latlng,tip=document.getElementById("tooltipdiv");if(tip){if(tip.style.left=x+10+"px",tip.style.top=y+20+"px","distance"===toolMode){var cursoreast=worldPoint.lng,cursorsouth=worldPoint.lat,count=TGMap.Measure.count();if(count<1)tip.innerHTML=GetText("cl_selectFirstPoint")+"&nbsp;";else if(/*!options.istouch &&*/count>0){var total=TGMap.Measure.getTotalDistance(),lastpoint=TGMap.Measure.lastpoint(),fd=total+TGMap.Measure.distanceBetweenPoints(cursorsouth,cursoreast,lastpoint[0],lastpoint[1]);tip.innerHTML=TGMap.Measure.formatDistance(fd)}}else if("selectposition"===toolMode){var tiptext="searchengine"==positionTarget?GetText("cl_selectNewObjectPosition"):"feedback"==positionTarget?GetText("cl_selectFeedbackTarget"):"property"==positionTarget?GetText("cl_selectQueryPorpertiesTarget"):"link"==positionTarget?GetText("cl_selectLinkPosition"):"emodel"==positionTarget?GetText("cl_selectFeedbackTarget"):"external"==positionTarget&&$_extPickTip?$_extPickTip:GetText("cl_selectPositionFromMap");tip.innerHTML=tiptext+"&nbsp;"}else"createsite"===toolMode||"createaddress"===toolMode||"createsearchobject"===toolMode?tip.innerHTML=$_OverrideTipText||GetText("cl_selectNewObjectPosition"):"movesite"===toolMode?tip.innerHTML=GetText("cl_selectMoveObjectPosition"):"drawpolyline"!==toolMode&&"drawpolygon"!==toolMode&&"drawrectangle"!==toolMode||!$_OverrideTipText||(tip.innerHTML=$_OverrideTipText);0===tip.innerHTML.trim().length?jQuery(tip).hide():jQuery(tip).show()}}}function $_hideTooltip(event){hideObj("tooltipdiv")}function $_setZoomScalePosition(){}function setStatus(message){var statusObj=document.getElementById("statusdiv");statusObj&&(statusObj.innerHTML=message)}function UpdateLayerState(index,value){window.teklaMap._UpdateMapPosition(),Tekla.MapLink&&Tekla.MapLink.update()}function removeInfoTimer(){$_infoTimer&&(clearTimeout($_infoTimer),infoTimeout=null)}function hideInfo(skipsave){removeInfoTimer(),Tekla.MapBubble.hideAll(skipsave)}function showMessagePanel(x,y,text){var infowindow=document.getElementById("messagepaneldiv"),infotext=document.getElementById("messagepaneltext");hideObj("messagepanelclosebutton"),infotext.innerHTML=text,infowindow.style.left=x+42+"px",infowindow.style.top=y-37+"px",showObj("messagepaneldiv")}function hideMessagePanel(){hideObj("messagepanelclosebutton"),hideObj("messagepaneldiv")}function doHover(obj){obj.style.textDecoration="underline"}function doMenuHover(obj){obj.className="menu_context_on"}function removeMenuHover(obj){obj.className="menu_context_off"}function doBackgroundHover(obj){obj.className="box_context_on"}function removeBackgroundHover(obj){obj.className="box_context_off"}function removeHover(obj){obj.style.textDecoration="none"}function $_revertToolMode(){toolMode=toolModePrevious,"pan"===toolMode?startPan():"distance"===toolMode?startMeter():"zoom"===toolMode&&startZoom()}function clearToolstate(){jQuery("body").removeClass(toolMode),cancelDrawLine(),$_hideTooltip(),$_cancelTooltip()}function $_zoomToDBExtents(db){for(var BB=new BBox,Id=0;Id<db.items.length;Id++){var obj=db.items[Id];obj&&obj.Name&&obj.RegisterBB(BB)}if(BB.Valid){var bounds=[[BB.northmin,BB.eastmin],[BB.northmax,BB.eastmax]];window.teklaMap._FitBounds(bounds),window.teklaMap._UpdateMapPosition()}}function $_existMySite(name){return $_DBFindObjectByName(MySitesDB,name)}function MyObjectsHandler(type){var f=null;try{f=TGMap.myObjects.knownTypes[type].onaction}catch(e){}if(f){for(var ids=[],i=0;i<MySitesDB.items.length;i++){var obj=MySitesDB.items[i];obj&&obj.Name&&obj.ReferenceId&&obj.MyOType==type&&ids.push(obj.ReferenceId)}f(0==ids.length?[-1]:ids)}}function $_updateMySites(){}function $_getAreaBB(marginal){var BB=new BBox,bounds=(window.teklaMap,window.teklaMap.getBounds()),east=bounds.getEast(),south=bounds.getSouth(),west=bounds.getWest(),north=bounds.getNorth();if(BB.RegisterPoint(south,west),BB.RegisterPoint(north,east),marginal)marginal>.1&&BB.Extend(marginal);else{var marg=256*currentWupp();BB.Extend(marg)}return BB}function startHideTimer(){removeInfoTimer(),$_infoTimer=setTimeout((function(){hideInfo()}),400)}function $_drawModeOn(){return document.onmousemove===drawZoom||"createsite"===toolMode||"createaddress"===toolMode||"createsearchobject"===toolMode||"drawrectangle"===toolMode||"drawpolygon"===toolMode||"drawpolyline"===toolMode||"distance"===toolMode||"selectposition"===toolMode||"movesite"===toolMode||$_isVisible("maincontextdiv")}function showShortInfo(DBIndex,Id,elem,x,y,content){var obj=null;if(DBIndex>=0&&Id&&!(obj=$_DBSelect(DBIndex,Id)))return;jQuery(elem).bind("mouseout.teklaShortInfo",(function(){Tekla.MapBubble.hideShort()})),Tekla.MapBubble.showShort(DBIndex,obj,x,y,content,null,(function(){jQuery(elem).unbind("mouseout.teklaShortInfo")}))}function showShortInfoWithContent(elem,x,y,name){showShortInfo(null,null,elem,x,y,{name:name})}function showInfo(DBIndex,Id,OverrideX,OverrideY,closeButton){if(!(document.onmouseup||!closeButton&&$_drawModeOn())){removeInfoTimer();var obj=$_DBSelect(DBIndex,Id);if(obj&&(!obj.oninfo||!0===obj.oninfo())){var cnt=obj.get_CenterPoint(),content=Tekla.MapBubble.show(DBIndex,obj);window.teklaMap.ShowBubble([cnt.y,cnt.x],content,__PopupAnchor(obj))}}}function setHandCursor(obj){jQuery(".leaflet-container").css("cursor","")}function setGrabCursor(obj){jQuery(".leaflet-container").css("cursor","crosshair")}function $_setCursor(c){var cursor=jQuery(".leaflet-container").css("cursor");$_Cursor!=cursor&&cursor!=c&&($_Cursor=cursor),jQuery(".leaflet-container").css("cursor",c)}function $_restoreCursor(){String.IsPrintable($_Cursor)&&(jQuery(".leaflet-container").css("cursor",$_Cursor),$_Cursor=null)}function $_layerEquals(lr,name){return lr.Name==name||lr.Label==name}function $_publishObjectData(result){result&&result.html&&result.target&&$_CallEventHandler(tekla.Map.EVENT.SHOWPROPERTIES,result.html,result.target)}function showProperties(provider,id,tag,cla){jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=action&Provider="+$_ENCODE(provider)+"&id="+id+(tag?"&tag="+$_ENCODE(tag):"")+(cla?"&class="+$_ENCODE(cla):""),success:function(data){$_publishObjectData($_EVALJSON(data))}})}function $_showByRef(referenceid,dbindex,mob){var DB=$_GetDBByIndex(dbindex);if(!DB)return!1;var obj=$_DBFindObjectByAttribute(DB,"ReferenceId",referenceid);if(!obj)return!1;mob&&window.Tekla.MobileSetTab&&window.Tekla.MobileSetTab("map"),$_ZoomToObject(obj);var content=Tekla.MapBubble.show(dbindex,obj),cnt=obj.get_CenterPoint();return window.teklaMap.ShowBubble([cnt.y,cnt.x],content,__PopupAnchor(obj)),!0}function showByRef(referenceid,status){var mob=window.teklaMap.options.IsMobile,found=$_showByRef(referenceid,OBJ_CATLAYER,mob);return found||(found=$_showByRef(referenceid,OBJ_SEARCH,mob)),status?found:void 0}function $_refreshObject(DBindex,Id,obj,cb){var LR=DBindex==OBJ_MYSITES?L_MYSITESLAYER:DBindex==OBJ_SEARCH?L_SEARCHLAYER:DBindex==OBJ_CATLAYER?L_CATLAYER:null;if(LR){var layer=$_findLayer(LR,obj);layer&&function _single(layer,obj,cb){if(cb)cb(layer,obj);else{var pres=obj.get_Presentation();if(pres)if(layer._icon){var icon=L.icon({iconUrl:pres&&pres.PointSymbol?pres.PointSymbol.Image:pres&&pres.Image||__getPinImage(),iconAnchor:__PinOffset(obj),className:__GetExtraClasses(pres,layer.options.isselected,obj.HLOn)});layer.setZIndexOffset(obj.HLOn?300:0),layer.setIcon(icon)}else{var presStyles={};presStyles.weight=pres&&pres.LineWidth?pres.LineWidth:$_defaultLineWidth,presStyles.color=pres&&pres.LineColor?pres.LineColor:$_defaultLineColor,presStyles.opacity=pres&&pres.LineOpacity?pres.LineOpacity:$_defaultLineOpacity,layer.options.fillColor&&(presStyles.fillColor=pres&&pres.FillColor?pres.FillColor:$_defaultFillColor,presStyles.fillOpacity=pres&&pres.FillOpacity?pres.FillOpacity:$_defaultFillOpacity),layer.setStyle(presStyles)}}}(layer,obj,cb)}}function $_findLayer(LR,obj){if(LR&&LR._layers&&obj)for(var o in LR._layers){var layer=LR._layers[o];if(layer)if(layer._layers)for(var s in layer._layers){var lr=layer._layers[s];if(lr.options&&lr.options.obj&&lr.options.obj.__id===obj.__id)return lr}else if(layer.options&&layer.options.obj&&layer.options.obj.__id===obj.__id)return layer}return null}
function ShowMessage(msg){alert(msg)}function $_generateLayerOnOff(){var layerStr="",selectedKeys=window.teklaMap._getIsThreeDMode()?Tekla.ThreeDMapLayers.getselected(!0):Tekla.Layers.getselected(!0);if(!selectedKeys||selectedKeys.length<1)return"";for(var i=0;i<selectedKeys.length;i++)layerStr+="&lon="+$_ENCODE(selectedKeys[i]);return layerStr}function $_showSiteResultWnd(html){window.Tekla.MobileShowHtml?html&&html.length>0&&window.Tekla.MobileShowHtml(html,!1):(html&&jQuery("#searchresults").empty().append(html),Tekla&&Tekla.SideBar&&Tekla.SideBar.opentab("#searchresults"))}function $_onReadyStateSearch_Data(data,readycb){var result=$_EVALJSON(data);SearchDB.Clear();var model=$_layerDisplayResults(SearchDB,result,LIST_CB);readycb&&readycb(model)}function doSearch(form,readycb){return form.q.value.length<1||jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=all&Name="+$_ENCODE(form.q.value)+(form.Municipality?"&Municipality="+$_ENCODE(form.Municipality.value):"")+(form.addressOnly&&form.addressOnly.checked?"&SearchMask=a":"")+(form.uid?"&uid="+$_ENCODE(form.uid.value):"")+(-1!=form.q.value.indexOf("currentarea:")?window.teklaMap._GetAreaString():""),cache:!1,success:function(data){jQuery(".ui-autocomplete-input").autocomplete("close"),Tekla&&Tekla.SideBar&&Tekla.SideBar.opentab("resulttab"),$_onReadyStateSearch_Data(data,readycb)}}),!1}function searchClick(DBIndex,Id,noZoom){$_DBSelect(DBIndex,Id)&&showSite(DBIndex,Id,noZoom)}function $_searchAreaDivisionByPosition(north,east){var form=document.areaDivisionForm,areaDiv=encodeURIComponent(form.areaDivision.value);north&&east&&(form.searchtext.value="",jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=areadivpt&areadivision="+areaDiv+"&North="+north+"&East="+east,success:function(data){$_onReadyStateAreaDivSearch_Data(data)}}))}function searchAreaDivision(form){form.searchtext.value.length>0&&jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=areadivpt&areadivision="+encodeURIComponent(form.areaDivision.value)+"&Name="+$_ENCODE(form.searchtext.value)+(form.Municipality?"&Municipality="+$_ENCODE(form.Municipality.value):""),success:function(data){$_onReadyStateAreaDivSearch_Data(data)}})}function $_areaDivSetArea(north1,east1,north2,east2){var s=Math.min(north1,north2),n=Math.max(north1,north2),w=Math.min(east1,east2),e=Math.max(east1,east2);window.teklaMap._FitBounds([[s,w],[n,e]]),window.teklaMap._UpdateMapPosition()}function $_onReadyStateAreaDivSearch_Data(data){var result=$_EVALJSON(data);if(result.outside)ShowMessage(GetText("cl_positionOutsideOfAnyArea"));else if(1==result.naddressfound){for(var html='<table class="areasearch"><tr><td colspan="2"><b>'+result.areaname+"</b></td></tr>",i=0;i<result.attributes.length;i++){var att=result.attributes[i];if(att.values)for(var v=0;v<att.values.length;v++){var val=att.values[v];html+="<tr>"+(val.e?'<td colspan="2"><a target="areaLink" class="bubblelink" href="'+val.v+'">'+val.e+"</a></td>":"<td>"+att.key+"</td><td>"+val.v+"</td>")+"</tr>"}else html+="<tr>"+(att.valueexp?'<td colspan="2"><a target="areaLink" class="bubblelink" href="'+att.value+'">'+att.valueexp+"</a></td>":"<td>"+att.key+"</td><td>"+att.value+"</td>")+"</tr>"}html+="</table>";var displayatsource=!1;result.displayat&&"source"==result.displayat&&(displayatsource=!0);var obj=new SR_Point(null,null,result.url,result.image,displayatsource?result.north:result.areanorth,displayatsource?result.east:result.areaeast);obj.set_FmtText(html);var Id=SearchDB.Insert(obj);displayatsource?(window.teklaMap._UserPositionDelete(),$_areaDivSetArea(result.north,result.east,result.north,result.east)):(window.teklaMap._UserPositionShow(result.north,result.east),$_areaDivSetArea(result.areanorth,result.areaeast,result.north,result.east)),showSite(OBJ_SEARCH,Id,!0)}else-1==result.naddressfound?(ShowMessage(GetText("cl_addressNrMissing")),updateSites()):result.naddressfound>0?(ShowMessage(GetText("cl_severalAddressFound")),updateSites()):(ShowMessage(GetText("cl_addressNotFound")),updateSites())}function doAdvancedSearch(form,close){var cids="",sel=jQuery("#selectedClassesList>span");return 0==sel.length?cids+="&cid=allc":sel.each((function(){cids+="&cid="+jQuery(this).attr("id").split("_")[1]})),jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=ext&Name="+(form.Text.value==GetText("cl_searchDetailTip")?"":$_ENCODE(form.Text.value))+cids+(form.MapArea.checked?window.teklaMap._GetAreaString():"")+(form.Municipality&&form.Municipality.value.length>0?"&Municipality="+$_ENCODE(form.Municipality.value):"")+(form.Area&&form.Area.value.length>0?"&Area="+$_ENCODE(form.Area.value):"")+(form.Occ&&form.Occ.value.length>0?"&Occ="+$_ENCODE(form.Occ.value):""),success:function(data){close&&jQuery("#advancedSearch").hide(),$_onReadyStateSearch_Data(data,(function(model){Tekla.SideBar.opentab("resulttab");var scope=angular.element($("#pane-search")).scope();scope&&scope.$evalAsync((function(){scope.refresh(model)}))}))}}),!1}var currentPlanRegHtml=null;function planRegulationLink(luplanid,planid){jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=getplanregulations&LUPlanId="+luplanid+(planid?"&PlanId="+planid:""),success:function(data){var result=$_EVALJSON(data);if(result){var html,sb=new StringBuilder("");if(result.name?sb.Append('<h3 class="planreg">'+result.name+"</h3>"):result.tip&&sb.Append('<h4 class="planreg">'+result.tip+"</h4>"),result.reg&&result.reg.length>0){sb.Append('<table class="planreg">');for(var i=0;i<result.reg.length;i++){var rgg=result.reg[i];sb.Append("<tr>"+(rgg.picsrc?'<td align="center"><img src="'+options.appPath+"/"+rgg.picsrc+'"></td>':"<td></td>")+"<td>"+(rgg.PlRegNum?rgg.PlRegNum:"")+"</td><td>"+rgg.Desc+"</td></tr>")}sb.Append("</table>")}html=sb.ToString()}Tekla.MapBubble.hideAll(),Tekla.HTMLWindow&&Tekla.HTMLWindow.show(html,{onClose:function(){currentPlanRegHtml=null}}),currentPlanRegHtml=html}})}function applyMaxLength(name,Limit){var obj=document.getElementById(name);obj&&obj.value.length>Limit&&(obj.value=obj.value.substring(0,Limit))}function $_linkShowAreaSearch(action){Tekla.SideBar.opentab("areasearchtab");var menu=document.getElementById("areaDivision");menu&&action.areatype&&(menu.value=action.areatype)}function $_querySetCookie(){$_setCookie($_queryCookieName,"true")}function $_queryIsCookieSet(){var ckie=$_getCookie($_queryCookieName);return!!ckie&&"true"==ckie}function qryVis(){showObj("querydiv")}function $_initQuery(){"fin"==options.lang&&String.IsPrintable($_queryTargetUrl)&&!$_queryIsCookieSet()&&setTimeout("qryVis();",1e3*$_queryTargetTimeout)}function showQuery(){hideObj("querydiv"),openUserQuery($_queryTargetUrl),$_querySetCookie()}function $_ClearElementInnetHTML(ele){var obj=document.getElementById(ele);obj&&(obj.innerHTML="")}function propLink(categoryid,id){window.teklaMap.printPage(categoryid,id)}function $_onReadyCommonProviderAction_Data(responseText){var result="string"==typeof responseText?$_EVALJSON(responseText):responseText;if(result){var zoomed=!1;result.keep||SearchDB.Clear(),result.setarea&&result.mnorth&&window.teklaMap._FitBounds([[result.mnorth-result.height/2,result.meast-result.width/2],[result.mnorth+result.height/2,result.meast+result.width/2]]),$_beginResultSet(OBJ_SEARCH),result.geoJSON&&($_layerGeoJSONDisplayResults(SearchDB,result.geoJSON),1==result.geoJSON.length&&result.geoJSON[0].referenceid&&($_showByRef(result.geoJSON[0].referenceid,OBJ_SEARCH),zoomed=!0)),$_endResultSet(OBJ_SEARCH),zoomed||window.teklaMap._UpdateMapPosition(!0),result.objectdata&&$_publishObjectData(result.objectdata)}}function providerAction(provider,searchtext){var url=actionUrl("Search")+"?Provider="+$_ENCODE(provider)+"&Op=Action&"+searchtext;jQuery.ajax({async:!0,type:"GET",url:url,dataType:tekla.utility.isSameOrigin(url)?"text":"jsonp",success:function(data){"string"==typeof data&&(data=$_EVALJSON(data)),$_onReadyCommonProviderAction_Data(data)}})}
L.CRS.Locus=L.extend({},L.CRS,{projection:L.Projection.LonLat,transformation:new L.Transformation(1,0,-1,0),scales:null,res:null,scale:function(zoom){if(window.teklaMap.options.isLatLon){this._ensureScales();var baseScale,iZoom=Math.floor(zoom);return zoom===iZoom?this._scales[zoom]:(baseScale=this._scales[iZoom])+(this._scales[iZoom+1]-baseScale)*(zoom-iZoom)}return zoom>=17?Math.pow(2,zoom-17):1/Math.pow(2,17-zoom)},_ensureScales:function(){if(!this.scales){this.res=[];for(var i=0;i<22;i++)this.res[i]=2*Math.PI*6378137/(256*Math.pow(2,i));this._scales=[];for(i=this.res.length-1;i>=0;i--)this.res[i]&&(this._scales[i]=1/this.res[i])}},_closestElement:function(array,element){for(var low,i=array.length;i--;)array[i]<=element&&(void 0===low||low<array[i])&&(low=array[i]);return low},zoom:function(scale){if(window.teklaMap.options.isLatLon){this._ensureScales();var downScale=this._closestElement(this._scales,scale),downZoom=this._scales.indexOf(downScale);if(scale===downScale)return downZoom;var nextZoom=downZoom+1,nextScale=this._scales[nextZoom];return void 0===nextScale?1/0:(scale-downScale)/(nextScale-downScale)+downZoom}return scale<=1?17-Math.log(1/scale)/Math.LN2:17+Math.log(scale)/Math.LN2},distance:function(latlng1,latlng2){var dx=latlng2.lng-latlng1.lng,dy=latlng2.lat-latlng1.lat;return Math.sqrt(dx*dx+dy*dy)},infinite:!0,zoom2Wupp:function(zoom){return window.teklaMap.options.isLatLon?(this._ensureScales(),this.res[zoom]):zoom<=17?Math.pow(2,17-zoom):1/Math.pow(2,zoom-17)},wupp2Zoom:function(wupp,fl){var zoom=1;if(window.teklaMap.options.isLatLon){this._ensureScales();for(var min=this.res[0],i=0;i<this.res.length;i++){var d=Math.abs(this.res[i]-wupp);d<min&&(zoom=i,min=d)}}else zoom=wupp<=1?17+Math.log(1/wupp)/Math.LN2:17-Math.log(wupp)/Math.LN2;return fl?Math.floor(zoom):zoom}}),L.LocusTileLayer=L.TileLayer.extend({_delays:{},_delaysForZoom:null,getTileUrl:function(coords){var data={r:L.Browser.retina?"@2x":"",s:this._getSubdomain(coords),x:coords.x,y:coords.y,z:this._getZoomForUrl()};if(this._map&&!this._map.options.crs.infinite){var invertedY=this._globalTileRange.max.y-coords.y;this.options.tms&&(data.y=invertedY),data["-y"]=invertedY}return data["-y"]=-coords.y-1,L.Util.template(this._url,L.extend(data,this.options))},createCanvas:function(tile,coords,done){var err,ctx=tile.getContext("2d"),_a=this.getTileSize(),width=_a.x,height=_a.y;tile.width=width,tile.height=height;var img=new Image;img.onload=function(){try{ctx.drawImage(img,0,0),tile.complete=!0}catch(e){err=e}finally{done(err,tile)}},img.src=this.getTileUrl(coords);var cO=this.options.crossOrigin;(cO||""===cO)&&(tile.crossOrigin=!0===cO?"":cO)},createTile:function(coords,done){var timeout=this.options.timeout,zoom=coords.z,tile=document.createElement("canvas");return timeout?(zoom!==this._delaysForZoom&&(this._clearDelaysForZoom(),this._delaysForZoom=zoom),this._delays[zoom]||(this._delays[zoom]=[]),this._delays[zoom].push(setTimeout((function(){_this.createCanvas(tile,coords,done)}),timeout))):this.createCanvas(tile,coords,done),tile},_clearDelaysForZoom:function(){var prevZoom=this._delaysForZoom,delays=null!=prevZoom?this._delays[prevZoom]:null;if(delays){for(var index=0;index<delays.length;index++)clearTimeout(delays[index]),delete delays[index];delete this._delays[prevZoom]}}}),L.locusTileLayer=function(url,options){return new L.LocusTileLayer(url,options)},function(factory,window){"function"==typeof define&&define.amd?define(["leaflet"],factory):"object"==typeof exports&&(module.exports=factory(require("leaflet"))),void 0!==window&&window.L&&(window.L.PolylineOffset=factory(L))}((function(L){function forEachPair(list,callback){if(list&&!(list.length<1))for(var i=1,l=list.length;i<l;i++)callback(list[i-1],list[i])}function lineEquation(pt1,pt2){if(pt1.x===pt2.x)return pt1.y===pt2.y?null:{x:pt1.x};var a=(pt2.y-pt1.y)/(pt2.x-pt1.x);return{a:a,b:pt1.y-a*pt1.x}}function intersection(l1a,l1b,l2a,l2b){var line1=lineEquation(l1a,l1b),line2=lineEquation(l2a,l2b);if(null===line1||null===line2||void 0===line1||void 0===line2)return null;if(line1.hasOwnProperty("x"))return line2.hasOwnProperty("x")?null:{x:line1.x,y:line2.a*line1.x+line2.b};if(line2.hasOwnProperty("x"))return{x:line2.x,y:line1.a*line2.x+line1.b};if(line1.a===line2.a)return null;var x=(line2.b-line1.b)/(line1.a-line2.a);return{x:x,y:line1.a*x+line1.b}}function translatePoint(pt,dist,heading){return{x:pt.x+dist*Math.cos(heading),y:pt.y+dist*Math.sin(heading)}}var PolylineOffset={offsetPointLine:function(points,distance){var offsetSegments=[];return forEachPair(points,L.bind((function(a,b){if(a.x!==b.x||a.y!==b.y){var offsetAngle=Math.atan2(a.y-b.y,a.x-b.x)-Math.PI/2;offsetSegments.push({offsetAngle:offsetAngle,original:[a,b],offset:[translatePoint(a,distance,offsetAngle),translatePoint(b,distance,offsetAngle)]})}}),this)),offsetSegments},offsetPoints:function(pts,offset,q){return this.joinLineSegments(this.offsetPointLine(pts,offset),offset,q)},joinSegments:function(s1,s2,offset,q){return this.circularArc(s1,s2,offset,q).filter((function(x){return x}))},joinLineSegments:function(segments,offset,q){var joinedPoints=[],first=segments[0],last=segments[segments.length-1];return first&&last&&(joinedPoints.push(first.offset[0]),forEachPair(segments,L.bind((function(s1,s2){joinedPoints=joinedPoints.concat(this.joinSegments(s1,s2,offset,q))}),this)),joinedPoints.push(last.offset[1])),joinedPoints},segmentAsVector:function(s){return{x:s[1].x-s[0].x,y:s[1].y-s[0].y}},getSignedAngle:function(s1,s2){var a=this.segmentAsVector(s1),b=this.segmentAsVector(s2);return Math.atan2(a.x*b.y-a.y*b.x,a.x*b.x+a.y*b.y)},circularArc:function(s1,s2,distance,q){if(s1.offsetAngle===s2.offsetAngle)return[s1.offset[1]];if(!q)return[intersection(s1.offset[0],s1.offset[1],s2.offset[0],s2.offset[1])];var signedAngle=this.getSignedAngle(s1.offset,s2.offset);if(signedAngle*distance>0&&signedAngle*this.getSignedAngle(s1.offset,[s1.offset[0],s2.offset[1]])>0)return[intersection(s1.offset[0],s1.offset[1],s2.offset[0],s2.offset[1])];var points=[],center=s1.original[1],rightOffset=distance>0,startAngle=rightOffset?s2.offsetAngle:s1.offsetAngle,endAngle=rightOffset?s1.offsetAngle:s2.offsetAngle;endAngle<startAngle&&(endAngle+=2*Math.PI);for(var step=Math.PI/8,alpha=startAngle;alpha<endAngle;alpha+=step)points.push(translatePoint(center,distance,alpha));return points.push(translatePoint(center,distance,endAngle)),rightOffset?points.reverse():points}};return L.Polyline.include({_projectLatlngs:function(latlngs,result,projectedBounds){if(latlngs.length>0&&latlngs[0]instanceof L.LatLng){var ring=latlngs.map(L.bind((function(ll){var point=this._map.latLngToLayerPoint(ll);return projectedBounds&&projectedBounds.extend(point),point}),this)),wupp=this._map.GetZoom();this.options.offset&&(ring=L.PolylineOffset.offsetPoints(ring,this.options.offset,wupp<=.5)),result.push(ring.map((function(xy){return L.point(xy.x,xy.y)})))}else latlngs.forEach(L.bind((function(ll){this._projectLatlngs(ll,result,projectedBounds)}),this))}}),L.Polyline.include({setOffset:function(offset){return this.options.offset=offset,this.redraw(),this}}),PolylineOffset}),window),function(factory,window){"function"==typeof define&&define.amd?define(["leaflet"],factory):"object"==typeof exports&&(module.exports=factory(require("leaflet"))),void 0!==window&&window.L&&(window.L.PolylineSymboled=factory(L))}((function(L){function lineLength(x,y,x0,y0){return Math.sqrt((x-=x0)*x+(y-=y0)*y)}function polyLength(parts){var i,len,l=0;for(i=1,len=parts.length;i<len;i++){var f=parts[i-1],s=parts[i];l+=lineLength(f.x,f.y,s.x,s.y)}return l}var PolylineSymboled={_angle:function(cx,cy,ex,ey){var dy=ey-cy,dx=ex-cx;return Math.atan2(dy,dx)},arrow:function(ctx,x,y,angle,symbol,headlen,arangle){"arrow"!==symbol&&"one-sided-arrow"!==symbol||(ctx.moveTo(x,y),ctx.lineTo(x-headlen*Math.cos(angle-arangle),y-headlen*Math.sin(angle-arangle))),"arrow"===symbol&&(ctx.moveTo(x,y),ctx.lineTo(x-headlen*Math.cos(angle+arangle),y-headlen*Math.sin(angle+arangle)))},circle:function(ctx,x,y,radius){ctx.arc(x,y,radius,0,2*Math.PI,!1)},triangle:function(ctx,x,y,angle,headlen,arangle){ctx.moveTo(x,y),ctx.lineTo(x-headlen*Math.cos(angle-arangle),y-headlen*Math.sin(angle-arangle)),ctx.lineTo(x-headlen*Math.cos(angle+arangle),y-headlen*Math.sin(angle+arangle)),ctx.lineTo(x,y)},square:function(ctx,x,y,angle,headlen){var hlen2=headlen*Math.sqrt(2),arangle=Math.PI/4;ctx.moveTo(x,y),ctx.lineTo(x-headlen*Math.cos(angle-arangle),y-headlen*Math.sin(angle-arangle)),ctx.lineTo(x-hlen2*Math.cos(angle),y-hlen2*Math.sin(angle)),ctx.lineTo(x-headlen*Math.cos(angle+arangle),y-headlen*Math.sin(angle+arangle)),ctx.lineTo(x,y)}};return L.Canvas.include({_addText:function(textopts){if(void 0===textopts.ctx||void 0===textopts.textcontent)return;let ctx=textopts.ctx,textcontent=textopts.textcontent,point=void 0===textopts.point?{x:0,y:0}:textopts.point,horizontalalignment=void 0===textopts.horizontalalignment?"left":textopts.horizontalalignment,verticalalignment=void 0===textopts.verticalalignment?"top":textopts.verticalalignment,rotation_deg=void 0===textopts.rotation_deg?0:textopts.rotation_deg,fontsize=void 0===textopts.fontsize?20:textopts.fontsize,bold=void 0!==textopts.bold&&textopts.bold;ctx.save();let transform=ctx.getTransform();ctx.font=(bold?"bold ":"")+fontsize+"px Arial";let textsize=ctx.measureText(textcontent);textsize.height=textsize.actualBoundingBoxAscent+textsize.actualBoundingBoxDescent;let horz_off=0,vert_off=0;"center"===horizontalalignment?horz_off=textsize.width/2:"right"===horizontalalignment&&(horz_off=textsize.width),"center"===verticalalignment?vert_off=textsize.height/2:"top"===verticalalignment&&(vert_off=textsize.height),ctx.translate(point.x,point.y),ctx.rotate(rotation_deg*Math.PI/180),ctx.translate(-point.x,-point.y),ctx.globalAlpha=.8,ctx.fillStyle="#FFFFFF",ctx.fillRect(point.x-horz_off-2,point.y+(vert_off-textsize.height)-2,textsize.width+4,textsize.height+4),ctx.globalAlpha=1,ctx.fillStyle="#3f0969",ctx.fillText(textcontent,point.x-horz_off,point.y+vert_off),ctx.setTransform(transform),ctx.restore()},_updatePoly:function(layer,closed){if(!this._drawing)return;var i,j,len2,p,parts=layer._parts,len=parts.length,ctx=this._ctx;if(!len)return;ctx.beginPath();let north_px=1/0,south_px=-1/0,east_px=-1/0,west_px=1/0;for(i=0;i<len;i++){for(j=0,len2=parts[i].length;j<len2;j++)p=parts[i][j],ctx[j?"lineTo":"moveTo"](p.x,p.y),south_px=Math.max(south_px,p.y),north_px=Math.min(north_px,p.y),east_px=Math.max(east_px,p.x),west_px=Math.min(west_px,p.x);closed&&ctx.closePath()}if(this._fillStroke(ctx,layer),layer.options.symbolOptions){var opts=layer.options.symbolOptions,minLengthPx=opts.MinDistance||125,headlen=opts.Length||20,arangle=opts.Angle||Math.PI/6,symbol=opts.Symbol||"arrow",aDistance=opts.Distance||50,radius=opts.Radius||15,filled=!1,extopts={},options=layer.options;for(extopts.weight=opts.LineWidth||options.weight/2,extopts.color=opts.LineColor||options.color,extopts.opacity=opts.LineOpacity||options.opacity,extopts.fillColor=opts.FillColor||options.fillColor,extopts.fillOpacity=opts.FillOpacity||options.fillOpacity,i=0;i<len;i++){if(polyLength(parts[i])>=minLengthPx){var currentDistance=0;for(j=0,len2=parts[i].length;j<len2;j++)if(p=parts[i][j],j>0){var f=parts[i][j-1],s=parts[i][j],angle=L.PolylineSymboled._angle(f.x,f.y,s.x,s.y),segmentLength=lineLength(f.x,f.y,s.x,s.y);if(currentDistance+segmentLength>aDistance)for(var alongSegment=0,go=!0,along=aDistance-currentDistance;go;){alongSegment+=along;var x=f.x+Math.cos(angle)*alongSegment,y=f.y+Math.sin(angle)*alongSegment;ctx.beginPath(),"circle"===symbol?(L.PolylineSymboled.circle(ctx,x,y,radius),filled=!0):"triangle"===symbol?(L.PolylineSymboled.triangle(ctx,x,y,angle,headlen,arangle),filled=!0):"square"===symbol?(L.PolylineSymboled.square(ctx,x,y,angle,headlen),filled=!0):L.PolylineSymboled.arrow(ctx,x,y,angle,symbol,headlen,arangle),alongSegment+aDistance<segmentLength?(along=aDistance,currentDistance=0):(go=!1,currentDistance=segmentLength-alongSegment),ctx.closePath(),extopts.fill=filled,this._fillStrokeSymbol(ctx,layer,extopts)}else currentDistance+=segmentLength}}}}if(layer.options.obj&&layer.options.obj.drawMeasurements&&layer.options.obj.Geometry.coordinates&&south_px-north_px>40&&east_px-west_px>60){var n=-1/0,w=(s=1/0,1/0),e=-1/0;for(const point of layer.options.obj.Geometry.coordinates[0])n=Math.max(n,point[1]),s=Math.min(s,point[1]),w=Math.min(w,point[0]),e=Math.max(e,point[0]);var cX=ctx.canvas._leaflet_pos.x,cY=ctx.canvas._leaflet_pos.y,cW=ctx.canvas.clientWidth,cH=ctx.canvas.clientHeight,mX=this._map._size.x,mY=this._map._size.y;let viewportEast=cX+mX+(cW-mX)/2,viewportNorth=cY+(cH-mY)/2;this._addText({ctx:ctx,point:{x:(east_px+west_px)/2,y:(north_px+south_px)/2},textcontent:((n-s)*(e-w)*1e-4).toFixed(2)+"ha",horizontalalignment:"center",verticalalignment:"center",rotation_deg:0,fontsize:layer._map._zoom,bold:!0}),this._addText({ctx:ctx,point:{x:Math.min(east_px,viewportEast),y:(north_px+south_px)/2},textcontent:(n-s).toFixed(0)+"m",horizontalalignment:"center",verticalalignment:"bottom",rotation_deg:-90,fontsize:layer._map._zoom,bold:!0}),this._addText({ctx:ctx,point:{x:(east_px+west_px)/2,y:Math.max(north_px,viewportNorth)},textcontent:(e-w).toFixed(0)+"m",horizontalalignment:"center",verticalalignment:"top",rotation_deg:0,fontsize:layer._map._zoom,bold:!0})}},_fillStrokeSymbol:function(ctx,layer,extopts){var options=layer.options;(extopts.fill||options.fill)&&(ctx.globalAlpha=extopts.fillOpacity||options.fillOpacity,ctx.fillStyle=extopts.fillColor||options.fillColor||options.color,ctx.fill(options.fillRule||"evenodd")),options.stroke&&0!==options.weight&&(ctx.setLineDash&&ctx.setLineDash(layer.options&&layer.options._dashArray||[]),ctx.globalAlpha=extopts.opacity||options.opacity,ctx.lineWidth=extopts.weight||options.weight,ctx.strokeStyle=extopts.color||options.color,ctx.lineCap=options.lineCap,ctx.lineJoin=options.lineJoin,ctx.stroke())}}),L.Polyline.include({setArrow:function(symbolOptions){return this.options.symbolOptions=symbolOptions,this.redraw(),this}}),PolylineSymboled}),window),L.Canvas.include({_updateSVGMarker:function(layer){if(!this._drawing||layer._empty())return;var svgpres=layer.options.svgpres;if(!svgpres)return;var p=layer._point,ctx=this._ctx;const bitmap=window.Tekla.BitmapManager.getBitmap(svgpres.svg),img=bitmap&&bitmap.img||void 0;if(img){const height=svgpres.size||1,width=height*img.width/img.height,wupp=currentWupp(),dstWidthPixels=width/wupp,dstHeightPixels=height/wupp;var dxPixels=(svgpres.sdy||0)/wupp,dyPixels=(svgpres.sdx||0)/wupp;if(dstWidthPixels>0&&dstHeightPixels>0){ctx.save(),(dxPixels||dyPixels)&&(ctx.lineWidth=2,ctx.strokeStyle="black",ctx.beginPath(),ctx.moveTo(p.x,p.y),ctx.lineTo(p.x+dxPixels,p.y-dyPixels),ctx.stroke());const angle=svgpres.sdir||0;ctx.translate(p.x+dxPixels,p.y-dyPixels),Math.abs(angle)>0&&ctx.rotate(-angle),ctx.globalAlpha=.8,ctx.drawImage(img,-dstWidthPixels/2,-dstHeightPixels/2,dstWidthPixels,dstHeightPixels),svgpres.hl?(ctx.fillStyle="rgba(0, 0, 0, 0.4)",ctx.fillRect(-dstWidthPixels/2,-dstHeightPixels/2,dstWidthPixels,dstHeightPixels)):svgpres.bg&&(ctx.fillStyle=svgpres.bg,ctx.fillRect(-dstWidthPixels/2,-dstHeightPixels/2,dstWidthPixels,dstHeightPixels)),layer.options.isselected&&(ctx.lineWidth=2,ctx.strokeStyle="#FFBE00",ctx.beginPath(),ctx.rect(-dstWidthPixels/2,-dstHeightPixels/2,dstWidthPixels,dstHeightPixels),ctx.stroke()),ctx.restore()}}}});var SVGMarker=L.CircleMarker.extend({_updatePath:function(){this._renderer._updateSVGMarker(this)},_updateBounds:function(){var svgpres=this.options.svgpres,bitmap=window.Tekla.BitmapManager.getBitmap(svgpres.svg),img=bitmap&&bitmap.img||void 0;if(img){const height=svgpres.size||1,width=height*img.width/img.height,wupp=currentWupp(),dstWidthPixels=width/wupp,dstHeightPixels=height/wupp;var dxPixels=(svgpres.sdy||0)/wupp,dyPixels=(svgpres.sdx||0)/wupp,dxM=Math.max(dxPixels,dyPixels);this._radius=Math.max(dstHeightPixels,dstWidthPixels)/2+dxM}var r=this._radius,r2=this._radiusY||r,w=this._clickTolerance(),p=[r+w,r2+w];this._pxBounds=new L.Bounds(this._point.subtract(p),this._point.add(p))}});
!function($,window){"use strict";var name="tekla.ims.mapbubble",defaults={autoFocus:!1},_m_id=1;function handleWidth(inValue){return parseFloat((""+inValue).replace(",","."))}var deleteItem=window.deleteItem=function(DBIndex,Id,event,noconf){Tekla.MapBubble.hideAll(),cancelEventPropagation(event);var obj=$_DBSelect(DBIndex,Id);if(noconf||obj&&obj.CustomDelete||confirm(GetText("cl_deleteConfirm"))){if(obj&&obj.CustomDelete)return void $_CallEventHandler(tekla.Map.EVENT.EXTERNALDELETEREQUESTED,"extdelete",obj);window.teklaMap.BeginGuiTrans(),$_DBDelete(DBIndex,Id),DBIndex==OBJ_MYSITES&&($_CallEventHandler(tekla.Map.EVENT.DRAWINGDELETED),window.teklaMap3&&window.Tekla.ThreeD&&window.Tekla.ThreeD.addMarkUps(MySitesDB,!0)),window.teklaMap.NeedLayerRedraw(),window.teklaMap.EndGuiTrans()}};function moveSite(dbindex,id,event){Tekla.MapBubble.hideAll(),toolMode="movesite",setStatus(GetText("cl_selectMoveObjectPosition")),window.teklaMap.AddMapMoveListener(updateTooltip),enableTooltip(),$_SelectedDBIndex=dbindex,$_SelectedId=id,jQuery(".leaflet-container").css("cursor","crosshair"),cancelEventPropagation(event)}function MapBubble(element,options){this.element=element,this.options=jQuery.extend({},defaults,options),this._defaults=defaults,this.prevPresentation=null,this.hasPresentation=!1,this.presentationHasChanges=!1,this._init()}MapBubble.prototype._init=function(){var o=this.options,$e=jQuery(this.element),self=this;if(o.prestypes&&o.prestypes.length>0){var presTab=$e.find(".presentation-tab");presTab.presentationselector({embedded:!0}),presTab.presentationselector("toggleTypes",o.prestypes);var presentation=o.presentation;o.obj&&(self.prevPresentation=o.obj.Presentation,presentation||(presentation=self.prevPresentation)),presTab.presentationselector("setPresentation",presentation,(function(){self._presentationChanged()})),self.hasPresentation=!0}if(jQuery.fn.minitabs?$e.minitabs():($e.find(".tabItems").hide(),self.hasPresentation=!1),"undefined"!=typeof tinyMCE){var ta=$e.find(".edit-bubble-htmldescription textarea");if(ta.length>0){var id="mce_"+_m_id++;ta.attr("id",id),ta.addClass(id)}}if(!o.customContent){if(o.visible&&o.visible.length>0){$e.addClass("element-filter");for(var i=0;i<o.visible.length;i++)$e.addClass("filter-"+o.visible[i])}if(o.editable){var propName;if(o.values)for(propName in o.values)!0===o.editable||-1!==o.editable.indexOf(propName)?o.values[propName]&&$e.find('[name="'+propName+'"]').val(o.values[propName]):$e.find('[name="'+propName+'"]').siblings().remove().end().replaceWith('<span class="'+propName+'">'+(o.values[propName]?o.values[propName]:"")+"</span>");o.editable.length>=0&&$e.find("input, textarea, select").each((function(){-1===o.editable.indexOf(jQuery(this).attr("name"))&&jQuery(this).siblings().remove().end().remove()}))}else if(o.obj){$e.find(".name").text(o.obj.Name||"");var expl=this._renderExplanation(o.obj)||"";""!==expl?$e.find(".explanation").html(expl):$e.find(".explanation").hide(),$e.find(".htmldescription").text(o.obj.htmldescription||""),$e.find(".links").html(this._renderlinks(o.dbindex,o.obj)),$e.find(".externallinks").html(this._renderexternaldocuments(o.obj)),$e.find(".map-selection").html(this._renderMapSelectionLink()),o.obj&&o.obj.CustomPicture&&jQuery("<img/>").attr("src",o.obj.CustomPicture).appendTo($e.find(".picture"))}else o.values&&$e.find(".name").text(o.values.name||"");0===$e.find("input, textarea, select").length&&$e.find("button.action-cancel").remove()}o.actions&&o.actions.length>0&&$e.find(".bubble-footer").prepend(function renderActionUL(def,index){var ul;return jQuery.isArray(def)&&def.length>0&&(jQuery.isArray(def[0])?(ul=jQuery('<div class="actionbar-multi-container"></div>'),jQuery(def).each((function(indx,value){indx>0&&ul.append('<div class="clear"></div>'),ul.append(renderActionUL(this,indx))}))):(ul=jQuery('<ul class="actionbar-list"></ul>'),jQuery(def).each((function(){ul.append(function renderActionLI(def){var li=jQuery('<li><a href="javascript:void(0);">'+def.name+"</a></li>");return def.cssClass&&li.find("a").addClass(def.cssClass),def.title&&li.find("a").attr("title",def.title),"function"==typeof def.action&&jQuery(li).click((function(ev){def.action(ev,self._getValues())})),li}(this))})))),ul}(o.actions)),$e.find(".action-ok").click((function(){return self.close(!0),!1})),$e.find(".close-bubble, .action-cancel").click((function(){self._cancel()})),$e.find("input").keydown((function(event){13==event.which&&event.preventDefault()}))},MapBubble.prototype._cancel=function(){var o=this.options,close=!0;"function"==typeof o.onCancel&&!1===o.onCancel()&&(close=!1),close&&this.close(!1)},MapBubble.prototype._presentationChanged=function(){var o=this.options;o.obj&&o.dbindex&&(o.obj.Presentation=jQuery.extend({},o.obj.Presentation,this._getPresentation()),this.presentationHasChanges=!0,$_refreshObject(o.dbindex,o.obj.__id,o.obj))},MapBubble.prototype._getPresentation=function(){var o=this.options;return!0===this.hasPresentation?jQuery(this.element).find(".presentation-tab").presentationselector("getPresentation",o.obj&&o.obj.get_PresTypes?o.obj.get_PresTypes():o.prestypes):null},MapBubble.prototype._getPinImage=function(obj){if(!obj)return null;var pres=obj.get_Presentation?obj.get_Presentation():null;return pres?pres.Image?pres.Image:__getPinImage():obj.Image&&"undefined"!=obj.Image?obj.Image:__getPinImage()},MapBubble.prototype.show=function(inX,inY){if(jQuery(this.element).show(),this.options.autoFocus){var $elem=jQuery(this.element).find(":input:first");if(1===$elem.length&&($elem.focus(),$elem.is("input:text, textarea")))if($elem[0].createTextRange){var txtRange=$elem[0].createTextRange();txtRange.moveStart("character",$elem[0].value.length),txtRange.select()}else $elem[0].setSelectionRange&&$elem[0].setSelectionRange(0,$elem[0].value.length)}"function"==typeof this.options.onShow&&this.options.onShow()},MapBubble.prototype.close=function(commit,skipAutoCommit){var o=this.options;this.presentationHasChanges&&o.obj&&this.prevPresentation&&(o.obj.Presentation=this.prevPresentation,$_refreshObject(o.dbindex,o.obj.__id,o.obj)),"function"==typeof this.options.onClose&&this.options.onClose(),!0===commit||!0!==skipAutoCommit&&this.options.autoCommit?this._save():cancelDrawing(),window.teklaMap.closePopup(),this._destroy()},MapBubble.prototype.isVisible=function(){return jQuery(this.element).is(":visible")},MapBubble.prototype.preventsOthers=function(){return!0===this.options.preventsOthers},MapBubble.prototype._renderExplanation=function(obj){var retVal=obj.get_FmtText();return retVal||(obj.AttrList?retVal=this._renderattrlist(obj):(obj.Explanation&&obj.Name!==obj.Explanation&&(retVal=String.escapeHTML(obj.Explanation,!0)),obj.CategoryPath&&(retVal+="<br/>"+obj.CategoryPath))),retVal},MapBubble.prototype._renderattrlist=function(obj){for(var retVal="",a=0;a<obj.AttrList.length;a++)retVal+="<br/>"+String.escapeHTML(obj.AttrList[a].n)+": "+String.escapeHTML(obj.AttrList[a].v,!0);return retVal},MapBubble.prototype._renderlinks=function(DBIndex,obj){function formatLink(href,text){return'<a class="bubblelink" onclick="'+href+'">'+text+"</a>"}var retVal="",urltype=obj.get_UrlType(),allowLinks=this.options.allowSpecialLinks;return(!urltype||!allowLinks||allowLinks.indexOf(urltype)>=0)&&(retVal+="SF"===urltype?formatLink("JavaScript:showFeedbackById("+DBIndex+","+obj.__id+", event)",GetText("feedbackLink")):$_isValidUrl(obj.Url)?formatLink("JavaScript:openUrlId("+DBIndex+","+obj.__id+")",GetText("PR"===urltype?"cl_planRegulations":"cl_additionalInfo")):""),retVal},MapBubble.prototype._renderexternaldocuments=function(obj){var retVal="",docs=obj.DocList;if(docs&&docs.length>0)for(var docI=0;docI<docs.length;docI++){var doc=docs[docI],url=doc.Url,exp=doc.Exp;String.IsPrintable(url)&&(retVal+='<br/><a class="bubblelink" href="JavaScript:openUrl(\''+url+"')\">"+(String.IsPrintable(exp)?exp:url+"...")+"</a>&nbsp;&nbsp;&nbsp;")}return retVal},MapBubble.prototype._renderMapSelectionLink=function(){var latLng=this.options.mouseClickLatlng;return latLng&&window.Tekla.mapObjectSelection?'<a class="bubblelink" href="JavaScript:openObjectSelectionMenu('+latLng.lat+","+latLng.lng+')">'+GetText("cl_chooseAnother")+"...</a>&nbsp;&nbsp;&nbsp;":""},MapBubble.prototype._save=function(){"function"==typeof this.options.onSave&&this.options.onSave(this._getValues())},MapBubble.prototype._getValues=function(){var retVal={};return"undefined"!=typeof tinymce&&tinymce.triggerSave(),jQuery(this.element).find("input, textarea, select").each((function(){var name=jQuery(this).attr("name");if(name&&name+""!="")if(retVal[name]){var temp=retVal[name];retVal[name]=[temp],retVal[name].push(jQuery(this).val())}else retVal[name]=jQuery(this).val()})),retVal.presentationHasChanges=this.presentationHasChanges,retVal.presentation=this._getPresentation(),retVal.presentation||(retVal.presentation=this.options.presentation),retVal},MapBubble.prototype._destroy=function(){if("undefined"!=typeof tinyMCE){var ta=jQuery(this.element).find(".edit-bubble-htmldescription textarea");if(ta.length>0){var id=ta.attr("id");tinymce.EditorManager.execCommand("mceRemoveEditor",!1,id);try{jQuery("textarea").blur(),jQuery("input").blur()}catch(e){}}}jQuery(this.element).hide(),jQuery(this.element).remove()},MapBubble.prototype.getDBindex=function(){return this.options.dbindex},window.Tekla||(window.Tekla={}),window.Tekla.MapBubble={INFO_TEMPLATE:"#info-bubble-template",SHORT_INFO_TEMPLATE:"#short-info-bubble-template",EDIT_TEMPLATE:"#edit-bubble-template",EDIT_EXT_TEMPLATE:"#edit-ext-bubble-template",EDIT_EXTADDR_TEMPLATE:"#edit-ea-bubble-template",EDIT_EXTSO_TEMPLATE:"#edit-eso-bubble-template",_parentContainer:null,bubbles:[],shortBubbles:[],currentShowTimeout:null,cancelCurrentShowTimeout:function(){this.currentShowTimeout&&(clearTimeout(this.currentShowTimeout),this.currentShowTimeout=null)},defaultOptions:{editable:!1},currentMunicipality:null,startInsertExternalAddress:function(municipality,event){Tekla.MapBubble.hideAll(),window.teklaMap._HandleRemove(),$_setCursor("crosshair"),toolMode="createaddress",setStatus(GetText("cl_selectNewObjectPosition")),window.teklaMap.AddMapMoveListener(updateTooltip),enableTooltip(),this.currentMunicipality=municipality,updateTooltip(event),cancelEventPropagation(event)},startInsertExternalSearchObject:function(municipality,event){Tekla.MapBubble.hideAll(),window.teklaMap._HandleRemove(),$_setCursor("crosshair"),toolMode="createsearchobject",setStatus(GetText("cl_selectNewObjectPosition")),window.teklaMap.AddMapMoveListener(updateTooltip),enableTooltip(),this.currentMunicipality=municipality,updateTooltip(event),cancelEventPropagation(event)},insert:function(toolMode,latlng,options){switch(toolMode){case"createaddress":this.insertExternalAddress(toolMode,this.currentMunicipality,latlng,options);break;case"createsearchobject":this.insertSearchObject(toolMode,this.currentMunicipality,latlng,options);break;default:this.insertMyObject(toolMode,latlng,options)}clearToolstate(),startPan()},insertExternalAddress:function(toolMode,municipality,latlng){var self=this,opts=jQuery.extend({},this.defaultOptions,{editable:!0,obj:null,autoCommit:!1,municipality:municipality,onCancel:function(){cancelDrawing()},onSave:function(values){var s=window.teklaMap._selectedPositionSouth,e=window.teklaMap._selectedPositionEast,obj=new SR_Point("","","",null,s,e),aid=SearchDB.Insert(obj);obj.SetAddress(aid,municipality,values.streetname,values.addressnumber,s,e),self._clearMapState()}}),html=this._createAndShowElement(this.EDIT_EXTADDR_TEMPLATE,opts,self._getTemplatePrepareFunc(this.EDIT_EXTADDR_TEMPLATE,opts));window.teklaMap.ShowBubble(latlng,html,new L.Point(0,0))},insertSearchObject:function(toolMode,municipality,latlng){var self=this,opts=jQuery.extend({},this.defaultOptions,{editable:!0,obj:null,autoCommit:!1,municipality:municipality,prestypes:["Point"],onCancel:function(){cancelDrawing()},onSave:function(values){var s=window.teklaMap._selectedPositionSouth,e=window.teklaMap._selectedPositionEast,obj=new SR_Point("","","",null,s,e),id=SearchDB.Insert(obj);obj.SetSearchObject(id,municipality,values.category,values.name,values.explanation,values.url,values.image,s,e),self._clearMapState()}});opts.preventsOthers=!0;var html=this._createAndShowElement(this.EDIT_EXTSO_TEMPLATE,opts,self._getTemplatePrepareFunc(this.EDIT_EXTSO_TEMPLATE,opts));window.teklaMap.ShowBubble(latlng,html,new L.Point(0,0))},insertMyObject:function(toolMode,latlng,extOptions){var drawingData="function"==typeof options.getDrawingData?options.getDrawingData():null,opts=null;!0!==(opts=jQuery.extend({},this.defaultOptions,drawingData||{},extOptions||{},{editable:!0,prestypes:this._getPresTypes(toolMode),overrideEmptyName:GetText("cl_ownDrawing"),autoFocus:!0,autoCommit:window.options.editBubbleAutoCommit,onCancel:function(){cancelDrawing()},onSave:function(values){var vals=jQuery.extend({},opts.values,values||{}),obj=Tekla.MapBubble.createObject(toolMode,vals&&vals.name&&""!==vals.name?vals.name:opts.overrideEmptyName||"",vals&&vals.explanation?vals.explanation:"",vals?vals.url:"",vals?vals.htmldescription:"",vals?vals.imageurl:"",vals&&vals.presentation?vals.presentation:opts.presentation,opts.myotype,vals?vals.width:null,opts.canDelete);if($_removeDrawingVisuals(),obj){obj.Editable=!0,obj.mapbubble={editable:opts.editable,visible:opts.visible},drawingData.skipBubble&&(obj.skipBubble=drawingData.skipBubble),drawingData.drawMeasurements&&(obj.drawMeasurements=drawingData.drawMeasurements);var id=MySitesDB.Insert(obj);opts.singleton&&(window.$_filterSingleton=id),$_CallEventHandler(tekla.Map.EVENT.BUBBLECOMMIT,"create",obj,values),window.teklaMap.RedrawLayers(),$_CallEventHandler(tekla.Map.EVENT.DRAWINGREADY,obj)}}})).skipBubble?(opts.preventsOthers=!0,window.teklaMap.ShowBubble(latlng,this._createAndShowElement(this.EDIT_TEMPLATE,opts),L.Point(0,0))):opts.onSave()},showShort:function(DBIndex,obj,overrideX,overrideY,values,onShow,onClose){if(!this.preventsOthers()&&(!obj||!0!==obj.skipBubble&&obj.Name)&&!$_drawModeOn()){var opts=jQuery.extend({},this.defaultOptions,{obj:obj,dbindex:DBIndex,onShow:onShow,onClose:onClose,editable:!1,visible:null});values&&(opts.values=values),this.shortBubbles.push(this._createAndShowElement(this.SHORT_INFO_TEMPLATE,opts,null,500))}},hideShort:function(){this.cancelCurrentShowTimeout(),jQuery(this.shortBubbles).each((function(){jQuery(this).mapbubble("close")})),this.shortBubbles=[]},show:function(DBIndex,obj,latlng){var self=this,html=null;if(obj){if(!0!==obj.skipBubble){var template=this.INFO_TEMPLATE,opts=jQuery.extend(!0,{},this.defaultOptions,{values:{name:obj.Name,explanation:obj.Explanation,width:obj.Width,url:obj.Url,htmldescription:obj.htmldescription,imageurl:obj.imageurl},presentation:obj.Presentation,autoCommit:!1,autoFocus:!0,mouseClickLatlng:latlng,obj:obj,prestypes:[],dbindex:DBIndex,actions:[]});obj.mapbubble&&obj.mapbubble.visible&&(opts.visible=obj.mapbubble.visible);var showWidth=(obj.Width>0||null===obj.Width)&&"LineString"===obj.get_Type();if(showWidth&&jQuery.isArray(opts.visible)&&opts.visible.push("width"),!0===obj.Editable?(obj.mapbubble&&obj.mapbubble.editable?opts.editable=obj.mapbubble.editable:opts.editable||(opts.editable=!0),showWidth&&jQuery.isArray(opts.editable)&&opts.editable.push("width")):opts.editable=!1,DBIndex===OBJ_SEARCH||DBIndex===OBJ_CATLAYER){if(opts.editable){var type=obj.get_EditType();switch(type){case"ext":template=this.EDIT_EXT_TEMPLATE,opts.editable=!1,opts.onSave=function(values){};break;case"ea":template=this.EDIT_EXTADDR_TEMPLATE,opts.values={streetname:obj.StreetName,addressnumber:obj.AddressNumber},opts.onSave=function(values){obj&&obj.UpdateAddress(obj.__id,values.streetname,values.addressnumber||""),self._clearMapState()},opts.actions.push({name:GetText("cl_move"),action:function(event){moveSite(DBIndex,obj.__id,event)}}),opts.actions.push({name:GetText("cl_delete"),action:function(event){deleteItem(DBIndex,obj.__id,event,!0)}});break;case"eso":template=this.EDIT_EXTSO_TEMPLATE,opts.values={category:obj.CategoryId,name:obj.Name,explanation:obj.Explanation,url:obj.Url,image:obj.Image},opts.onSave=function(values){obj&&obj.UpdateSearchObject(obj.__id,values.category,values.name,values.explanation,values.url,values.image),self._clearMapState()},opts.actions.push({name:GetText("cl_move"),action:function(event){moveSite(DBIndex,obj.__id,event)}}),opts.actions.push({name:GetText("cl_delete"),action:function(event){deleteItem(DBIndex,obj.__id,event,!0)}});break;default:template=this.INFO_TEMPLATE}}jQuery.each(this.getObjectActions(type,DBIndex,obj,opts),(function(){opts.actions.push(this)}))}else DBIndex===OBJ_MYSITES&&opts.editable&&(template=this.EDIT_TEMPLATE,opts.autoCommit=window.options.editBubbleAutoCommit,opts.onSave=function(values){self._updateObjectBasicData(DBIndex,obj,values)},opts.prestypes=[obj.get_Type()],"Point"===obj.get_Type()&&!1!==obj.GeometryEditable&&opts.actions.push({name:GetText("cl_move"),action:function(event){moveSite(DBIndex,obj.__id,event)}}),opts.actions.push({name:GetText("cl_delete"),action:function(event){deleteItem(DBIndex,obj.__id,event,!1)}}));opts.preventsOthers=!0,html=this._createAndShowElement(template,opts,self._getTemplatePrepareFunc(template,opts))}return!0===obj.Editable&&!1!==obj.GeometryEditable&&window.teklaMap._HandleActivate(obj),html}},getObjectActions:function(type,DBIndex,obj,options){var retVal=[],addDefaultActions=!0,self=this;if(DBIndex===OBJ_CATLAYER)addDefaultActions=obj&&"ACP"===obj.get_UrlType();else if(obj.Editable)switch(type){case"ext":retVal.push({name:GetText("apply"),action:function(){window.Tekla.CoordinateTransformation.transform(obj.North,obj.East,(function(data){var returnurl=obj.returnurl;String.IsPrintable(obj.tpid)&&(returnurl=returnurl.replace("{tpid}",obj.tpid)),returnurl=(returnurl=returnurl.replace("{north}",data.north)).replace("{east}",data.east),String.IsPrintable(returnurl)&&(document.location.href=returnurl)}),{targetSystem:obj.Conv})}}),retVal.push({name:GetText("cl_move"),action:function(event){moveSite(DBIndex,obj.__id,event)}}),addDefaultActions=!1;break;case"ea":retVal.push({name:GetText("cl_addAddressLocation"),action:function(event){self.startInsertExternalAddress(obj.Municipality,event)}}),addDefaultActions=!1;break;case"eso":retVal.push({name:GetText("cl_addSearchObject"),action:function(event){self.startInsertExternalSearchObject(obj.Municipality,event)}}),addDefaultActions=!1}return addDefaultActions&&(!0!==this.enableCopyingOfDrawings||obj.Permanent||obj.MyOType||retVal.push({name:GetText("cl_addToOwnObjects"),action:function(){if(obj&&(!0!==$_DBFindObjectByName(MySitesDB,obj.Name)||confirm(GetText("cl_targetWithSameNameExitsI")))){var newObj=MySitesDB.InsertClone(obj,!0);newObj&&(newObj.Editable=!0,newObj.set_Dirty(TXWConst.EDITSTATE_ALL),$_isValidUrl(newObj.Url,!0)||(newObj.Url=null),$_CallEventHandler(tekla.Map.EVENT.DRAWINGREADY,newObj),window.teklaMap._UpdateMapPosition())}}}),Tekla.MapLink&&window.options&&!1!==window.options.showBubbleMapLink&&retVal.push({title:GetText("cl_createMapLinkToTarget"),name:"",cssClass:"icon icon-ims icon-locationlink-small",action:function(){var north,east;if(obj.North&&obj.East)north=obj.North,east=obj.East;else if(obj.PointArray&&obj.PointArray.length>0)north=obj.PointArray[0].south,east=obj.PointArray[0].east;else{var cnt=obj.get_CenterPoint(!1);cnt&&(north=cnt.y,east=cnt.x)}Tekla.MapLink.show(north,east,obj.Name)}})),retVal},preventsOthers:function(){var retVal=!1;return jQuery(this.bubbles).each((function(){!0===jQuery(this).mapbubble("preventsOthers")&&(retVal=!0)})),retVal},hideAll:function(skipAutoCommit,dbindex){var newBubbles=[];jQuery(this.bubbles).each((function(){!dbindex&&0!==dbindex||jQuery(this).mapbubble("getDBindex")===dbindex?jQuery(this).mapbubble("close",!1,skipAutoCommit):newBubbles.push(this)})),this.bubbles=newBubbles,this.shortBubbles=[]},isVisible:function(){var retVal=!1;return jQuery(this.bubbles).each((function(){!0===jQuery(this).mapbubble("isVisible")&&(retVal=!0)})),retVal},_getTemplatePrepareFunc:function(template,opts){if(template===this.EDIT_EXTADDR_TEMPLATE){var mun=opts.obj&&opts.obj.Municipality||opts.municipality;return function(templateElement,readyFunc){function renderListAndReady(){var arr=StreetNameDB.get_StreetNames(mun),selectElem=templateElement.find(".edit-ea-bubble-streetname").empty();if(arr&&arr.length>0){for(var options="",i=0;i<arr.length;i++)options+='<option value="'+arr[i]+'">'+arr[i]+"</option>";selectElem.append(options)}readyFunc()}mun&&(StreetNameDB.ExistMunicipality(mun)?renderListAndReady():StreetNameDB.Load(mun,renderListAndReady))}}return template===this.EDIT_EXTSO_TEMPLATE?function(templateElement,readyFunc){var selectElem=templateElement.find(".eso-bubble-category").empty();if(Tekla.ServiceSearch){var options="";Tekla.ServiceSearch.enumerate((function e(node){node.data.key>3&&(options+='<option value="'+node.data.key+'">'+node.data.title+"</option>")})),selectElem.append(options)}readyFunc()}:null},_clearMapState:function(){clearToolstate(),startPan(),window.teklaMap.RedrawLayersImmediate()},createObject:function(toolMode,name,explanation,url,html,imageurl,currentPresentation,myotype,width,canDelete){var obj=null;if("drawpolygon"===toolMode||"drawpolyline"===toolMode||"createsite"===toolMode||"drawrectangle"===toolMode){if(obj=new SR_Geo(name,explanation),html&&(obj.htmldescription=html),imageurl&&(obj.imageurl=$_tryGetValidUrl(imageurl,!0)),(myotype||""===myotype)&&(obj.MyOType=myotype),canDelete&&obj.setCanDelete(canDelete),url&&(obj.Url=$_tryGetValidUrl(url,!0)),width){var parsedVal=handleWidth(width);obj.Width=parsedVal>0&&!isNaN(parsedVal)?parsedVal:null}else""===width&&(obj.Width=null);obj.set_Dirty(TXWConst.EDITSTATE_ALL);var ptss=mapDrawing.points;if(ptss&&("drawrectangle"===toolMode&&2===ptss.length||"drawpolygon"===toolMode&&ptss.length>2||"drawpolyline"===toolMode&&ptss.length>=2)){var ispolygon="drawpolygon"===toolMode||"drawrectangle"===toolMode,presentation={};currentPresentation&&(presentation.LineColor=currentPresentation.LineColor,presentation.LineWidth=currentPresentation.LineWidth,presentation.LineType=currentPresentation.LineType,presentation.LineOpacity=currentPresentation.LineOpacity,currentPresentation.Image&&(presentation.Image=currentPresentation.Image));var geometry={type:ispolygon?"Polygon":"LineString"};ispolygon?("drawrectangle"===toolMode?(geometry.coordinates=$_ConvertPointsToPolygon([ptss[0],[ptss[0][0],ptss[1][1]],ptss[1],[ptss[1][0],ptss[0][1]]]),obj.IsRectangle=!0):geometry.coordinates=$_ConvertPointsToPolygon(ptss),currentPresentation&&(presentation.FillColor=currentPresentation.FillColor,presentation.FillOpacity=currentPresentation.FillOpacity)):geometry.coordinates=$_ConvertPointsToLineString(ptss),obj.set_Geometry(geometry),obj.set_Presentation(presentation)}else"createsite"===toolMode&&window.teklaMap._selectedPositionSouth&&window.teklaMap._selectedPositionEast?(obj.set_Geometry({type:"Point",coordinates:$_ConvertPointsToPoint(window.teklaMap._selectedPositionSouth,window.teklaMap._selectedPositionEast)}),currentPresentation&&obj.set_Presentation({Image:currentPresentation.Image})):obj=null}return obj},_updateObjectBasicData:function(dbindex,obj,values){if(obj&&values){var hasChanges=!1,refreshObject=!1;!values.name&&""!==values.name||obj.Name===values.name||(obj.Name=values.name,hasChanges=!0);var url=$_tryGetValidUrl(values.url,!0);url!==obj.Url&&(obj.Url=url,hasChanges=!0),!values.explanation&&""!==values.explanation||obj.Explanation===values.explanation||(obj.Explanation=values.explanation,hasChanges=!0),!values.htmldescription&&""!==values.htmldescription||obj.htmldescription===values.htmldescription||(obj.htmldescription=values.htmldescription,hasChanges=!0);var imageurl=$_tryGetValidUrl(values.imageurl,!0);if(imageurl!==obj.imageurl&&(obj.imageurl=imageurl,hasChanges=!0),void 0!==values.width){var width=handleWidth(values.width);width<=0||isNaN(width)&&null!==obj.Width?(obj.Width=null,refreshObject=!0,hasChanges=!0):isNaN(width)||obj.Width===width||(obj.Width=width,hasChanges=!0,refreshObject=!0)}$_CallEventHandler(tekla.Map.EVENT.BUBBLECOMMIT,"change",obj,values)&&(hasChanges=!0),values.presentationHasChanges&&(values.presentation&&(obj.Presentation=jQuery.extend({},obj.Presentation,values.presentation),obj.set_Dirty(TXWConst.EDITSTATE_PRESENTATION),$_DBSetDirty(dbindex,!0),$_CallEventHandler(tekla.Map.EVENT.DRAWINGPRESENTATIONCHANGED,obj)),refreshObject=!0),!0===hasChanges&&(obj.set_Dirty(TXWConst.EDITSTATE_PROPERTIES),$_DBSetDirty(dbindex,!0),$_CallEventHandler(tekla.Map.EVENT.DRAWINGPROPERTIESCHANGED,obj)),!0===refreshObject&&$_refreshObject(dbindex,obj.__id,obj)}},_getPresTypes:function(toolMode){return"drawpolygon"===toolMode||"drawrectangle"===toolMode?["Polygon"]:"drawpolyline"===toolMode?["LineString"]:["Point"]},_createAndShowElement:function(template,options,prepareTemplateFunc,delay){var elem=null,self=this;function show(){self.hideAll(),elem.appendTo(self._parentContainer),elem.mapbubble(options),self.bubbles.push(elem),(!delay||delay<100)&&(delay=100);var prevOnClose=options.onClose;options.onClose=function(){var arr=self.bubbles;self.bubbles=[];for(var i=0;i<arr.length;i++)arr[i]!==elem&&self.bubbles.push(arr[i]);"function"==typeof prevOnClose&&prevOnClose()}}return options.template=template,(elem=(elem=this.TEMPLATES?jQuery(this.TEMPLATES).find(template):jQuery(template)).clone().removeAttr("id")).find("textarea").val(""),$_CallEventHandler(tekla.Map.EVENT.BUBBLECREATE,options),options.customContent&&elem.addClass("custom-content").find(".bubble-content").empty().append(options.customContent),"function"==typeof prepareTemplateFunc?prepareTemplateFunc(elem,show):show(),elem[0]}},jQuery.fn.mapbubble=function(options){if(!("string"==typeof options&&this.length>0))return this.each((function(){jQuery(this).data(name)||jQuery(this).data(name,new MapBubble(this,options))}));var args=arguments,instance=jQuery(this).data(name);return instance&&instance[options]?instance[options].apply(instance,jQuery.makeArray(args).slice(1)):void 0}}(jQuery,window);
function ObjSelectionViewModel(){var container=$("#map-object-selection")[0],selectionArray=null,selectionCb=null,closeAfterSelection=!1,currentHighlight=null,currentHighlightObj=null,self=this;this.objects=ko.observableArray([]),this.additionalObjects=ko.observableArray([]),this.hasAdditionalObjects=ko.computed((function(){return self.additionalObjects().length>0})),this.additionalObjectsLoading=ko.observable(!1),this.setSelection=function(array){self.clearSelection(),selectionArray=array},this.clearSelection=function(){this.clearHighlight(),selectionArray&&selectionArray.forEach((function(p){p.remove()}))},this.select=function(obj){selectionCb&&selectionCb(obj),closeAfterSelection&&self.closeDialog(!0)},this.highlight=function(obj){self.clearHighlight(),"Point"===obj.Geometry.type&&obj.ReferenceId||"GeometryCollection"===obj.Geometry.type&&obj.Geometry.members?.length>0&&"Point"===obj.Geometry.members[0].geometry.type&&obj.ReferenceId?(currentHighlightObj=LayerDB.FindByReferenceId(obj.ReferenceId))&&currentHighlightObj.HighLight(TXWConst.CATEGORY):currentHighlight=window.Tekla.mapObjectSelection.visualizeSelected(obj.Geometry,!1)},this.clearHighlight=function(){currentHighlight&&(currentHighlight.remove(),currentHighlight=null),currentHighlightObj&&(currentHighlightObj.UnhighLight(TXWConst.CATEGORY),currentHighlightObj=null)},this.closeDialog=function(fromSelection){container.style.display="none",selectionCb&&!fromSelection&&selectionCb(),selectionCb=null,self.clearSelection()},this.openDialog=function(callback,autoClose){container.style.display="block",selectionCb=callback,closeAfterSelection=autoClose},this.addAdditionalObject=function(container){self.additionalObjects().some((function(ao){return container.ReferenceId===ao.ReferenceId}))||self.additionalObjects.push(container)},ko.applyBindings(this,container)}function MapObjectSelection(map){var db=window.LayerDB,t=window.turf,self=this,options=new ObjSelectionViewModel,getTwentySidedCoordinates=function(latLong){var locationPix=map.project(latLong);return[[locationPix.x+35,locationPix.y],[locationPix.x+33,locationPix.y-11],[locationPix.x+28,locationPix.y-21],[locationPix.x+21,locationPix.y-28],[locationPix.x+11,locationPix.y-33],[locationPix.x-0,locationPix.y-35],[locationPix.x-11,locationPix.y-33],[locationPix.x-21,locationPix.y-28],[locationPix.x-28,locationPix.y-21],[locationPix.x-33,locationPix.y-11],[locationPix.x-35,locationPix.y],[locationPix.x-33,locationPix.y+11],[locationPix.x-28,locationPix.y+21],[locationPix.x-21,locationPix.y+28],[locationPix.x-11,locationPix.y+33],[locationPix.x,locationPix.y+35],[locationPix.x+11,locationPix.y+33],[locationPix.x+21,locationPix.y+28],[locationPix.x+28,locationPix.y+21],[locationPix.x+33,locationPix.y+11],[locationPix.x+35,locationPix.y]].map((function(ll){var up=map.unproject(ll);return[up.lng,up.lat]}))},getSelectionPolygon=function(latLong){return t.polygon([getTwentySidedCoordinates(latLong).map((function(ll){return[ll[0],ll[1]]}))])},addAndVisualize=function(geom,obj,filter){filter&&!filter(obj)||(self.visualizeSelected(geom,!0),-1===options.objects.indexOf(obj)&&options.objects.push(obj))},handleGeometryObject=function(obj,geom,selectionPoint,selectionPoly,filter){switch(geom.type){case"Polygon":var turfPoly=t.polygon(geom.coordinates);t.booleanPointInPolygon(selectionPoint,turfPoly)?filter&&!filter(obj)||(self.visualizeSelected(geom,!0),-1===options.objects.indexOf(obj)&&options.objects.unshift(obj)):t.booleanDisjoint(selectionPoly,turfPoly)||addAndVisualize(geom,obj,filter);break;case"Point":var point=t.point(geom.coordinates);t.booleanPointInPolygon(point,selectionPoly)&&addAndVisualize(geom,obj,filter);break;case"LineString":var turfLine=t.lineString(geom.coordinates);t.booleanDisjoint(selectionPoly,turfLine)&&!t.booleanContains(selectionPoly,turfLine)||addAndVisualize(geom,obj,filter)}},handleLineObjectSelection=function(obj,geom,selectionLine,selectionPoly1,selectionPoly2,filter){switch(geom.type){case"Polygon":var turfPoly=t.polygon(geom.coordinates);t.booleanDisjoint(selectionLine,turfPoly)&&t.booleanDisjoint(selectionPoly1,turfPoly)&&t.booleanDisjoint(selectionPoly2,turfPoly)||addAndVisualize(geom,obj,filter);break;case"Point":var point=t.point(geom.coordinates);(t.booleanPointOnLine(point,selectionLine)||t.booleanPointInPolygon(point,selectionPoly1)||t.booleanPointInPolygon(point,selectionPoly2))&&addAndVisualize(geom,obj,filter);break;case"LineString":var turfLine=t.lineString(geom.coordinates);t.booleanDisjoint(selectionLine,turfLine)&&t.booleanDisjoint(selectionPoly1,turfLine)&&t.booleanDisjoint(selectionPoly2,turfLine)||addAndVisualize(geom,obj,filter)}},visualizeArray=function(array,autoHide){return array.map((function(obj){return self.visualizeSelected(obj,autoHide)}))};this.visualizeSelected=function(geom,autoHide){var latLngs=[],coordinates=geom.coordinates,mapObj=null;switch(geom.type){case"GeometryCollection":for(var r=0;r<geom.members.length;r++){var sub=geom.members[r];"LineString"===sub.geometry.type&&(sub.geometry.coordinates.forEach((function(lngLat){latLngs.push([lngLat[1],lngLat[0]])})),mapObj=L.polyline(latLngs,{color:"#005f9e"}).addTo(map))}break;case"Polygon":coordinates.forEach((function(poly){poly.forEach((function(lngLat){latLngs.push([lngLat[1],lngLat[0]])}))})),mapObj=L.polygon(latLngs,{color:"#005f9e"}).addTo(map);break;case"Point":mapObj=L.circleMarker([coordinates[1],coordinates[0]],{radius:5,color:"#005f9e"}).addTo(map);break;case"LineString":coordinates.forEach((function(lngLat){latLngs.push([lngLat[1],lngLat[0]])})),mapObj=L.polyline(latLngs,{color:"#005f9e"}).addTo(map)}return mapObj&&autoHide&&setTimeout((function(){mapObj.remove()}),1e3),mapObj},this.selectMapObjects=function(coords,callback,autoClose,filter,additionalObjectsCallback){var selectionArray;options.objects.removeAll(),options.additionalObjects.removeAll(),selectionArray=coords.lat&&coords.lng?function(latLong,filter){var selectionPoint=t.point([latLong.lng,latLong.lat]),selectionPoly=getSelectionPolygon(latLong);return db.GetObjectsWithGeometry().forEach((function(obj){var geom=obj.Geometry;geom.members?geom.members.forEach((function(member){handleGeometryObject(obj,member.geometry||member,selectionPoint,selectionPoly,filter)})):handleGeometryObject(obj,geom,selectionPoint,selectionPoly,filter)})),[selectionPoly.geometry]}(coords,filter):Array.isArray(coords)?function(coordinates,filter){var selectionLine=t.lineString(coordinates),selectionPoly1=getSelectionPolygon({lat:coordinates[0][1],lng:coordinates[0][0]}),selectionPoly2=getSelectionPolygon({lat:coordinates[1][1],lng:coordinates[1][0]});return db.GetObjectsWithGeometry().forEach((function(obj){var geom=obj.Geometry;geom.members?geom.members.forEach((function(member){handleLineObjectSelection(obj,member,selectionLine,selectionPoly1,selectionPoly2,filter)})):handleLineObjectSelection(obj,geom,selectionLine,selectionPoly1,selectionPoly2,filter)})),[selectionLine.geometry,selectionPoly1.geometry,selectionPoly2.geometry]}(coords,filter):[],options.objects().length>0?(additionalObjectsCallback&&additionalObjectsCallback(options),options.setSelection(visualizeArray(selectionArray,!1)),options.openDialog(callback,autoClose)):("function"==typeof DisplayInfo&&DisplayInfo(GetText("noObjectsFound")),visualizeArray(selectionArray,!0),options.closeDialog(!1))}}
!function($,window){window.TGMap||(window.TGMap={});var TGMap=window.TGMap;window.TGMap.METERS2MILES=1609.344,window.TGMap.METERS2FEETS=3.28083989501312,window.TGMap.ScaleBar={_maxlen:120,update:function(wupp,opt){var defWidth,ratio,applyoptions=opt||options,unit="m";if(applyoptions.isLatLon){var cnt=window.teklaMap.getCenter(),p1=meters2LatLon(cnt.lng,cnt.lat),pi180=Math.PI/180,f=Math.cos(p1.lat*pi180);defWidth=wupp*this._maxlen*f,ratio=wupp*f}else defWidth=wupp*this._maxlen,ratio=wupp;applyoptions.isImperialUnits?defWidth>=1609.344?(unit="mi",defWidth/=TGMap.METERS2MILES,ratio/=TGMap.METERS2MILES):(defWidth*=TGMap.METERS2FEETS,unit="ft",ratio*=TGMap.METERS2FEETS):defWidth>1e3&&(unit="km",defWidth/=1e3,ratio/=1e3);var rounded=this.getLength(defWidth),inpixels=rounded/ratio,txt="&nbsp;"+rounded+" "+unit+"&nbsp;";jQuery("#scalebar").width(Math.round(inpixels)),jQuery("#scaletext").html(txt)},getLength:function(max){var dig=parseInt(Math.log(max)/Math.log(10)),pow10=Math.pow(10,dig),first=parseInt(max/pow10);return(first>5?5:first>2?2:1)*pow10}},window.TGMap.Measure={_endPosition:null,_activeInd:null,_pointArray:null,_map:null,init:function(map){this._map=map},count:function(){return this._pointArray?this._pointArray.length:0},lastpoint:function(){return this.count()>0?this._pointArray[this._pointArray.length-1]:null},_markerMove:function(e){TGMap.Measure._endPosition=e},_dragstart:function(e){TGMap.Measure._activeInd=e.target.options.ind},_markerDragEnd:function(){var e=TGMap.Measure._endPosition,ind=TGMap.Measure._activeInd;TGMap.Measure._pointArray[ind]=[e.latlng.lat,e.latlng.lng],TGMap.Measure.updateLines(),e.preventDefault&&e.preventDefault()},formatDistance:function(dis,opt){var ret=dis;return(opt||options).isImperialUnits?dis>16093?(TGMap.METERS2MILES,ret=(dis/TGMap.METERS2MILES).toFixed(1)+" mi"):ret=(dis*TGMap.METERS2FEETS).toFixed()+" ft":ret=dis>1e4?(dis/1e3).toFixed(1)+" km":dis+" m",ret},distanceBetweenPoints:function(n1,e1,n2,e2,fmt,opt){var distance;if((opt||options).isLatLon){var p1=meters2LatLon(e1,n1),p2=meters2LatLon(e2,n2),pi180=Math.PI/180,dLat=(p2.lat-p1.lat)*pi180,dLon=(p2.lon-p1.lon)*pi180,a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(p1.lat*pi180)*Math.cos(p2.lat*pi180)*Math.sin(dLon/2)*Math.sin(dLon/2);distance=6378137*(2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)))}else distance=Math.sqrt(Math.pow(e2-e1,2)+Math.pow(n2-n1,2));return fmt?this.formatDistance(Math.round(distance),opt):Math.round(distance)},_imageUrl:function(){return options.appPath+"/Images/measure-pin.png"},addPoint:function(n,e){null==this._pointArray&&(this._pointArray=[]),this.drawImage(n,e,this._pointArray.length),this._pointArray.push([n,e]),this.updateLines()},drawLineString:function(R){var polyline=L.polyline(this._pointArray,{color:"#005596",weight:4,fill:!1});L_MEASURELAYER.addLayer(polyline)},drawImage:function(n,e,ind){var icon=L.icon({iconUrl:this._imageUrl(),iconAnchor:[distanceStartOffsetX,distanceStartOffsetY]}),draggableMarker=L.marker([n,e],{icon:icon,draggable:!0,ind:ind});TGMap.Measure;draggableMarker.on("dragstart",TGMap.Measure._dragstart),draggableMarker.on("drag",TGMap.Measure._markerMove),draggableMarker.on("dragend",TGMap.Measure._markerDragEnd),L_MEASURELAYER?L_MEASURELAYER.addLayer(draggableMarker):(L_MEASURELAYER=new L.FeatureGroup,L_MEASURELAYER.addLayer(draggableMarker),window.teklaMap.addLayer(L_MEASURELAYER))},drawImages:function(){if(this._pointArray)for(var i=0;i<this._pointArray.length;i++)this.drawImage(this._pointArray[i][0],this._pointArray[i][1],i)},clear:function(){L_MEASURELAYER&&L_MEASURELAYER.clearLayers(),this._pointArray&&(this._pointArray=null)},deleteLines:function(){this._pointArray&&(this._pointArray=null),L_MEASURELAYER&&L_MEASURELAYER.clearLayers(),this.updateMeterDistances()},deleteLastPoint:function(){this._pointArray&&this._pointArray.length>0&&this._pointArray.splice(-1,1),this.updateLines(),setStatus(GetText("cl_lastMeasurePointRemoved"))},updateLines:function(skipimg){this._pointArray&&(L_MEASURELAYER&&L_MEASURELAYER.clearLayers(),this.updateMeterDistances(),skipimg||this.drawImages(),this.drawLineString())},getTotalDistance:function(){var ret=0,arr=this._pointArray;if(arr)for(var i=1;i<arr.length;i++)ret+=TGMap.Measure.distanceBetweenPoints(arr[i][0],arr[i][1],arr[i-1][0],arr[i-1][1]);return ret},updateMeterDistances:function(){var extdiv=jQuery("#mob-total-distance").length>0;if(this._pointArray&&this._pointArray.length>1){new StringBuilder("");for(var distance,istotal=this._pointArray.length>=2,totaldistance=0,i=1;i<this._pointArray.length;i++){var cp=[(this._pointArray[i-1][0]+this._pointArray[i][0])/2,(this._pointArray[i-1][1]+this._pointArray[i][1])/2];distance=TGMap.Measure.distanceBetweenPoints(this._pointArray[i][0],this._pointArray[i][1],this._pointArray[i-1][0],this._pointArray[i-1][1]);var cIcon=new L.DivIcon({className:"measure-stage-container",html:'<div class="measure-stage-text">'+TGMap.Measure.formatDistance(distance)+"</div>",iconSize:[60,18]}),marker=L.marker(cp,{icon:cIcon});if(L_MEASURELAYER.addLayer(marker),totaldistance+=distance,istotal&&i==this._pointArray.length-1)if(extdiv)jQuery("#mob-total-distance").text(TGMap.Measure.formatDistance(totaldistance));else{cp=[this._pointArray[i][0],this._pointArray[i][1]],cIcon=new L.DivIcon({className:"measure-stage-container",html:'<div class="measure-total-text">'+TGMap.Measure.formatDistance(totaldistance)+"</div>",iconSize:[60,18],iconAnchor:[30,34]}),marker=L.marker(cp,{icon:cIcon});L_MEASURELAYER.addLayer(marker)}}}else extdiv&&jQuery("#mob-total-distance").text("")}}}(jQuery,window);
!function($,window){window.Tekla=window.Tekla||{},window.Tekla.MyObjects=window.Tekla.MyObjects||{},window.Tekla.MyObjects.renderMapObjectLI=function(obj,dbname,showTools,texts,overrides){if(!obj||!obj.Name)return null;var name=overrides&&(overrides.Name||""===overrides.Name)?overrides.Name:obj.Name||"",image=overrides&&overrides.Image?overrides.Image:function getMapObjectImage(obj){if(obj.Presentation&&obj.Presentation.Image)return obj.Presentation.Image;if(obj.Image)return obj.Image;var type=obj.get_Type();return"Polygon"===type?__getPolygonImage():"LineString"===type?__getLineImage():__getPinImage()}(obj),explanation=overrides&&(overrides.Explanation||""===overrides.Explanation)?overrides.Explanation:obj.Explanation||"",meas=obj.get_Measures?obj.get_Measures():void 0,li=jQuery('<li> <div class="myobject-img">'+$_dynPointImgOrSpan2(obj.Presentation,image,!0,"Map object icon")+'</div> <div class="myobject-data">  <h4><button type="button">'+String.escapeHTML(name)+"</button></h4> <p>"+(explanation.length>0?String.escapeHTML(explanation,!0):"")+"</p>"+(!0!==showTools?(obj.htmldescription?'<div style="float: clear;">'+obj.htmldescription+"</div>":"")+(obj.imageurl?'<img src="'+obj.imageurl+'" />':""):"")+(meas?(meas.length?"  <p> "+texts.length+": "+TGMap.Measure.formatDistance(meas.length)+"</p>":"")+(meas.area?"  <p> "+texts.area+": "+meas.area+"m<sup>2</sup></p>":""):"")+" </div></li>").click((function(){showDrawing(dbname,obj.__id)})).hover((function(){jQuery(this).addClass("hover")}),(function(){jQuery(this).removeClass("hover")}));if(!1!==showTools||obj.getCanDelete&&obj.getCanDelete()){var toolPanel=jQuery('<div class="myobject-tools"><a class="icon icon-ims icon-close-small" href="#" title="'+texts.deleteObjectTip+'"></a></div>');toolPanel.find("a.icon-close-small").click((function(){return confirm(texts.confirmDeleteObject)&&deleteItem(dbname,obj.__id,window.event,!0,!0),!1})),li.append(toolPanel)}return li}}(jQuery,window);
!function($,window){"use strict";function what(map,latlng){jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+"?Op=areadatacoords&n="+latlng.latlng.lat+"&e="+latlng.latlng.lng+"&id=1",success:function(data){var result=$_EVALJSON(data);if(result){result.coords&&map.SetPosition(result.coords.north,result.coords.east);var html='<div style="padding: 10px"><h4 style="font-size: 1.5em; margin-top: 0px; margin-bottom: 0px">'+GetText("pointedLocInfo")+"</h4><h5>"+GetText("nearestAddress")+"</h5>",na=result.nearestaddress;if(na)if("found"===na.status)(obj=new SR_Geo(na.address,GetText("nearestAddress"))).set_Geometry({type:"Point",coordinates:$_ConvertPointsToPoint(na.coords.north,na.coords.east)}),obj.set_Presentation({Image:options.appPath+"/Images/pointer-blue.png"}),html+='<ul class="search-list"><li class="search-row"><a  onmousedown="searchClick('+OBJ_SEARCH+","+SearchDB.Insert(obj)+');">'+na.address+'<span class="search-category">'+GetText("nearestAddress")+"</span></li></ul>";else"notfound"!==na.status&&"toofar"!==na.status||(html+=GetText("cl_addressNotFound"));if(ad=result.areadivisions){html+="<h5>"+GetText("belongingToAreas")+'</h5><ul class="search-list">';for(var i=0;i<ad.length;i++){var ad;if(!0!==(ad=ad[i]).outside){var obj,fmt=FormatData(ad.name,ad.attributes);(obj=new SR_Geo(ad.name,null)).set_Geometry({type:"Point",coordinates:$_ConvertPointsToPoint(ad.coords.north,ad.coords.east)}),obj.set_Presentation({Image:options.appPath+"/Images/pointer-blue.png"}),obj.set_FmtText(fmt),html+='<li class="search-row"><a  onmousedown="searchClick('+OBJ_SEARCH+","+SearchDB.Insert(obj)+');"><span class="search-category">'+ad.name+"</span>"+fmt+"</li>"}else html+='<li class="search-row"><span class="search-category">'+(ad.name||ad.areaname||"")+'</span><span class="areasearch">'+GetText("cl_positionOutsideOfAnyArea")+"</span></li>"}html+="</ul>"}html+="</div>",Tekla.SideBar&&Tekla.SideBar.opentab("#searchresults"),jQuery("#searchresults").html(html)}}})}function FormatData(areaname,ad){var html="";if(ad)for(var i=0;i<ad.length;i++){var adi=ad[i];if(adi.values)for(var v=0;v<adi.values.length;v++){var val=adi.values[v];html+="<tr>"+(val.e?'<td colspan="2"><a target="areaLink" class="bubblelink" href="'+val.v+'">'+val.e+"</a></td>":"<td>"+adi.key+"</td><td>"+val.v+"</td>")+"</tr>"}else html+="<tr>"+(adi.valueexp?'<td colspan="2"><a target="areaLink" class="bubblelink" href="'+adi.value+'">'+adi.valueexp+"</a></td>":"<td>"+adi.key+"</td><td>"+adi.value+"</td>")+"</tr>"}return'<table class="areasearch">'+html+"</table>"}window.Tekla||(window.Tekla={}),window.Tekla.PopUp={_map:null,_ditems:[],init:function(map,options){this._map=map;var def={what:!1,adddrawings:!1,clearSearch:!1},customItems=options?jQuery.extend(def,options.items||{}):def;map.contextmenu.insertItem({text:GetText("centerMap"),callback:function(e){map.panTo(e.latlng)}},20),window.Tekla.mapObjectSelection&&map.contextmenu.insertItem({text:GetText("selectFromHere"),callback:function(e){openObjectSelectionWithLatLng(e.latlng)}}),customItems.print&&(map.contextmenu.insertItem("-",21),map.contextmenu.insertItem({text:GetText("print"),callback:function(e){window.teklaMap.printPage()}},22)),Tekla.MapLink&&customItems.maplink&&(map.contextmenu.insertItem("-",23),map.contextmenu.insertItem({text:GetText("cl_createMapLinkToTarget"),callback:function(e){Tekla.MapLink.show(e.latlng.lat,e.latlng.lng)}},24)),customItems.what&&(map.contextmenu.insertItem("-",25),map.contextmenu.insertItem({text:GetText("whatIsHere"),callback:function(e){what(map,e)}},26)),customItems.adddrawings&&(map.contextmenu.insertItem("-"),map.contextmenu.insertItem({text:GetText("insertPoint"),callback:function(e){!function _addSite(self,latlng){self._selectedPositionSouth=Math.round(latlng.latlng.lat),self._selectedPositionEast=Math.round(latlng.latlng.lng),Tekla.MapBubble.insert("createsite",latlng.latlng,null)}(map,e)}},27),map.contextmenu.insertItem({text:GetText("drawPolyline"),callback:function(e){createDraw(!1)}},28),map.contextmenu.insertItem({text:GetText("drawPolygon"),callback:function(e){createDraw(!0)}},29),map.contextmenu.insertItem({text:GetText("drawRectangle"),callback:function(e){createDrawRectangle()}},29)),customItems.clearSearch&&(map.contextmenu.insertItem("-",30),map.contextmenu.insertItem({text:GetText("clearVisualizations"),callback:function(e){map._ClearDynContext()}},31));var self=this;this._map.on("contextmenu.beforeshow",(function(){"drawpolyline"===toolMode||"drawpolygon"===toolMode?self._ditems=[self._map.contextmenu.insertItem({text:GetText("cl_endDrawing"),callback:function(e){showSiteProperties(e.latlng)}},0),self._map.contextmenu.insertItem({text:GetText("cl_removeLastPoint"),callback:function(e){removeLastPoint()}},1),self._map.contextmenu.insertItem({text:GetText("removeDrawing"),callback:function(e){deleteDrawing()}},2),self._map.contextmenu.insertItem("-",3)]:"drawrectangle"===toolMode?self._ditems=[self._map.contextmenu.insertItem({text:GetText("cl_endDrawing"),callback:function(e){showSiteProperties(e.latlng)}},0),self._map.contextmenu.insertItem({text:GetText("removeDrawing"),callback:function(e){deleteDrawing()}},1),self._map.contextmenu.insertItem("-",2)]:"distance"===toolMode&&self._ditems.push(self._map.contextmenu.insertItem({text:GetText("endMeasure"),callback:function(e){endMeter()}},0),self._map.contextmenu.insertItem({text:GetText("cl_removeLastPoint"),callback:function(e){TGMap.Measure.deleteLastPoint()}},1),self._map.contextmenu.insertItem({text:GetText("removeDrawing"),callback:function(e){TGMap.Measure.deleteLines()}},2),self._map.contextmenu.insertItem("-",3))})),this._map.on("contextmenu.hide",(function(){if(self._ditems){for(var i=0;i<self._ditems.length;i++)self._map.contextmenu.removeItem(self._ditems[i]);self._ditems.length=0}}))}}}(jQuery,window);
!function($,window){"use strict";var defaultPresentation={LineColor:"#333399",LineType:"solid",LineWidth:4,LineOpacity:.7,FillColor:"#333399",FillOpacity:.75},name="tekla.ims.presentationselector",defaults={leaveTimeout:300,embedded:!1,onPresentationChange:null,presentation:defaultPresentation};function trP2op(val){var ret=1-val/100;return ret<.001?.001:ret>1?1:ret}function op2trP(val){var ret=Math.floor(100*(1-val)+.5);return ret<=.001?0:ret>100?100:ret}function PresentationSelector(element,options){this.element=element,this.options=jQuery.extend({},defaults,options),this._defaults=defaults,this._init()}PresentationSelector.prototype._init=function(){var $p=jQuery(this.element),self=this;jQuery.fn.msDropDown&&($p.find(".point-image").each((function(){jQuery(this).msDropDown({rowHeight:30})})),$p.find(".line-type").each((function(){jQuery(this).msDropDown({rowHeight:50})}))),$p.find(".update-presentation").bind("change.tekla.updatevisual",(function(ev){self.options.onPresentationChange&&self.options.onPresentationChange(ev)})),jQuery.fn.colorPicker&&$p.find(".colorpicker").colorPicker(),this.setPresentation(self.options.presentation),!1===self.options.embedded&&$p.find(".close-element").click((function(){return self.hide(),!1}))},PresentationSelector.prototype.show=function(event){var $p=jQuery(this.element),w=$p.width(),h=$p.height();$p.css("left",event.pageX-w/2).css("top",event.pageY-h-25).show()},PresentationSelector.prototype.hide=function(){jQuery(this.element).hide()},PresentationSelector.prototype.toggle=function(event){jQuery(this.element).is(":visible")?this.hide():this.show(event)},PresentationSelector.prototype.toggleTypes=function(types){var toggleDiv=jQuery(this.element).find(".presentation-mode-toggle");if(toggleDiv.removeClass().attr("class","presentation-mode-toggle"),types)for(var i=0;i<types.length;i++)toggleDiv.addClass(types[i])},PresentationSelector.prototype.getPresentation=function(types){var presentation={};return types&&-1===types.indexOf("Point")||(presentation.Image=jQuery(this.element).find(".point-image").val()),types&&-1===types.indexOf("Polygon")||(presentation.FillColor=jQuery(this.element).find(".fill-color").val(),presentation.FillOpacity=trP2op(jQuery(this.element).find(".fill-transparency").val())),types&&-1===types.indexOf("Polygon")&&-1===types.indexOf("LineString")||(presentation.LineColor=jQuery(this.element).find(".line-color").val(),presentation.LineWidth=jQuery(this.element).find(".line-width").val(),presentation.LineType=jQuery(this.element).find(".line-type").val(),presentation.LineOpacity=trP2op(jQuery(this.element).find(".line-transparency").val())),presentation},PresentationSelector.prototype.setPresentation=function(presentation,changeHandler){var $pres=presentation,$p=jQuery(this.element);this.options.onPresentationChange=null;var pointImage=$pres&&$pres.Image?$pres.Image:defaultPresentation.Image;pointImage&&($p.find(".point-image").val(pointImage),jQuery.fn.msDropDown&&$p.find(".point-image").data("dd").setIndexByValue(pointImage));var lineType=$pres&&$pres.LineType?$pres.LineType:defaultPresentation.LineType;lineType&&($p.find(".line-type").val(lineType),jQuery.fn.msDropDown&&$p.find(".line-type").data("dd").setIndexByValue(lineType)),$p.find(".line-color").val($pres&&$pres.LineColor?$pres.LineColor:defaultPresentation.LineColor),$p.find(".line-color").change(),$p.find(".line-width").val($pres&&$pres.LineWidth?$pres.LineWidth:defaultPresentation.LineWidth),$p.find(".fill-color").val($pres&&$pres.FillColor?$pres.FillColor:defaultPresentation.FillColor),$p.find(".fill-color").change(),$p.find(".fill-transparency").val(op2trP($pres&&$pres.FillOpacity?$pres.FillOpacity:defaultPresentation.FillOpacity)),$p.find(".line-transparency").val(op2trP($pres&&$pres.LineOpacity?$pres.LineOpacity:defaultPresentation.LineOpacity)),changeHandler&&(this.options.onPresentationChange=changeHandler)},jQuery.fn.presentationselector=function(options){var retVal=this.each((function(){if(jQuery.data(this,name)){if("object"==typeof options){var instance=jQuery.data(this,name);instance.options=jQuery.extend({},instance.options,options)}}else jQuery.data(this,name,new PresentationSelector(this,options))}));if("string"==typeof options&&this.length>0){var args=arguments,instance=jQuery.data(this[0],name);if(instance&&instance[options])return instance[options].apply(instance,jQuery.makeArray(args).slice(1))}return retVal}}(jQuery,window);
!function($,window){window.Tekla||(window.Tekla={}),window.Tekla.BaseMaps||(window.Tekla.BaseMaps={_themes:null,_threedbm:null,_active:null,_map:null,_atd:null,activavalidatezoom:function(num){var min=this._active.minZoom,max=this._active.maxZoom;return this._active.scaledMinZoom&&this._active.scaledMinZoom<min&&(min=this._active.scaledMinZoom),this._active.scaledMaxZoom&&this._active.scaledMaxZoom>max&&(max=this._active.scaledMaxZoom),num<min?min:num>max?max:num},activewuppcount:function(){return this._active.maplevels.length},activelastupdate:function(){return this._active.lastupdate?this._active.lastupdate:""},activemaplegendpath:function(){return this._active.maplegendpath},activecopyright:function(){return this._active.copyright?this._active.copyright:""},activeIsThreeD:function(){return this._active==this._atd},active:function(){return this._active},fitToActive:function(){window.teklaMap3&&Tekla.ThreeDMaterial&&this.activeIsThreeD()&&this._atd&&this._atd.materials&&Tekla.ThreeDMaterial.fitToMaterials(this._atd.materials)},activeZoomRange:function(){var min=this._active.minZoom,max=this._active.maxZoom;return this._active.scaledMinZoom&&this._active.scaledMinZoom<min&&(min=this._active.scaledMinZoom),this._active.scaledMaxZoom&&this._active.scaledMaxZoom>max&&(max=this._active.scaledMaxZoom),[min,max]},setOpacityA:function(v){this._active.L_layer&&(this._active.L_layer.setOpacity(v),this._active.opacity=v)},setZIndexA:function(v){var prev=0;return this._active.L_layer&&(this._active.L_layer.setZIndex(v),prev=this._active.zIndex||0,this._active.zIndex=v),prev},setZIndex:function(key,v){var ind=this.findindex(key);ind>0&&(this._themes[ind].L_layer&&this._themes[ind].L_layer.setZIndex(v),this._themes[ind].zIndex=v)},getZIndexA:function(){return this._active.L_layer&&this._active.zIndex||0},init:function(data,active,threedbm,map){if(this._themes=data,this._map=map,this._threedbm=threedbm,this._themes.length>0){for(var i=0;i<this._themes.length;i++){var bm=this._themes[i],uri=(options.tileServer||options.appPath)+"/Tile?basemap={basemap}&x={x}&y={-y}&z={z}";bm.scaledMinZoom||bm.scaledMaxZoom?this._themes[i].L_layer=L.locusTileLayer(uri,{maxZoom:bm.scaledMaxZoom?bm.scaledMaxZoom:bm.maxZoom,minZoom:bm.scaledMinZoom?bm.scaledMinZoom:bm.minZoom,maxNativeZoom:bm.scaledMaxZoom?bm.maxZoom:void 0,minNativeZoom:bm.scaledMinZoom?bm.minZoom:void 0,basemap:bm.name}):this._themes[i].L_layer=L.locusTileLayer(uri,{maxZoom:bm.maxZoom,minZoom:bm.minZoom,basemap:bm.name}),this._themes[i].zIndex=i,this._themes[i].L_layer.setZIndex(i)}active&&this.setbasemap(active)||this.setactive(0)}},setbasemap:function(name){var index=this.findindex(name);return index>=0&&(this.setactive(index),!0)},setactive:function(index){this._active=this._themes[index];for(var i=0;i<this._themes.length;i++)this._themes[i].name!==this._active.name&&this._map.removeLayer(this._themes[i].L_layer);this._active.L_layer.setOpacity(this._active.opacity||1),this._map.addLayer(this._active.L_layer);var zoomNumber=this._map.getZoom(),range=this.activeZoomRange();zoomNumber<range[0]?this._map.setZoom(range[0]):zoomNumber>range[1]&&this._map.setZoom(range[1]),this._map.options.minZoom=range[0],this._map.options.maxZoom=range[1]},setActiveThreeD:function(index){window.teklaMap3&&Tekla.ThreeDMaterial&&(this._atd=this._threedbm[index],this._active=this._atd,this._atd.materials&&Tekla.ThreeDMaterial.setState(this._atd.materials,!0,!0))},findindex:function(name){for(var i=0;i<this._themes.length;i++)if(this._themes[i].name===name)return i;return-1},findIndexType:function(name,thd){var source=thd?this._threedbm:this._themes;if(source)for(var i=0;i<source.length;i++)if(source[i].name===name)return i;return-1},get:function(name){var i=this.findindex(name);return i>=0?this._themes[i]:null},getType:function(name,thd){var i=this.findIndexType(name,thd);return i>=0?thd?this._threedbm[i]:this._themes[i]:null},getall:function(internal){for(var array=[],i=0;i<this._themes.length;i++){var thm=this._themes[i],basemap={name:thm.name,label:thm.label,cssClass:thm.cssClass};!0===internal&&thm.usage&&(basemap.usage=thm.usage),array.push(basemap)}return array},getThreeDAll:function(internal){var array=[];if(this._threedbm)for(var i=0;i<this._threedbm.length;i++){var bm=this._threedbm[i],basemap={name:bm.name,label:bm.label,cssClass:bm.cssClass};array.push(basemap)}return array}}),window.Tekla.Layers||(window.Tekla.Layers={_layers:null,_globallayers:null,_map:null,_filters:{},init:function(data,map){this._layers=data,this._map=map},getFilter:function(name){return name?this._filters[name]:void 0},existgloballayer:function(info){return!!this._globallayers&&this._globallayers.Find(info)},_pushgl:function(info){this._globallayers&&this._globallayers.push(info)},_walkTree2:function(list,removefunc){if(list)for(var i=0;i<list.length;i++)removefunc(list[i])?(list.splice(i,1),i--):this._walkTree2(list[i].children,removefunc)},filterout:function(full,layers){for(var loop=0;loop<4;loop++)this._walkTree2(full,(function(layer){return layer.isFolder?!layer.children||layer.children.length<1||void 0:layers.indexOf(layer.key)<0}));return full},addgloballayer:function(info,update,layermax,visbFilter){var added=!1;return this._globallayers||(this._globallayers=[]),!1===this.existgloballayer(info)&&(this._pushgl(info),layermax&&$_GlobalLayerLevels_Add(info,layermax),visbFilter&&(this._filters[info]=visbFilter),update&&$_updateCategory([{layer:info,info:info}],!0),added=!0),added},addgloballayers:function(infoarray){for(var $_Array=[],i=0;i<infoarray.length;i++){var namekey=infoarray[i];this.addgloballayer(namekey,!1)&&$_Array.push(namekey)}$_Array.length>0&&$_updateCategory($_Array,!0)},removegloballayer:function(namekeystart){if(this._globallayers){for(var i=0;i<this._globallayers.length;){var gli=this._globallayers[i];!namekeystart||gli.startsWith(namekeystart)?($_updateCategory_Cached(gli,!1),$_GlobalLayerLevels_Remove(gli),this._globallayers.remove(gli)):i++}$_updateCategoryMove(!0,!1)}},__getinfo:function(levels){if(levels)for(var i=0;i<levels.length;i++)if(levels[i].isvec)return levels[i].info;return null},find2:function(key){return this.find(this._layers,key)},setOpacity:function(key,v){var layer=this.find(this._layers,key);layer&&!layer.children&&layer.select&&layer.L_layer&&(layer.L_layer.setOpacity(v),layer.opacity=v)},setZIndex:function(key,v){var prev=0,layer=this.find(this._layers,key);return layer&&!layer.children&&(layer.select&&layer.L_layer&&layer.L_layer.setZIndex(v),prev=layer.zIndex||0,layer.zIndex=v),prev},getZIndex:function(key){var layer=this.find(this._layers,key);return layer&&!layer.children&&layer.select&&layer.L_layer&&layer.zIndex||0},_refreshRasterWupp:function(key,wupp){var layer=this.find(this._layers,key);if(layer&&layer.maplevels&&layer.maplevels.length>0){var level=Tekla.Layers.findlevelByLayer(layer,wupp);if(layer&&level&&layer.L_layer){var isOn=this._map.hasLayer(layer.L_layer);level.isrst?isOn||this._map.addLayer(layer.L_layer):isOn&&this._map.removeLayer(layer.L_layer)}}},_refreshlayer:function(layer){var wupp=currentWupp(),level=Tekla.Layers.findlevelByLayer(layer,wupp);if(level){if((layer.isrst||level.isrst)&&!layer.L_layer){var uri=(options.tileServer||options.appPath)+"/Tile/Layer?layer={layer}&x={x}&y={-y}&z={z}";layer.L_layer=layer.scaledMinZoom||layer.scaledMaxZoom?L.locusTileLayer(uri,{maxZoom:layer.scaledMaxZoom?layer.scaledMaxZoom:layer.maxZoom,minZoom:layer.scaledMinZoom?layer.scaledMinZoom:layer.minZoom,maxNativeZoom:layer.scaledMaxZoom?layer.maxZoom:void 0,minNativeZoom:layer.scaledMinZoom?layer.minZoom:void 0,layer:layer.key}):L.locusTileLayer(uri,{maxZoom:layer.maxZoom,minZoom:layer.minZoom,layer:layer.key}),layer.L_layer.setZIndex(layer.order),layer.zIndex=layer.order}level.isrst&&(layer.select?this._map.addLayer(layer.L_layer):layer.L_layer&&this._map.removeLayer(layer.L_layer)),level.isvec&&$_updateCategory([{layer:layer.key}],layer.select)}else{if(layer.isvec)this.__getinfo(layer.maplevels)&&$_updateCategory([{layer:layer.key}],layer.select),LayerDB.AddCategory(layer.key,!1);layer.isrst&&layer.L_layer&&this._map.removeLayer(layer.L_layer)}Tekla.MapLink&&Tekla.MapLink.update()},__enumInfo:function(info,f){if(info)if("string"==typeof info)f(info);else for(var i=0;i<info.length;i++)f(info[i])},__contains:function(info,key){return"string"==typeof info?info===key:info.indexOf(key)>-1},iscategoryselected:function(catname){var found=this._walkTree(this._layers,(function(layer){if(!layer.isFolder&&layer.select){var wupp=currentWupp(),level=Tekla.Layers.findlevelByLayer(layer,wupp);if(level&&level.isvec&&Tekla.Layers.__contains(level.info,catname))return!0}}));return found||this.existgloballayer(catname)},travel:function(isexpand){jQuery("#layerTree").dynatree("getRoot").visit((function(node){node.expand(isexpand)}))},setselected:function(name,select,force){var layer=this.find(this._layers,name);if(layer&&!layer.children&&(force||layer.select!==select)&&(layer.select=select,this._refreshlayer(layer),jQuery("#layerTree").length>0)){Tekla.MapLayers.enableListener(!1);var node=jQuery("#layerTree").dynatree("getTree").getNodeByKey(name);node.data.unselectable&&0==select?(node.data.unselectable=!1,node.select(select),node.data.unselectable=!0):node.select(select),Tekla.MapLayers.enableListener(!0)}},_walkTree:function(list,func){if(list){for(var i=0;i<list.length;i++)if(func(list[i])||this._walkTree(list[i].children,func))return!0;return!1}},getselected:function(istitle,rasteronly){var array=[];return this._walkTree(this._layers,(function(layer){!layer.isFolder&&layer.select&&(!rasteronly||rasteronly&&layer.isrst)&&array.push(istitle?layer.title:layer.key)})),array.length>0?array:null},getselected2:function(istitle,rasteronly){var array=[];return this._walkTree(this._layers,(function(layer){!layer.isFolder&&layer.select&&(!rasteronly||rasteronly&&layer.isrst)&&array.push(layer)})),array.length>0?array:null},_getselectedlayers:function(){var array=[];return this._walkTree(this._layers,(function(layer){!layer.isFolder&&layer.select&&array.push(layer)})),array.length>0?array:null},_getselectedCategoriesOrdered:function(mincnt){var array={},cnt=1;return this._walkTree(this._layers,(function(layer){if(!layer.isFolder&&layer.select){var level=Tekla.Layers.findlevelByLayer(layer,currentWupp());if(level&&level.isvec&&level.info)if("string"==typeof level.info)array[level.info]=cnt++;else{for(var a=0;a<level.info.length;a++)array[level.info]=cnt;cnt++}}})),cnt>mincnt?array:null},applyvector:function(){var selarray=this._getselectedlayers(),wupp=currentWupp(),$_Array=null;if(selarray&&selarray.length>0){for(var i=0;i<selarray.length;i++){var layer=selarray[i];if(layer.isvec){Tekla.Layers.findlevelByLayer(layer,wupp);$_Array||($_Array=[]),$_Array.push({layer:layer.key})}if(layer.isrst){if(!layer.L_layer){var uri=(options.tileServer||options.appPath)+"/Tile/Layer?layer={layer}&x={x}&y={-y}&z={z}";layer.scaledMinZoom||layer.scaledMaxZoom?layer.L_layer=L.locusTileLayer(uri,{maxZoom:layer.scaledMaxZoom?layer.scaledMaxZoom:layer.maxZoom,minZoom:layer.scaledMinZoom?layer.scaledMinZoom:layer.minZoom,maxNativeZoom:layer.scaledMaxZoom?layer.maxZoom:void 0,minNativeZoom:layer.scaledMinZoom?layer.minZoom:void 0,layer:layer.key}):layer.L_layer=L.locusTileLayer(uri,{maxZoom:layer.maxZoom,minZoom:layer.minZoom,layer:layer.key}),layer.L_layer.setZIndex(layer.order)}this._map.addLayer(layer.L_layer)}Tekla.MapLayers._changeCb&&Tekla.MapLayers._changeCb(layer,!0)}$_Array&&$_updateCategory($_Array,!0),window.Tekla.MapLayers.refreshrange()}},getlayertype:function(name){var layer=this.find(this._layers,name);if(!layer||!layer.maplevels)return null;for(var r=!1,v=!1,i=0;i<layer.maplevels;i++){var lvl=layer.maplevels[i];lvl.isrst&&(r=!0),lvl.isvec&&(v=!0)}return{v:v,r:r}},find:function(list,name){if(!list)return null;for(var i=0;i<list.length;i++){if(list[i].key===name)return list[i];if(list[i].children){var ret=this.find(list[i].children,name);if(ret)return ret}}return null},visiblebyinfo:function(name,info,wupp){var layer=this.find(this._layers,name);if(layer&&layer.maplevels)return this.findlevelByLayer(layer,wupp);if(info&&this.existgloballayer(info)){var value=$_GlobalLayerLevels_Find(info);return!(value&&wupp>value)||null}return null},findlevel:function(levels,wupp,minScaled,maxScled){for(var i=0;i<levels.length;i++)if(Math.abs(levels[i].wupp-wupp)<.01)return levels[i];return null},findlevelByLayer:function(layer,wupp){var levels=layer.maplevels;if(!levels||levels.length<1)return null;for(var i=0;i<levels.length;i++)if(Math.abs(levels[i].wupp-wupp)<.01)return levels[i];var crs=this._map.options.crs;if(layer.scaledMinZoom&&crs.zoom2Wupp(layer.scaledMinZoom)>levels[0].wupp)return levels[0];if(layer.scaledMaxZoom&&crs.zoom2Wupp(layer.scaledMaxZoom)<levels[levels.length-1].wupp)return levels[levels.length-1];return null},getLayersForBaseMap:function(){var retVal=[];return function iterateList(list){if(list)for(var i=0;i<list.length;i++)list[i].isFolder||retVal.push({name:list[i].key,label:list[i].title,def:!0===list[i].select}),iterateList(list[i].children)}(this._layers),retVal}}),window.Tekla.ThreeDMapLayers||(window.Tekla.ThreeDMapLayers={_container:null,_changeCb:null,_map:null,_showMetaCb:null,_layers:null,init:function(contselector,treeData,layersOn,changecb,showMetaCb,map){this._container=contselector,this._changeCb=changecb,this._map=map,this._showMetaCb=showMetaCb,this._layers=treeData,jQuery("#"+contselector).dynatree({checkbox:!0,selectMode:3,children:treeData,onSelect:function(select,node){var allMaterials=[];node.data.children&&node.data.children.length>0?Tekla.ThreeDMapLayers._walkChildren(node.data.children,(function(layer){layer.materials&&allMaterials.push.apply(allMaterials,layer.materials),Tekla.ThreeDMapLayers._changeCb&&Tekla.ThreeDMapLayers._changeCb(layer,select),layer.select=select})):node.data.materials&&(allMaterials.push.apply(allMaterials,node.data.materials),node.data.select=select,Tekla.ThreeDMapLayers._changeCb&&Tekla.ThreeDMapLayers._changeCb(node.data,select)),Tekla.ThreeDMaterial.setState(allMaterials,select,!1),Tekla.MapLink&&Tekla.MapLink.update()},onDblClick:function(){return!1},onClick:function(node,event){var tcn=event&&event.target?event.target.className:"";if(tcn&&-1!=tcn.indexOf("metadata")&&Tekla.MapLayers._showMetaCb)return Tekla.MapLayers._showMetaCb(node.data),!1;tcn&&-1!=tcn.indexOf("-title")&&0==node.data.isFolder&&node.toggleSelect()},onRender:function(node,nodeSpan){node.data.unselectable&&0==node.data.isFolder&&jQuery(nodeSpan).addClass("dynatree-node-disabled")},onKeydown:function(node,event){if(32==event.which)return!1},cookieId:"dt3-layers",idPrefix:"dt3-layers-",minExpandLevel:options.layerTreeMinExpandLevel>=1?options.layerTreeMinExpandLevel:8,classNames:{nodeIcon:"",connector:""}})},updatestate:function(){return!0},UpdateLayers:function(){},fitToLayer:function(title){var array=[];return jQuery("#threeDLayerTree").dynatree("getRoot").visit((function(node){var layer=node.data;if(layer.title===title){var allMaterials=[];layer.children&&layer.children.length>0?Tekla.ThreeDMapLayers._walkChildren(layer.children,(function(layer){layer.materials&&allMaterials.push.apply(allMaterials,layer.materials)})):layer.materials&&allMaterials.push.apply(allMaterials,layer.materials),allMaterials.length>0&&Tekla.ThreeDMaterial.fitToMaterials(allMaterials)}})),array.length>0?array:null},_walkChildren:function(list,func){if(list){for(var i=0;i<list.length;i++)if(func(list[i])||this._walkChildren(list[i].children,func))return!0;return!1}},_walkTree:function(list,func){if(list){for(var i=0;i<list.length;i++)if(func(list[i])||this._walkTree(list[i].children,func))return!0;return!1}},_getselectedlayers:function(){var array=[];return this._walkTree(this._layers,(function(layer){layer.select&&array.push(layer)})),array.length>0?array:null},getselected:function(istitle){var array=[];return jQuery("#threeDLayerTree").dynatree("getRoot").visit((function(node){var layer=node.data;layer.select&&array.push(istitle?layer.title:layer.key)})),array.length>0?array:null},applyInitialState:function(){var selarray=this._getselectedlayers();if(selarray&&selarray.length>0){for(var allMaterials=[],i=0;i<selarray.length;i++){var layer=selarray[i];layer.children&&layer.children.length>0?Tekla.ThreeDMapLayers._walkChildren(layer.children,(function(layer){layer.materials&&allMaterials.push.apply(allMaterials,layer.materials),Tekla.ThreeDMapLayers._changeCb&&Tekla.ThreeDMapLayers._changeCb(layer,!0)})):layer.materials&&(allMaterials.push.apply(allMaterials,layer.materials),Tekla.ThreeDMapLayers._changeCb&&Tekla.ThreeDMapLayers._changeCb(layer,!0))}Tekla.ThreeDMaterial.setState(allMaterials,!0,!1)}},travel:function(isexpand){jQuery("#threeDLayerTree").dynatree("getRoot").visit((function(node){node.expand(isexpand)}))},setselected:function(name,select,force){var layer=this.find(this._layers,name);if(layer){if(layer.select=select,jQuery("#threeDLayerTree").length>0){var node=jQuery("#threeDLayerTree").dynatree("getTree").getNodeByKey(name);node.data.unselectable&&0==select?(node.data.unselectable=!1,node.select(select),node.data.unselectable=!0):node.select(select)}Tekla.MapLink&&Tekla.MapLink.update()}},find:function(list,name){if(!list)return null;for(var i=0;i<list.length;i++){if(list[i].key===name)return list[i];if(list[i].children){var ret=this.find(list[i].children,name);if(ret)return ret}}return null}})}(jQuery,window);
!function($,window){window.TGMap||(window.TGMap={}),window.TGMap.geolocation||(window.TGMap.geolocation={_map:null,_statusCB:null,_isWatch:!1,_isSet:!1,_isMapFollow:!1,_ntry:0,_watchId:0,_visual:null,_position:null,reset:function(isw){this._isWatch=isw,this._isSet=!1,this._ntry=0,this._watchId=void 0},GetPosition:function(){return this._position},status:function(status,loc){"function"==typeof this._statusCB&&this._statusCB(status,loc),this._position=loc},_removeVisual:function(){this._visual&&(TGMap.geolocation._map.removeLayer(this._visual),delete this._visual,this._visual=null)},_needMapRefresh:function(data){var bounds=TGMap.geolocation._map.getBounds(),screenWidth=bounds.getEast()-bounds.getWest(),screenHeight=bounds.getNorth()-bounds.getSouth(),point=new L.LatLng(data.north,data.east),center=TGMap.geolocation._map.getCenter();return Math.abs(center.lat-point.lat)>.3*screenHeight||Math.abs(center.lng-point.lng)>.3*screenWidth},_onUserChange:function(e){if(TGMap.geolocation._isMapFollow&&TGMap.geolocation._isSet&&TGMap.geolocation._position){var position=TGMap.geolocation._position;TGMap.geolocation._isMapFollow=!1,TGMap.geolocation.status(null),TGMap.geolocation.status({status:"ok",accuracy:position.accuracy},position)}},onsuccess:function(position){var accuracy=position.coords.accuracy;TGMap.geolocation._map;Tekla.CoordinateTransformation.transform(position.coords.latitude,position.coords.longitude,(function(data){var state=null,loc={};if(data&&data.north&&data.east&&(state={status:"outofbounds",accuracy:accuracy},TGMap.geolocation._removeVisual(),!data.outofbounds)){if((!TGMap.geolocation._isSet||TGMap.geolocation._isMapFollow&&TGMap.geolocation._needMapRefresh(data))&&(TGMap.geolocation._map.setView(new L.LatLng(data.north,data.east),accuracy>5e3?11:accuracy>500?15:accuracy>250?16:accuracy>50?17:19),TGMap.geolocation._map._getIsThreeDMode()&&window.Tekla.ThreeD.setView(data.north,data.east)),accuracy<500){if(TGMap.geolocation._visual&&TGMap.geolocation._map.removeLayer(TGMap.geolocation._visual),accuracy<1){var _visual1=L.circle([data.north,data.east],{fillColor:"#005596",fillOpacity:.2,radius:1}),_visual2=L.circle([data.north,data.east],{fillColor:"#005596",fillOpacity:.5,radius:accuracy});TGMap.geolocation._visual=L.featureGroup([_visual1,_visual2])}else TGMap.geolocation._visual=L.circle([data.north,data.east],{fillColor:"#005596",fillOpacity:.5,radius:accuracy});TGMap.geolocation._visual&&TGMap.geolocation._map.addLayer(TGMap.geolocation._visual),state.status=TGMap.geolocation._isMapFollow?"ok-map-follow":"ok"}else state.status="ok-inaccurate";loc.north=data.north,loc.east=data.east,loc.accuracy=accuracy,TGMap.geolocation._isSet=!0}TGMap.geolocation.status(state,loc)}),{sourceSystem:"EPSG:4326",decimalCount:4})},onerror:function(error){switch(error.code){case error.TIMEOUT:if(0===TGMap.geolocation._ntry){var params={maximumAge:0,timeout:6e4,enableHighAccuracy:!1};TGMap.geolocation._isWatch?(TGMap.geolocation._watchId=navigator.geolocation.watchPosition(TGMap.geolocation.onsuccess,TGMap.geolocation.onerror,params),TGMap.geolocation._isWatch=!1,TGMap.geolocation._isMapFollow=!1):(TGMap.geolocation._ntry+=1,navigator.geolocation.getCurrentPosition(TGMap.geolocation.onsuccess,TGMap.geolocation.onerror,params))}else TGMap.geolocation.status(null);break;case error.PERMISSION_DENIED:case error.POSITION_UNAVAILABLE:case error.UNKNOWN_ERROR:TGMap.geolocation.status(null),TGMap.geolocation._map.Toaster(GetText("geoLocationErrorTip"))}},setstate:function(state,map,statusCB,isWatch){if(this._statusCB=statusCB,this._map=map,isWatch?this._map.on("zoomend dragend",TGMap.geolocation._onUserChange):this._map.off("zoomend dragend",TGMap.geolocation._onUserChange),state)"ok"===state.status&&TGMap.geolocation._isWatch?(TGMap.geolocation._isMapFollow=!0,TGMap.geolocation.status({status:"ok-map-follow",accuracy:TGMap.geolocation._position.accuracy},TGMap.geolocation._position)):(TGMap.geolocation._isWatch&&void 0!==TGMap.geolocation._watchId&&(navigator.geolocation.clearWatch(TGMap.geolocation._watchId),TGMap.geolocation._watchId=void 0),TGMap.geolocation._removeVisual(),TGMap.geolocation.status(null));else if(navigator.geolocation){this.reset(isWatch);var params={maximumAge:0,timeout:6e4,enableHighAccuracy:!0};isWatch?(TGMap.geolocation._watchId=navigator.geolocation.watchPosition(TGMap.geolocation.onsuccess,TGMap.geolocation.onerror,params),TGMap.geolocation._isMapFollow=!0):navigator.geolocation.getCurrentPosition(TGMap.geolocation.onsuccess,TGMap.geolocation.onerror,params)}else TGMap.geolocation.status(null)}})}(jQuery,window);
!function($,window){window.TGMap||(window.TGMap={}),window.TGMap.Style={default:{LineWidth:2,FillOpacity:.7,LineColor:"Red",LineType:"solid",FillColor:"Green",HoverFillColor:"black"},highlight:{LineWidth:2,FillOpacity:.5,LineColor:"Red",LineType:"solid",FillColor:"Red"},hover:{LineWidth:2,FillOpacity:.5,LineColor:"#FFF000",LineType:"solid",FillColor:"#FFF00D"}},window.TGMap.myObjects={knownTypes:{},insert:function(obj,opts){if(obj){var ins=!0;if(opts&&opts.Filter&&("Name"===opts.Filter?1==$_DBFindObjectByName(MySitesDB,obj.Name)&&(ins=confirm(GetText("cl_targetWithSameNameExitsI"))):obj.ReferenceId&&"ReferenceId"===opts.Filter&&!(ins=!MySitesDB.FindByReferenceId(obj.ReferenceId))&&opts.Error&&alert(opts.Error)),Tekla.MyObjects.show(),ins){var newObj=MySitesDB.InsertClone(obj);newObj.DocList=null;var url=newObj.Url;newObj.HLOn&&(newObj.HLOn=!1),$_isValidUrl(url,!0)||(newObj.Url=null),newObj.MyOType&&TGMap.myObjects.knownTypes[newObj.MyOType]&&TGMap.myObjects.knownTypes[newObj.MyOType].onbeforecopy&&TGMap.myObjects.knownTypes[newObj.MyOType].onbeforecopy(newObj),window.teklaMap._UpdateMapPosition(),$_CallEventHandler(tekla.Map.EVENT.DRAWINGREADY,newObj)}}}},window.Tekla||(window.Tekla={}),window.Tekla.MapLayers={_container:null,_timer:null,_changeCb:null,_refreshCb:null,_enableListener:!0,_map:null,_showMetaCb:null,enableListener:function(val){this._enableListener=val},refreshrange:function(){this._refreshCb&&this._refreshCb()},init:function(contselector,treeData,layersOn,changecb,refreshCb,showMetaCb,map){this._container=contselector,this._changeCb=changecb,this._map=map,this._refreshCb=refreshCb,this._showMetaCb=showMetaCb,jQuery("#"+contselector).dynatree({checkbox:!0,selectMode:3,children:treeData,onSelect:function(select,node){Tekla.Layers.setselected(node.data.key,select),Tekla.MapLayers._enableListener&&Tekla.MapLayers._changeCb&&Tekla.MapLayers._changeCb(Tekla.Layers.find2(node.data.key)||node.data,select),Tekla.MapLayers._map.Trigger(tekla.Map.EVENT.LAYERSHOWSTATECHANGED,node.data.key,select)},onDblClick:function(){return!1},onClick:function(node,event){var tcn=event&&event.target?event.target.className:"";if(tcn&&-1!=tcn.indexOf("metadata")&&Tekla.MapLayers._showMetaCb)return Tekla.MapLayers._showMetaCb(node.data),!1;tcn&&-1!=tcn.indexOf("-title")&&0==node.data.isFolder&&node.toggleSelect()},onRender:function(node,nodeSpan){node.data.unselectable&&0==node.data.isFolder&&jQuery(nodeSpan).addClass("dynatree-node-disabled")},onKeydown:function(node,event){if(32==event.which)return!1},cookieId:"dt-layers",idPrefix:"dt-layers-",minExpandLevel:options.layerTreeMinExpandLevel>=1?options.layerTreeMinExpandLevel:8,classNames:{nodeIcon:"",connector:""}})},updatestate:function(node){return!0},UpdateLayers:function(){},queue:function(){this.clearqueue(),this._timer=setTimeout("Tekla.MapLayers.UpdateLayers();",500)},clearqueue:function(){this._timer&&clearTimeout(this._timer),this._timer=null},update:function(){if(Tekla.MapLayers._container){var rootNode=jQuery("#"+Tekla.MapLayers._container).dynatree("getRoot");try{var needRender=!1,zoomNumber=Tekla.MapLayers._map.getZoom(),wupp=currentWupp();rootNode.visit((function(node){if(!node.data.isFolder){var minZoom=node.data.scaledMinZoom||node.data.minZoom,maxZoom=node.data.scaledMaxZoom||node.data.maxZoom,unselectable=!(zoomNumber>=minZoom&&zoomNumber<=maxZoom);unselectable!=node.data.unselectable&&(node.data.unselectable=unselectable,needRender=!0),node.isSelected()&&!isNaN(wupp)&&Tekla.Layers._refreshRasterWupp(node.data.key,wupp)}return!0}),!1),needRender&&rootNode.render()}catch(e){console.log(e)}}this._refreshCb&&this._refreshCb()},visibleLayers:function(){if(Tekla.MapLayers._container){var layers=[],rootNode=jQuery("#"+Tekla.MapLayers._container).dynatree("getRoot");try{rootNode.visit((function(node){return!node.data.isFolder&&node.isSelected()&&layers.push(node.data.key),!0}),!1)}catch(e){console.log(e)}return layers}}}}(jQuery,window);

var options;!function($,window){var document=window.document;window.GetText=function(key){return options.texts[key]||""},window.tekla=window.tekla||{};var tekla=null;(tekla=window.tekla=window.tekla||{}).MapQuery=function(){this.options=window.tekla.Map.defaultOptions},tekla.MapQuery.prototype.getLayersForBaseMap=function(baseMapName){var retVal=[];return function iterateList(list){if(list)for(var i=0;i<list.length;i++)list[i].isFolder||retVal.push({name:list[i].key,label:list[i].title,def:!0===list[i].select}),iterateList(list[i].children)}(this.options.mapData.layers),retVal},tekla.MapQuery.prototype.getThreeDLayersForBaseMap=function(){var retVal=[];return function iterateList(list){if(list)for(var i=0;i<list.length;i++)list[i].isFolder||retVal.push({name:list[i].key,label:list[i].title,def:!0===list[i].select}),iterateList(list[i].children)}(this.options.mapData.threedlayers),retVal},tekla.MapQuery.prototype.GetBaseMaps=function(threeed){if(this.options){var source=threeed?this.options.mapData.threedbasemaps:this.options.mapData.basemaps;if(source){for(var layers=threeed?this.getThreeDLayersForBaseMap():this.getLayersForBaseMap(),array=[],i=0;i<source.length;i++){var bm=source[i],basemap={name:bm.name,label:bm.label,cssClass:bm.cssClass,Layers:layers};array.push(basemap)}return array}}return null},tekla.Map=L.Map.extend({initialize:function(container,opts){var o;this.options=this.options||{},this.isInited=!1,this.eventHandlers=[],(L.Browser.ie||L.Browser.edge)&&opts&&opts.NoExt?(this.options=opts,options=opts,o=opts):(o=jQuery.extend(!0,this.options,tekla.Map.defaultOptions,opts),this.options=o,options=o),window.Tekla.MapBubble&&(window.Tekla.MapBubble.defaultOptions=jQuery.extend(window.Tekla.MapBubble.defaultOptions||{},o.drawings||{}),window.Tekla.MapBubble._parentContainer=document.getElementById(container)),this.bmHandler=new BaseMapHandler(this),o.templates&&window.Tekla&&window.Tekla.MapBubble&&(window.Tekla.MapBubble.TEMPLATES=jQuery(o.templates)),this.md=document.getElementById(container),this.md&&(this.md.className&&this.md.className.length>0&&(this.md.className+=" "),this.md.className+="tekla-map",o.cssScope&&(this.m.className+=" "+o.cssScope));var tooltipdiv=document.createElement("div");tooltipdiv.id="tooltipdiv",tooltipdiv.className="map-tooltip",tooltipdiv.style.position="absolute",tooltipdiv.style.left="300px",tooltipdiv.style.top="500px",tooltipdiv.style.width="100px",tooltipdiv.style.display="none",tooltipdiv.style.backgroundColor="#FFFFFF",tooltipdiv.style.zIndex="7000",this.md.appendChild(tooltipdiv);var self=this;if($_EventHandler=function(){return self.Trigger.apply(self,arguments)},jQuery(this.md).append('<span class="icon-ims-hover" style="width:0px;height:0px;position:absolute;right:0px;bottom:0px"></span>'),this.options.zoomControl=!1,this.options.attributionControl=!1,this.options.contextmenu=!0,this.options.contextmenuWidth=160,this.options.preferCanvas=!0,this.options.crs=L.CRS.Locus,this.options.trackResize=!0,this.options.zoomAnimation=!0,this.options.zoomAnimationThreshold=4,this.options.snapZoom=1,this.options.zoomSnap=1,this.options.closePopupOnClick=!0,L.Map.prototype.initialize.call(this,container,this.options),window.map=this,window.teklaMap=this,this.options.initMapObjectSelection){if(o.selectionTemplate)try{var sel=jQuery(o.selectionTemplate);this.md.appendChild(sel[0])}catch(e){}window.Tekla.mapObjectSelection=new MapObjectSelection(this)}opts&&opts.NoExt||(Tekla.ThreeD&&Tekla.ThreeD.init(options.appPath,options.appTexts,options.pointBudget),Tekla.BaseMaps.init(options.mapData.basemaps,options.baseMap,window.teklaMap3?options.mapData.threedbasemaps:[],this),Tekla.Layers.init(options.mapData.layers,this),Tekla.ThreeDMaterial&&Tekla.ThreeDMaterial.init(options.mapData.threedmaterials)),TGMap&&TGMap.Measure&&TGMap.Measure.init(this),this.MoveListenerArray=[],this._ActiveHandleId=null,options.nodefaultcopyright||this.AddControl({copyright:!0}),this.Trigger(tekla.Map.EVENT.BASEMAPCHANGED)}}),tekla.Map.prototype._PrepareBubble=function(dbi,obj,latlng){return obj.oninfo&&!0!==obj.oninfo()?null:Tekla.MapBubble.show(dbi,obj,latlng)},tekla.Map.prototype.ShowBubble=function(latlng,content,offset){var self=this;jQuery(content).css("display","none"),setTimeout((function(){self._ShowBubble(latlng,content,offset)}),100)},tekla.Map.prototype._ShowBubble=function(latlng,content,offset){var maxHeight;jQuery(content).css("display","block");var cnt=0;jQuery(content).find(".tabContents").each((function(){var h=jQuery(this).height();(!maxHeight||h>maxHeight)&&(maxHeight=h),cnt++})),cnt>1&&maxHeight>80&&maxHeight<300&&(maxHeight+=10,jQuery(content).find(".tabDetails").css("minHeight",maxHeight+"px")),window.Tekla.MapBubble&&(window.Tekla.MapBubble._mouseClickLatlng=latlng);L.popup({closeButton:"",offset:offset||new L.Point(-3,-26)}).setLatLng(latlng).setContent(content).openOn(this);if("undefined"!=typeof tinymce){var ta=jQuery(content).find("[name='htmldescription']");if(ta&&ta.length>0){var id=ta.attr("id");tinymce.EditorManager.execCommand("mceFocus",!0,id),tinymce.EditorManager.execCommand("mceRemoveEditor",!1,id),tinymce.EditorManager.execCommand("mceAddEditor",!0,{id:id,options:{language:options.lang,menubar:"edit insert view format",plugins:["advlist","autolink","lists","link","image","charmap","anchor","visualblocks","code","table"],statusbar:!1,toolbar:!1,promotion:!1,height:250}})}}},tekla.Map.prototype._AttachControl=function(control){var tmp=document.getElementById("mapWrapper");tmp?tmp.appendChild(control):this.md.appendChild(control)},tekla.Map.prototype.AddMapMoveListener=function(listener){0==this.MoveListenerArray.Find(listener)&&this.MoveListenerArray.push(listener)},tekla.Map.prototype.RemoveMapMoveListener=function(listener){this.MoveListenerArray.remove(listener)},tekla.Map.prototype.HandleMapMove=function(event){for(var l=this.MoveListenerArray.length,i=0;i<l;i++)this.MoveListenerArray[i]&&this.MoveListenerArray[i](event)},tekla.Map.prototype._HandleRemove=function(){this._ActiveHandleId&&(this._ActiveHandleId=null,this._HandleRemoveAll())},tekla.Map.prototype._HandleRemoveIf=function(id){this._ActiveHandleId==id&&this._HandleRemoveAll()},tekla.Map.prototype._HandleGetActive=function(){return this._ActiveHandleId},tekla.Map.prototype._HandleActivate=function(obj){this._ActiveHandleId!=obj.__id?(_resetHilighted(),this._HandleRemoveAll()):_resetHilighted(),L_HANDLESLAYER&&(L_HANDLESLAYER.clearLayers(),this.hasLayer(L_HANDLESLAYER)&&this.removeLayer(L_HANDLESLAYER)),L_HANDLESLAYER=new L.FeatureGroup,L_drawHandles(L_HANDLESLAYER,obj,!0),this.addLayer(L_HANDLESLAYER),this._ActiveHandleId=obj.__id},tekla.Map.prototype._HandleRemoveAll=function(){L_HANDLESLAYER&&L_HANDLESLAYER.clearLayers(),this._ActiveHandleId=void 0},tekla.Map.prototype._UserPositionHideDelayed=function(delay){if(!options.userPositionKeep){setTimeout(this._UserPositionDelete,delay||$_UserPositionTimeOut)}},tekla.Map.prototype._UserPositionDelete=function(){L_USERPOSITIONLAYER&&(this.removeLayer(L_USERPOSITIONLAYER),L_USERPOSITIONLAYER=null),this._selectedPositionSouth=null,this._selectedPositionEast=null,startPan()},tekla.Map.prototype._UserPositionShow=function(north,east){L_USERPOSITIONLAYER&&this.removeLayer(L_USERPOSITIONLAYER);var icon=L.icon({iconUrl:options.appPath+"/images/selectpoint.gif",iconAnchor:[14,32]});L_USERPOSITIONLAYER=L.marker([north,east],{icon:icon}),this.addLayer(L_USERPOSITIONLAYER),this._selectedPositionSouth=north,this._selectedPositionEast=east},tekla.Map.prototype._UserPositionGet=function(){return[this._selectedPositionSouth,this._selectedPositionEast]},tekla.Map.prototype._MapObjectPositionDelete=function(){L_MAPOBJECTPOSITIONLAYER&&(this.removeLayer(L_MAPOBJECTPOSITIONLAYER),L_MAPOBJECTPOSITIONLAYER=null),startPan()},tekla.Map.prototype._MapObjectPositionShow=function(north,east){L_MAPOBJECTPOSITIONLAYER&&this.removeLayer(L_MAPOBJECTPOSITIONLAYER);var icon=new L.DivIcon({zIndexOffset:100,className:"fu-mapobject-position-container",html:'<div class="fu-mapobject-position-cursor">&#x271B;</div>',iconSize:[100,100],iconAnchor:[52,52]});L_MAPOBJECTPOSITIONLAYER=L.marker([north,east],{icon:icon,zIndexOffset:50}),this.addLayer(L_MAPOBJECTPOSITIONLAYER)},tekla.Map.prototype._ClearDynContext=function(){clearToolstate(),this._ClearVisualizations(!0),jQuery(".pane").hide(),jQuery(".searchboxinput").val(""),window.Tekla.MobileClear&&window.Tekla.MobileClear(),startPan()},tekla.Map.prototype._ClearVisualizations=function(meter){hideInfo(),this.BeginGuiTrans(),meter&&(TGMap.Measure.deleteLines(),deleteDrawing()),SearchDB.Clear(),this._UserPositionDelete(),this.NeedLayerRedraw(),this.EndGuiTrans()},tekla.Map.prototype._UpdateScale=function(){TGMap.ScaleBar.update(currentWupp())},tekla.Map.prototype._GetAreaString=function(){var bounds=this.getBounds();return"&south="+bounds.getSouth()+"&west="+bounds.getWest()+"&north="+bounds.getNorth()+"&east="+bounds.getEast()},tekla.Map.prototype._FitBounds=function(bounds){if(this._getIsThreeDMode()){var northmin=bounds[0][0],eastmin=bounds[0][1],northmax=bounds[1][0],eastmax=bounds[1][1],east=Math.round(eastmax+eastmin)/2,north=Math.round(northmax+northmin)/2;window.Tekla.ThreeD.setView(north,east)}Tekla.SideBar&&Tekla.SideBar.isVisible()?this.fitBounds(bounds,{paddingTopLeft:[400,0]}):this.fitBounds(bounds)},tekla.Map.prototype._UpdateMapPosition=function(queryserver){this.BeginGuiTrans(this._GetSelectedRefIds()),this._UpdateScale(),queryserver&&$_queryOnMouseup(),this.NeedLayerRedraw(),this.EndGuiTrans()},tekla.Map.prototype._setThreeDMode=function(threed){if(threed)$("#webglViewerWrapper").show(),$("#lmapcontainer").hide(),$("#mapcontainer").hide(),jQuery("body").addClass("threed").removeClass("twod"),jQuery(window).trigger("resize");else{$("#lmapcontainer").show(),$("#mapcontainer").show(),jQuery("body").addClass("twod").removeClass("threed");var self=window.teklaMap;L.Util.requestAnimFrame(self.invalidateSize,self,!1,self._container)}},tekla.Map.prototype._getIsThreeDMode=function(){return jQuery("body").hasClass("threed")},tekla.Map.prototype._RefreshObject=function(DBindex,Id,obj,cb){return $_refreshObject(DBindex,Id,obj,cb)},tekla.Map.prototype._UnselectAll=function(dbi){var LR=dbi===OBJ_MYSITES?L_MYSITESLAYER:L_CATLAYER;if(LR)for(var o in LR._layers){var layer=LR._layers[o];layer&&layer.options.isselected&&(layer.options.isselected=!1,layer._icon?jQuery(layer._icon).removeClass("map-selected"):layer instanceof SVGMarker?layer.redraw():__setStyleUnselected(layer))}this.__selectedRefIds=null},tekla.Map.prototype._SetSelectMode=function(v,a,dbi){this.__isSelectMode=v,this.__allowSelection=a,v||this._UnselectAll(dbi)},tekla.Map.prototype._GetSelectedObjects=function(){if(!this.__isSelectMode&&!this.__allowSelection)return null;var ret=[],LR=this.__allowSelection?L_MYSITESLAYER:L_CATLAYER;if(LR)for(var o in LR._layers){var layer=LR._layers[o];if(layer&&layer.options.isselected){var obj=layer.options.obj;obj&&(obj.CustomSelectable||obj.CustomClass)&&ret.push(layer.options.obj)}}return ret},tekla.Map.prototype._GetSelectedRefIds=function(){var sel=this._GetSelectedObjects(),ret={};if(sel&&sel.length>0)for(var i=0;i<sel.length;i++){var rid=sel[i].ReferenceId;ret[rid]=rid}return ret},tekla.Map.prototype.GetActiveThemeName=function(){var t=Tekla.BaseMaps.active();return t?t.name:""},tekla.Map.prototype._HideToaster=function(){jQuery(".toaster-container").hide(),this._toasttimeout&&(clearTimeout(this._toasttimeout),this._toasttimeout=null)},tekla.Map.prototype.Toaster=function(text){var dest=jQuery(".toaster-container .toaster-text");if(dest&&dest.length>0){dest.html(text),jQuery(".toaster-container").show();this._toasttimeout&&(clearTimeout(this._toasttimeout),this._toasttimeout=null),this._toasttimeout=setTimeout(this._HideToaster,5e3)}else alert(text)},tekla.Map.prototype.BeginGuiTrans=function(sel){this._needRedraw=!1,null!=sel&&(this.__selectedRefIds=sel)},tekla.Map.prototype.NeedLayerRedraw=function(){this._needRedraw=!0},tekla.Map.prototype.RedrawLayersImmediate=function(){L.Util.cancelAnimFrame(this._layerRedrawRequest),this._layerRedrawRequest=L.Util.requestAnimFrame((function(){$_internalUpdateDatabaseTypes()}),this),this._needRedraw=!1},tekla.Map.prototype.EndGuiTrans=function(force){this._needRedraw&&this.RedrawLayersImmediate()},tekla.Map.prototype.RedrawLayers=function(sel){this.BeginGuiTrans(sel),this._needRedraw=!0,this.EndGuiTrans()},tekla.Map.APIVERSION="2.0.0",tekla.Map.EVENT={NEARESTADDRESS:"nearestAddress",SEARCHREADY:"searchReady",ZOOMINGTOOBJECT:"zoomingToObject",BUBBLECREATE:"bubbleCreate",BUBBLECOMMIT:"bubbleCommit",SHOWPROPERTIES:"showProperties",LOADSTARTED:"loadStarted",LOADREADY:"loadReady",DRAWINGALL:"drawingAll",DRAWINGGEOMETRYCHANGED:"drawingGeometryChanged",DRAWINGPROPERTIESCHANGED:"drawingPropertiesChanged",DRAWINGPRESENTATIONCHANGED:"drawingPresentationChanged",DRAWINGDELETED:"drawingDeleted",DRAWINGREADY:"drawingReady",DRAWINGPRESENTATION:"drawingPresentation",BASEMAPCHANGED:"basemapChanged",MAPSIZEMAXIMIZED:"mapsizemaximized",MAPSIZERESTORED:"mapsizerestored",VIEWPORTCHANGED:"viewchanged",EXTERNALDELETEREQUESTED:"externaldeleterequested",SELECTIONCHANGED:"SelectionChanged",INITED:"inited",POINTCLOUDADDED:"pointcloudadded",LAYERSHOWSTATECHANGED:"LayerShowStateChanged",ALL:"all"},tekla.Map.prototype.GetBaseMaps=function(){var retVal=Tekla.BaseMaps.getall();if(retVal&&retVal.length>0)for(var i=0;i<retVal.length;i++)retVal[i].Layers=Tekla.Layers.getLayersForBaseMap(retVal[i].name);return retVal},tekla.Map.prototype.GetBaseMap=function(){var t=Tekla.BaseMaps.active();return t?t.name:""},tekla.Map.prototype.CurrentLayer=function(){var t=Tekla.BaseMaps.active();return t?t.name:""},tekla.Map.prototype.CurrentLayerScript=function(){return $_generateLayerOnOff()},tekla.Map.prototype.GetNamedAreas=function(){return this.options.mapData.namedAreas},tekla.Map.prototype.AddNamedAreaMenu=function(selector){var $sel=jQuery("#"+selector).empty(),self=this,arr=self.GetNamedAreas(),hash=[];arr&&arr.length>0?(jQuery(arr).each((function(indx){var option=jQuery('<option value="'+this.name+'">'+this.label+"</option>");this.north&&this.east&&this.south&&this.west||(option.prop("disabled",!0),0===indx&&option.prop("selected",!0)),$sel.append(option),hash[this.name]=this})),$sel.change((function(){var opt=hash[jQuery(this).val()];jQuery(this).find("option").eq(0).prop("selected",!0),opt&&opt.north&&opt.east&&opt.south&&opt.west&&self.SetArea(opt.north,opt.east,opt.south,opt.west)}))):$sel.hide()},tekla.Map.defaultOptions={lang:"fi",appPath:"",baseURL:"",naviMap:"",pinOffsetN:32,pinOffsetE:14,zoomMarginal:0,userPositionKeep:!0,movehandlerUseTimer:!0,movehandlerTimerInterval:300,maxPointEditablePointCount:100,tileServerUrls:null,disableMyObjects:!1,editBubbleAutoCommit:!1,mailtoUseWindowOpen:!1,panTreshold:.15,showImageForPolygon:!0,showBubbleInExactSearch:!0,showOpenInNewWindow:!1,emailUsingWindowOpen:!1,shareOnFacebookURI:"https://www.facebook.com/sharer/sharer.php?u={url}",shareOnTwitterURI:"https://twitter.com/intent/tweet?url={url}&text={name}",handleColor:"blue",handleInsertColor:"gray",wheelTimeOut:400,serviceSearchOpenExpanded:!0,distanceUnit:"m",enableCopyingOfDrawings:!1,layerTreeMinExpandLevel:5,isLatLon:!1,isImperialUnits:!1,clusterPolyobjects:!0,istouch:!1,mySitesClustered:!1,getCurrentPresentation:null,_getCurrentPresentation:function(){return"function"==typeof this.getCurrentPresentation?this.getCurrentPresentation():null},mapControls:null,drawings:null,tileSize:256,tileOrigin:null,texts:{},mapData:{settings:{SVGRMin:2,SVGRMax:512,CatLayerMax:512,ClusteringLevelMin:8}}},tekla.Map.prototype.ensureInit=function(updateMapPosition,queryserver){this.isInited||(this.init(),this.isInited=!0),updateMapPosition&&window.teklaMap._UpdateMapPosition(queryserver)},tekla.Map.prototype.setViewCoordinates=function(center,zoomNumber,options){this.setView(center,zoomNumber,options),window.teklaMap3&&Tekla.ThreeD&&Tekla.ThreeD.setView(center[0],center[1])},tekla.Map.prototype.setBoundsCoordinates=function(bounds,options){if(this.fitBounds(bounds,options),window.teklaMap3&&Tekla.ThreeD){var n=bounds[1][0],e=bounds[1][1],s=bounds[0][0],w=bounds[0][1];Tekla.ThreeD.setView(s+(n-s)/2,w+(e-w)/2)}},tekla.Map.prototype.initCommon=function(){var o=this.options;if(options.center){var cntr=options.center;if(3===cntr.length)this.setView([cntr[0]||0,cntr[1]||0],this.options.crs.wupp2Zoom(cntr[2]),{animate:!1,animation:!1});else if(4===cntr.length){var n=Math.max(cntr[2],cntr[0]),e=Math.max(cntr[3],cntr[1]),s=Math.min(cntr[2],cntr[0]),w=Math.min(cntr[3],cntr[1]);this.setBoundsCoordinates([[s,w],[n,e]],{animate:!1})}}else if(options.wupp>=0)this.setViewCoordinates([options.centerN||0,options.centerE||0],this.options.crs.wupp2Zoom(options.wupp),{animate:!1,animation:!1});else{var width=options.width>=0?options.width:100,height=options.height>=0?options.height:100;if(!isNaN(options.centerN)&&!isNaN(options.centerE)){var cnt=[options.centerN||0,options.centerE||0];this.setBoundsCoordinates([[cnt[0]-height/2,cnt[1]-width/2],[cnt[0]+height/2,cnt[1]+width/2]],{animate:!1})}}this.bmHandler.SetBaseMap(options.baseMap),$_setZoomScalePosition(),this._UpdateScale(),Tekla.MapLayers&&Tekla.MapLayers.update(),this.on("zoomend",(function(){if(window.teklaMap._UpdateMapPosition(!0),Tekla.MapLink){var center=window.teklaMap.GetCenter();Tekla.MapLink.update(center[0],center[1])}Tekla.MapLayers.update()})),this.on("move",(function(){this.HandleMapMove(e)})),this.on("moveend",(function(){if(window.teklaMap._UpdateMapPosition(!0),this.HandleMapMove(e),Tekla.MapLink){var center=window.teklaMap.GetCenter();Tekla.MapLink.update(center[0],center[1])}})),this.on("mousemove",(function(e){this.HandleMapMove(e)})),mapDrawing={},o.enableCopyingOfDrawings&&this.EnableCopyingOfDrawing(),startPan(),$_showCoordinates_enable(),function preloadImages(){!function preloadImage(){var d=document;if(d.images){d.MM_p||(d.MM_p=[]);var i,j=d.MM_p.length,a=arguments;for(i=0;i<a.length;i++)0!==a[i].indexOf("#")&&(d.MM_p[j]=new Image,d.MM_p[j++].src=a[i])}}(options.appPath+"/Images/b.gif",options.appPath+"/Images/b2.gif",__getPinImage(),options.appPath+"/Images/empty.gif",__getPolygonImage(),__getLineImage(),options.appPath+"/Content/images/geoloc-loader.gif")}(),this.SetNearestAddressForDrawings(!0===o.nearestaddress),o.mapControls&&this.AddControl(o.mapControls);var _self=this;jQuery(".toaster-text").click((function(){_self._HideToaster()}))},tekla.Map.prototype.init=function(){var i,o=this.options;if(o.linkresult&&o.linkresult.setarea&&o.linkresult.mnorth&&(o.centerN=o.linkresult.mnorth,o.centerE=o.linkresult.meast,o.linkresult.width&&(o.width=o.linkresult.width,o.height=o.linkresult.height)),$_coordinatesInit(this.options.mapData.settings.CoordDef,this.options.mapData.settings.CoordDistKey,this.options.mapData.settings.CoordStatusKey),this.initCommon(),this.options.linkresult){if(linkresult=this.options.linkresult,linkresult.onlayers)for(i=0;i<linkresult.onlayers.length;i++)Tekla.Layers.setselected(linkresult.onlayers[i],!0);if(linkresult.offlayers)for(i=0;i<linkresult.offlayers.length;i++)Tekla.Layers.setselected(linkresult.onlayers[i],!1)}if(linkresult){if(linkresult.query){var qt=linkresult.query.type;if("address"==qt||"all"==qt||"linksearch"==qt||"cat"==qt)if("undefined"!=typeof angular){Tekla.SideBar.opentab("resulttab");var model=$_layerDisplayResults(SearchDB,linkresult,LIST_CB),scope=angular.element(jQuery("#pane-search")).scope();scope&&scope.$evalAsync((function(){scope.refresh(model),jQuery("#pane-search").show()}))}else $_layerDisplayResults(SearchDB,linkresult,LIST_NO);else"link"==linkresult.query.type?linkresult.results&&$_layerDisplayResults(SearchDB,linkresult,LIST_NO,"decode"):"searchengine"==linkresult.query.type?($_displaySeResults(linkresult),freeSiteSearchLink(linkresult)):"feedbackcollection"==linkresult.query.type?linkresult.results&&$_layerDisplayResults(SearchDB,linkresult,LIST_COLLECTION):"getlocation"==linkresult.query.type?$_GetLocation(linkresult):"esite"==linkresult.query.type&&$_eSiteLink(linkresult)}if(linkresult.formactions)for(var a=0;a<linkresult.formactions.length;a++)"feedback"==linkresult.formactions[a].type?$_linkShowFeedback(linkresult.formactions[a]):"areasearch"==linkresult.formactions[a].type&&$_linkShowAreaSearch(linkresult.formactions[a])}L.DomEvent&&jQuery(".disable-map-events").each((function(){var div=jQuery(this)[0];div&&L.DomEvent.disableClickPropagation(div)})),this.Trigger(tekla.Map.EVENT.INITED)};var maxStyles={height:"100%","max-height":"1800px",position:"absolute",width:"100%",float:"none","margin-left":"0px","margin-right":"0px","margin-top":"0px","margin-bottom":"0px"};function createFeatureTypeKey(options){var retVal=null;if(options&&(options.provider||""===options.provider)&&(retVal="provider="+encodeURIComponent(options.provider),options.params))for(var parm in options.params)options.params.hasOwnProperty(parm)&&(retVal+="&"+encodeURIComponent(parm)+"="+encodeURIComponent(options.params[parm]));return retVal}function ControlContainer(name,map){this.name=name,this.map=map,this.columns=[]}function MapSizeControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPRIGHT,MaximizeTip:GetText("maximizeMapSizeTip")||"",RestoreTip:GetText("restoreMapSizeTip")||"",margin:{right:0,top:0}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPRIGHT,this.map=map,this.type="mapsize",this.margin=o.margin}function ScaleControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.BOTTOMLEFT,margin:{bottom:4}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.BOTTOMLEFT,this.type="scale",this.map=map,this.margin=o.margin,o.control&&(this.ensureElement(o.control),this.location=void 0)}function _attachCH(elem,func){elem&&func&&(elem.onclick=function(ev){ev&&ev.preventDefault(),func(ev)})}function createToolButton(left,toolIcon,title,func,width,height){var elem=document.createElement("a");return elem.className="disable-map-events icon-ims icon-navi "+toolIcon,elem.style.position="absolute",elem.style.left=left+"px",elem.href="#",width&&(elem.style.width=width+"px"),height&&(elem.style.height=height+"px"),title&&(elem.title=title,elem.setAttribute("aria-label",title)),_attachCH(elem,func),elem}function MeasureControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,margin:{bottom:5}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.type="measure",this.map=map,this.margin=o.margin,o.control&&(this.ensureElement(o.control),this.location=void 0)}function ZoomControl(type,options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,margin:{bottom:5}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.margin=o.margin,this.type=type,this.map=map,o.control&&(this.ensureElement(null,o.control),this.location=void 0)}function LayerControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,margin:{bottom:5}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.margin=o.margin,this.type="layers",this.map=map,o.control&&(this.ensureElement(o.control),this.location=void 0,this.wrapper=jQuery("body"))}function GeoLocationControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,margin:{bottom:5}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.margin=o.margin,this.type="geolocation",this.map=map,o.control&&(this.ensureElement(o.control),this.location=void 0,this.wrapper=jQuery("body"))}function BaseMapSwitcherControl(options,map){var defaults={margin:{top:0,bottom:5},location:tekla.Map.CONTROLCONTAINER.TOPLEFT,column:2},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.column=o.column||2,this.buttons=[],this.map=map,this.type="basemapswitcher",this.margin=o.margin,o.control&&(this.location=void 0,this.ensureElement(null,o.control,o.threedcontrol))}function DrawControl(geomType,options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,savePreviousDrawing:!0,margin:{top:0,bottom:5},cssClass:null};switch(this.gType=geomType,geomType){case"Polygon":this.type="drawpolygon";break;case"Rectangle":this.type="drawrectangle";break;case"Polyline":this.type="drawpolyline";break;case"Point":this.type="drawpoint"}var o=this.options=jQuery.extend(!0,defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.id=o.id,this.map=map,this.margin=o.margin}function SearchControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,column:2,tooltipText:"",placeholderText:"",toggleSpeed:200,toggleTimeout:500,categories:[],margin:{left:5,top:0}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.column=o.column||1,this.map=map,this.margin=o.margin,this.type="search"}function ImportKmlControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,tooltipText:"",margin:{top:0,bottom:5}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.column=o.column||1,this.map=map,this.margin=o.margin,this.type="importkml"}function _findKmlPres(data,geotype){for(var i=0;i<data.length;i++){var setType=data[i].type;if("LineString"===geotype&&("Line"===setType||"LineWithWidth"===setType)||"Point"===geotype&&"Point"===setType||"Polygon"===geotype&&"Area"===setType)return data[i].data}return null}function LoadingIndicatorControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT,column:1,margin:{top:0,bottom:5}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT,this.column=o.column||1,this.map=map,this.type="loadingindicator",this.margin=o.margin}function CopyrightControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.BOTTOMLEFT,column:1,margin:{top:0,bottom:-1}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT,this.column=o.column||2,this.map=map,this.type="copyright",this.margin=o.margin,o.control&&(this.ensureElement(o.control),this.location=void 0)}function OpenInNewWindowControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPRIGHT,text:GetText("cl_openInNewWindow")||"",openMainIMS:!0,margin:{right:45,top:0}},o=this.options=jQuery.extend(!0,{},defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPRIGHT,this.map=map,this.type="openinnewwindow",this.margin=o.margin}function NamedAreasVisualizerControl(options,map){this.options=jQuery.extend(!0,{},{percent:100},options||{}),this.map=map,this.type="namedareasvisualizer",this.updateAreas()}function BaseMapHandler(map){this.map=map,this.customBaseMaps={}}function MapLegendControl(options,map){var defaults={location:tekla.Map.CONTROLCONTAINER.TOPLEFT,margin:{top:0,bottom:5},cssClass:null},o=this.options=jQuery.extend(!0,defaults,options||{});this.location=o.location||tekla.Map.CONTROLCONTAINER.TOPLEFT,this.id=o.id,this.map=map,this.margin=o.margin,this.layer=o.layer,o.control&&this.ensureElement(o.control),this._loaded=!1}tekla.Map.prototype.Maximize=function(){$("#webglViewerWrapper").length?this.MaximizeThreeD():this.MaximizeTwoD()},tekla.Map.prototype.MaximizeThreeD=function(){if(!this.maximized){var self=this;Tekla.MapBubble.hideAll(),self.prevScroll=jQuery(window).scrollTop(),jQuery(window).scrollTop(0),jQuery("body").addClass("tekla-map-maximized-state"),self.maximized=!0,self.Resize({KeepCenter:!0}),self.Trigger(tekla.Map.EVENT.MAPSIZEMAXIMIZED),jQuery(document).bind("keydown.teklamap",(function(event){27===event.keyCode&&self.RestoreSize()}))}},tekla.Map.prototype.MaximizeTwoD=function(){if(!this.maximized){var self=this;Tekla.MapBubble.hideAll(),self.prevScroll=jQuery(window).scrollTop(),self.origLocation=jQuery("<span></span>").hide(),self.origStyles=[];var mpCont=jQuery(this._container);for(var getStyle in maxStyles)self.origStyles[getStyle]="width"===getStyle?mpCont[0].style.width:mpCont.css(getStyle);for(var setStyle in maxStyles)"width"===setStyle?mpCont[0].style.width=maxStyles[setStyle]:mpCont.css(setStyle,maxStyles[setStyle]);var movediv=mpCont.after(self.origLocation).detach();self.fullPageWrapper=jQuery('<div class="tekla-map-maximized-wrapper" style="height:100%; width:100%; max-height:1800px; position:absolute; margin: 0;padding:0; background-color:white;"></div>').append(movediv),jQuery("body").prepend(self.fullPageWrapper).addClass("tekla-map-maximized"),self.maximized=!0,self.Resize({KeepCenter:!0}),self.Trigger(tekla.Map.EVENT.MAPSIZEMAXIMIZED),jQuery(document).bind("keydown.teklamap",(function(event){27===event.keyCode&&self.RestoreSize()}))}},tekla.Map.prototype.RestoreSize=function(){$("#webglViewerWrapper").length?this.RestoreSizeThreeD():this.RestoreSizeTwoD()},tekla.Map.prototype.RestoreSizeThreeD=function(){if(!0===this.maximized){Tekla.MapBubble.hideAll(),jQuery("body").removeClass("tekla-map-maximized-state");this.Resize({KeepCenter:!0}),this.maximized=!1,this.prevScroll&&jQuery(window).scrollTop(this.prevScroll),jQuery(document).unbind("keydown.teklamap"),window.teklaMap._UpdateMapPosition(),this.Trigger(tekla.Map.EVENT.MAPSIZERESTORED)}},tekla.Map.prototype.RestoreSizeTwoD=function(){if(!0===this.maximized){Tekla.MapBubble.hideAll();var movediv=jQuery(this._container).detach();for(var style in jQuery("body").removeClass("tekla-map-maximized"),this.origStyles)movediv.css(style,this.origStyles[style]);this.origLocation.replaceWith(movediv),this.fullPageWrapper.remove(),this.Resize({KeepCenter:!0}),this.maximized=!1,this.prevScroll&&jQuery(window).scrollTop(this.prevScroll),delete this.fullPageWrapper,jQuery(document).unbind("keydown.teklamap"),window.teklaMap._UpdateMapPosition(),this.Trigger(tekla.Map.EVENT.MAPSIZERESTORED)}},tekla.Map.prototype.ToggleMapSize=function(){!0===this.maximized?this.RestoreSize():this.Maximize()},tekla.Map.prototype.Move=function(container){jQuery(this._container).appendTo(jQuery(container)),this.Resize({KeepCenter:!0})},tekla.Map.prototype.AddControl=function(options){if(options)if("function"==typeof options.GetElement){var container=this.getControlContainer(options.location);container&&container.AddControl(options)}else{if(options.basemapswitcher&&(this.bmswitcher?this.bmswitcher.SetOptions(options.basemapswitcher):(this.bmswitcher=new BaseMapSwitcherControl(options.basemapswitcher,this),this.AddControl(this.bmswitcher))),options.layers&&(options.layers.layers||options.layers.allLayers))try{if(tekla.Map.defaultOptions.mapData.layers){var filtered=options.layers.allLayers?tekla.Map.defaultOptions.mapData.layers:Tekla.Layers.filterout(tekla.Map.defaultOptions.mapData.layers,options.layers.layers);this.AddControl(new LayerControl(options.layers,this)),Tekla.MapLayers.init("layerTree",filtered,null,null,null,null,this)}}catch(e){}options.geolocation&&this.AddControl(new GeoLocationControl(options.geolocation,this)),options.zoomin&&this.AddControl(new ZoomControl("zoomin",options.zoomin,this)),options.zoomout&&this.AddControl(new ZoomControl("zoomout",options.zoomout,this)),options.measure&&this.AddControl(new MeasureControl(options.measure,this)),options.scale&&this.AddControl(new ScaleControl(options.scale,this)),options.drawpoint&&this.AddControl(new DrawControl("Point",options.drawpoint,this)),options.drawpolygon&&this.AddControl(new DrawControl("Polygon",options.drawpolygon,this)),options.drawpolyline&&this.AddControl(new DrawControl("Polyline",options.drawpolyline,this)),options.drawrectangle&&this.AddControl(new DrawControl("Rectangle",options.drawrectangle,this)),options.loadingindicator&&this.AddControl(new LoadingIndicatorControl(options.loadingindicator,this)),options.objectsinfo&&this.AddControl(new ObjectsInfoControl(options.objectsinfo,this)),options.mapsize&&this.AddControl(new MapSizeControl(options.mapsize,this)),options.search&&this.AddControl(new SearchControl(options.search,this)),options.importkml&&this.AddControl(new ImportKmlControl(options.importkml,this)),options.copyright&&this.AddControl(new CopyrightControl(options.copyright,this)),options.openinnewwindow&&this.AddControl(new OpenInNewWindowControl(options.openinnewwindow,this)),options.namedareasvisualizer&&this.AddControl(new NamedAreasVisualizerControl(options.namedareasvisualizer,this)),options.maplegend&&this.AddControl(new MapLegendControl(options.maplegend,this)),options.popup&&Tekla.PopUp&&Tekla.PopUp.init(this,options.popup)}},tekla.Map.prototype.RemoveControl=function(options){if(options){var containers=this.containers;if(containers)for(prop in options)if(options.hasOwnProperty(prop)&&options[prop])for(var containerName in containers)containers.hasOwnProperty(containerName)&&containers[containerName]&&containers[containerName].RemoveControl&&containers[containerName].RemoveControl(options[prop],prop)}},tekla.Map.prototype.getControlContainer=function(containerName){var containers=this.containers=this.containers||{};return containers[containerName]?containers[containerName]:containerName===tekla.Map.CONTROLCONTAINER.TOPRIGHT||containerName===tekla.Map.CONTROLCONTAINER.TOPLEFT||containerName===tekla.Map.CONTROLCONTAINER.BOTTOMLEFT||containerName===tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT||containerName===tekla.Map.CONTROLCONTAINER.TOP||containerName===tekla.Map.CONTROLCONTAINER.BOTTOM?containers[containerName]=new ControlContainer(containerName,this):this.getControlContainer(tekla.Map.CONTROLCONTAINER.TOPLEFT),containers[containerName]},tekla.Map.prototype.SetControlOffsets=function(offsets){if(offsets)for(var prop in offsets)if(offsets.hasOwnProperty(prop)){var container=this.getControlContainer(prop);container&&container.SetOffsets(offsets[prop])}},tekla.Map.prototype.PickPosition=function(pickReadyCB,tipText,options){$_extPickTip=tipText,$_extEventHandler=pickReadyCB,$_extPickOptions=options,startPositionSelect("external")},tekla.Map.prototype.DeletePosition=function(){this._UserPositionDelete()},tekla.Map.prototype.SetPosition=function(north,east){this._UserPositionShow(north,east)},tekla.Map.prototype.SetPresentation=function(obj,presentation){var o=this.FetchObject(obj);o&&o.set_Presentation(presentation)},tekla.Map.prototype.SetEditable=function(obj,state){var o=this.FetchObject(obj);o&&o.set_Editable(!0===state)},tekla.Map.prototype.Flush=function(){window.teklaMap._UpdateMapPosition()},tekla.Map.prototype.Init=function(){this.ensureInit(!0)},tekla.Map.prototype.Clear=function(all){Tekla.MapBubble.hideAll();var nObjects=MySitesDB.Count(!0);this._HandleRemoveAll(),MySitesDB.Clear(),nObjects>0&&this.Trigger(tekla.Map.EVENT.DRAWINGDELETED),all&&SearchDB.Clear(),this.Flush()},tekla.Map.TOOLS={PAN:"pan",ZOOM:"zoom"},tekla.Map.prototype.SetTool=function(tool){tool===tekla.Map.TOOLS.PAN?(clearToolstate(),startPan()):tool===tekla.Map.TOOLS.ZOOM?(clearToolstate(),startZoom()):"zoomin"===tool?this.ZoomIn():"zoomout"===tool&&this.ZoomOut()},tekla.Map.prototype.ZoomIn=function(){this.zoomIn(1),$_CallEventHandler(tekla.Map.EVENT.VIEWPORTCHANGED)},tekla.Map.prototype.ZoomOut=function(){this.zoomOut(1),$_CallEventHandler(tekla.Map.EVENT.VIEWPORTCHANGED)},tekla.Map.prototype.SetCenter=function(north,east,zoom){this.ensureInit(!1),this.isInited&&north&&east&&(zoom&&this.setZoom(Tekla.BaseMaps.activavalidatezoom(this.options.crs.wupp2Zoom(zoom))),Tekla.MapBubble.hideAll(),this.panTo(new L.LatLng(north,east)),this.ensureInit(!0,!0),$_CallEventHandler(tekla.Map.EVENT.VIEWPORTCHANGED))},tekla.Map.prototype.UpdateLayers=function(){this.ensureInit(!1),this.isInited&&window.Tekla.Layers&&window.Tekla.Layers.applyvector()},tekla.Map.prototype.SetZoom=function(zoom){this.ensureInit(!1),this.isInited&&zoom&&(this.setZoom(Tekla.BaseMaps.activavalidatezoom(this.options.crs.wupp2Zoom(zoom))),this.ensureInit(!0),$_CallEventHandler(tekla.Map.EVENT.VIEWPORTCHANGED))},tekla.Map.prototype.GetCenter=function(){var center=get_Center(!0);return[center.n,center.e]},tekla.Map.prototype.GetZoom=function(){return currentWupp()},tekla.Map.prototype.GetZoomNumber=function(){return currentWupp()},tekla.Map.prototype.SetArea=function(north,east,south,west){var n=Math.max(south,north),e=Math.max(west,east),bounds=[[Math.min(south,north),Math.min(west,east)],[n,e]];this._FitBounds(bounds)},tekla.Map.prototype.GetArea=function(sb){var area=this.getBounds(),east=area.getEast(),south=area.getSouth(),west=area.getWest(),north=area.getNorth();return sb&&Tekla.SideBar&&Tekla.SideBar.isVisible()&&(west+=400*currentWupp()),[south,west,north,east]},tekla.Map.prototype.SetBaseMap=function(name){return this.ensureInit(!1),this.bmHandler.SetBaseMap(name)},tekla.Map.prototype.AddCustomBaseMap=function(context){return this.bmHandler.AddCustomBaseMap(context)},tekla.Map.prototype.GetCurrentBaseMap=function(){return Tekla.BaseMaps.active()},tekla.Map.prototype.DrawingsCount=function(){return this.GetDrawings().length},tekla.Map.prototype.GetDrawings=function(){for(var ret=[],Id=0;Id<MySitesDB.items.length;Id++){var obj=MySitesDB.GetAt(Id);$_DBIsValidObject(obj)&&ret.push(obj)}return ret},tekla.Map.prototype.GetDrawingsJSON=function(filter){for(var ret=[],arr=MySitesDB.items,i=0;i<arr.length;i++){var obj=arr[i];if($_DBIsValidObject(obj)||filter&&obj&&obj.IsDeleted){var apply=!0,attrs=null;filter&&((attrs=filter(obj))||(apply=!1)),apply&&(attrs&&"object"==typeof attrs||(attrs={Attributes:["Name","Explanation","Url","ReferenceId","StreetAddress","Geometry"]}),ret.push(this.$_ToGeomObjAttrs(obj,attrs)))}}return ret},tekla.Map.prototype.AddBaseMapButton=function(name){this.AddControl({basemapswitcher:{basemaps:[name]}})},tekla.Map.prototype.SetBaseMapButtons=function(keys){if(keys&&keys.length>0)for(var i=0;keys.length<i;i++)this.AddBaseMapButton(keys[i])},tekla.Map.prototype.DrawPin=function(data){this.DrawPoint(data)},tekla.Map.prototype.DrawPoint=function(data){deleteDrawing(),Tekla.MapBubble.hideAll();var tip=data&&data.DrawTip?String.escapeHTML(data.DrawTip,!0):null;this.setDrawingData(data,"Point"),createSite(tip)},tekla.Map.prototype.DrawPolygon=function(data){this.drawPath(!0,data)},tekla.Map.prototype.DrawRectangle=function(data){this.drawRectangle(data)},tekla.Map.prototype.DrawPolyline=function(data){this.drawPath(!1,data)},tekla.Map.prototype.CancelDraw=function(){deleteDrawing()},tekla.Map.prototype.EndDraw=function(){Tekla.MapBubble.insert(toolMode,null,{skipBubble:!0})},tekla.Map.prototype.setDrawingData=function(data,geomType,typeid){var extData=jQuery.extend({},this.options.drawings||{},data||{});options.getDrawingData=function(){return extData},options._getCurrentPresentation=extData.presentation?function(){return extData.presentation}:options.getCurrentPresentation},tekla.Map.prototype.drawPath=function(filled,data){deleteDrawing(),Tekla.MapBubble.hideAll(),this.setDrawingData(data,!0===filled?"Polygon":"Polyline"),createDraw(filled,data&&data.DrawTip?String.escapeHTML(data.DrawTip,!0):null)},tekla.Map.prototype.drawRectangle=function(data){deleteDrawing(),Tekla.MapBubble.hideAll(),this.setDrawingData(data,!0,"Polygon"),createDrawRectangle(data&&data.DrawTip?String.escapeHTML(data.DrawTip,!0):null)},tekla.Map.prototype.convertToDrawData=function(dp,texts,type){var globalDefaultPresentation=null,o=this.options;"function"==typeof o.getCurrentPresentation&&(globalDefaultPresentation=o.getCurrentPresentation()),globalDefaultPresentation||(globalDefaultPresentation={LineColor:"red",LineWidth:2,LineType:"solid",FillColor:"blue",FillOpacity:.5});var retVal=null;switch(type){case"Point":retVal={DrawTip:texts&&texts.pointtip?texts.pointtip:null,values:{name:texts&&texts.pointname?texts.pointname:null},presentation:{Image:dp&&dp.pointimage?dp.pointimage:globalDefaultPresentation.Image}};break;case"Polygon":retVal={DrawTip:texts&&texts.areatip?texts.areatip:null,values:{name:texts&&texts.areaname?texts.areaname:null},presentation:{Image:dp&&dp.areaimage?dp.areaimage:null,LineColor:dp&&dp.arealinecolor?dp.arealinecolor:globalDefaultPresentation.LineColor,LineWidth:dp&&dp.arealinewidth?dp.arealinewidth:globalDefaultPresentation.LineWidth,LineType:dp&&dp.arealinetype?dp.arealinetype:globalDefaultPresentation.LineType,LineOpacity:dp&&dp.arealineopacity?dp.arealineopacity:globalDefaultPresentation.LineOpacity,FillColor:dp&&dp.areafillcolor?dp.areafillcolor:globalDefaultPresentation.FillColor,FillOpacity:dp&&dp.areaopacity?dp.areaopacity:globalDefaultPresentation.FillOpacity}};break;case"Polyline":retVal={DrawTip:texts&&texts.linetip?texts.linetip:null,values:{name:texts&&texts.linename?texts.linename:null},presentation:{Image:dp&&dp.lineimage?dp.lineimage:null,LineColor:dp&&dp.linecolor?dp.linecolor:globalDefaultPresentation.LineColor,LineWidth:dp&&dp.linewidth?dp.linewidth:globalDefaultPresentation.LineWidth,LineType:dp&&dp.linetype?dp.linetype:globalDefaultPresentation.LineType,LineOpacity:dp&&dp.lineopacity?dp.lineopacity:globalDefaultPresentation.LineOpacity}}}return retVal&&dp&&dp.skipBubble&&(retVal.skipBubble=!0),retVal},tekla.Map.prototype.AddPoint=function(point){var id=null;if(point&&point.east&&point.north&&point.name){var obj=new SR_Geo(point.name||"",point.explanation);obj.set_Geometry({type:"Point",coordinates:[point.east,point.north]}),$_isValidUrl(point.url,!0)&&(obj.Url=point.url),point.image&&(obj.Presentation={Image:point.image}),obj.Editable=!0===point.editable,id=MySitesDB.Insert(obj),this.Trigger(tekla.Map.EVENT.DRAWINGREADY,obj)}return id},tekla.Map.prototype.AddPolygon=function(polygon){return polygon&&polygon.coordinates&&polygon.coordinates.length>=1&&polygon.coordinates[0].length>=1?this.addPath(polygon,"Polygon"):null},tekla.Map.prototype.AddPolyline=function(polyline){return polyline&&polyline.coordinates&&polyline.coordinates.length>=2?this.addPath(polyline,"LineString"):null},tekla.Map.prototype.addPath=function(poly,type){var obj=new SR_Geo(poly.name||"",poly.explanation);obj.set_Geometry({type:type,coordinates:poly.coordinates}),poly.url&&(obj.Url=$_tryGetValidUrl(poly.url,!0)),poly.presentation&&(obj.Presentation=poly.presentation),obj.Editable=!0===poly.editable,!0===poly.CanDelete&&obj.setCanDelete(!0),obj.set_Dirty(TXWConst.EDITSTATE_ALL);var id=MySitesDB.Insert(obj);return this.Trigger(tekla.Map.EVENT.DRAWINGREADY,obj),id},tekla.Map.prototype.Delete=function(id,flush){var ret=$_DBDelete(OBJ_MYSITES,id);return ret&&flush&&this.Flush(),ret},tekla.Map.prototype.SetWheelTimeOut=function(value){options.wheelTimeOut=value,this.refreshWheelTimeout()},tekla.Map.prototype.refreshWheelTimeout=function(){},tekla.Map.prototype.DoSearch=function(searchtext,category,municipality,currentarea){this.Search({searchtext:searchtext,category:category,municipality:municipality,currentarea:currentarea})},tekla.Map.prototype.Search=function(options){function complete(){"function"==typeof options.onComplete&&options.onComplete()}if(options){var category=options.category,searchtext=options.searchtext;if(searchtext){var url="";if(category&&("string"==typeof category||category.length>0)){if(url+="?Op=ext&Name="+encodeURIComponent(searchtext),"string"==typeof category)url+="&cidname="+encodeURIComponent(category);else if(category.length>0)for(var i=0;i<category.length;i++)url+="&cidname="+encodeURIComponent(category[i])}else url+="?Op=all&Name="+encodeURIComponent(searchtext);var self=this;self.Trigger(tekla.Map.EVENT.LOADSTARTED),jQuery.ajax({async:!0,type:"GET",url:actionUrl("Search")+url+(options.municipality?"&Municipality="+encodeURIComponent(options.municipality):"")+"&IsExact=true"+(options.currentarea?window.teklaMap._GetAreaString():""),dataType:tekla.utility.isSameOrigin(url)?"text":"jsonp",success:function(result){if(result&&" "!==result){"string"==typeof result&&(result=$_EVALJSON(result)),SearchDB.Clear(),$_layerDisplayResults(SearchDB,result,LIST_NO);var count=SearchDB.Count(!0);self.Trigger(tekla.Map.EVENT.SEARCHREADY,{result:result,count:count}),0===count&&$_internalUpdateDatabaseTypes(!0)}"function"==typeof options.onSuccess&&options.onSuccess(result)},complete:function(){self.Trigger(tekla.Map.EVENT.LOADREADY),complete()}})}else complete()}},tekla.Map.prototype.SetNearestAddressForDrawings=function(flag){var self=this;function findNearestAddress(obj){if(!0===self.nearestAddressForDrawings&&obj&&obj.get_CenterPoint){var coords=obj.get_CenterPoint();coords&&self.FindNearestAddress(coords.y,coords.x,(function(data){!function updateObject(data,obj){data&&data.status&&(obj&&(obj.StreetAddress=data.address),self.Trigger(tekla.Map.EVENT.NEARESTADDRESS,data.address+" ("+TGMap.Measure.formatDistance(data.distance)+")"))}(data,obj)}))}}void 0===self.nearestAddressForDrawings?!0===flag&&(self.Bind(tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,(function(eventName,action,obj){findNearestAddress(obj)})),self.Bind(tekla.Map.EVENT.DRAWINGREADY,(function(eventName,obj){findNearestAddress(obj)})),self.nearestAddressForDrawings=flag):self.nearestAddressForDrawings=flag},tekla.Map.prototype.FindNearestAddress=function(north,east,onready){if(north&&east&&onready){var url=actionUrl("Search")+"?Op=findnearestaddress&n="+north+"&e="+east;jQuery.ajax({async:!0,type:"GET",dataType:tekla.utility.isSameOrigin(url)?"json":"jsonp",url:url,success:function(data){onready&&onready(data)}})}},tekla.Map.prototype.SetLayerVisible=function(layerName,visible,threed){this.isInited&&(threed?Tekla.ThreeDMapLayers.setselected(layerName,!1!==visible):Tekla.Layers.setselected(layerName,!1!==visible))},tekla.Map.prototype.HideAllLayers=function(){if(this.isInited){var selected=Tekla.Layers.getselected();if(selected&&selected.length>0)for(var i=0;i<selected.length;i++)Tekla.Layers.setselected(selected[i],!1)}},tekla.Map.prototype.ZoomToDrawing=function(obj){if(Array.isArray(obj)){var db={};db.items=obj,$_zoomToDBExtents(db)}else if(obj&&obj.Geometry)$_ZoomToObject(obj);else{var iObj=$_DBSelect(OBJ_MYSITES,obj);iObj&&$_ZoomToObject(iObj)}},tekla.Map.prototype.ShowDrawing=function(obj){var actualObj=obj&&obj.Geometry?obj:$_DBSelect(OBJ_MYSITES,obj);actualObj&&($_ZoomToObject(actualObj),Tekla.MapBubble.show(OBJ_MYSITES,actualObj))},tekla.Map.prototype.HighlightDrawing=function(options){if(options.referenceid){var obj=MySitesDB.FindByReferenceId(options.referenceid);obj&&obj.HighLight(TXWConst.MYSITES,options.presentation)}},tekla.Map.prototype.RemoveHighlights=function(){HLDB.RemoveAll()},tekla.Map.prototype.ZoomToObject=function(obj){this.ZoomToDrawing(obj)},tekla.Map.prototype.FetchDrawing=function(obj){return this.FetchObject(obj)},tekla.Map.prototype.FetchObject=function(obj){return jQuery.isObject(obj)?obj:$_DBSelect(OBJ_MYSITES,obj)},tekla.Map.prototype.FetchDrawingByReferenceId=function(referenceid){return referenceid?MySitesDB.FindByReferenceId(referenceid):null},tekla.Map.prototype.RegisterEventHandler=function(eF){this.Bind(tekla.Map.EVENT.ALL,eF)},tekla.Map.prototype.AddEditButtons=function(presentation,texts){var buttons=presentation?presentation.buttontypes:null;(!buttons||1&buttons)&&this.AddControl({drawpoint:{tip:texts?texts.pointbuttontip:null,data:this.convertToDrawData(presentation,texts,"Point")}}),(!buttons||2&buttons)&&this.AddControl({drawpolyline:{tip:texts?texts.linebuttontip:null,data:this.convertToDrawData(presentation,texts,"Polyline")}}),(!buttons||4&buttons)&&this.AddControl({drawpolygon:{tip:texts?texts.areabuttontip:null,data:this.convertToDrawData(presentation,texts,"Polygon")}})},tekla.Map.prototype.GetDrawingsListAsHTML=function(getprop,filter){var count=0,retVal=jQuery('<div class="myobjects"></div>'),ul=jQuery('<ul class="myobject-list"></ul>').appendTo(retVal);if("function"!=typeof filter){var inFilter=filter;filter=function(obj){return obj.Editable||!0===inFilter}}for(var i=0;i<MySitesDB.items.length;i++){var obj=MySitesDB.items[i];obj&&obj.Name&&filter(obj)&&obj.__id!==window.$_filterSingleton&&(ul.append(Tekla.MyObjects.renderMapObjectLI(obj,OBJ_MYSITES,!1,window.options.texts,getprop?getprop(obj):null)),count++)}return{count:count,html:retVal}},tekla.Map.prototype.MySitesHtml=function(getprop,includeNotEditable){return this.GetDrawingsListAsHTML(getprop,includeNotEditable)},tekla.Map.prototype.GetSelectedObjectId=function(){return $_GetSelection()},tekla.Map.prototype.AddProviderLayer=function(options){var self=this;function addLayer(item){var key=createFeatureTypeKey(item);key&&self.AddGlobalLayer(key,item.maxLevel,item.filter)}if(jQuery.isArray(options))for(var i=0;i<options.length;i++)addLayer(options[i]);else addLayer(options)},tekla.Map.prototype.RemoveProviderLayer=function(options){var key=createFeatureTypeKey(options);key&&this.RemoveGlobalLayer(key)},tekla.Map.prototype.AddGeometry=function(geoJSON,DBIndex,clearDB){var permanentItems=null,DB=DBIndex?$_GetDBByIndex(DBIndex):MySitesDB;if(clearDB&&(permanentItems=DB.GetPermanentItems(),DB.Clear(!0)),Tekla.MapBubble.hideAll(!1,$_GetIndexByDB(DB)),this.BeginGuiTrans(),$_layerGeoJSONDisplayResults(DB,geoJSON,null),clearDB&&permanentItems)for(var fs=window.$_filterSingleton,i=0;i<permanentItems.length;i++)fs&&permanentItems[i].__id==window.$_filterSingleton?(window.$_filterSingleton=DB.Insert(permanentItems[i]),fs=void 0):DB.Insert(permanentItems[i]);this.NeedLayerRedraw(),this.EndGuiTrans(),window.teklaMap3&&window.Tekla.ThreeD&&(DB.SetThreeDItemEditability(!1),window.Tekla.ThreeD.addMarkUps(MySitesDB))},tekla.Map.prototype.$_ToGeomObj=function(obj){return this.$_ToGeomObjAttrs(obj,{Attributes:["Name","Explanation","Url","ReferenceId","StreetAddress","Geometry"]})},tekla.Map.prototype.$_ToGeomObjAttrs=function(obj,attrs){function applyGeometry(obj,o){if(obj.Geometry)o.geometry=obj.Geometry;else if(obj.PointArray){o.geometry={},o.geometry.type=obj.get_Filled()?"Polygon":"LineString",o.geometry.coordinates=[];var p=o.geometry.coordinates;obj.get_Filled()&&(o.geometry.coordinates[0]=[],p=o.geometry.coordinates[0]);for(var i=0;i<obj.PointArray.length;i++)p[i]=[],p[i][0]=obj.PointArray[i].east,p[i][1]=obj.PointArray[i].south}else o.geometry={},o.geometry.type="Point",o.geometry.coordinates=[],o.geometry.coordinates[0]=obj.East,o.geometry.coordinates[1]=obj.North}if(!obj)return null;var a,o={};if(attrs&&attrs.Attributes&&attrs.Attributes.length>0)for(a=0;a<attrs.Attributes.length;a++){var attribute=attrs.Attributes[a];"Geometry"==attribute?applyGeometry(obj,o):"Presentation"==attribute?obj.Presentation&&(o.Presentation=obj.Presentation):obj.hasOwnProperty(attribute)&&(o[attribute]=obj[attribute])}if(attrs&&attrs.Extra&&attrs.Extra.length>0)for(a=0;a<attrs.Extra.length;a++){var extra=attrs.Extra[a];o[extra.key]=extra.value}return o},tekla.Map.prototype.StartPolygonSelect=function(data){this.ClearSelectorPolygon(),(data=data||{}).singleton=!0,data.skipBubble=!0===data.SkipForm||!0===data.skipBubble,this.drawPath(!0,data)},tekla.Map.prototype.GetSelectorPolygon=function(){return this.EndDraw(),window.$_filterSingleton?this.$_ToGeomObj($_DBSelect(OBJ_MYSITES,window.$_filterSingleton)):null},tekla.Map.prototype.SetSelectorPolygon=function(data){if(this.ClearSelectorPolygon(),data){var obj=new SR_Geo(data.Name,data.Explanation);return obj.set_Geometry(data.geometry),obj.set_Presentation(data.presentation),obj.Editable=obj.editable=!0===data.Editable,obj.skipBubble=!0===data.SkipForm||!0===data.skipBubble,obj.singleton=!0,obj.Permanent=!0===data.Permanent,obj.NoCluster=!0===data.NoCluster,window.$_filterSingleton=MySitesDB.Insert(obj),this.Flush(),window.$_filterSingleton}},tekla.Map.prototype.ClearSelectorPolygon=function(){window.$_filterSingleton&&(this.Delete(window.$_filterSingleton,!0),window.$_filterSingleton=null)},tekla.Map.prototype.AddGlobalLayer=function(namekey,layermax,visibFilter){Tekla.Layers.addgloballayer(namekey,!0,layermax,visibFilter)},tekla.Map.prototype.AddGlobalLayers=function(layerarray){Tekla.Layers.addgloballayers(layerarray)},tekla.Map.prototype.RemoveGlobalLayer=function(namekeystart){Tekla.Layers.removegloballayer(namekeystart),window.teklaMap._UpdateMapPosition()},tekla.Map.prototype.CopySearchResult=function(clear,count){SearchDB.CopyObjectsToDB(MySitesDB,count),clear&&SearchDB.Clear(),window.teklaMap._UpdateMapPosition()},tekla.Map.prototype.ClearSearchResults=function(){SearchDB.Clear(),window.teklaMap._UpdateMapPosition()},tekla.Map.prototype.EnableCopyingOfDrawing=function(text){window.Tekla.MapBubble&&(window.Tekla.MapBubble.enableCopyingOfDrawings=!0),text&&(options.texts.cl_addToOwnObjects=text)},tekla.Map.prototype.Resize=function(opt){L.Util.requestAnimFrame(this.invalidateSize,this,!1,this._container)},tekla.Map.prototype.SetCategotyLayerMax=function(v){try{options.mapData.settings.CatLayerMax=v}catch(e){}},tekla.Map.prototype.ShowAll=function(){$_zoomToDBExtents(MySitesDB)},tekla.Map.prototype.Trigger=function(eventName){var retVal=null;if(this.eventHandlers){var arr=this.eventHandlers[eventName],i=0;if(arr&&arr.length>0)for(i=0;i<arr.length;i++){(eventRet=arr[i].apply(this,arguments))&&(retVal=retVal?jQuery.merge(retVal,eventRet):eventRet)}if((arr=this.eventHandlers[tekla.Map.EVENT.ALL])&&arr.length>0)for(i=0;i<arr.length;i++){var eventRet;(eventRet=arr[i].apply(this,arguments))&&(retVal=retVal?jQuery.merge(retVal,eventRet):eventRet)}}return retVal},tekla.Map.prototype.Bind=function(eventName,callback){var self=this;function registerEvent(eventName,callback){var arr=self.eventHandlers[eventName];arr||(arr=[]),arr.push(callback),self.eventHandlers[eventName]=arr}eventName&&"function"==typeof callback&&(eventName===tekla.Map.EVENT.DRAWINGALL?self.Bind([tekla.Map.EVENT.DRAWINGGEOMETRYCHANGED,tekla.Map.EVENT.DRAWINGPROPERTIESCHANGED,tekla.Map.EVENT.DRAWINGPRESENTATIONCHANGED,tekla.Map.EVENT.DRAWINGDELETED,tekla.Map.EVENT.DRAWINGREADY,tekla.Map.EVENT.EXTERNALDELETEREQUESTED,tekla.Map.EVENT.SELECTIONCHANGED],callback):jQuery.isArray(eventName)?jQuery(eventName).each((function(){registerEvent(this,callback)})):registerEvent(eventName,callback))},tekla.Map.prototype.ProviderAction=function(provider,actionspec){providerAction(provider,actionspec)},tekla.Map.CONTROLCONTAINER={TOPLEFT:"topleft",TOPRIGHT:"topright",BOTTOMLEFT:"bottomleft",BOTTOMRIGHT:"bottomright",BOTTOM:"bottom",TOP:"top"},ControlContainer.prototype.AddControl=function(control){var name,col=this.getColumn(control.column),elem=control.GetElement();if(elem&&col){var dims=this.getControlDimensions(col.controls);this.name===tekla.Map.CONTROLCONTAINER.BOTTOMLEFT||this.name===tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT?elem.style.bottom=dims.height+(control.margin&&control.margin.bottom||0)+"px":(name=this.name)!==tekla.Map.CONTROLCONTAINER.BOTTOM&&name!==tekla.Map.CONTROLCONTAINER.TOP&&(elem.style.top=dims.height+(control.margin&&control.margin.top||0)+"px"),this.name!==tekla.Map.CONTROLCONTAINER.TOPRIGHT&&this.name!==tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT||(elem.style.right="0",elem.style.right=(control.margin&&control.margin.right||0)+"px"),this.name===tekla.Map.CONTROLCONTAINER.BOTTOM?(elem.style.bottom="0",elem.style.left="0",elem.style.right="0"):this.name===tekla.Map.CONTROLCONTAINER.TOP&&(elem.style.top="0",elem.style.left="0",elem.style.right="0"),col.container.appendChild(elem),col.controls.push(control)}},ControlContainer.prototype.SetOffsets=function(offsets){offsets&&(this.getColumn(1),isNaN(offsets.top)||(this.control.style.top=offsets.top+"px"),isNaN(offsets.left)||(this.control.style.left=offsets.left+"px"))},ControlContainer.prototype.RemoveControl=function(control,type){var cols=this.columns;if(cols){for(var prop in cols)if(cols.hasOwnProperty(prop)&&cols[prop])for(var i=0;i<cols[prop].controls.length;i++){var existingControl=cols[prop].controls[i];!existingControl||type&&type!==existingControl.type||control.id&&control.id!==existingControl.id||(jQuery(existingControl.GetElement()).remove(),delete cols[prop].controls[i])}this.update()}},ControlContainer.prototype.update=function(){for(var cols=this.columns,iCol=0;iCol<cols.length;iCol++)if(cols[iCol]){var controls=cols[iCol].controls;cols[iCol].controls=[];for(var iControl=0;iControl<controls.length;iControl++)controls[iControl]&&(cols[iCol].container.removeChild(controls[iControl].GetElement(!0)),this.AddControl(controls[iControl]))}},ControlContainer.prototype.getColumn=function(column){var div;this.control||((div=document.createElement("div")).style.position="absolute",this.name===tekla.Map.CONTROLCONTAINER.BOTTOM?(div.style.left="0",div.style.right="0",div.style.bottom="0",div.style.zIndex="7223"):this.name===tekla.Map.CONTROLCONTAINER.TOP?(div.style.left="0",div.style.right="0",div.style.top="0",div.style.zIndex="7223"):(this.name===tekla.Map.CONTROLCONTAINER.TOPRIGHT||this.name===tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT?div.style.right="5px":div.style.left="5px",this.name===tekla.Map.CONTROLCONTAINER.BOTTOMLEFT||this.name===tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT?div.style.bottom="2px":div.style.top="5px",div.style.zIndex="7222"),div.style.background="transparent",div.style.width="100%",this.control=div,this.map._AttachControl(this.control));(column=column||1,this.columns[column])||((div=document.createElement("div")).style.position="absolute",this.name===tekla.Map.CONTROLCONTAINER.BOTTOM?(div.style.left="0",div.style.right="0",div.style.bottom="0"):this.name===tekla.Map.CONTROLCONTAINER.TOP?(div.style.left="0",div.style.right="0",div.style.top="0"):(this.name===tekla.Map.CONTROLCONTAINER.TOPRIGHT||this.name===tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT?div.style.right=1==column?"0":32*(column-1)+"px":div.style.left=1==column?"0":32*(column-1)+"px",this.name===tekla.Map.CONTROLCONTAINER.BOTTOMLEFT||this.name===tekla.Map.CONTROLCONTAINER.BOTTOMRIGHT?div.style.bottom="0":div.style.top="0"),div.style.zIndex="1",div.style.background="transparent",div.style.width="100%",this.columns[column]={container:div,controls:[]},this.control.appendChild(div));return this.columns[column]},ControlContainer.prototype.getControlDimensions=function(list){for(var retVal={height:0},i=0;i<list.length;i++){var lsti=list[i];lsti.height?retVal.height+=lsti.height:lsti.control&&(retVal.height+=jQuery(lsti.control).outerHeight()||26),lsti.margin&&(retVal.height+=(lsti.margin.bottom||0)+(lsti.margin.top||0))}return retVal},MapSizeControl.prototype.ensureElement=function(){var self=this,o=self.options;if(!self.control){var a=document.createElement("a");o&&o.MaximizeTip&&(a.title=o.MaximizeTip),a.className="disable-map-events icon-ims icon-minmaxmap",a.style.position="absolute",a.style.cursor="pointer",a.onclick=function(event){return cancelEventPropagation(event),self.map.ToggleMapSize(),!1},self.control=a}},MapSizeControl.prototype.GetElement=function(){var self=this,o=self.options;return self.ensureElement(),self.map.Bind(tekla.Map.EVENT.MAPSIZERESTORED,(function(){o&&o.MaximizeTip&&(self.control.title=o.MaximizeTip),jQuery(self.control).removeClass("maxed")})),self.map.Bind(tekla.Map.EVENT.MAPSIZEMAXIMIZED,(function(){o&&o.RestoreTip&&(self.control.title=o.RestoreTip),jQuery(self.control).addClass("maxed")})),self.control},ScaleControl.prototype.ensureElement=function(control){if(!this.control)if(control)self.control=control;else{this.control=document.createElement("div"),this.control.style.position="absolute",this.control.className="map-scale";var img=document.createElement("div");img.id="scalebar",img.className="map-ruler";var span=this.textSpan=document.createElement("span");span.id="scaletext",this.control.appendChild(span),this.control.appendChild(img)}},ScaleControl.prototype.GetElement=function(){return this.ensureElement(),this.control},MeasureControl.prototype.GetElement=function(){return this.ensureElement(),this.control},MeasureControl.prototype.ensureElement=function(control){if(!this.control){var func=function(event){cancelEventPropagation(event),startMeter()};control?(this.control=control,_attachCH(this.control,func)):this.control=createToolButton(0,"icon-measure",GetText("cl_measureDistance"),func)}},ZoomControl.prototype.GetElement=function(){return this.ensureElement(),this.control},ZoomControl.prototype.ensureElement=function(topOffset,control){var self=this;if(!self.control)if("zoomin"===self.type){var func=function(event){cancelEventPropagation(event),self.map._getIsThreeDMode()||self.map.ZoomIn()};control?(self.control=control,_attachCH(self.control,func)):self.control=createToolButton(0,"icon-zoomin",GetText("cl_zoomIn"),func)}else if("zoomout"===self.type){func=function(event){cancelEventPropagation(event),self.map._getIsThreeDMode()||self.map.ZoomOut()};control?(self.control=control,_attachCH(self.control,func)):self.control=createToolButton(0,"icon-zoomout",GetText("cl_zoomOut"),func)}},LayerControl.prototype.GetElement=function(){return this.ensureElement(),this.control},LayerControl.prototype.ensureElement=function(control){if(!this.control){var func=function(event){return cancelEventPropagation(event),jQuery("#layerTreeContainer").toggle("slide",{direction:"left"},400),window.Tekla.MapLayers&&Tekla.MapLayers.update(),!1};jQuery("#layerTreeClose").bind("click",(function(){jQuery("#layerTreeContainer").hide("slide",{direction:"left"},400)})),control?(this.control=control,_attachCH(this.control,func)):this.control=createToolButton(0,"icon-layers",GetText("menu"),func)}},GeoLocationControl.prototype.GetElement=function(){return this.ensureElement(),this.control},GeoLocationControl.prototype.ensureElement=function(control){var self=this;if(!self.control&&navigator.geolocation){var func=function(event){return cancelEventPropagation(event),self.toggleGeoLocation(),!1};control?(self.control=control,_attachCH(self.control,func)):self.control=createToolButton(0,"icon-geolocation",GetText("geoLocationTip"),func)}},GeoLocationControl.prototype.toggleGeoLocation=function(){var self=this;if($wrapper=self.wrapper||jQuery(self.map.md),!$wrapper.hasClass("geolocation-loading")){$wrapper.addClass("geolocation-loading"),$ctrl=jQuery(self.control);var currentState=$ctrl.data("geolocation-state");TGMap.geolocation.setstate(currentState,self.map,(function(state,loc){if($ctrl.data("geolocation-state",state),$wrapper.removeClass("geolocation-active geolocation-loading geolocation-inaccurate geolocation-outofbounds geolocation-map-follow"),$ctrl.attr("title",GetText("geoLocationTip")),state){var accuracyText=state.accuracy>0?" ("+GetText("geoLocationAccuracy")+": "+state.accuracy+"m)":"";"ok-map-follow"===state.status?($wrapper.addClass("geolocation-active geolocation-map-follow"),$ctrl.attr("title",GetText("geoLocationTip")+accuracyText)):"ok"===state.status?($wrapper.addClass("geolocation-active"),$ctrl.attr("title",GetText("geoLocationTip")+accuracyText)):"ok-inaccurate"===state.status?($wrapper.addClass("geolocation-inaccurate"),$ctrl.attr("title",GetText("geoLocationInaccurateTip")+accuracyText)):"outofbounds"===state.status&&($wrapper.addClass("geolocation-outofbounds"),$ctrl.attr("title",GetText("geoLocationOutOfBoundsTip"))),self.options.appCb&&self.options.appCb(state,loc)}}),options.istouch)}},BaseMapSwitcherControl.prototype.ensureElement=function(current,control,threedcontrol){var o=this.options,self=this,baseMaps=Tekla.BaseMaps.getall(!0),threeDBaseMaps=Tekla.BaseMaps.getThreeDAll();function appendBaseMapLI(toAdd,threed){if(null!=toAdd){var context={},fCustom=!1;if("string"==typeof toAdd&&toAdd?context.baseMapName=toAdd:toAdd.basemap&&(context.baseMapName=toAdd.basemap,context.name=toAdd.name,context.label=toAdd.label,context.layers=toAdd.layers,fCustom=!0),context.baseMapName){for(var source=threed?threeDBaseMaps:baseMaps,i=0;!context.baseMap&&i<source.length;i++)source[i].name===context.baseMapName&&(context.basemap=source[i]);if(context.basemap){context.label||(context.label=context.basemap.label||context.basemap.name),context.name||(context.name=context.basemap.name);var li=document.createElement("li");li.threed=threed,context.basemap.cssClass&&(li.className=context.basemap.cssClass),self.selectedSet||(li.className+=" selected",self.selectedSet=!0),!0===fCustom&&self.map.AddCustomBaseMap(context);var a=document.createElement("a");if(a.innerHTML='<span class="preview"></span><span class="label">'+context.label+"</span>",a.href="#",a.onclick=function(li,context){return function(event){return cancelEventPropagation(event),self.map.SetBaseMap(context.name),"function"==typeof o.onchange&&o.onchange(),!1}}(0,context),li.appendChild(a),options.basemapmetacb){var layer=window.Tekla.BaseMaps.getType(context.basemap.name,threed);if(layer&&(layer.hasmetadata||layer.maplegendpath)){var ma=document.createElement("a");ma.innerHTML+='<a class="meta"><span title="'+GetText("showAddInfoTip")+'" class="toolbar-icon24 toolbar-info24"></span></a>',ma.onclick=function(li,context){return function(event){return cancelEventPropagation(event),options.basemapmetacb(context.name),!1}}(0,context),li.appendChild(ma)}}self.buttons[context.name]=li,li&&(threed&&self.threedcontrol?self.threedcontrol.appendChild(li):self.control.appendChild(li))}}}}if(self.control||(self.threedcontrol=threedcontrol,baseMaps&&baseMaps.length>0&&(control?self.control=control:(self.control=document.createElement("ul"),self.control.id="basemap-switcher",self.control.className="disable-map-events basemap-switcher",self.control.style.zIndex=7222)),self.map.Bind(tekla.Map.EVENT.BASEMAPCHANGED,(function(eventName,baseMapName){for(var item in self.buttons)jQuery(self.buttons[item]).removeClass("selected");var li=self.buttons[baseMapName];li&&self.map._setThreeDMode(li.threed),self.buttons[baseMapName]||appendBaseMapLI(baseMapName),self.buttons[baseMapName]&&jQuery(self.buttons[baseMapName]).addClass("selected"),Tekla.MapLink&&Tekla.MapLink.update()}))),!0!==self.newOptions&&self.control){if(!0===o.preserveDefaultOrder||!o.basemaps)for(var i=0;i<baseMaps.length;i++)(!o.basemaps&&"navimap"!==baseMaps[i].usage||o.basemaps&&o.basemaps.indexOf(baseMaps[i].name)>=0)&&appendBaseMapLI(baseMaps[i].name);if(!0===o.preserveDefaultOrder||!o.basemaps)for(i=0;i<threeDBaseMaps.length;i++)(!o.basemaps||o.basemaps&&o.basemaps.indexOf(threeDBaseMaps[i].name)>=0)&&appendBaseMapLI(threeDBaseMaps[i].name,!0);if(o.basemaps)for(i=0;i<o.basemaps.length;i++)!0===o.preserveDefaultOrder&&"string"==typeof o.basemaps[i]||appendBaseMapLI(o.basemaps[i]);$.contextMenu&&($.contextMenu({selector:".threed-switcher li.selected",callback:function(){window.Tekla.BaseMaps.fitToActive()},items:{fit:{name:GetText("zoomTo")}}}),$.contextMenu({selector:"#menu-threedlayer-selector li span.dynatree-selected a",callback:function(){var label=$(this).text();window.Tekla.ThreeDMapLayers.fitToLayer(label)},items:{fit:{name:GetText("zoomTo")}}})),self.newOptions=!0}},BaseMapSwitcherControl.prototype.GetElement=function(){return this.ensureElement(),this.control},BaseMapSwitcherControl.prototype.SetOptions=function(options){this.newOptions=!0,this.options=jQuery.extend(this.options,options||{}),this.ensureElement()},DrawControl.prototype.GetElement=function(){return this.ensureElement(),this.control},DrawControl.prototype.ensureElement=function(){var self=this;function createToolButton(left,toolIcon,title,func){var elem=document.createElement("a");elem.className="disable-map-events icon-ims icon-tool "+toolIcon;var cssClass=self.options.cssClass;return cssClass&&(elem.className+=" "+cssClass),elem.style.position="absolute",elem.style.left=left+"px",elem.href="#",title&&(elem.title=title),func&&(elem.onclick=function(ev){ev&&ev.preventDefault(),func(ev)}),elem}if(!self.control){var o=self.options,map=self.map;switch(self.gType){case"Point":self.control=createToolButton(0,"icon-drawpoint",o.tip,(function(event){return cancelEventPropagation(event),!0===o.savePreviousDrawing&&map.EndDraw(),map._getIsThreeDMode()?(window.Tekla.ThreeD&&window.Tekla.ThreeD.setActiveTool("textMarkup"),!1):(map.DrawPoint(o.data),!1)}));break;case"Polyline":self.control=createToolButton(0,"icon-drawpolyline",o.tip,(function(event){return cancelEventPropagation(event),!0===o.savePreviousDrawing&&map.EndDraw(),map.DrawPolyline(o.data),!1}));break;case"Polygon":self.control=createToolButton(0,"icon-drawpolygon",o.tip,(function(event){return cancelEventPropagation(event),!0===o.savePreviousDrawing&&map.EndDraw(),map.DrawPolygon(o.data),!1}));break;case"Rectangle":self.control=createToolButton(0,"icon-drawrectangle",o.tip,(function(event){return cancelEventPropagation(event),!0===o.savePreviousDrawing&&map.EndDraw(),o.data&&o.data.singleDrawing&&L_MYSITESLAYER&&(L_MYSITESLAYER.clearLayers(),MySitesDB.Clear(!0)),map.DrawRectangle(o.data),!1}))}}},SearchControl.prototype.GetElement=function(){return this.ensureElement(),this.control},SearchControl.prototype.ensureElement=function(){function delayedHide(){leaveTimer&&clearTimeout(leaveTimer),leaveTimer=setTimeout((function(){sbox.hide(o.toggleSpeed||200)}),o.toggleTimeout),closeOnBlur=!1}var self=this,o=self.options,closeOnBlur=!1;if(!self.control&&self.map){var searchField=jQuery('<form action="#"><div class="tekla-ims-search" title="'+(o.tooltipText||"")+'"><input type="text" placeholder="'+(o.placeholderText||"")+'" class="search-box" aria-label="'+(o.tooltipText||"")+'" style="display:none"></input><input type="submit" class="icon-ims icon-search" value="" aria-label="'+(o.tooltipText||"")+'"></input></div></form>'),leaveTimer=null,sbox=searchField.find(".search-box");o.toggleTimeout>0&&(searchField.mouseenter((function(){closeOnBlur=!1,leaveTimer&&clearTimeout(leaveTimer),sbox.show(o.toggleSpeed||200).focus()})).mouseleave((function(){sbox.is(":focus")?closeOnBlur=!0:delayedHide()})),sbox.blur((function(){1==closeOnBlur&&delayedHide()}))),searchField.submit((function(){var $form=jQuery(self.control);return $form.addClass("loading"),$form.find(":input").prop("disabled",!0),self.map.Search({searchtext:sbox.val(),category:o.categories,onComplete:function(){$form.removeClass("loading"),$form.find(":input").prop("disabled",!1)}}),!1})),jQuery.fn.placeholder&&sbox.placeholder(),self.control=searchField[0],self.control.style.position="absolute"}},ImportKmlControl.prototype.GetElement=function(){return this.ensureElement(),this.control},ImportKmlControl.prototype.ensureElement=function(){var o=this.options;if(!this.control&&this.map){var searchField=jQuery('<form action="#" enctype="multipart/form-data"><a title="'+(o.tooltipText||"")+'" id="ims-import-kml" style="position: relative; overflow: hidden;" class="icon-ims icon-tool icon-importkml" href="#"></a></form>'),sbox=searchField.find("#ims-import-kml");new qq.FileUploaderBasic({button:sbox[0],action:actionUrl("Import","ImportKml",!0),multiple:!1,allowedExtensions:["kml"],messages:{typeError:o.messages.typeError,sizeError:o.messages.sizeError,fileExistsError:o.messages.fileExistsError,minSizeError:"{file} is too small, minimum file size is {minSizeLimit}.",emptyError:"{file} is empty, please select files again without it.",noFilesError:"No files to upload.",onLeave:"The files are being uploaded, if you leave now the upload will be cancelled."},onComplete:function(id,fileName,responseJSON){if(responseJSON&&responseJSON.errorMessage)alert(responseJSON.errorMessage);else{var result=$_EVALJSON(responseJSON),zoomObj=null;if(null!=result&&result.geoJSON&&result.geoJSON.length>0){for(var i=0;i<result.geoJSON.length;i++){var item=result.geoJSON[i],data=_findKmlPres(o.kmlpres,item.geometry.type);if(null!=data){var obj=new SR_Geo(data.values.name,item.explanation);obj.MyOType=data.myotype,obj.set_Dirty(TXWConst.EDITSTATE_ALL),obj.Editable=!0,obj.mapbubble={editable:data.editable,visible:data.visible},obj.Geometry=item.geometry,obj.Presentation=data.presentation;MySitesDB.Insert(obj);$_CallEventHandler(tekla.Map.EVENT.BUBBLECOMMIT,"create",obj,data.values),zoomObj=obj}}window.teklaMap.RedrawLayers(),$_CallEventHandler(tekla.Map.EVENT.DRAWINGREADY,obj),zoomObj&&$_ZoomToObject(zoomObj)}}},params:{types:o.types||"",maxCount:o.maxcount||0}});this.control=searchField[0],this.control.style.position="absolute"}},LoadingIndicatorControl.prototype.GetElement=function(){return this.ensureElement(),this.control},LoadingIndicatorControl.prototype.ensureElement=function(){var self=this;if(!self.control&&self.map){var loaderindicator=jQuery(self.location===tekla.Map.CONTROLCONTAINER.BOTTOM||self.location===tekla.Map.CONTROLCONTAINER.TOP?'<div style="position:absolute" class="fw-progress-bar-container"><div class="fw-progress-bar"></div></div>':'<div style="position:absolute" class="loader-indicator-container"><span style="border:0" class="icon-ims icon-loading-indicator loader-indicator"></span></div>');self.control=loaderindicator[0],self.control.style.position="absolute",self.loading=0,self.map.Bind(tekla.Map.EVENT.LOADSTARTED,(function(){self.loading+=1,self.update()})),self.map.Bind(tekla.Map.EVENT.LOADREADY,(function(){self.loading-=1,self.update()})),self.update()}},LoadingIndicatorControl.prototype.update=function(){this.loading>0?jQuery(this.control).show():jQuery(this.control).hide()},CopyrightControl.prototype.GetElement=function(){return this.ensureElement(),this.control},CopyrightControl.prototype.ensureElement=function(control){var div,self=this;self.control||(control?div=self.control=control:((div=document.createElement("div")).id="copy1",div.className="map-copyright",div.innerHTML="&nbsp;",div.style.position="absolute",self.control=div),self.map.Bind(tekla.Map.EVENT.BASEMAPCHANGED,(function(){var text=self.getCopyrightText();div.innerHTML=text,"&nbsp;"===text?jQuery(div).hide():jQuery(div).show()})))},CopyrightControl.prototype.getCopyrightText=function(){var lastUpdate=Tekla.BaseMaps.activelastupdate(),text=Tekla.BaseMaps.activecopyright();return lastUpdate&&(text&&(text+=". "),text+=lastUpdate),text||"&nbsp;"},OpenInNewWindowControl.prototype.ensureElement=function(){var self=this,o=self.options;if(!self.control){var div=document.createElement("div");div.style.position="absolute",div.style.right="45px",div.className="openinnewwindow";var a=document.createElement("a");a.innerHTML=GetText("cl_openInNewWindow"),a.onclick=function(){var url=options.baseURL;if(url=self.changeQueryString(document.URL),!0===o.openMainIMS){var iQ=url.indexOf("?"),qPart=iQ>0?url.substr(iQ):null;url=options.appPath+"/"+options.lang+"/map"+(qPart||"")}window.open(url)},div.appendChild(a),self.control=div}},OpenInNewWindowControl.prototype.changeQueryString=function(url){if(url){var first=!0,retVal=url,iQ=url.indexOf("?");if(iQ>=0){var strip=["cp","z","basemap","theme","layers"],qsParams=url.substr(iQ+1).split("&");retVal=url.substr(0,iQ);for(var i=0;i<qsParams.length;i++){var pair=qsParams[i].split("=");-1===strip.indexOf(pair[0].toLowerCase())&&(retVal+=(first?"?":"&")+pair[0]+"="+pair[1],first=!1)}}var mapL=this.map,center=mapL.GetCenter();return retVal+(first?"?":"&")+"basemap="+encodeURIComponent(mapL.GetBaseMap())+"&cp="+center[0]+","+center[1]+"&z="+mapL.GetZoom()}},OpenInNewWindowControl.prototype.GetElement=function(){return this.ensureElement(),this.control},NamedAreasVisualizerControl.prototype.updateAreas=function(){var self=this,arr=self.map.GetNamedAreas();if(arr&&arr.length>0){NamedAreasDB.Clear();var areaRange=null;jQuery(arr).each((function(){if(this.north&&this.east&&this.south&&this.west){var sqMeters=Math.abs(this.east-this.west)*Math.abs(this.north-this.south);areaRange?(areaRange.min=Math.min(areaRange.min,sqMeters),areaRange.max=Math.max(areaRange.max,sqMeters)):areaRange={min:sqMeters,max:sqMeters}}})),jQuery(arr).each((function(){var area=this;if(area.north&&area.east&&area.south&&area.west){var obj=new SR_Geo(area.name||"","");obj.set_Geometry({type:"Polygon",coordinates:[[[area.west,area.north],[area.east,area.north],[area.east,area.south],[area.west,area.south],[area.west,area.north]]]});obj.set_Presentation(jQuery.extend({LineColor:"#000000",LineType:"solid",LineWidth:2,LineOpacity:.6,FillColor:"#ffffff",FillOpacity:.2},window.options.presentations.namedarea||{})),obj.Editable=!1,obj.isVisible=function(){var area=window.teklaMap.GetArea(!0),areawidth=.5*(area.east-area.west),areaheight=.5*(area.north-area.south);return Math.abs(area.east-area.west)<areawidth&&Math.abs(area.north-area.south)<areaheight},obj.oninfo=function(){self.map.SetArea(area.north,area.east,area.south,area.west)},NamedAreasDB.Insert(obj)}}))}},NamedAreasVisualizerControl.prototype.GetElement=function(){return null},NamedAreasVisualizerControl.prototype.SetOptions=function(options){return null},BaseMapHandler.prototype.SetBaseMap=function(name){var customMap=this.customBaseMaps[name],nameKey=customMap?customMap.basemap.name:name,index=Tekla.BaseMaps.findindex(nameKey);if(index>=0){if(Tekla.BaseMaps.setactive(index),customMap&&(map.HideAllLayers(),customMap.layers))for(var i=0;i<customMap.layers.length;i++)map.SetLayerVisible(customMap.layers[i]);window.teklaMap._UpdateMapPosition();var bMap=Tekla.BaseMaps.get(nameKey);jQuery(this.map.md).css("background-color",bMap.backgroundColor||"#FFF"),this.map.Trigger(tekla.Map.EVENT.BASEMAPCHANGED,name)}else window.teklaMap3&&window.Tekla.ThreeD&&(index=Tekla.BaseMaps.findIndexType(nameKey,!0))>=0&&(Tekla.BaseMaps.setActiveThreeD(index),this.map.Trigger(tekla.Map.EVENT.BASEMAPCHANGED,name))},BaseMapHandler.prototype.AddCustomBaseMap=function(context){context&&context.name&&(this.customBaseMaps[context.name]=context)},MapLegendControl.prototype.GetElement=function(){return this.ensureElement(),this.control},MapLegendControl.prototype.ensureElement=function(control){var self=this;if(!self.control){var map=self.map,func=function(event){cancelEventPropagation(event),self._loaded?$(".map-legend-container").toggle():$.getJSON(options.metadataURL.replace("_LR_",self.layer),(function(data){data.LegendType&&($(map.md).parent().append(jQuery('<div class="map-legend-container">'+("image"===data.LegendType?'<img src="'+data.LegendValue+'" />':data.LegendValue)+"</div>")),self._loaded=!0)}))};control?(self.control=control,_attachCH(self.control,func)):self.control=createToolButton(0,"icon-map-legend",GetText("mapLegend"),func)}}}(jQuery,window),function($,window){var document=window.document;if(window.tekla&&window.tekla.mapApiOptions){var o=jQuery.extend({drawings:{overrideEmptyName:" ",allowSpecialLinks:["ACP"],editable:["explanation"],visible:["name","explanation"]}},window.tekla.mapApiOptions),head=document.getElementsByTagName("head");if(head&&head.length>0){var injct=document.createElement("link");injct.type="text/css",injct.rel="stylesheet",injct.href=o.styleUri,head[0].appendChild(injct)}window.tekla.Map.defaultOptions=jQuery.extend(!0,{},window.tekla.Map.defaultOptions,o||{}),delete window.tekla.mapApiOptions}}(jQuery,window);
function Browser$ClipBoard(elem){var isInput="INPUT"===elem.tagName||"TEXTAREA"===elem.tagName,succeed=!1;if(isInput){var origSelectionStart,origSelectionEnd,target=elem;origSelectionStart=elem.selectionStart,origSelectionEnd=elem.selectionEnd;var currentFocus=document.activeElement;target.focus(),target.setSelectionRange(0,target.value.length);try{succeed=document.execCommand("copy")}catch(e){succeed=!1}currentFocus&&"function"==typeof currentFocus.focus&&currentFocus.focus(),isInput&&elem.setSelectionRange(origSelectionStart,origSelectionEnd)}return succeed}function Browser$Email(subject,url){var target="mailto:?subject="+$_ENCODE(subject)+"&body="+$_ENCODE(subject)+"%20"+$_ENCODE(url);options.emailUsingWindowOpen?window.open(target,"email"):window.location=target}function $_scanForm(form){for(var sb=new StringBuilder(""),i=0;i<form.length;i++){var element=form[i],fieldvalue="";if(String.IsPrintable(element.name)){switch(element.type.toLowerCase()){case"submit":case"hidden":case"password":case"text":case"textarea":fieldvalue="&"+element.name+"="+$_ENCODE(element.value);break;case"checkbox":case"radio":element.checked&&(fieldvalue="&"+element.name+"="+element.value);break;case"select-one":var selIndex=element.selectedIndex;if(selIndex>=0){var option=element.options[selIndex];fieldvalue="&"+element.name+"="+option.value}break;case"select-multiple":for(var e=0;e<element.length;e++){var optionm=element.options[e];optionm.selected&&(fieldvalue+="&"+element.name+"="+optionm.value)}break;case"button":fieldvalue="&"+element.name+"="+element.value;break;default:alert("Unknown type: "+type)}sb.Append(fieldvalue)}}return sb.ToString()}function $_clearForm(form){for(var i=0;i<form.length;i++){var element=form[i];if(String.IsPrintable(element.name))switch(element.type.toLowerCase()){case"submit":case"hidden":case"password":case"text":case"textarea":element.value="";break;case"checkbox":case"radio":case"button":break;case"select-one":element.length>0&&(element.selectedIndex=0);break;case"select-multiple":for(var e=0;e<element.length;e++){var option=element.options[e];option.selected&&(option.selected=!1)}}}}function hideObj(objname){jQuery("#"+objname).hide()}function showObj(objname){jQuery("#"+objname).show()}
function StringBuilder(value){this.sts=[""],this.Append(value)}function $_ENCODE(s){return encodeURIComponent(s)}function $_ENCODE_Safe(s){return s?$_ENCODE(s):""}function $_EVALJSON(s){return eval("("+s+")")}function $_CloneObject(obj,deep){if(!obj||!obj.constructor)return null;var objectClone=new obj.constructor;for(var property in obj)objectClone[property]=deep&&"object"==typeof obj[property]?obj[property]?$_CloneObject(obj[property],deep):null:obj[property];return objectClone}function $_splitNameValue(actionString,sep){var n="",v="";sep||(sep=$_nameSeparator);var a1=actionString.indexOf(sep);return a1>=0&&(n=actionString.slice(0,a1),(a1=(v=actionString.slice(a1+1)).indexOf(sep))>0&&(v=v.slice(0,a1))),{name:n,value:v}}function FileGetExtension(file){var ext=/^.+\.([^.]+)$/.exec(file);return null==ext?"":ext[1]}function FileIsImage(file){var ext=FileGetExtension(file);if(ext)for(var c=ext.toLowerCase(),extensions=["jpg","jpeg","tif","tiff","gif","png"],i=0;i<extensions.length;i++)if(c===extensions[i])return!0;return!1}function UtilGetDate(Lang){var Now=new Date,Day=Now.getDate(),Month=Now.getMonth()+1,Year=Now.getYear();Year<1e3&&(Year+=1900);var hrs=Now.getHours(),mns=Now.getMinutes(),scs=Now.getSeconds(),DayExpl="fin"==Lang?["Sunnuntai","Maanantai","Tiistai","Keskiviikko","Torstai","Perjantai","Lauantai"][Now.getDay()]:void 0;return(DayExpl?DayExpl+" ":"")+Day+"."+Month+"."+Year+" "+(hrs+":"+(mns>9?mns:"0"+mns)+":"+(scs>9?scs:"0"+scs))}StringBuilder.prototype.Append=function(value){value&&this.sts.push(value)},StringBuilder.prototype.ToString=function(){return this.sts.join("")},String.prototype.stripSpaces=function(){return this.replace(/\s/g,"")},
/*! https://mths.be/startswith v0.2.0 by @mathias */
String.prototype.startsWith||function(){"use strict";var defineProperty=function(){try{var object={},$defineProperty=Object.defineProperty,result=$defineProperty(object,object,object)&&$defineProperty}catch(error){}return result}(),toString={}.toString,startsWith=function(search){if(null==this)throw TypeError();var string=String(this);if(search&&"[object RegExp]"==toString.call(search))throw TypeError();var stringLength=string.length,searchString=String(search),searchLength=searchString.length,position=arguments.length>1?arguments[1]:void 0,pos=position?Number(position):0;pos!=pos&&(pos=0);var start=Math.min(Math.max(pos,0),stringLength);if(searchLength+start>stringLength)return!1;for(var index=-1;++index<searchLength;)if(string.charCodeAt(start+index)!=searchString.charCodeAt(index))return!1;return!0};defineProperty?defineProperty(String.prototype,"startsWith",{value:startsWith,configurable:!0,writable:!0}):String.prototype.startsWith=startsWith}(),String.escapeHTML=function(text,b){if(!text)return"";if(text.indexOf("<")>=0||text.indexOf(">")>=0||text.indexOf("&")>=0){var d=document.createElement("div"),ret="";if(b)for(var rw=text.split("<br/>"),i=0;i<rw.length;i++){var t=document.createTextNode(rw[i]);d.appendChild(t),ret+=d.innerHTML,i!=rw.length-1&&(ret+="<br/>"),d.removeChild(t)}else{t=document.createTextNode(text);d.appendChild(t),ret=d.innerHTML,d.removeChild(t)}return ret}return text},String.removeTags=function(text){return text.replace(/<\/?[^>]+>/gi,"")},String.unescapeHTML=function(text){var d=document.createElement("div");return d.innerHTML=String.removeTags(text),d.childNodes[0]?d.childNodes[0].nodeValue:""},String.format=function(){if(arguments.length<1)return null;for(var str=arguments[0],i=1;i<arguments.length;i++)str=str.replace(new RegExp("\\{"+(i-1)+"\\}","gm"),arguments[i]);return str},String.get_Safe=function(s){return s&&"undefined"!=s?s:""},String.IsPrintable=function(value){return null!=value&&"undefined"!=value&&value.length>0},String.IsNullOrEmpty=function(value){return!(null!=value&&"undefined"!=value&&value.length>0)},String.GetNetNonWhiteSpace=function(text){if(text)for(var i=0;i<text.length;i++){var ch=text.charAt(i);if(" "!=ch)return ch}return null},String.prototype.rtrim=function(){return this.replace(/\s+$/,"")},Array.prototype.remove=function(s){for(var i=0;i<this.length;i++)s==this[i]&&this.splice(i,1)},Array.prototype.Find=function(s){for(var i=0;i<this.length;i++)if(s==this[i])return!0;return!1},Array.prototype.FindByAttr=function(a,s){for(var i=0;i<this.length;i++)if(s==this[i][a])return this[i];return null},Array.prototype.indexOf||(Array.prototype.indexOf=function(obj,fromIndex){for(var i=null==fromIndex?0:fromIndex<0?Math.max(0,this.length+fromIndex):fromIndex,j=this.length;i<j;i++)if(this[i]===obj)return i;return-1}),function(jQuery,window){jQuery.fn.center||(jQuery.fn.center=function(){var $wnd=jQuery(window);return this.css("position","absolute"),this.css("top",Math.max(0,($wnd.height()-this.outerHeight())/2+$wnd.scrollTop())+"px"),this.css("left",Math.max(0,($wnd.width()-this.outerWidth())/2+$wnd.scrollLeft())+"px"),this}),String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^\s\s*/,"").replace(/\s\s*$/,"")})}(jQuery,window),function(window){var tekla=window.tekla=window.tekla||{};tekla.utility=tekla.utility||{},tekla.utility.isSameOrigin=function(url){var loc=window.location,a=document.createElement("a");return a.href=url,a.hostname==loc.hostname&&a.port==loc.port&&a.protocol==loc.protocol}}(window);
!function(factory){var L;if("function"==typeof define&&define.amd)define(["leaflet"],factory);else if("undefined"!=typeof module)L=require("leaflet"),module.exports=factory(L);else{if(void 0===window.L)throw new Error("Leaflet must be loaded first");factory(window.L)}}((function(L){L.Map.mergeOptions({ImsHandler:!0}),tekla.Map.ImsHandler=L.Handler.extend({addHooks:function(){L.DomEvent.on(this._map._container,"click",this._click,this),L.DomEvent.on(this._map._container,"doubleclick",this._doubleClick,this)},removeHooks:function(){L.DomEvent.off(this._map._container,"click",this._click,this),L.DomEvent.off(this._map._container,"doubleclick",this._doubleClick,this)},_doubleClick:function(e){var handled=!1;"drawpolyline"===toolMode||"drawpolygon"===toolMode||"drawrectangle"===toolMode?(showSiteProperties(this._map.mouseEventToLatLng(e)),handled=!0):"distance"===toolMode&&(endMeter(),handled=!0),handled&&e.preventDefault&&e.preventDefault()},_adjustPan:function(e){if(!this._panAnim||!this._panAnim._inProgress){var LeftOffset=Tekla.SideBar&&Tekla.SideBar.isVisible()?400:0,size=this._map.getSize(),offset=jQuery(this._map._container).offset(),pointX=e.pageX-offset.left,pointY=e.pageY-offset.top,width=size.x,height=size.y,dx=0,dy=0,widthTH=width*options.panTreshold,heightTH=height*options.panTreshold,scrollX=.3*(width-LeftOffset),scrollY=.3*height;pointX<widthTH+LeftOffset&&(dx=-scrollX),pointX>width-widthTH&&(dx=scrollX),pointY<heightTH&&(dy=-scrollY),pointY>height-heightTH&&(dy=scrollY),(dx||dy)&&this._map.panBy([dx,dy])}},_click:function(e){if("distance"===toolMode){var pt=this._map.mouseEventToLatLng(e);this._adjustPan(e),TGMap.Measure.addPoint(pt.lat,pt.lng)}else if("drawpolyline"===toolMode||"drawpolygon"===toolMode||"drawrectangle"===toolMode){var pointsouth=(pt=this._map.mouseEventToLatLng(e)).lat,pointeast=pt.lng;null==mapDrawing.points&&(mapDrawing.points=[]),mapDrawing.points.push([pointsouth,pointeast]),this._adjustPan(e),"drawrectangle"===toolMode&&2===mapDrawing.points.length?map.EndDraw():$_redrawDrawing(),e.preventDefault&&e.preventDefault()}else if("createsite"===toolMode||"createaddress"===toolMode||"createsearchobject"===toolMode||"movesite"===toolMode){var n=(pt=this._map.mouseEventToLatLng(e)).lat;e=pt.lng;if("createsite"==toolMode)window.teklaMap._selectedPositionSouth=Math.round(n),window.teklaMap._selectedPositionEast=Math.round(e),Tekla.MapBubble.insert(toolMode,pt,null),$_MouseMoved=!0;else if("createaddress"==toolMode)window.teklaMap._selectedPositionSouth=Math.round(n),window.teklaMap._selectedPositionEast=Math.round(e),Tekla.MapBubble.insert(toolMode,pt);else if("createsearchobject"==toolMode)window.teklaMap._selectedPositionSouth=Math.round(n),window.teklaMap._selectedPositionEast=Math.round(e),Tekla.MapBubble.insert(toolMode,pt);else if("movesite"==toolMode){var obj=$_DBSelect($_SelectedDBIndex,$_SelectedId);obj&&($_DBSetDirty($_SelectedDBIndex,!0),obj.Move(n,e,$_SelectedId),window.teklaMap.RedrawLayers(),clearToolstate(),startPan())}e.preventDefault&&e.preventDefault()}else if("selectposition"===toolMode){n=(pt=this._map.mouseEventToLatLng(e)).lat,e=pt.lng;window.teklaMap._UserPositionShow(Math.round(n),Math.round(e)),setStatus(GetText("cl_positionSelected")),$_hideTooltip(),$_cancelTooltip(),$_revertToolMode();var userPos=window.teklaMap._UserPositionGet();""==positionTarget||("searchengine"==positionTarget?$_SearchEngineInsert(userPos[0],userPos[1]):"feedback"==positionTarget?$_feedbackTargetSelected(userPos[0],userPos[1]):"property"==positionTarget?$_objectPropertyGet():"link"==positionTarget?(Tekla.MapLink.update(userPos[0],userPos[1]),window.teklaMap._UserPositionHideDelayed()):"areadivision"==positionTarget?$_searchAreaDivisionByPosition(userPos[0],userPos[1]):"emodel"==positionTarget?$_extendedFeedbackTargetSelected(userPos[0],userPos[1]):"external"==positionTarget?$_extEventHandler&&($_extPickOptions&&$_extPickOptions.targetSRS?Tekla.CoordinateTransformation.transform(userPos[0],userPos[1],(function(data){data&&data.north&&data.east&&$_extEventHandler(data.north,data.east)}),{targetSystem:$_extPickOptions.targetSRS,decimalCount:4}):$_extEventHandler(userPos[0],userPos[1])):positionTarget),positionTarget="",e.preventDefault&&e.preventDefault()}}}),L.Map.addInitHook("addHandler","ImsHandler",tekla.Map.ImsHandler)}));

