  <!--
	var map, baseLayer, layer, diffLayer, selectLayer, popupFeature, popupMarker,markers,popup;
	var toolbar;
        var cloudFeature, cloudPopup;
        var projds;
	var wfasDataBounds = new  OpenLayers.Bounds(-2050500.000,-2136500.000,2536500.000,752500.000);
	var 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:false,maxResolution:5750,isBaseLayer:true});
	
		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:false,maxResolution:5750,visibility: true,isBaseLayer:false});

		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:false,maxResolution:5750,visibility: true,isBaseLayer:false});

	    	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:false,maxResolution:5750,visibility: false,isBaseLayer:false,buffer:0,displayInLayerSwitcher: false});

	    	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:false,maxResolution:5750,visibility: false,isBaseLayer:false,buffer:0,displayInLayerSwitcher: false});

		selectLayer = new OpenLayers.Layer.Vector("Regional Statistics", {styleMap: new OpenLayers.Style(OpenLayers.Feature.Vector.style["select"]), displayInLayerSwitcher: false});

		map.addLayers([baseLayer,layer,countries,GACC, selectLayer]);
		
		protocol_1 = OpenLayers.Protocol.WFS.fromWMSLayer(countries, {
			featurePrefix: 'ms',
			geometryName: 'msGeometry',
			featureType: 'countries'
		});
		countries.addOptions({protocol: protocol_1});
		protocol_2 = OpenLayers.Protocol.WFS.fromWMSLayer(GACC,{
                                featurePrefix: 'ms',
                                geometryName: 'msGeometry',
                                featureType: 'GACC'
                });
		GACC.addOptions({protocol: protocol_2});
		
		getFeatureControl = new OpenLayers.Control.GetFeature({
			protocol: protocol_1,
			title: "GetFeature Control",
			box: false,
			hover: false,
			multiple: false,
			toggleKey: "ctrlKey"
		});
	    
		getFeatureControl.events.register("featureselected", this, function(e) {
			
			selectLayer.addFeatures([e.feature]);

			var wkt = new OpenLayers.Format.WKT();

			inputParams = { wktText: wkt.write(e.feature),
					date: formatDate(myPicker.getValue()),
					dataset: layer.params.LAYERS};

			Ext.Ajax.request({
				url : "/cgi-bin/subset_stats.py", 
				params : inputParams,
				method: 'POST',
				success: function ( result, request) { 
					popup = new GeoExt.Popup({
						id: 'gs-popup',
						title: "Statistics for your selection",
						map: map,
						feature: e.feature,
    						location: e.feature,
    						width: 200,
    						html: result.responseText,
    						collapsible: true,
						listeners: {close: function(){selectLayer.destroyFeatures();}}

					});
					popup.show();
				},
				failure: function ( result, request) { 
					Ext.MessageBox.alert('Failed', result.responseText); 
				} 
			});
		});

		getFeatureControl.events.register("beforefeatureselected", this, function(e) {
			var popup  = Ext.getCmp('gs-popup');
			
			if (popup!=undefined)
				popup.close();
		});
		
		getFeatureControl.events.register("featureunselected", this, function(e) {
			selectLayer.removeFeatures([e.feature]);
		});
		
		getFeatureControl.events.register("deactivate", this, function() {
			selectLayer.destroyFeatures();
				
			var popup  = Ext.getCmp('gs-popup');
			
			if (popup!=undefined)
				popup.close();
		});

		map.setCenter(wfasDataBounds.getCenterLonLat());
        }//end function init

	/**
         * @param {Event} evt
         */
        function onPopupMouseDown(evt) {
        	destroyPopup();
	    	OpenLayers.Event.stop(evt);
        }

	/**
         * @param {OpenLayers.LonLat} position
         */
	function addCloudPopup(latlon,result) {
            this.updatePlot = function(period){
		document.getElementById('plotdiv').innerHTML= "<img src='" + plotURL + "&interval=" + period + "'></img>";
	    } 
	    var plotURL = "php/dirlist.php?dataset="
                                + layer.params.LAYERS + "&lon=" + latlon.lon  
				+ "&lat=" + latlon.lat
				+ "&window=" + Ext.getCmp('win').getValue(); 
	    cloudFeature = new OpenLayers.Feature(layer, latlon); 
            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='" + plotURL + "&interval=6 months" + "'></img></div>";

            destroyPopup();
	    cloudPopup = cloudFeature.createPopup(true);
 	    map.addPopup(cloudPopup);
	    cloudPopup.show();           
	 /*	popup = new GeoExt.Popup({
			id: 'gs-popup',
                        title: "Statistics for your selection",
                        map: map,
                        feature: cloudFeature,
                        location: latlon,
                        html:cloudFeature.data.popupContentHTML,
                        collapsible: true
                });
            popup.show(); */
	}
        
        function destroyPopup() {

           if (cloudPopup != null) {
                map.removePopup(cloudPopup);
                cloudPopup.destroy();
                cloudPopup = null;
            }
	/*	var popup  = Ext.getCmp('gs-popup');

                        if (popup!=undefined)
                                popup.close();*/
        }
        
	function generateLegendHtml(){
		var legendHtml = '';
		for (var i = 1; i < map.layers.length-1; i++) {
			legendHtml +=  map.layers[i].name + ":<br>";
			legendHtml += '<img src="' + '/cgi-bin/mapserv?' + 'map=' + 
				map.layers[i].params.MAP +
				'&SERVICE=WMS&REQUEST=GetLegendGraphic&FORMAT=image/gif&VERSION=1.1.0&LAYER=' + map.layers[i].params.LAYERS + '"</img><br>';
		}
		return legendHtml;
	}//end generateLegendHtml

	/**
	 * A utility function to format
	 * a javascript date in a 
	 * YYYY-MM-DD format
         * @param {Date} dateVal
         */
        function formatDate(dateVal){
		var dow = null;
		
		if(dateVal<=new Date("2003/01/03")){
			dow=4;
		}else if (dateVal<=new Date("2006/12/31")){
			dow=2;
		}else{
			dow=1;
		}
					
		while(dateVal.getDay()!=dow){
			dateVal.setDate( dateVal.getDate() +1);
		}//end while
                                        
		var monthDate = dateVal.getDate()<10?"0" + dateVal.getDate():dateVal.getDate();
		var month = dateVal.getMonth()<9?"0" + (dateVal.getMonth()+1):dateVal.getMonth()+1;//months in javascript are indexed from 0 (0 is Jan, 1 is Feb, etc)
		var timeVal = dateVal.getFullYear() + "-" + month + "-" + monthDate;
		return timeVal;
	}
	
	function identify(pos){
		//translate this viewport's pixel position to map coordinates:
		var lonlat = map.getLonLatFromViewPortPx(pos);
		Ext.getCmp('pointPanel').expand(true);
		projds.load({ params: { x: lonlat.lon, y: lonlat.lat, 
					time: layer.params.TIME, 
					dataset: layer.params.LAYERS,
					window: Ext.getCmp('win').getValue()}
			    , add:true});
		//addCloudPopup(lonlat);				
        }
	
	updateDisplay=function(aLayer,newName,newParams){
		aLayer.setName(newName);
		aLayer.mergeNewParams(newParams);
		aLayer.setOpacity(opacitySlider.getValue()/100);
		map.removeLayer(map.layers[1]);
		map.addLayer(aLayer);
		map.setLayerIndex(aLayer,1);
		var legend = generateLegendHtml();
		Ext.getCmp('legend').body.update(legend);
	}//end updateDisplay

	function downloadData(isDiffLayer, options){ 
		try {
    			Ext.destroy(Ext.get('downloadIframe'));
		}
		catch(e) {}

		var bbox, downloadURL, res=1000;
		
		if (!options.bbox){
			bbox = wfasDataBounds.toArray();
		}else{
			bbox = options.bbox.toArray();
		}
	
		//check to see if we should download data for a single WFAS image:
		if(isDiffLayer){ //download the result from comparing 2  WFAS images: 
			downloadURL = '/cgi-bin/mapserv?'//wfas/img_difference.php?'
				+ 'SERVICE=wcs&REQUEST=GetCoverage&VERSION=1.0.0&COVERAGE=diff' 
				+ '&DATASET=' + Ext.getCmp('datatype').getValue()
				+ '&QUERYDATE=' + formatDate(options.queryDate)
				+ '&BASEDATE=' +  formatDate(options.baseDate)
				+ '&CRS=EPSG:2163'
				+ '&BBOX=' +  bbox[0] + ',' + bbox[1] + ',' + bbox[2] + ',' + bbox[3]
				+ '&RESX=' + res + '&RESY=' + res + '&FORMAT=' +options.format;

		}else{ //single WFAS image:
			downloadURL = '/cgi-bin/mapserv?&MAP=%2Fhome%2Fapetkov/wfas/wfas_time_index.map&'
				+ 'SERVICE=wcs&REQUEST=GetCoverage&VERSION=1.0.0&COVERAGE=' 
				+ options.dataset + '&TIME=' + options.time
				+ '&CRS=EPSG:2163'
				+ '&BBOX=' +  bbox[0] + ',' + bbox[1] + ',' + bbox[2] + ',' + bbox[3]
				+ '&RESX=' + res + '&RESY=' + res + '&FORMAT=' + options.format;

			}//end if

		Ext.DomHelper.append(document.body, {
    			tag: 'iframe',
    			id:'downloadIframe',
			frameBorder: 0,
			width: 0,
			height: 0,
			css: 'display:none;visibility:hidden;height:0px;',
    			src: downloadURL
 		});//end Ext.DomHelper.append

	}//end downloadData
	
