var map,baseLayer,layer,diffLayer,selectLayer,popup,toolbar,cloudFeature,cloudPopup,projds,wfasDataBounds=new OpenLayers.Bounds(-2050500,-2136500,2536500,752500),getFeatureControl;function init(){map=new OpenLayers.Map($("center"),{controls:[]});map.addControl(new OpenLayers.Control.PanZoom);baseLayer=new OpenLayers.Layer.WMS("Blue Marble","/cgi-bin/mapserv",{layers:"bluemarble",format:"image/jpeg",map:"/home/apetkov/wfas/wfas_time_index.map"},{buffer:0,maxExtent:wfasDataBounds,projection:"EPSG:2163",singleTile:!1,maxResolution:5750,isBaseLayer:!0});layer=new OpenLayers.Layer.WMS("Dep from Average","/cgi-bin/mapserv",{layers:"da",format:"image/gif",map:"/home/apetkov/wfas/wfas_time_index.map"},
{buffer:0,maxExtent:wfasDataBounds,projection:"EPSG:2163",singleTile:!1,maxResolution:5750,visibility:!0,isBaseLayer:!1});diffLayer=new OpenLayers.Layer.WMS("Comparing images","php/img_difference.php",{layers:"diff",format:"image/gif",map:"/home/apetkov/wfas/img_diff.map"},{buffer:0,maxExtent:wfasDataBounds,projection:"EPSG:2163",singleTile:!1,maxResolution:5750,visibility:!0,isBaseLayer:!1});countries=new OpenLayers.Layer.WMS("State/Provincial Boundaries","/cgi-bin/mapserv?map=/home/apetkov/wfas/countries.map",
{layers:"countries",transparent:"true",format:"image/gif",map:"/home/apetkov/wfas/countries.map"},{projection:"EPSG:2163",maxExtent:wfasDataBounds,singleTile:!1,maxResolution:5750,visibility:!1,isBaseLayer:!1,buffer:0,displayInLayerSwitcher:!1});GACC=new OpenLayers.Layer.WMS("GACC Boundaries","/cgi-bin/mapserv?map=/home/apetkov/wfas/countries.map",{layers:"GACC",transparent:"true",format:"image/gif",map:"/home/apetkov/wfas/countries.map"},{projection:"EPSG:2163",maxExtent:wfasDataBounds,singleTile:!1,
maxResolution:5750,visibility:!1,isBaseLayer:!1,buffer:0,displayInLayerSwitcher:!1});selectLayer=new OpenLayers.Layer.Vector("Regional Statistics",{styleMap:new OpenLayers.Style(OpenLayers.Feature.Vector.style.select),displayInLayerSwitcher:!1});map.addLayers([baseLayer,layer,countries,GACC,selectLayer]);protocol_1=OpenLayers.Protocol.WFS.fromWMSLayer(countries,{featurePrefix:"ms",geometryName:"msGeometry",featureType:"countries",featureName:"state_or_p"});countries.addOptions({protocol:protocol_1});
protocol_2=OpenLayers.Protocol.WFS.fromWMSLayer(GACC,{featurePrefix:"ms",geometryName:"msGeometry",featureType:"GACC",featureName:"NAT_CODE"});GACC.addOptions({protocol:protocol_2});getFeatureControl=new OpenLayers.Control.GetFeature({protocol:protocol_1,title:"GetFeature Control",box:!1,hover:!1,multiple:!1,toggleKey:"ctrlKey"});getFeatureControl.events.register("featureselected",this,function(a){selectLayer.addFeatures([a.feature]);inputParams={wktText:(new OpenLayers.Format.WKT).write(a.feature),
date:formatDate(ImgDatePicker.getValue()),dataset:layer.params.LAYERS};Ext.Ajax.request({url:"/cgi-bin/subset_stats.py",params:inputParams,method:"POST",success:function(b){popup=new GeoExt.Popup({id:"gs-popup",title:"Raster statistics for "+a.feature.attributes[getFeatureControl.protocol.featureName],map:map,feature:a.feature,location:a.feature,width:200,html:b.responseText,collapsible:!0,listeners:{close:function(){selectLayer.destroyFeatures()}}});popup.show()},failure:function(a){Ext.MessageBox.alert("Failed",
a.responseText)}})});getFeatureControl.events.register("beforefeatureselected",this,function(){var a=Ext.getCmp("gs-popup");a!=void 0&&a.close()});getFeatureControl.events.register("featureunselected",this,function(a){selectLayer.removeFeatures([a.feature])});getFeatureControl.events.register("deactivate",this,function(){selectLayer.destroyFeatures();var a=Ext.getCmp("gs-popup");a!=void 0&&a.close()});map.setCenter(wfasDataBounds.getCenterLonLat())}init();function onPopupMouseDown(a){destroyPopup();OpenLayers.Event.stop(a)}
function addCloudPopup(a){this.updatePlot=function(a){document.getElementById("plotdiv").innerHTML="<img src='"+b+"&interval="+a+"'></img>"};var b="php/dirlist.php?dataset="+layer.params.LAYERS+"&lon="+a.lon+"&lat="+a.lat+"&window="+Ext.getCmp("win").getValue();cloudFeature=new OpenLayers.Feature(layer,a);cloudFeature.popupClass=OpenLayers.Popup.FramedCloud;cloudFeature.data.popupContentHTML="Time span: <a href=\"javascript:updatePlot('1 year')\">1yr</a> <a href=\"javascript:updatePlot('3 years')\">3yr</a> <a href=\"javascript:updatePlot('5 years')\">5yr</a> <a href=\"javascript:updatePlot('30 years')\">All</a><p> Export: <a href=\"php/xlsexport.php?type=plotdata\">.xls</a><br><div class='floatleft' id='plotdiv'><img src='"+b+
"&interval=6 months'></img></div>";destroyPopup();cloudPopup=cloudFeature.createPopup(!0);map.addPopup(cloudPopup);cloudPopup.show()}function destroyPopup(){cloudPopup!=null&&(map.removePopup(cloudPopup),cloudPopup.destroy(),cloudPopup=null)}
function generateLegendHtml(){for(var a="",b=1;b<map.layers.length-1;b++)a+=map.layers[b].name+":<br>",a+='<img src="/cgi-bin/mapserv?map='+map.layers[b].params.MAP+"&SERVICE=WMS&REQUEST=GetLegendGraphic&FORMAT=image/gif&VERSION=1.1.0&LAYER="+map.layers[b].params.LAYERS+'"</img><br>';return a}
function formatDate(a){var b=null;for(b=a<=new Date("2003/01/03")?4:a<=new Date("2006/12/31")?2:1;a.getDay()!=b;)a.setDate(a.getDate()+1);b=a.getDate()<10?"0"+a.getDate():a.getDate();var d=a.getMonth()<9?"0"+(a.getMonth()+1):a.getMonth()+1;return a.getFullYear()+"-"+d+"-"+b}
function identify(a){a=map.getLonLatFromViewPortPx(a);Ext.getCmp("pointPanel").expand(!0);AppDataStores.projds.load({params:{x:a.lon,y:a.lat,time:layer.params.TIME,dataset:layer.params.LAYERS,window:Ext.getCmp("win").getValue()},add:!0})}function updateDisplay(a,b,d){a.setName(b);a.mergeNewParams(d);a.setOpacity(opacitySlider.getValue()/100);map.removeLayer(map.layers[1]);map.addLayer(a);map.setLayerIndex(a,1);a=generateLegendHtml();Ext.getCmp("legend").body.update(a)}
function downloadData(a,b){try{Ext.destroy(Ext.get("downloadIframe"))}catch(d){}var c;c=b.bbox?b.bbox.toArray():wfasDataBounds.toArray();c=a?"/cgi-bin/mapserv?SERVICE=wcs&REQUEST=GetCoverage&VERSION=1.0.0&COVERAGE=diff&DATASET="+Ext.getCmp("datatype").getValue()+"&QUERYDATE="+formatDate(b.queryDate)+"&BASEDATE="+formatDate(b.baseDate)+"&CRS=EPSG:2163&BBOX="+c[0]+","+c[1]+","+c[2]+","+c[3]+"&RESX=1000&RESY=1000&FORMAT="+b.format:"/cgi-bin/mapserv?&MAP=%2Fhome%2Fapetkov/wfas/wfas_time_index.map&SERVICE=wcs&REQUEST=GetCoverage&VERSION=1.0.0&COVERAGE="+
b.dataset+"&TIME="+b.time+"&CRS=EPSG:2163&BBOX="+c[0]+","+c[1]+","+c[2]+","+c[3]+"&RESX=1000&RESY=1000&FORMAT="+b.format;Ext.DomHelper.append(document.body,{tag:"iframe",id:"downloadIframe",frameBorder:0,width:0,height:0,css:"display:none;visibility:hidden;height:0px;",src:c})};var ImgDatePicker=new Ext.ux.form.DateFieldPlus({hideLabel:!0,name:"datestamp",id:"dateField",format:"Y-m-d",renderTodayButton:!1,showToday:!1,showWeekNumber:!1,renderPrevNextYearButtons:!0,disableMonthPicker:!0,width:190});var BaseImgDatePicker=new Ext.ux.form.DateFieldPlus({hideLabel:!0,hidden:!0,id:"baseImgDateField",format:"Y-m-d",renderTodayButton:!1,showToday:!1,showWeekNumber:!1,renderPrevNextYearButtons:!0,disableMonthPicker:!0,width:190});var FileSearchDatePicker=new Ext.ux.form.DateFieldPlus({hideLabel:!0,id:"fileSearchDate",format:"Y-m-d",renderTodayButton:!1,showToday:!1,showWeekNumber:!1,renderPrevNextYearButtons:!0,disableMonthPicker:!0,width:190});function AppDataStores(){return{dataInfo:new Ext.data.JsonStore({url:"php/datasets.php",autoLoad:!1,fields:[{name:"value"},{name:"formText"},{name:"minDate"},{name:"maxDate"}],listeners:{loadexception:function(){alert("The data set info did not load.")},load:function(){ImgDatePicker.setMinValue(this.getAt(0).get("minDate"));ImgDatePicker.setMaxValue(this.getAt(0).get("maxDate"));ImgDatePicker.setValue(this.getAt(0).get("maxDate"));BaseImgDatePicker.setMinValue(this.getAt(0).get("minDate"));BaseImgDatePicker.setMaxValue(this.getAt(0).get("maxDate"));
BaseImgDatePicker.setValue(this.getAt(0).get("minDate"));FileSearchDatePicker.setValue(this.getAt(0).get("maxDate"));Ext.getCmp("datatype").setValue(this.getAt(0).get("value"));Ext.getCmp("productfilesearch").setValue(this.getAt(0).get("value"));layer.mergeNewParams({TIME:formatDate(ImgDatePicker.getValue())})}}}),operationStore:new Ext.data.SimpleStore({fields:["value","formText"],data:[[1,"Single image"],[2,"Compare images"]]}),projds:new Ext.data.JsonStore({url:"php/pointinfo.php",fields:[{name:"lon"},
{name:"lat"},{name:"x"},{name:"y"},{name:"dataset"},{name:"date"},{name:"value"}],listeners:{loadexception:function(a,b,d){Ext.Msg.alert("Status","The data did not load. \n"+d.responseText)},load:function(){var a=new OpenLayers.LonLat(this.getAt(this.getTotalCount()-1).get("x"),this.getAt(this.getTotalCount()-1).get("y"));addCloudPopup(a)}}}),fileSearchDataStore:new Ext.data.JsonStore({url:"php/file_search.php",root:"results",totalProperty:"totalRecords",fields:["product","date","dataset"],listeners:{loadexception:function(a,
b,d,c){alert("Response Text>>"+d.responseText);alert("The data did not load. \n"+a+"\n"+b+"\n"+d+"\n"+c.message)},beforeload:function(){Ext.getCmp("center-tabpanel").setActiveTab("filesearchgrid")}}})}}AppDataStores=new AppDataStores;function MapPanelToolbar(){var a=[],b,d=function(){a.push(" ");a.push("-");a.push(" ")};b=new GeoExt.Action({control:new OpenLayers.Control.ZoomToMaxExtent,map:map,iconCls:"zoomfull",tooltip:"Zoom to maximum map extent"});a.push(b);d();b=new GeoExt.Action({control:new OpenLayers.Control.ZoomBox,map:map,iconCls:"zoomin",toggleGroup:"tools",tooltip:"Zoom in: click in the map or use the left mouse button and drag to create a rectangle"});a.push(b);b=new GeoExt.Action({control:new OpenLayers.Control.ZoomBox({out:!0}),
map:map,iconCls:"zoomout",toggleGroup:"tools",tooltip:"Zoom out: click in the map or use the left mouse button and drag to create a rectangle"});a.push(b);b=new GeoExt.Action({control:new OpenLayers.Control.DragPan,isDefault:!0,map:map,iconCls:"pan",toggleGroup:"tools",tooltip:"Pan map: keep the left mouse button pressed and drag the map"});a.push(b);d();b=new GeoExt.Action({control:new OpenLayers.Control.Identify(identify,{title:"Point query: click on the map to retrieve the value of the currently selected WFAS dataset."}),
map:map,iconCls:"id",toggleGroup:"tools",tooltip:"Point query: click on the map to retrieve the value of the currently selected WFAS dataset."});a.push(b);b=new GeoExt.Action({control:getFeatureControl,map:map,iconCls:"stats",toggleGroup:"tools",tooltip:"Raster Regional statistics"});a.push(b);d();var c=new OpenLayers.Control.NavigationHistory;map.addControl(c);b=new GeoExt.Action({control:c.previous,iconCls:"back",tooltip:"Previous view",disabled:!0});a.push(b);b=new GeoExt.Action({tooltip:"Next view",
control:c.next,iconCls:"next",disabled:!0});a.push(b);d();return a};var MapPanel=new GeoExt.MapPanel({title:"Map",layout:"fit",map:map,height:800,width:800,tbar:new MapPanelToolbar,border:!1});var baseImgLabel=new Ext.form.TextField({fieldLabel:"Base Image Date",css:"float: none",hidden:!0,listeners:{render:function(){this.getEl().up(".x-form-item").setDisplayed(!1)}}}),opacitySlider=new Ext.Slider({width:190,value:100,increment:10,minValue:0,maxValue:100,plugins:new Ext.slider.Tip({getText:function(a){return String.format("<b>{0}%</b>",a.value)}}),listeners:{changecomplete:function(a,b){map.layers[1].setOpacity(b/100)}}}),ProductSelectorPanel=new Ext.FormPanel({title:"Product Selector",
labelAlign:"left",labelWidth:300,buttonAlign:"center",waitMsgTarget:!0,items:[new Ext.form.FieldSet({title:"Viewing Options",autoHeight:!0,defaultType:"combobox",items:[new Ext.form.TextField({fieldLabel:"Operation",hidden:!0}),new Ext.form.ComboBox({name:"operation",id:"operation",hideLabel:!0,store:AppDataStores.operationStore,valueField:"value",displayField:"formText",emptyText:"Select operation",width:190,mode:"local",triggerAction:"all",editable:"false",lazyRender:"false",value:AppDataStores.operationStore.getAt(0).get("formText"),
listeners:{select:function(a,b){a.setValue(b.get("formText"));b.get("value")==1?(BaseImgDatePicker.hide(),baseImgLabel.getEl().up(".x-form-item").setDisplayed(!1)):(BaseImgDatePicker.show(),baseImgLabel.getEl().up(".x-form-item").setDisplayed(!0))}}}),new Ext.form.TextField({fieldLabel:"Product",hidden:!0}),new Ext.form.ComboBox({name:"datatype",id:"datatype",hideLabel:!0,store:AppDataStores.dataInfo,valueField:"value",displayField:"formText",emptyText:"Select a product type",width:190,mode:"local",
triggerAction:"all",editable:"false",lazyRender:"false",listeners:{select:function(a,b){a.setValue(b.get("value"));ImgDatePicker.setMinValue(b.get("minDate"));ImgDatePicker.setMaxValue(b.get("maxDate"));ImgDatePicker.setValue(b.get("maxDate"));BaseImgDatePicker.setMinValue(b.get("minDate"));BaseImgDatePicker.setMaxValue(b.get("maxDate"));BaseImgDatePicker.setValue(b.get("minDate"))}}}),new Ext.form.TextField({fieldLabel:"Date",hidden:!0}),ImgDatePicker,baseImgLabel,BaseImgDatePicker,new Ext.form.TextField({fieldLabel:"Opacity",
hidden:!0}),opacitySlider]})],buttons:[new Ext.Button({text:"Update Map",listeners:{click:function(){var a,b;Ext.getCmp("operation").getRawValue()==AppDataStores.operationStore.getAt(0).get("formText")?(a=AppDataStores.dataInfo.getAt(AppDataStores.dataInfo.find("value",Ext.getCmp("datatype").getValue())).get("formText"),newDataset=Ext.getCmp("datatype").getValue(),b={TIME:formatDate(ImgDatePicker.getValue()),layers:newDataset},updateDisplay(layer,a,b)):(a="Comparing images",b={DATASET:Ext.getCmp("datatype").getValue(),
QUERYDATE:formatDate(ImgDatePicker.getValue()),BASEDATE:formatDate(BaseImgDatePicker.getValue())},Ext.Ajax.request({url:"php/compute_difference.php",params:b,success:function(){a="Comparing images";updateDisplay(diffLayer,a,b)},failure:function(a){Ext.MessageBox.alert("Failed",a.responseText)}}));a=null}}}),new Ext.SplitButton({text:"Download",menu:new Ext.menu.Menu({items:[{text:"Geotiff",handler:function(){Ext.getCmp("operation").getValue()==AppDataStores.operationStore.getAt(0).get("formText")?
downloadData(!1,{dataset:layer.params.LAYERS,time:layer.params.TIME,bbox:map.getExtent(),format:"GTIFF"}):downloadData(!0,{dataset:Ext.getCmp("datatype").getValue(),queryDate:ImgDatePicker.getValue(),baseDate:BaseImgDatePicker.getValue(),bbox:map.getExtent(),format:"GTIFF"})}},{text:"Google Earth KMZ",handler:function(){downloadData(!1,{dataset:layer.params.LAYERS,time:layer.params.TIME,bbox:map.getExtent(),format:"KMZ"})}}]})})]});boundaryList=new GeoExt.tree.LayerContainer({text:"Boundaries",layerStore:MapPanel.layers,leaf:!1,expanded:!0,loader:{filter:function(a){return a.get("layer").name.indexOf("Boundaries")!==-1},baseAttrs:{checkedGroup:"group1"}}});
var treeConfig=(new OpenLayers.Format.JSON).write([{nodeType:"gx_baselayercontainer",expanded:!0},{text:"WFAS Rasters",nodeType:"gx_overlaylayercontainer",expanded:!0}],!0),LayerTreePanel=new Ext.tree.TreePanel({title:"Map Layers",root:{nodeType:"async",children:Ext.decode(treeConfig)},rootVisible:!1,loader:new Ext.tree.TreeLoader({applyLoader:!1}),listeners:{checkChange:function(a){if(a.attributes.checked==1&&a.attributes.checkedGroup=="group1")selectLayer.destroyFeatures(),getFeatureControl.protocol=
a.layer.options.protocol}},lines:!1});var DataSearchFormPanel=new Ext.FormPanel({title:"File Search",hideLabel:!0,autoWidth:!0,id:"filesearch",buttonAlign:"center",items:[{xtype:"label",text:"Search By:",cls:"x-form-check-group-label"},{xtype:"radio",hideLabel:"true",boxLabel:"Product Type",id:"productsearch",name:"filesearch",inputValue:2},{xtype:"combo",hideLabel:!0,width:190,listWidth:207,store:AppDataStores.dataInfo,id:"productfilesearch",valueField:"value",displayField:"formText",emptyText:"Select a product type",editable:!1,mode:"local",
triggerAction:"all",lazyRender:!0},{xtype:"radio",hideLabel:"true",boxLabel:"Date",id:"datesearch",name:"filesearch",inputValue:1,checked:!0},FileSearchDatePicker],buttons:[{text:"Search",handler:function(){var a="",b=Ext.getCmp("productfilesearch").getValue();a=Ext.getCmp("datesearch").checked?"date":"product";AppDataStores.fileSearchDataStore.baseParams={type:a,date:formatDate(FileSearchDatePicker.getValue()),product:b};AppDataStores.fileSearchDataStore.load({params:{start:0,limit:25}})}},{id:"reset-button",
type:"reset",text:"Clear",handler:function(){AppDataStores.fileSearchDataStore.removeAll()}}]});var PointQueryFormPanel=new Ext.form.FormPanel({title:"Enter coordinates:",header:!1,defaultType:"numberfield",labelWidth:90,buttonAlign:"center",border:!1,defaults:{width:100},items:[{xtype:"numberfield",fieldLabel:"Latitude",name:"lat",id:"lat",value:44,minValue:22,maxValue:50,lazyRender:!0},{fieldLabel:"Longitude",name:"lon",id:"lon",value:-110.5,minValue:-130,maxValue:-60},{fieldLabel:"Window size",name:"win",id:"win",value:1,minValue:1,maxValue:7}],buttons:[{text:"Submit",handler:function(){AppDataStores.projds.load({params:{lon:Ext.getCmp("lon").getValue(),
lat:Ext.getCmp("lat").getValue(),time:layer.params.TIME,dataset:layer.params.LAYERS,window:Ext.getCmp("win").getValue()},add:!0})}},{id:"reset-button",type:"reset",text:"Reset",handler:function(){Ext.getCmp("lat").reset();Ext.getCmp("lon").reset()}}]}),PointQueryPanel={id:"pointPanel",title:"Point query",border:!0,items:[PointQueryFormPanel]};function WestPanel(){var a={region:"west",id:"west-panel",title:"Control Panel",split:!0,width:220,minSize:175,maxSize:400,collapsible:!0,margins:"0 0 0 5",layout:"accordion",layoutConfig:{animate:!0},items:[ProductSelectorPanel,LayerTreePanel,DataSearchFormPanel,PointQueryPanel]};AppDataStores.dataInfo.load();return new Ext.Panel(a)};var PointResultsGridPanel=new Ext.grid.GridPanel({store:AppDataStores.projds,columns:[{header:"Latitude",sortable:!1,dataIndex:"lat"},{header:"Longitude",sortable:!1,dataIndex:"lon"},{id:"dataset",header:"Dataset",sortable:!1,dataIndex:"dataset"},{id:"date",header:"Date",sortable:!1,dataIndex:"date"},{header:"Value",sortable:!1,dataIndex:"value"}],viewConfig:{forceFit:!1},title:"Point query results",stripeRows:!0,autoWidth:!0,frame:!0});function FileSearchGridPanel(){var a=new Ext.PagingToolbar({pageSize:25,store:AppDataStores.fileSearchDataStore,displayInfo:!0,displayMsg:"Displaying results {0} - {1} of {2}",emptyMsg:"No results to display"});return new Ext.grid.GridPanel({store:AppDataStores.fileSearchDataStore,id:"filesearchgrid",viewConfig:{forceFit:!0},loadMask:!0,columns:[{header:"WFAS Product",sortable:!1,dataIndex:"product"},{header:"Date",sortable:!1,dataIndex:"date"},{header:"Download",sortable:!1,dataIndex:"dataset"}],
title:"File search results",stripeRows:!0,autoWidth:!0,frame:!0,bbar:a})};function CenterPanel(){var a={region:"center",xtype:"tabpanel",id:"center-tabpanel",deferredRender:!1,activeTab:0,layoutOnTabChange:!0,items:[MapPanel,PointResultsGridPanel,new FileSearchGridPanel]};return new Ext.TabPanel(a)};function EastPanel(){var a={region:"east",id:"east-panel",title:"Information Panel",split:!0,width:200,minSize:175,maxSize:400,collapsible:!0,margins:"0 0 0 5",layout:"accordion",layoutConfig:{animate:!0},items:[{title:"Map Legend",id:"legend",height:0.5*Ext.getBody().getViewSize().height,html:generateLegendHtml(),border:!0},{title:"Help",autoScroll:!0,autoLoad:{url:"doc/product_selector.html",scripts:!0},border:!0}]};return new Ext.Panel(a)};Ext.BLANK_IMAGE_URL="lib/ext/Ext/resources/images/wfas/s.gif";Ext.ns("Application");Ext.onReady(function(){Ext.QuickTips.init();new Ext.Viewport({layout:"border",items:[new WestPanel,new CenterPanel,new EastPanel]});LayerTreePanel.root.appendChild(boundaryList)});

