/*
 COPYRIGHT 2009 ESRI

 TRADE SECRETS: ESRI PROPRIETARY AND CONFIDENTIAL
 Unpublished material - all rights reserved under the
 Copyright Laws of the United States and applicable international
 laws, treaties, and conventions.

 For additional information, contact:
 Environmental Systems Research Institute, Inc.
 Attn: Contracts and Legal Services Department
 380 New York Street
 Redlands, California, 92373
 USA

 email: contracts@esri.com
 */

if(!dojo._hasResource["esri.layers.KMLLayer"]){dojo._hasResource["esri.layers.KMLLayer"]=true;dojo.provide("esri.layers.KMLLayer");dojo.require("esri.utils");dojo.require("esri.layers.layer");dojo.require("esri.layers.MapImageLayer");dojo.require("esri.layers.FeatureLayer");dojo.require("esri.dijit.Popup");dojo.declare("esri.layers.KMLLayer",[esri.layers.Layer],{serviceUrl:"http://utility.arcgis.com/sharing/kml",constructor:function(_1,_2){if(!_1){console.log("KMLLayer:constructor - please provide url for the KML file");}this._outSR=(_2&&_2.outSR)||new esri.SpatialReference({wkid:4326});this._options=_2;if(esri.config.defaults.kmlService){this.serviceUrl=esri.config.defaults.kmlService;}var _3=(this.linkInfo=_2&&_2.linkInfo);if(_3){this.visible=!!_3.visibility;this._waitingForMap=!!_3.viewFormat;}if(!_3||(_3&&_3.visibility&&!this._waitingForMap)){this._parseKml();}this.refresh=dojo.hitch(this,this.refresh);},getFeature:function(_4){if(!_4){return;}var _5=_4.type,id=_4.id,_6,i,_7;switch(_5){case "esriGeometryPoint":case "esriGeometryPolyline":case "esriGeometryPolygon":var _8=this["_"+_5];if(_8){_6=dojo.getObject("_mode._featureMap."+id,false,_8);}break;case "GroundOverlay":var _9=this._groundLyr;if(_9){var _a=_9.getImages();_7=_a.length;for(i=0;i<_7;i++){if(_a[i].id===id){_6=_a[i];break;}}}break;case "ScreenOverlay":break;case "NetworkLink":dojo.some(this._links,function(_b){if(_b.linkInfo&&_b.linkInfo.id===id){_6=_b;return true;}else{return false;}});break;case "Folder":var _c=this.folders;_7=_c?_c.length:0;for(i=0;i<_7;i++){if(_c[i].id===id){_6=_c[i];break;}}break;default:console.log("KMLLayer:getFeature - unknown feature type");break;}return _6;},getLayers:function(){var _d=[];if(this._groundLyr){_d.push(this._groundLyr);}if(this._fLayers){_d=_d.concat(this._fLayers);}if(this._links){dojo.forEach(this._links,function(_e){if(_e.declaredClass){_d.push(_e);}});}return _d;},setFolderVisibility:function(_f,_10){if(!_f){return;}this._fireUpdateStart();_f.visible=_10;if(_10){_10=this._areLocalAncestorsVisible(_f);}this._setState(_f,_10);this._fireUpdateEnd();},onRefresh:function(){},_parseKml:function(map){var _11=this;this._fireUpdateStart();this._io=esri.request({url:this.serviceUrl,content:{url:this._url.path+this._getQueryParameters(map),model:"simple",folders:"",refresh:this.loaded?true:undefined,outSR:dojo.toJson(this._outSR.toJson())},callbackParamName:"callback",load:function(_12){_11._io=null;_11._initLayer(_12);},error:function(err){_11._io=null;err=dojo.mixin(new Error(),err);err.message="Unable to load KML: "+_11.url+" "+(err.message||"");_11._fireUpdateEnd(err);_11.onError(err);}});},_initLayer:function(_13){if(this.loaded){this._removeInternalLayers();}this.name=_13.name;this.description=_13.description;this.snippet=_13.snippet;this.visibility=_13.visibility;this.featureInfos=_13.featureInfos;var i,len;var _14=(this.folders=_13.folders),_15=[],_16;if(_14){len=_14.length;for(i=0;i<len;i++){_16=(_14[i]=new esri.layers.KMLFolder(_14[i]));if(_16.parentFolderId===-1){_15.push(_16);}}}var _17=(this._links=_13.networkLinks),_18;len=_17?_17.length:0;for(i=0;i<len;i++){if(_17[i].viewRefreshMode&&_17[i].viewRefreshMode.toLowerCase().indexOf("onregion")!==-1){continue;}_18=dojo.mixin({},this._options);_18.linkInfo=_17[i];if(_18.id){_18.id=_18.id+"_"+i;}_17[i]=new esri.layers.KMLLayer(_17[i].href,_18);_17[i]._parentLayer=this;_17[i]._parentFolderId=this._getLinkParentId(_17[i].linkInfo.id);}var _19=_13.groundOverlays;if(_19&&_19.length>0){_18=dojo.mixin({},this._options);if(_18.id){_18.id=_18.id+"_"+"mapImage";}var _1a=(this._groundLyr=new esri.layers.MapImageLayer(_18));len=_19.length;for(i=0;i<len;i++){_1a.addImage(new esri.layers.KMLGroundOverlay(_19[i]));}}var _1b=dojo.getObject("featureCollection.layers",false,_13);if(_1b&&_1b.length>0){this._fLayers=[];dojo.forEach(_1b,function(_1c,i){var _1d=dojo.getObject("featureSet.features",false,_1c),_1e;if(_1d&&_1d.length>0){_18=dojo.mixin({outFields:["*"],infoTemplate:_1c.popupInfo?new esri.dijit.PopupTemplate(_1c.popupInfo):null,editable:false},this._options);if(_18.id){_18.id=_18.id+"_"+i;}_1c.layerDefinition.capabilities="Query,Data";_1e=new esri.layers.FeatureLayer(_1c,_18);if(_1e.geometryType){this["_"+_1e.geometryType]=_1e;}this._fLayers.push(_1e);}},this);if(this._fLayers.length===0){delete this._fLayers;}}len=_15.length;for(i=0;i<len;i++){_16=_15[i];this._setState(_16,_16.visible);}this._fireUpdateEnd();if(this.loaded){this._addInternalLayers();this.onRefresh();}else{this.loaded=true;this.onLoad(this);}},_addInternalLayers:function(){var map=this._map;this._fireUpdateStart();if(this._links){dojo.forEach(this._links,function(_1f){if(_1f.declaredClass){map.addLayer(_1f);if(_1f._waitingForMap){_1f._waitingForMap=null;if(_1f.visible){_1f._parseKml(map);}else{_1f._wMap=map;}}}});}var _20=map.spatialReference,_21=this._outSR,_22,_23;if(_20.wkid){_22=(_20._isWebMercator()&&_21._isWebMercator())||(_20.wkid===_21.wkid);}else{if(_20.wkt){_22=(_20.wkt===_21.wkt);}else{console.log("KMLLayer:_setMap - map has invalid spatial reference");return;}}if(!_22){if(_20._isWebMercator()&&_21.wkid===4326){_23=esri.geometry.geographicToWebMercator;}else{if(_21._isWebMercator()&&_20.wkid===4326){_23=esri.geometry.webMercatorToGeographic;}else{console.log("KMLLayer:_setMap - unsupported workflow. Spatial reference of the map and kml layer do not match, and the conversion cannot be done on the client.");return;}}}if(this._groundLyr){if(_23){dojo.forEach(this._groundLyr.getImages(),function(_24){_24.extent=_23(_24.extent);});}map.addLayer(this._groundLyr);}var _25=this._fLayers;if(_25&&_25.length>0){dojo.forEach(_25,function(_26){if(_23){var _27=_26.graphics,i,_28,len=_27?_27.length:0;for(i=0;i<len;i++){_28=_27[i].geometry;if(_28){_27[i].setGeometry(_23(_28));}}}map.addLayer(_26);});}this.onVisibilityChange(this.visible);},_removeInternalLayers:function(){var map=this._map;if(this._links){dojo.forEach(this._links,function(_29){if(_29.declaredClass&&_29._io){_29._io.cancel();}});}if(map){dojo.forEach(this.getLayers(),map.removeLayer,map);}},_setState:function(_2a,_2b){var _2c=_2a.featureInfos,_2d,_2e,i,len=_2c?_2c.length:0,_2f=_2b?"show":"hide";for(i=0;i<len;i++){_2d=_2c[i];_2e=this.getFeature(_2d);if(!_2e){continue;}if(_2d.type==="Folder"){this._setState(_2e,_2b&&_2e.visible);}else{if(_2d.type==="NetworkLink"){this._setInternalVisibility(_2e,_2b);}else{_2e[_2f]();}}}},_areLocalAncestorsVisible:function(_30){var _31=_30.parentFolderId,_32=_30.visible;while(_32&&_31!==-1){var _33=this.getFeature({type:"Folder",id:_31});_32=_32&&_33.visible;_31=_33.parentFolderId;}return _32;},_setInternalVisibility:function(_34,_35){var _36=_34._parentLayer,_37=_34._parentFolderId;_35=_35&&_34.visible;while(_35&&_36){_35=_35&&_36.visible;if(_37>-1){_35=_35&&_36._areLocalAncestorsVisible(_36.getFeature({type:"Folder",id:_37}));}_37=_36._parentFolderId;_36=_36._parentLayer;}this._setIntState(_34,_35);},_setIntState:function(_38,_39){if(!_38){return;}dojo.forEach(_38.getLayers(),function(_3a){if(_3a.linkInfo){_38._setIntState(_3a,_39&&_3a.visible&&_38._areLocalAncestorsVisible(_38.getFeature({type:"Folder",id:_3a._parentFolderId})));}else{_3a.setVisibility(_39);}});},_getLinkParentId:function(id){var _3b=-1;if(this.folders){dojo.some(this.folders,function(_3c){if(_3c.networkLinkIds&&dojo.indexOf(_3c.networkLinkIds,id)!==-1){_3b=_3c.id;return true;}return false;});}return _3b;},_checkAutoRefresh:function(){var _3d=this.linkInfo;if(_3d){if(this.visible){if(this.loaded&&this._map){var _3e=_3d.refreshMode,_3f=_3d.refreshInterval,_40=_3d.viewRefreshMode,_41=_3d.viewRefreshTime;if(_3e&&_3e.toLowerCase().indexOf("oninterval")!==-1&&_3f>0){this._stopAutoRefresh();this._timeoutHandle=setTimeout(this.refresh,_3f*1000);}if(_40&&_40.toLowerCase().indexOf("onstop")!==-1&&_41>0){if(!this._extChgHandle){this._extChgHandle=dojo.connect(this._map,"onExtentChange",this,this._extentChanged);}}}}else{this._stopAutoRefresh();dojo.disconnect(this._extChgHandle);delete this._extChgHandle;}}},_stopAutoRefresh:function(){clearTimeout(this._timeoutHandle);this._timeoutHandle=null;},_getQueryParameters:function(map){map=map||this._map;var _42={},_43=this.linkInfo,_44=map&&map.extent;if(this._url.query){dojo.mixin(_42,this._url.query);}if(_43){var _45=_43.viewFormat,_46=_43.httpQuery,_47=_43.viewBoundScale;if(_44&&_45){var _48=_44,_49=_44,sr=_44.spatialReference;if(sr){if(sr._isWebMercator()){_48=esri.geometry.webMercatorToGeographic(_44);}else{if(sr.wkid===4326){_49=esri.geometry.geographicToWebMercator(_44);}}}var _4a=_48.getCenter(),_4b=Math.max(_49.getWidth(),_49.getHeight());if(_47){_48=_48.expand(_47);}_45=_45.replace(/\[bboxWest\]/ig,_48.xmin).replace(/\[bboxEast\]/ig,_48.xmax).replace(/\[bboxSouth\]/ig,_48.ymin).replace(/\[bboxNorth\]/ig,_48.ymax).replace(/\[lookatLon\]/ig,_4a.x).replace(/\[lookatLat\]/ig,_4a.y).replace(/\[lookatRange\]/ig,_4b).replace(/\[lookatTilt\]/ig,0).replace(/\[lookatHeading\]/ig,0).replace(/\[lookatTerrainLon\]/ig,_4a.x).replace(/\[lookatTerrainLat\]/ig,_4a.y).replace(/\[lookatTerrainAlt\]/ig,0).replace(/\[cameraLon\]/ig,_4a.x).replace(/\[cameraLat\]/ig,_4a.y).replace(/\[cameraAlt\]/ig,_4b).replace(/\[horizFov\]/ig,60).replace(/\[vertFov\]/ig,60).replace(/\[horizPixels\]/ig,map.width).replace(/\[vertPixels\]/ig,map.height).replace(/\[terrainEnabled\]/ig,0);dojo.mixin(_42,dojo.queryToObject(_45));}if(_46){_46=_46.replace(/\[clientVersion\]/ig,esri.version).replace(/\[kmlVersion\]/ig,2.2).replace(/\[clientName\]/ig,"ArcGIS API for JavaScript").replace(/\[language\]/ig,dojo.locale);dojo.mixin(_42,dojo.queryToObject(_46));}}var _4c=[],_4d;for(_4d in _42){if(esri._isDefined(_42[_4d])){_4c.push(_4d+"="+_42[_4d]);}}_4c=_4c.join("&");return _4c?("?"+_4c):"";},_setMap:function(map,_4e){this._map=map;var div=this._div=dojo.create("div",null,_4e);dojo.style(div,"position","absolute");this._addInternalLayers();return div;},_unsetMap:function(map,_4f){if(this._io){this._io.cancel();}this._stopAutoRefresh();dojo.disconnect(this._extChgHandle);delete this._extChgHandle;this._removeInternalLayers();var div=this._div;if(div){_4f.removeChild(div);dojo.destroy(div);}this._map=this._wMap=this._div=null;},onVisibilityChange:function(_50){if(!this.loaded){if(this.linkInfo&&_50){if(!this._waitingForMap){this._parseKml(this._wMap);}}return;}this._fireUpdateStart();this._setInternalVisibility(this,_50);this._checkAutoRefresh();this._fireUpdateEnd();},refresh:function(){if(!this.loaded||!this._map||this._io){return;}this._parseKml();},_extentChanged:function(){this._stopAutoRefresh();this._timeoutHandle=setTimeout(this.refresh,this.linkInfo.viewRefreshTime*1000);}});dojo.declare("esri.layers.KMLGroundOverlay",[esri.layers.MapImage],{constructor:function(_51){if(esri._isDefined(this.visibility)){this.visible=!!this.visibility;}}});dojo.declare("esri.layers.KMLFolder",null,{constructor:function(_52){dojo.mixin(this,_52);if(esri._isDefined(this.visibility)){this.visible=!!this.visibility;}}});}