/*
Copyright (c) 2008-2009, The Open Planning Project
All rights reserved.

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

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Open Planning Project nor the names
      of its contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

var GeoExplorer=Ext.extend(Ext.util.Observable,{map:null,layers:null,capabilities:null,mapPanel:null,alignToGrid:false,capGrid:null,popupCache:null,constructor:function(config){var query=Ext.urlDecode(document.location.search.substr(1));var queryConfig=Ext.util.JSON.decode(query.q);this.initialConfig=Ext.apply({},queryConfig,config);Ext.apply(this,this.initialConfig);this.addEvents("ready");if(this.proxy){OpenLayers.ProxyHost=this.proxy;}
this.popupCache={};this.load();},load:function(){GeoExplorer.util.dispatch([function(done){Ext.onReady(function(){this.createLayout();done();},this);},function(done){this.initCapabilities();this.capabilities.load({callback:done});}],this.activate,this);},initCapabilities:function(){var url;var args={SERVICE:"WMS",REQUEST:"GetCapabilities"};var argIndex=this.ows.indexOf("?");if(argIndex>-1){var search=this.ows.substring(this.ows.indexOf("?")+1);var url=this.ows.replace(search,Ext.urlEncode(Ext.apply(Ext.urlDecode(search),args)));}else{url=this.ows+"?"+Ext.urlEncode(args);}
if(this.proxy){url=this.proxy+encodeURIComponent(url);}
this.capabilities=new GeoExt.data.WMSCapabilitiesStore({url:url});},createLayout:function(){this.map=new OpenLayers.Map({allOverlays:true,controls:[new OpenLayers.Control.Navigation(),new OpenLayers.Control.PanPanel(),new OpenLayers.Control.ZoomPanel()]});var onDoubleClick=function(ctrl,evt){OpenLayers.Event.stop(evt?evt:window.event);};var controls=this.map.controls[1].controls;for(var i=0;i<controls.length;i++){OpenLayers.Event.observe(controls[i].panel_div,"dblclick",OpenLayers.Function.bind(onDoubleClick,this.map.controls[0],controls[i]));}
this.map.events.on({"preaddlayer":function(evt){if(evt.layer.mergeNewParams){var maxExtent=evt.layer.maxExtent;evt.layer.mergeNewParams({transparent:true,format:"image/png",tiled:true,tilesorigin:[maxExtent.left,maxExtent.bottom]});}},scope:this});var mapConfig=this.initialConfig.map||{};this.mapPanel=new GeoExt.MapPanel({layout:"anchor",border:true,region:"center",map:this.map,center:mapConfig.center&&new OpenLayers.LonLat(mapConfig.center[0],mapConfig.center[1]),zoom:mapConfig.zoom,items:[{xtype:"gx_zoomslider",vertical:true,height:100,plugins:new GeoExt.ZoomSliderTip({template:"<div>Zoom Level: {zoom}</div>"})},this.createMapOverlay()]});this.layers=this.mapPanel.layers;var addLayerButton=new Ext.Button({tooltip:"Add Layers",disabled:true,iconCls:"icon-addlayers",handler:this.showCapabilitiesGrid,scope:this});this.on("ready",function(){addLayerButton.enable();});var removeLayerAction=new Ext.Action({text:"Remove Layer",iconCls:"icon-removelayers",disabled:true,tooltip:"Remove Layer",handler:function(){var node=layerTree.getSelectionModel().getSelectedNode();if(node&&node.layer){var layer=node.layer;var store=node.layerStore;var record=store.getAt(store.findBy(function(record){return record.get("layer")===layer;}));store.remove(record);removeLayerAction.disable();}}});var layerTree=new Ext.tree.TreePanel({border:false,rootVisible:false,root:new GeoExt.tree.LayerContainer({text:'Map Layers',layerStore:this.layers}),enableDD:true,selModel:new Ext.tree.DefaultSelectionModel({listeners:{beforeselect:function(){var count=this.mapPanel.layers.queryBy(function(r){return!(r.get("layer")instanceof OpenLayers.Layer.Vector);}).getCount();if(count>1){removeLayerAction.enable();}},scope:this}}),listeners:{contextmenu:function(node,e){node.select();var c=node.getOwnerTree().contextMenu;c.contextNode=node;c.showAt(e.getXY());},scope:this},contextMenu:new Ext.menu.Menu({items:[{text:"Zoom to Layer Extent",iconCls:"icon-zoom-visible",handler:function(){var node=layerTree.getSelectionModel().getSelectedNode();if(node&&node.layer){this.map.zoomToExtent(node.layer.restrictedExtent);}},scope:this},removeLayerAction]})});var layersContainer=new Ext.Panel({autoScroll:true,border:false,region:'center',title:"Layers",items:[layerTree],tbar:[addLayerButton,Ext.apply(new Ext.Button(removeLayerAction),{text:""})]});var legendContainer=new GeoExt.LegendPanel({title:"Legend",border:false,region:'south',height:200,collapsible:true,split:true,autoScroll:true,ascending:false,map:this.map,defaults:{cls:'legend-item'}});var westPanel=new Ext.Panel({border:true,layout:"border",region:"west",width:250,split:true,collapsible:true,collapseMode:"mini",items:[layersContainer,legendContainer]});var toolbar=new Ext.Toolbar({xtype:"toolbar",region:"north",disabled:true,items:this.createTools()});this.on("ready",function(){var disabled=toolbar.items.filterBy(function(item){return item.initialConfig&&item.initialConfig.disabled;});toolbar.enable();disabled.each(function(item){item.disable();});});var viewport=new Ext.Viewport({layout:"fit",hideBorders:true,items:{layout:"border",deferredRender:false,items:[toolbar,this.mapPanel,westPanel]}});},activate:function(){this.addLayers();Ext.QuickTips.init();this.fireEvent("ready");},addLayers:function(){var mapConfig=this.initialConfig.map;if(mapConfig&&mapConfig.layers){var conf,id,record,layer,records=[];for(var i=0;i<mapConfig.layers.length;++i){conf=mapConfig.layers[i];id=this.capabilities.find("name",conf.name);if(id>=0){Ext.data.Record.AUTO_ID++;record=this.capabilities.getAt(id).copy(Ext.data.Record.AUTO_ID);layer=record.get("layer").clone();record.set("layer",null);record.set("layer",layer);layer.restrictedExtent=OpenLayers.Bounds.fromArray(record.get("llbbox"));if(this.alignToGrid){layer.maxExtent=new OpenLayers.Bounds(-180,-90,180,90);}else{layer.maxExtent=layer.restrictedExtent;}
layer.visibility=("visibility"in conf)?conf.visibility:true;if(conf.title){layer.setName(conf.title);record.set("title",conf.title);}
records.push(record);}}
this.layers.add(records);if(this.mapPanel.center){this.map.setCenter(this.mapPanel.center,this.mapPanel.zoom);}else if(this.mapPanel.extent){this.map.zoomToExtent(this.mapPanel.extent);}else{this.map.zoomToMaxExtent();}}},initCapGrid:function(){var capGridPanel=new GeoExplorer.CapabilitiesGrid({store:this.capabilities,mapPanel:this.mapPanel,layout:'fit',region:'center',autoScroll:true,alignToGrid:this.alignToGrid,listeners:{rowdblclick:function(panel,index,evt){panel.addLayers();}}});this.capGrid=new Ext.Window({title:"Available Layers",closeAction:'hide',layout:'border',height:300,width:600,items:[capGridPanel],bbar:["->",new Ext.Button({text:"Add Layers",iconCls:"icon-addlayers",handler:function(){capGridPanel.addLayers();},scope:this}),new Ext.Button({text:"Done",handler:function(){this.capGrid.hide();},scope:this})],listeners:{hide:function(win){capGridPanel.getSelectionModel().clearSelections();}}});},showCapabilitiesGrid:function(){if(!this.capGrid){this.initCapGrid();}
this.capGrid.show();},createMapOverlay:function(){var scaleLinePanel=new Ext.Panel({cls:'olControlScaleLine overlay-element overlay-scaleline',border:false});scaleLinePanel.on('render',function(){var scaleLine=new OpenLayers.Control.ScaleLine({div:scaleLinePanel.body.dom});this.map.addControl(scaleLine);scaleLine.activate();},this);var zoomStore=new GeoExt.data.ScaleStore({map:this.map});var zoomSelector=new Ext.form.ComboBox({emptyText:'Zoom level',tpl:'<tpl for="."><div class="x-combo-list-item">1 : {[parseInt(values.scale)]}</div></tpl>',editable:false,triggerAction:'all',mode:'local',store:zoomStore,width:110});zoomSelector.on('click',function(evt){evt.stopEvent();});zoomSelector.on('mousedown',function(evt){evt.stopEvent();});zoomSelector.on('select',function(combo,record,index){this.map.zoomTo(record.data.level);},this);var zoomSelectorWrapper=new Ext.Panel({items:[zoomSelector],cls:'overlay-element overlay-scalechooser',border:false});this.map.events.register('zoomend',this,function(){var scale=zoomStore.queryBy(function(record){return this.map.getZoom()==record.data.level;});if(scale.length>0){scale=scale.items[0];zoomSelector.setValue("1 : "+parseInt(scale.data.scale,10));}else{if(!zoomSelector.rendered){return;}
zoomSelector.clearValue();}});var mapOverlay=new Ext.Panel({cls:'map-overlay',items:[scaleLinePanel,zoomSelectorWrapper]});mapOverlay.on("afterlayout",function(){scaleLinePanel.body.dom.style.position='relative';scaleLinePanel.body.dom.style.display='inline';mapOverlay.getEl().on("click",function(x){x.stopEvent();});mapOverlay.getEl().on("mousedown",function(x){x.stopEvent();});},this);return mapOverlay;},createTools:function(){var toolGroup="toolGroup";var navAction=new GeoExt.Action({tooltip:"Pan Map",iconCls:"icon-pan",enableToggle:true,pressed:true,allowDepress:false,control:new OpenLayers.Control.Navigation(),map:this.map,toggleGroup:toolGroup});var historyControl=new OpenLayers.Control.NavigationHistory();this.map.addControl(historyControl);var navPreviousAction=new GeoExt.Action({tooltip:"Zoom to Previous Extent",iconCls:"icon-zoom-previous",disabled:true,control:historyControl.previous});var navNextAction=new GeoExt.Action({tooltip:"Zoom to Next Extent",iconCls:"icon-zoom-next",disabled:true,control:historyControl.next});var info={controls:[]};var infoButton=new Ext.Button({tooltip:"Get Feature Info",iconCls:"icon-getfeatureinfo",toggleGroup:toolGroup,enableToggle:true,allowDepress:false,toggleHandler:function(button,pressed){for(var i=0,len=info.controls.length;i<len;i++){if(pressed){info.controls[i].activate();}else{info.controls[i].deactivate();}}}});var updateInfo=function(){var queryableLayers=this.mapPanel.layers.queryBy(function(x){return x.get("queryable");});var map=this.mapPanel.map;var control;for(var i=0,len=info.controls.length;i<len;i++){control=info.controls[i];control.deactivate();control.destroy();}
info.controls=[];queryableLayers.each(function(x){var control=new OpenLayers.Control.WMSGetFeatureInfo({url:x.get("layer").url,queryVisible:true,layers:[x.get("layer")],eventListeners:{getfeatureinfo:function(evt){this.displayPopup(evt,x.get("title")||x.get("name"));},scope:this}});map.addControl(control);info.controls.push(control);if(infoButton.pressed){control.activate();}},this);};this.mapPanel.layers.on("update",updateInfo,this);this.mapPanel.layers.on("add",updateInfo,this);this.mapPanel.layers.on("remove",updateInfo,this);var activeIndex=0;var measureSplit=new Ext.SplitButton({iconCls:"icon-measure-length",tooltip:"Measure",enableToggle:true,toggleGroup:toolGroup,allowDepress:false,handler:function(button,event){if(!button.pressed){button.toggle();}else{button.menu.items.itemAt(activeIndex).setChecked(true);}},listeners:{toggle:function(button,pressed){if(!pressed){button.menu.items.each(function(i){i.setChecked(false);});}},render:function(button){Ext.ButtonToggleMgr.register(button);}},menu:new Ext.menu.Menu({items:[new Ext.menu.CheckItem(new GeoExt.Action({text:"Length",iconCls:"icon-measure-length",map:this.map,toggleGroup:toolGroup,group:toolGroup,allowDepress:false,map:this.map,control:this.createMeasureControl(OpenLayers.Handler.Path,"Length")})),new Ext.menu.CheckItem(new GeoExt.Action({text:"Area",iconCls:"icon-measure-area",map:this.map,toggleGroup:toolGroup,group:toolGroup,allowDepress:false,map:this.map,control:this.createMeasureControl(OpenLayers.Handler.Polygon,"Area")}))]})});measureSplit.menu.items.each(function(item,index){item.on({checkchange:function(item,checked){measureSplit.toggle(checked);if(checked){activeIndex=index;measureSplit.setIconClass(item.iconCls);}}});});var tools=[new Ext.Button({text:"GeoExplorer",iconCls:"icon-geoexplorer",handler:this.displayAppInfo}),"-",new Ext.Button({tooltip:"Bookmark",handler:this.bookmark,scope:this,iconCls:"icon-save"}),"-",navAction,infoButton,measureSplit,"-",new Ext.Button({handler:function(){this.map.zoomIn();},tooltip:"Zoom In",iconCls:"icon-zoom-in",scope:this}),new Ext.Button({tooltip:"Zoom Out",handler:function(){this.map.zoomOut();},iconCls:"icon-zoom-out",scope:this}),navPreviousAction,navNextAction,new Ext.Button({tooltip:"Zoom to Visible Extent",iconCls:"icon-zoom-visible",handler:function(){var extent,layer;for(var i=0,len=this.map.layers.length;i<len;++i){layer=this.map.layers[i];if(layer.getVisibility()){if(extent){extent.extend(layer.maxExtent);}else{extent=layer.maxExtent.clone();}}}
if(extent){this.map.zoomToExtent(extent);}},scope:this})];return tools;},createMeasureControl:function(handlerType,title){var styleMap=new OpenLayers.StyleMap({"default":new OpenLayers.Style(null,{rules:[new OpenLayers.Rule({symbolizer:{"Point":{pointRadius:4,graphicName:"square",fillColor:"white",fillOpacity:1,strokeWidth:1,strokeOpacity:1,strokeColor:"#333333"},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"#666666",strokeDashstyle:"dash"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"#666666",fillColor:"white",fillOpacity:0.3}}})]})});var cleanup=function(){if(measureToolTip){measureToolTip.destroy();}};var makeString=function(metricData){var metric=metricData.measure;var metricUnit=metricData.units;measureControl.displaySystem="english";var englishData=metricData.geometry.CLASS_NAME.indexOf("LineString")>-1?measureControl.getBestLength(metricData.geometry):measureControl.getBestArea(metricData.geometry);var english=englishData[0];var englishUnit=englishData[1];measureControl.displaySystem="metric";var dim=metricData.order==2?'<sup>2</sup>':'';return metric.toFixed(2)+" "+metricUnit+dim+"<br>"+
english.toFixed(2)+" "+englishUnit+dim;};var measureToolTip;var measureControl=new OpenLayers.Control.Measure(handlerType,{persist:true,handlerOptions:{layerOptions:{styleMap:styleMap}},eventListeners:{measurepartial:function(event){cleanup();measureToolTip=new Ext.ToolTip({html:makeString(event),title:title,autoHide:false,closable:true,draggable:false,mouseOffset:[0,0],showDelay:1,listeners:{hide:cleanup}});if(event.measure>0){var px=measureControl.handler.lastUp;var p0=this.mapPanel.getPosition();measureToolTip.targetXY=[p0[0]+px.x,p0[1]+px.y];measureToolTip.show();}},measure:function(event){cleanup();measureToolTip=new Ext.ToolTip({target:Ext.getBody(),html:makeString(event),title:title,autoHide:false,closable:true,draggable:false,mouseOffset:[0,0],showDelay:1,listeners:{hide:function(){measureControl.cancel();cleanup();}}});},deactivate:cleanup,scope:this}});return measureControl;},displayPopup:function(evt,title){var popup;var popupKey=evt.xy.x+"."+evt.xy.y;if(!(popupKey in this.popupCache)){var lonlat=this.map.getLonLatFromPixel(evt.xy);popup=new GeoExt.Popup({title:"Feature Info",layout:"accordion",map:this.map,lonlat:lonlat,width:250,height:300,listeners:{close:function(panel){delete this.popupCache[popupKey];},scope:this}});popup.show();this.popupCache[popupKey]=popup;}else{popup=this.popupCache[popupKey];}
var html=evt.text;if(!(html==''||html.match(/<body>\s*<\/body>/))){popup.add({title:title,layout:"fit",html:html,autoScroll:true,autoWidth:true,collapsible:true});}
popup.doLayout();},bookmark:function(){var config=this.extractConfiguration();var query=Ext.urlEncode({q:Ext.util.JSON.encode(config)});var url=document.location.protocol+"//"+
document.location.hostname+
document.location.pathname+"?"+query;var win=new Ext.Window({title:"Bookmark URL",layout:'form',labelAlign:'top',modal:true,bodyStyle:"padding: 5px",width:300,items:[{xtype:'textfield',fieldLabel:'Permalink',readOnly:true,anchor:"100%",selectOnFocus:true,value:url}]});win.show();win.items.first().selectText();return url;},extractConfiguration:function(){var config={};var center=this.map.getCenter();config.map={center:[center.lon,center.lat],zoom:this.map.zoom};config.map.layers=[];this.layers.each(function(layerRecord){if(layerRecord.get("layer").displayInLayerSwitcher){var c={title:layerRecord.get("title"),name:(layerRecord.get("layer").params&&layerRecord.get("layer").params.LAYERS)||layerRecord.get("name"),visibility:layerRecord.get("layer").getVisibility()};config.map.layers.push(c);}});return config;},displayAppInfo:function(){var win=new Ext.Window({title:"About GeoExplorer",html:"<iframe style=\"border: none; height: 100%; width: 100%\" src=\"about.html\"><a target=\"_blank\" href=\"about.html\">About GeoExplorer</a> </iframe>",modal:true,width:300,height:350});win.show();}});Ext.namespace("GeoExplorer");GeoExplorer.CapabilitiesGrid=Ext.extend(Ext.grid.GridPanel,{store:null,cm:null,mapPanel:null,url:null,autoExpandColumn:"title",initComponent:function(){if(!this.store){this.store=new GeoExt.data.WMSCapabilitiesStore({url:this.url+"?service=wms&request=GetCapabilities"});this.store.load();}
var expander=new Ext.grid.RowExpander({tpl:new Ext.Template('<p><b>Abstract:</b> {abstract}</p>')});this.plugins=expander;this.cm=new Ext.grid.ColumnModel([expander,{header:"Name",dataIndex:"name",width:180,sortable:true},{id:"title",header:"Title",dataIndex:"title",sortable:true},{header:"Queryable",dataIndex:"queryable"}]);GeoExplorer.CapabilitiesGrid.superclass.initComponent.call(this);},addLayers:function(base){var sm=this.getSelectionModel();var records=sm.getSelections();var record,layer,newRecords=[];for(var i=0;i<records.length;i++){Ext.data.Record.AUTO_ID++;record=records[i].copy(Ext.data.Record.AUTO_ID);layer=record.get("layer").clone();record.set("layer",null);record.set("layer",layer);layer.restrictedExtent=OpenLayers.Bounds.fromArray(record.get("llbbox"));if(this.alignToGrid){layer.maxExtent=new OpenLayers.Bounds(-180,-90,180,90);}else{layer.maxExtent=layer.restrictedExtent;}
newRecords.push(record);}
if(newRecords.length){var index=this.mapPanel.layers.findBy(function(r){return r.get("layer")instanceof OpenLayers.Layer.Vector;});if(index!==-1){this.mapPanel.layers.insert(index,newRecords);}else{this.mapPanel.layers.add(newRecords);}}}});Ext.namespace("GeoExplorer");GeoExplorer.util={dispatch:function(functions,complete,scope){complete=complete||Ext.emptyFn;scope=scope||this;var requests=functions.length;var responses=0;var storage={};function respond(){++responses;if(responses===requests){complete.call(scope,storage);}}
function trigger(index){window.setTimeout(function(){functions[index].apply(scope,[respond,storage]);});}
for(var i=0;i<requests;++i){trigger(i);}}};