function onItemPick (Format){
	//check to see if we should download data for a single WFAS image:
        if(Ext.getCmp('operation').getValue()==operationStore.getAt(0).get('formText')){
        	downloadData(false,{dataset: layer.params.LAYERS,
                time:  layer.params.TIME,
                bbox: map.getExtent(),format: Format});
        }else{ //data for 2 compared images:
        	downloadData(   true,
                {dataset: Ext.getCmp('datatype').getValue(),
                queryDate: myPicker.getValue(),
                baseDate: baseImgPicker.getValue(),
                bbox: map.getExtent(),
                format: Format});//end downloadData
        }//end if
}

	var setToolbarContent = function() {
		var toolbarItems = [], action, actions = {};
		
		var addSeparator = function() { 
			toolbarItems.push(" ");
			toolbarItems.push("-");
               		toolbarItems.push(" "); 
        	};
		
		action = new GeoExt.Action({
                	control: new OpenLayers.Control.ZoomToMaxExtent(), 
                	map: map,
                	iconCls: 'zoomfull',
			tooltip: 'Zoom to maximum map extent'
		});
	
		toolbarItems.push(action);
		addSeparator();

		action = 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'
		});

		toolbarItems.push(action);

		action = new GeoExt.Action({
			control : new OpenLayers.Control.ZoomBox({
                    		out: true
			}), 
			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'
                });
                
		toolbarItems.push(action);

		action = new GeoExt.Action({
			control: new OpenLayers.Control.DragPan(),
			isDefault: true,
			map: map,
			iconCls: 'pan', 
			toggleGroup: 'tools',
			tooltip: 'Pan map: keep the left mouse button pressed and drag the map'
                });
                
		toolbarItems.push(action);
		addSeparator();
            
		action = new GeoExt.Action({
			/*control: new OpenLayers.Control(
			//	{//displayClass: 'id', trigger: identify,
			//	eventListeners: {"deactivate": function(e){
			//				destroyPopup();}
						}
				}),*/
                	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.'
                });

		toolbarItems.push(action);

		action = new GeoExt.Action({
			control: getFeatureControl,
			map: map,
			iconCls: 'stats',
			toggleGroup: 'tools',
			tooltip: 'Raster Regional statistics'
		});

		toolbarItems.push(action);
		addSeparator();

		var nav = new OpenLayers.Control.NavigationHistory();

		map.addControl(nav);

		action = new GeoExt.Action({
			control: nav.previous,
			iconCls: 'back',
			tooltip: "Previous view",
			disabled: true
		});

		toolbarItems.push(action);

		action = new GeoExt.Action({
			tooltip: "Next view",
			control: nav.next,
			iconCls: 'next',
			disabled: true
		});

		toolbarItems.push(action);
		addSeparator();

		return toolbarItems;
  	}

	var myPicker = new Ext.ux.form.DateFieldPlus({
			hideLabel: true,
			name: 'datestamp',
			id: 'dateField',
			format: 'Y-m-d',
			renderTodayButton: false,
			showToday: false,
			showWeekNumber: false,
			renderPrevNextYearButtons: true,
			disableMonthPicker: true,
			width:190
                    });
	var baseImgLabel = new Ext.form.TextField({ //used strictly for the label
			fieldLabel: 'Base Image Date',
			css: 'float: none',
			hidden: true,
			listeners: {'render' : function(){
                                this.getEl().up('.x-form-item').setDisplayed(false);
                        }}
	});
	 var baseImgPicker = new Ext.ux.form.DateFieldPlus({
			hideLabel: true,
			hidden: true,
			id: 'baseImgDateField',
			format: 'Y-m-d',
			renderTodayButton: false,
			showToday: false,
			showWeekNumber: false,
			renderPrevNextYearButtons: true,
			disableMonthPicker: true,
			width:190
        });
	var opacitySlider = new Ext.Slider({
			width: 190,
			value: 100,
			increment: 10,
			minValue: 0,
			maxValue: 100,
			plugins: new Ext.slider.Tip({
			getText: function(slider){
				return String.format('<b>{0}%</b>', slider.value);
            			}
        		}),
			listeners:{'changecomplete':	function(theSlider, newVal){
				map.layers[1].setOpacity(newVal/100);
				}}
	});

	var fileSearchDatePicker= new Ext.ux.form.DateFieldPlus({
			hideLabel: true,
			id: 'fileSearchDate',
			format: 'Y-m-d',
			renderTodayButton: false,
			showToday: false,
			showWeekNumber: false,
			renderPrevNextYearButtons: true,
			disableMonthPicker: true,
			width:190
        });
      var dataInfo = new Ext.data.JsonStore({
        url: 'php/datasets.php',
	autoLoad: true,
        fields: [
                {name: 'value'},
                {name: 'formText'},
                {name: 'minDate'},
                {name: 'maxDate'}
        ]
        ,listeners: {
                        loadexception: function(proxy, store, response, e) {
                                alert("The data set info did not load.");
                        }//end loadexception
			,load: function(){
				myPicker.setMinValue(this.getAt(0).get('minDate'));
				myPicker.setMaxValue(this.getAt(0).get('maxDate'));
				myPicker.setValue(this.getAt(0).get('maxDate'));
				baseImgPicker.setMinValue(this.getAt(0).get('minDate'));
				baseImgPicker.setMaxValue(this.getAt(0).get('maxDate'));
				baseImgPicker.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(myPicker.getValue())});
			}
        }//end adding listeners
     });

	var operationStore = new Ext.data.SimpleStore({
		fields: ['value', 'formText'],
		data : [[1, 'Single image'],[2, 'Compare images']]
	});

        // -->
    Ext.onReady(function() {

    Ext.BLANK_IMAGE_URL = 'lib/ext/Ext/resources/images/wfas/s.gif';
        Ext.QuickTips.init();
	init();
	
	var fs = new Ext.FormPanel({
        	title:'Product Selector',
        	labelAlign: 'left',
        	labelWidth: 300,
		buttonAlign: 'center',
		waitMsgTarget: true,
       		items: [
            	new Ext.form.FieldSet({
                title: 'Viewing Options',
                autoHeight: true,
		defaultType: 'combobox',
                items: [
			new Ext.form.TextField({ //used strictly for the label
				fieldLabel: 'Operation',
				hidden: true
			}),
			new Ext.form.ComboBox({
				name: 'operation',
				id: 'operation',
				hideLabel: true,
            			store: operationStore,
				valueField: 'value',
            			displayField:'formText',
				emptyText:'Select operation',
                        	width:190,
				mode: 'local',
				triggerAction: 'all',
				editable: 'false',
				lazyRender: 'false',
				value:operationStore.getAt(0).get('formText'),
				listeners:{'select':	function(theSelect,rec){
					theSelect.setValue(rec.get('formText'));
					//here should only be necessary to update the url for the data variable.
					//maybe also show/hide the calendar filed for the base image.
					if(rec.get('value')==1){
						baseImgPicker.hide();
						baseImgLabel.getEl().up('.x-form-item').setDisplayed(false);//hide the label
					}else{
						baseImgPicker.show();
						baseImgLabel.getEl().up('.x-form-item').setDisplayed(true); //show the label
					}
				}}
				}),
			new Ext.form.TextField({ //used strictly for the label
				fieldLabel: 'Product',
				hidden: true
			}),
			new Ext.form.ComboBox({
				name: 'datatype',
				id: 'datatype',
				hideLabel: true,
            			store: dataInfo,
				valueField: 'value',
            			displayField:'formText',
				emptyText:'Select a product type',
                        	width:190,
				mode: 'local',
				triggerAction: 'all',
				editable: 'false',
				lazyRender: 'false',
				//value:dataInfo.getAt(0).get('formText'),
				listeners:{'select':	function(theSelect,rec){
					theSelect.setValue(rec.get('value'));
					myPicker.setMinValue(rec.get('minDate'));
					myPicker.setMaxValue(rec.get('maxDate'));
					myPicker.setValue(rec.get('maxDate'));
					baseImgPicker.setMinValue(rec.get('minDate'));
					baseImgPicker.setMaxValue(rec.get('maxDate'));
					baseImgPicker.setValue(rec.get('minDate'));
				}}
				}),
				new Ext.form.TextField({ //used strictly for the label
					fieldLabel: 'Date',
					hidden: true
				}), 
				myPicker,
				baseImgLabel,
				baseImgPicker,
 				new Ext.form.TextField({ //used strictly for the label
					fieldLabel: 'Opacity',
					hidden: true
				}),
				opacitySlider   				      
		]
            })
        ],
	buttons: [new Ext.Button({
					text : 'Update Map',
					listeners:{'click':function(){
						
						var newName, newLayer, newParams, legend, layerTree;

						if(Ext.getCmp('operation').getRawValue()==operationStore.getAt(0).get('formText')){
							newName  = dataInfo.getAt(dataInfo.find('value', Ext.getCmp('datatype')
                                                                .getValue())).get('formText');
							newDataset = Ext.getCmp('datatype').getValue();
							 newParams = {	'TIME': formatDate(myPicker.getValue()),'layers': newDataset};
							updateDisplay(layer,newName,newParams);						
						}else{//not a single file viewing, compare images
							newName='Comparing images';
							newParams = {'DATASET':  Ext.getCmp('datatype').getValue(),
									'QUERYDATE': formatDate(myPicker.getValue()),	
									'BASEDATE' : formatDate(baseImgPicker.getValue())};	
							Ext.Ajax.request({
									url : 'php/compute_difference.php' , 
									params : newParams,
									success: function ( result, request ) {
										newName='Comparing images';
										updateDisplay(diffLayer, newName,newParams);
									},
									failure: function ( result, request) { 
											Ext.MessageBox.alert('Failed', result.responseText); 
									} 
							});//end Ajax request
						}//end if
						newLayer = null;
						newName  = null;
						legend   = null;
						layerTree= null;
					}}
			        }),//end button
				 new Ext.SplitButton({
                                        text : 'Download',
					menu: new Ext.menu.Menu({
						items: [{text: 'Geotiff', handler: function(){onItemPick('GTIF');}},//end handler
							{text: 'Google Earth KMZ', handler: function(){onItemPick('KMZ');}}
						]
					}) 
				})//end button
	]
    });
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(proxy, store, response, e) {
                    		Ext.Msg.alert('Status','The data did not load. \n' + response.responseText);
                  	}//end loadexception
		  	,load: function() {
 				var point = new OpenLayers.LonLat(this.getAt(this.getTotalCount()-1).get('x'), 
						this.getAt(this.getTotalCount()-1).get('y'));				       
				addCloudPopup(point);
                        }//end load function
                   }//end adding listeners
});

