/*

Copyright (c) 2008-2010, The Open Source Geospatial Foundation
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 Source Geospatial Foundation 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.

*/

Ext.namespace("GeoExt");GeoExt.LayerOpacitySlider=Ext.extend(Ext.Slider,{layer:null,complementaryLayer:null,delay:5,changeVisibilityDelay:5,aggressive:false,changeVisibility:false,value:null,inverse:false,constructor:function(config){if(config.layer){this.layer=this.getLayer(config.layer);this.bind();this.complementaryLayer=this.getLayer(config.complementaryLayer);if(config.inverse!==undefined){this.inverse=config.inverse;}
config.value=(config.value!==undefined)?config.value:this.getOpacityValue(this.layer);delete config.layer;delete config.complementaryLayer;}
GeoExt.LayerOpacitySlider.superclass.constructor.call(this,config);},bind:function(){if(this.layer&&this.layer.map){this.layer.map.events.on({changelayer:this.update,scope:this});}},unbind:function(){if(this.layer&&this.layer.map){this.layer.map.events.un({changelayer:this.update,scope:this});}},update:function(evt){if(evt.property==="opacity"&&evt.layer==this.layer){this.setValue(this.getOpacityValue(this.layer));}},setLayer:function(layer){this.unbind();this.layer=this.getLayer(layer);this.setValue(this.getOpacityValue(layer));this.bind();},getOpacityValue:function(layer){var value;if(layer&&layer.opacity!==null){value=parseInt(layer.opacity*(this.maxValue-this.minValue));}else{value=this.maxValue;}
if(this.inverse===true){value=(this.maxValue-this.minValue)-value;}
return value;},getLayer:function(layer){if(layer instanceof OpenLayers.Layer){return layer;}else if(layer instanceof GeoExt.data.LayerRecord){return layer.getLayer();}},initComponent:function(){GeoExt.LayerOpacitySlider.superclass.initComponent.call(this);if(this.changeVisibility&&this.layer&&(this.layer.opacity==0||(this.inverse===false&&this.value==this.minValue)||(this.inverse===true&&this.value==this.maxValue))){this.layer.setVisibility(false);}
if(this.complementaryLayer&&((this.layer&&this.layer.opacity==1)||(this.inverse===false&&this.value==this.maxValue)||(this.inverse===true&&this.value==this.minValue))){this.complementaryLayer.setVisibility(false);}
if(this.aggressive===true){this.on('change',this.changeLayerOpacity,this,{buffer:this.delay});}else{this.on('changecomplete',this.changeLayerOpacity,this);}
if(this.changeVisibility===true){this.on('change',this.changeLayerVisibility,this,{buffer:this.changeVisibilityDelay});}
if(this.complementaryLayer){this.on('change',this.changeComplementaryLayerVisibility,this,{buffer:this.changeVisibilityDelay});}
this.on("beforedestroy",this.unbind,this);},changeLayerOpacity:function(slider,value){if(this.layer){value=value/(this.maxValue-this.minValue);if(this.inverse===true){value=1-value;}
this.layer.setOpacity(value);}},changeLayerVisibility:function(slider,value){var currentVisibility=this.layer.getVisibility();if((this.inverse===false&&value==this.minValue)||(this.inverse===true&&value==this.maxValue)&&currentVisibility===true){this.layer.setVisibility(false);}else if((this.inverse===false&&value>this.minValue)||(this.inverse===true&&value<this.maxValue)&&currentVisibility==false){this.layer.setVisibility(true);}},changeComplementaryLayerVisibility:function(slider,value){var currentVisibility=this.complementaryLayer.getVisibility();if((this.inverse===false&&value==this.maxValue)||(this.inverse===true&&value==this.minValue)&&currentVisibility===true){this.complementaryLayer.setVisibility(false);}else if((this.inverse===false&&value<this.maxValue)||(this.inverse===true&&value>this.minValue)&&currentVisibility==false){this.complementaryLayer.setVisibility(true);}},addToMapPanel:function(panel){this.on({render:function(){var el=this.getEl();el.setStyle({position:"absolute",zIndex:panel.map.Z_INDEX_BASE.Control});el.on({mousedown:this.stopMouseEvents,click:this.stopMouseEvents});},scope:this});},removeFromMapPanel:function(panel){var el=this.getEl();el.un({mousedown:this.stopMouseEvents,click:this.stopMouseEvents,scope:this});this.unbind();},stopMouseEvents:function(e){e.stopEvent();}});Ext.reg('gx_opacityslider',GeoExt.LayerOpacitySlider);
Ext.namespace("GeoExt");GeoExt.MapPanel=Ext.extend(Ext.Panel,{map:null,layers:null,center:null,zoom:null,prettyStateKeys:false,extent:null,stateEvents:["aftermapmove","afterlayervisibilitychange","afterlayeropacitychange"],initComponent:function(){if(!(this.map instanceof OpenLayers.Map)){this.map=new OpenLayers.Map(Ext.applyIf(this.map||{},{allOverlays:true}));}
var layers=this.layers;if(!layers||layers instanceof Array){this.layers=new GeoExt.data.LayerStore({layers:layers,map:this.map.layers.length>0?this.map:null});}
if(typeof this.center=="string"){this.center=OpenLayers.LonLat.fromString(this.center);}else if(this.center instanceof Array){this.center=new OpenLayers.LonLat(this.center[0],this.center[1]);}
if(typeof this.extent=="string"){this.extent=OpenLayers.Bounds.fromString(this.extent);}else if(this.extent instanceof Array){this.extent=OpenLayers.Bounds.fromArray(this.extent);}
GeoExt.MapPanel.superclass.initComponent.call(this);this.addEvents("aftermapmove","afterlayervisibilitychange","afterlayeropacitychange");this.map.events.on({"moveend":this.onMoveend,"changelayer":this.onLayerchange,scope:this});},onMoveend:function(){this.fireEvent("aftermapmove");},onLayerchange:function(e){if(e.property){if(e.property==="visibility"){this.fireEvent("afterlayervisibilitychange");}else if(e.property==="opacity"){this.fireEvent("afterlayeropacitychange");}}},applyState:function(state){this.center=new OpenLayers.LonLat(state.x,state.y);this.zoom=state.zoom;var i,l,layer,layerId,visibility,opacity;var layers=this.map.layers;for(i=0,l=layers.length;i<l;i++){layer=layers[i];layerId=this.prettyStateKeys?layer.name:layer.id;visibility=state["visibility_"+layerId];if(visibility!==undefined){visibility=(/^true$/i).test(visibility);if(layer.isBaseLayer){if(visibility){this.map.setBaseLayer(layer);}}else{layer.setVisibility(visibility);}}
opacity=state["opacity_"+layerId];if(opacity!==undefined){layer.setOpacity(opacity);}}},getState:function(){var state;if(!this.map){return;}
var center=this.map.getCenter();state={x:center.lon,y:center.lat,zoom:this.map.getZoom()};var i,l,layer,layerId,layers=this.map.layers;for(i=0,l=layers.length;i<l;i++){layer=layers[i];layerId=this.prettyStateKeys?layer.name:layer.id;state["visibility_"+layerId]=layer.getVisibility();state["opacity_"+layerId]=layer.opacity==null?1:layer.opacity;}
return state;},updateMapSize:function(){if(this.map){this.map.updateSize();}},renderMap:function(){var map=this.map;map.render(this.body.dom);this.layers.bind(map);if(map.layers.length>0){if(this.center||this.zoom!=null){map.setCenter(this.center,this.zoom);}else if(this.extent){map.zoomToExtent(this.extent);}else{map.zoomToMaxExtent();}}},afterRender:function(){GeoExt.MapPanel.superclass.afterRender.apply(this,arguments);if(!this.ownerCt){this.renderMap();}else{this.ownerCt.on("move",this.updateMapSize,this);this.ownerCt.on({"afterlayout":{fn:this.renderMap,scope:this,single:true}});}},onResize:function(){GeoExt.MapPanel.superclass.onResize.apply(this,arguments);this.updateMapSize();},onBeforeAdd:function(item){if(typeof item.addToMapPanel==="function"){item.addToMapPanel(this);}
GeoExt.MapPanel.superclass.onBeforeAdd.apply(this,arguments);},remove:function(item,autoDestroy){if(typeof item.removeFromMapPanel==="function"){item.removeFromMapPanel(this);}
GeoExt.MapPanel.superclass.remove.apply(this,arguments);},beforeDestroy:function(){if(this.ownerCt){this.ownerCt.un("move",this.updateMapSize,this);}
if(this.map&&this.map.events){this.map.events.un({"moveend":this.onMoveend,"changelayer":this.onLayerchange,scope:this});}
if(!this.initialConfig.map||!(this.initialConfig.map instanceof OpenLayers.Map)){if(this.map&&this.map.destroy){this.map.destroy();}}
delete this.map;GeoExt.MapPanel.superclass.beforeDestroy.apply(this,arguments);}});GeoExt.MapPanel.guess=function(){return Ext.ComponentMgr.all.find(function(o){return o instanceof GeoExt.MapPanel;});};Ext.reg('gx_mappanel',GeoExt.MapPanel);
Ext.namespace("GeoExt");GeoExt.SliderTip=Ext.extend(Ext.slider.Tip,{hover:true,minWidth:10,offsets:[0,-10],dragging:false,init:function(slider){GeoExt.SliderTip.superclass.init.apply(this,arguments);if(this.hover){slider.on("render",this.registerThumbListeners,this);}
this.slider=slider;},registerThumbListeners:function(){var thumb,el;for(var i=0,ii=this.slider.thumbs.length;i<ii;++i){thumb=this.slider.thumbs[i];el=thumb.tracker.el;(function(thumb,el){el.on({mouseover:function(e){this.onSlide(this.slider,e,thumb);this.dragging=false;},mouseout:function(){if(!this.dragging){this.hide.apply(this,arguments);}},scope:this})}).apply(this,[thumb,el]);}},onSlide:function(slider,e,thumb){this.dragging=true;return GeoExt.SliderTip.superclass.onSlide.apply(this,arguments);}});
Ext.namespace("GeoExt");GeoExt.LayerOpacitySliderTip=Ext.extend(GeoExt.SliderTip,{template:'<div>{opacity}%</div>',compiledTemplate:null,init:function(slider){this.compiledTemplate=new Ext.Template(this.template);GeoExt.LayerOpacitySliderTip.superclass.init.call(this,slider);},getText:function(thumb){var data={opacity:thumb.value};return this.compiledTemplate.apply(data);}});
Ext.namespace("GeoExt","GeoExt.data");GeoExt.data.LayerReader=function(meta,recordType){meta=meta||{};if(!(recordType instanceof Function)){recordType=GeoExt.data.LayerRecord.create(recordType||meta.fields||{});}
GeoExt.data.LayerReader.superclass.constructor.call(this,meta,recordType);};Ext.extend(GeoExt.data.LayerReader,Ext.data.DataReader,{totalRecords:null,readRecords:function(layers){var records=[];if(layers){var recordType=this.recordType,fields=recordType.prototype.fields;var i,lenI,j,lenJ,layer,values,field,v;for(i=0,lenI=layers.length;i<lenI;i++){layer=layers[i];values={};for(j=0,lenJ=fields.length;j<lenJ;j++){field=fields.items[j];v=layer[field.mapping||field.name]||field.defaultValue;v=field.convert(v);values[field.name]=v;}
values.layer=layer;records[records.length]=new recordType(values,layer.id);}}
return{records:records,totalRecords:this.totalRecords!=null?this.totalRecords:records.length};}});
Ext.namespace("GeoExt.data");GeoExt.data.LayerRecord=Ext.data.Record.create([{name:"layer"},{name:"title",type:"string",mapping:"name"}]);GeoExt.data.LayerRecord.prototype.getLayer=function(){return this.get("layer");};GeoExt.data.LayerRecord.prototype.setLayer=function(layer){if(layer!==this.data.layer){this.dirty=true;if(!this.modified){this.modified={};}
if(this.modified.layer===undefined){this.modified.layer=this.data.layer;}
this.data.layer=layer;if(!this.editing){this.afterEdit();}}};GeoExt.data.LayerRecord.prototype.clone=function(id){var layer=this.getLayer()&&this.getLayer().clone();return new this.constructor(Ext.applyIf({layer:layer},this.data),id||layer.id);};GeoExt.data.LayerRecord.create=function(o){var f=Ext.extend(GeoExt.data.LayerRecord,{});var p=f.prototype;p.fields=new Ext.util.MixedCollection(false,function(field){return field.name;});GeoExt.data.LayerRecord.prototype.fields.each(function(f){p.fields.add(f);});if(o){for(var i=0,len=o.length;i<len;i++){p.fields.add(new Ext.data.Field(o[i]));}}
f.getField=function(name){return p.fields.get(name);};return f;};
Ext.namespace("GeoExt.data");GeoExt.data.ScaleStore=Ext.extend(Ext.data.Store,{map:null,constructor:function(config){var map=(config.map instanceof GeoExt.MapPanel?config.map.map:config.map);delete config.map;config=Ext.applyIf(config,{reader:new Ext.data.JsonReader({},["level","resolution","scale"])});GeoExt.data.ScaleStore.superclass.constructor.call(this,config);if(map){this.bind(map);}},bind:function(map,options){this.map=(map instanceof GeoExt.MapPanel?map.map:map);this.map.events.register('changebaselayer',this,this.populateFromMap);if(this.map.baseLayer){this.populateFromMap();}else{this.map.events.register('addlayer',this,this.populateOnAdd);}},unbind:function(){if(this.map){this.map.events.unregister('addlayer',this,this.populateOnAdd);this.map.events.unregister('changebaselayer',this,this.populateFromMap);delete this.map;}},populateOnAdd:function(evt){if(evt.layer.isBaseLayer){this.populateFromMap();this.map.events.unregister('addlayer',this,this.populateOnAdd);}},populateFromMap:function(){var zooms=[];var resolutions=this.map.baseLayer.resolutions;var units=this.map.baseLayer.units;for(var i=resolutions.length-1;i>=0;i--){var res=resolutions[i];zooms.push({level:i,resolution:res,scale:OpenLayers.Util.getScaleFromResolution(res,units)});}
this.loadData(zooms);},destroy:function(){this.unbind();GeoExt.data.ScaleStore.superclass.destroy.apply(this,arguments);}});
Ext.namespace("GeoExt.data");GeoExt.data.LayerStoreMixin=function(){return{map:null,reader:null,constructor:function(config){config=config||{};config.reader=config.reader||new GeoExt.data.LayerReader({},config.fields);delete config.fields;var map=config.map instanceof GeoExt.MapPanel?config.map.map:config.map;delete config.map;if(config.layers){config.data=config.layers;}
delete config.layers;var options={initDir:config.initDir};delete config.initDir;arguments.callee.superclass.constructor.call(this,config);if(map){this.bind(map,options);}},bind:function(map,options){if(this.map){return;}
this.map=map;options=options||{};var initDir=options.initDir;if(options.initDir==undefined){initDir=GeoExt.data.LayerStore.MAP_TO_STORE|GeoExt.data.LayerStore.STORE_TO_MAP;}
var layers=map.layers.slice(0);if(initDir&GeoExt.data.LayerStore.STORE_TO_MAP){this.each(function(record){this.map.addLayer(record.getLayer());},this);}
if(initDir&GeoExt.data.LayerStore.MAP_TO_STORE){this.loadData(layers,true);}
map.events.on({"changelayer":this.onChangeLayer,"addlayer":this.onAddLayer,"removelayer":this.onRemoveLayer,scope:this});this.on({"load":this.onLoad,"clear":this.onClear,"add":this.onAdd,"remove":this.onRemove,"update":this.onUpdate,scope:this});this.data.on({"replace":this.onReplace,scope:this});},unbind:function(){if(this.map){this.map.events.un({"changelayer":this.onChangeLayer,"addlayer":this.onAddLayer,"removelayer":this.onRemoveLayer,scope:this});this.un("load",this.onLoad,this);this.un("clear",this.onClear,this);this.un("add",this.onAdd,this);this.un("remove",this.onRemove,this);this.data.un("replace",this.onReplace,this);this.map=null;}},onChangeLayer:function(evt){var layer=evt.layer;var recordIndex=this.findBy(function(rec,id){return rec.getLayer()===layer;});if(recordIndex>-1){var record=this.getAt(recordIndex);if(evt.property==="order"){if(!this._adding&&!this._removing){var layerIndex=this.map.getLayerIndex(layer);if(layerIndex!==recordIndex){this._removing=true;this.remove(record);delete this._removing;this._adding=true;this.insert(layerIndex,[record]);delete this._adding;}}}else if(evt.property==="name"){record.set("title",layer.name);}else{this.fireEvent("update",this,record,Ext.data.Record.EDIT);}}},onAddLayer:function(evt){if(!this._adding){var layer=evt.layer;this._adding=true;this.loadData([layer],true);delete this._adding;}},onRemoveLayer:function(evt){if(this.map.unloadDestroy){if(!this._removing){var layer=evt.layer;this._removing=true;this.remove(this.getById(layer.id));delete this._removing;}}else{this.unbind();}},onLoad:function(store,records,options){if(!Ext.isArray(records)){records=[records];}
if(options&&!options.add){this._removing=true;for(var i=this.map.layers.length-1;i>=0;i--){this.map.removeLayer(this.map.layers[i]);}
delete this._removing;var len=records.length;if(len>0){var layers=new Array(len);for(var j=0;j<len;j++){layers[j]=records[j].getLayer();}
this._adding=true;this.map.addLayers(layers);delete this._adding;}}},onClear:function(store){this._removing=true;for(var i=this.map.layers.length-1;i>=0;i--){this.map.removeLayer(this.map.layers[i]);}
delete this._removing;},onAdd:function(store,records,index){if(!this._adding){this._adding=true;var layer;for(var i=records.length-1;i>=0;--i){layer=records[i].getLayer();this.map.addLayer(layer);if(index!==this.map.layers.length-1){this.map.setLayerIndex(layer,index);}}
delete this._adding;}},onRemove:function(store,record,index){if(!this._removing){var layer=record.getLayer();if(this.map.getLayer(layer.id)!=null){this._removing=true;this.removeMapLayer(record);delete this._removing;}}},onUpdate:function(store,record,operation){if(operation===Ext.data.Record.EDIT){if(record.modified&&record.modified.title){var layer=record.getLayer();var title=record.get("title");if(title!==layer.name){layer.setName(title);}}}},removeMapLayer:function(record){this.map.removeLayer(record.getLayer());},onReplace:function(key,oldRecord,newRecord){this.removeMapLayer(oldRecord);},getByLayer:function(layer){var index=this.findBy(function(r){return r.getLayer()===layer;});if(index>-1){return this.getAt(index);}},destroy:function(){this.unbind();GeoExt.data.LayerStore.superclass.destroy.call(this);}};};GeoExt.data.LayerStore=Ext.extend(Ext.data.Store,new GeoExt.data.LayerStoreMixin);GeoExt.data.LayerStore.MAP_TO_STORE=1;GeoExt.data.LayerStore.STORE_TO_MAP=2;
