L.BingLayer=L.TileLayer.extend({options:{imagerySet:"Aerial",culture:"",style:"",retinaDpi:"d2",attribution:"Bing",minZoom:1,maxZoom:21},initialize:function(t,e){"object"==typeof t&&(e=t,t=!1),L.TileLayer.prototype.initialize.call(this,null,e),(e=this.options).key=e.key||e.bingMapsKey,e.imagerySet=e.imagerySet||e.type,t&&(e.key=t)},tile2quad:function(t,e,i){for(var r="",o=i;o>0;o--){var a=0,n=1<<o-1;t&n&&(a+=1),e&n&&(a+=2),r+=a}return r},getTileUrl:function(t){var e={subdomain:this._getSubdomain(t),quadkey:this.tile2quad(t.x,t.y,this._getZoomForUrl()),culture:this.options.culture};return L.Util.template(this._url,e)},callRestService:function(t,e,i){i=i||this;for(var r="_bing_metadata_"+L.Util.stamp(this);window[r];)r+="_";t+="&jsonp="+r;var o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("src",t),window[r]=function(t){if(delete window[r],o.remove(),t.errorDetails)throw new Error(t.errorDetails);e.call(i,t)},document.body.appendChild(o)},_makeApiUrl:function(t,e,i){var r={version:"v1",restApi:t,resourcePath:e};return i=L.extend({key:this.options.key},i),L.Util.template("https://dev.virtualearth.net/REST/{version}/{restApi}/{resourcePath}",r)+L.Util.getParamString(i)},loadMetadata:function(){if(!this.metaRequested){this.metaRequested=!0;var t=this.options,e=this._makeApiUrl("Imagery/Metadata",t.imagerySet,{UriScheme:"https",include:"ImageryProviders",culture:t.culture,style:t.style});this.callRestService(e,(function(e){var i=e.resourceSets[0].resources[0];if(!i.imageUrl)throw new Error("imageUrl not found in response");i.imageUrlSubdomains&&(t.subdomains=i.imageUrlSubdomains),this._providers=i.imageryProviders?this._prepAttrBounds(i.imageryProviders):[],this._attributions=[],this._url=i.imageUrl,t.retinaDpi&&t.detectRetina&&t.zoomOffset&&(this._url+="&dpi="+t.retinaDpi),this.fire("load",{meta:e}),this._map&&this._update()}))}},_prepAttrBounds:function(t){return t.forEach((function(t){t.coverageAreas.forEach((function(t){t.bounds=L.latLngBounds([t.bbox[0],t.bbox[1]],[t.bbox[2],t.bbox[3]])}))})),t},_update:function(t){this._url&&(L.GridLayer.prototype._update.call(this,t),this._update_attribution())},_update_attribution:function(t){var e=this._map.attributionControl;if(e){var i=this._map.getBounds();i=L.latLngBounds(i.getSouthWest().wrap(),i.getNorthEast().wrap());var r=this._getZoomForUrl(),o=this._providers.map((function(e){return!t&&e.coverageAreas.some((function(t){return r<=t.zoomMax&&r>=t.zoomMin&&i.intersects(t.bounds)}))}));o.forEach((function(t,i){t!=this._attributions[i]&&(t?e.addAttribution(this._providers[i].attribution):e.removeAttribution(this._providers[i].attribution))}),this),this._attributions=o}else this._attributions={}},onAdd:function(t){this.loadMetadata(),L.GridLayer.prototype.onAdd.call(this,t)},onRemove:function(t){this._providers&&this._update_attribution(!0),L.GridLayer.prototype.onRemove.call(this,t)}}),L.bingLayer=function(t,e){return new L.BingLayer(t,e)};