fileSearchDataStore = new Ext.data.JsonStore({
        url: 'php/file_search.php',
	root: 'results',
	totalProperty: 'totalRecords',
	fields: ['product','date','dataset'],
	listeners: {
			loadexception: function(proxy, store, response, e) {
                    		alert("Response Text>>"+response.responseText);
                    		alert("The data did not load. \n"+proxy+"\n"+store+"\n"+response+"\n"+e.message);
                  	}//end loadexception
		  	,beforeload: function(aStore, options)  {
                        	Ext.getCmp('center-tabpanel').setActiveTab('filesearchgrid');
			}//end load function
                   }//end adding listeners
});

var form = new Ext.form.FormPanel({
        title: 'Enter coordinates:',
        header: false,
        defaultType: 'numberfield',
        labelWidth: 90,
	buttonAlign: 'center',
	border: false,
        defaults: {
        	width: 100
        },
        items: [{
		xtype: 'numberfield', 
		fieldLabel: 'Latitude',
		name: 'lat',
		id: 'lat',
		value: 44,
		minValue: 22,
		maxValue: 50,
		lazyRender: true
        },{
            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(){
			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:true});
		}//end handler
        },{
                id: 'reset-button',
                type: 'reset',
                text: 'Reset',
		handler:function(){
			Ext.getCmp('lat').reset();
			Ext.getCmp('lon').reset();
		}
        }]//end buttons array


    });

var dsForm = new Ext.FormPanel({
        title:'File Search',
	hideLabel: true,
        autoWidth: true,
	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: true,
				width: 190,
				listWidth: 207,
            			store: dataInfo,
				id: 'productfilesearch',
				valueField: 'value',
            			displayField:'formText',
				emptyText:'Select a product type',
				editable: false,
				mode: 'local',
                                triggerAction: 'all',
                                lazyRender: true
		    	},
			{xtype: 'radio', hideLabel: 'true', boxLabel: 'Date', id: 'datesearch', name: 'filesearch', inputValue: 1, checked:true},
			fileSearchDatePicker
         ],buttons:[{
                text : 'Search',
		handler: function(){

			var searchType = '';
			var dataSet = Ext.getCmp('productfilesearch').getValue();
			if  (Ext.getCmp('datesearch').checked){
				searchType = 'date';
			}else{
				searchType = 'product';
			}	

			fileSearchDataStore.baseParams = {type: searchType, date: formatDate(fileSearchDatePicker.getValue()),product:  dataSet };	
			fileSearchDataStore.load({params:{start:0,limit:25}});

		}//end handler
        },{
                id: 'reset-button',
                type: 'reset',
                text: 'Clear',
		handler:function(){
			fileSearchDataStore.removeAll();
		}
        }]//end buttons array

});
 var grid = new Ext.grid.GridPanel({
                store: projds,    
                columns: [
                    {header: 'Latitude',sortable: false, dataIndex: 'lat'},
                    {header: 'Longitude',sortable: false, dataIndex: 'lon'},
                    {id:'dataset', header: 'Dataset', sortable: false, dataIndex: 'dataset'},
                    {id:'date', header: 'Date',sortable: false, dataIndex: 'date'},
                    {header: 'Value', sortable: false, dataIndex: 'value'}
                ],
                viewConfig: {
                    forceFit: false
                },
                title: 'Point query results',
		stripeRows: true,
                autoWidth: true,
                frame: true
            });

var pagingBar = new Ext.PagingToolbar({
        pageSize: 25,
        store: fileSearchDataStore,
        displayInfo: true,
        displayMsg: 'Displaying results {0} - {1} of {2}',
        emptyMsg: "No results to display"
    });

 var fileSearchGrid = new Ext.grid.GridPanel({
                store: fileSearchDataStore,    
		id: 'filesearchgrid',
		viewConfig:{forceFit:true},
		loadMask: true,
                columns: [
                    {header: 'WFAS Product',sortable: false, dataIndex: 'product'},
                    {header: 'Date',sortable: false, dataIndex: 'date'},
                    {header: 'Download',sortable: false, dataIndex: 'dataset'}
                ],
                title: 'File search results',
		stripeRows: true,
                autoWidth: true,
                frame: true,
		bbar: pagingBar
            });

var mapPanel = new GeoExt.MapPanel({
	title: 'Map',
	layout: 'fit',
	map: map,
	height: 800,
	width: 800,
	tbar: setToolbarContent(),
	border: false
});

boundaryList = new GeoExt.tree.LayerContainer({
        text: 'Boundaries',
        layerStore: mapPanel.layers,
        leaf: false,
        expanded: true,
        loader: {
            filter: function(record) {
                return record.get("layer").name.indexOf("Boundaries") !== -1
            },
            baseAttrs: {
                checkedGroup: "group1"
            }
        }    
});

    // using OpenLayers.Format.JSON to create a nice formatted string of the
    // configuration for editing it in the UI
    var treeConfig = new OpenLayers.Format.JSON().write([{
        nodeType: "gx_baselayercontainer",
        expanded: true
    }, {
	text: "WFAS Rasters",
        nodeType: "gx_overlaylayercontainer",
        expanded: true
    } ], true);

var layerTree = new Ext.tree.TreePanel({
    title: 'Map Layers',
    root: {
        nodeType: "async",
        // the children property of an Ext.tree.AsyncTreeNode is used to
        // provide an initial set of layer nodes. We use the treeConfig
        // from above, that we created with OpenLayers.Format.JSON.write.
        children: Ext.decode(treeConfig)
    },
    rootVisible: false,
    loader: new Ext.tree.TreeLoader({
            // applyLoader has to be set to false to not interfer with loaders
            // of nodes further down the tree hierarchy
            applyLoader: false
    }),
    listeners: {
	'checkChange': function(node){
		if (node.attributes.checked==1 && 
		    node.attributes.checkedGroup == 'group1'){
			selectLayer.destroyFeatures(); 
			getFeatureControl.protocol = node.layer.options.protocol;
		}
	} 
    },
    lines: false
});

      var viewport = new Ext.Viewport({
            layout:'border',
            items:[
	    {region: 'west',
                    id: 'west-panel',
                    title: 'Control Panel',
                    split: true,
                    width: 220,
                    minSize: 175,
                    maxSize: 400,
                    collapsible: true,
                    margins: '0 0 0 5',
                    layout: 'accordion',
                    layoutConfig:{
                        animate: true
                    },
		   items: [fs, 
			layerTree,
			dsForm
		   ,{
			id: 'pointPanel',
                        title: 'Point query',
			border: true,
			items: [form]
		    }]
                },{
                    region:'center',
		    xtype: 'tabpanel',
		    id: 'center-tabpanel',
                    deferredRender:false,
                    activeTab: 0,
                    layoutOnTabChange : true,  
                    items:[mapPanel,
		    	grid,
			fileSearchGrid
		]
                },{
                    region: 'east',
                    id: 'east-panel',
                    title: 'Information Panel',
                    split: true,
                    width: 200,
                    minSize: 175,
                    maxSize: 400,
                    collapsible: true,
                    margins: '0 0 0 5',
                    layout: 'accordion',
                    layoutConfig:{
                        animate: true
                    },
                    items: [ 
		    {
                        title: 'Map Legend',
			id: 'legend',
			height: 0.5 * Ext.getBody().getViewSize().height,
                        html: generateLegendHtml(),
                        border: true
                    },{
                        title: 'Help',
                        autoScroll: true,
			autoLoad: {url:'doc/product_selector.html',scripts:true},
                        border: true
                    }]
		}             
	     ]
        });
layerTree.root.appendChild(boundaryList);
    });

