/*!
 * Ext JS Library 3.0+
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
Ext.onReady(function(){

    Ext.QuickTips.init();
    
    // for this demo configure local and remote urls for demo purposes
    var url = {
        local:  'csi.json',  // static data file
        remote: 'http://'+host+'/database/entries/viewfilteredgrid'
    };

    // configure whether filter query is encoded or not (initially)
    var encode = false;
    
    // configure whether filtering is performed locally or remotely (initially)
    var local = true;
	
	analyteListStore = new Ext.data.JsonStore({
		autoDestroy: true,
		url: 'http://'+host+'/database/analytes/listall',
		storeId: 'analyteStore',
		// reader configs
		root: 'analytes',
		idProperty: 'name',
		fields: ['name']
	});

    store = new Ext.data.JsonStore({
        // store configs
        autoDestroy: true,
        url: (url.remote),
        remoteSort: false,
        sortInfo: {
            field: 'event_id',
            direction: 'ASC'
        },
        storeId: 'myStore',
        
        // reader configs
        idProperty: 'id',
        root: 'entries',
        totalProperty: 'total',
        fields: [
        		{name: 'id'},
						{name: 'event_id'},
						{name: 'Event'},
						{name: 'monitoringlocation_id'},
						{name: 'monitoringset_id'},
						{name: 'Date', type: 'date', dateFormat: 'Y-m-d'},
						{name: 'Location_Name'},
						{name: 'analyte_id'},
						{name: 'Detection_Limit', type: 'float'},
						{name: 'Value', type: 'float'},
						{name: 'Units'},
						{name: 'Remarks'},
						{name: 'Test_location'},
						{name: 'Flow'},
						{name: 'Source'},			
						{name: 'Type'}]
    });

    var filters = new Ext.ux.grid.GridFilters({
        // encode and local configuration options defined previously for easier reuse
				encode: encode,
				local: false,
        filters: [{
            type: 'numeric',
            dataIndex: 'id'
        }, {
            type: 'string',
            dataIndex: 'Location_Name'
        }, {
            type: 'list',
            dataIndex: 'analyte_id',
			store: analyteListStore,
			labelField:'name'
        }, {
            type: 'numeric',
            dataIndex: 'Value'
        }, {
            type: 'date',
            dataIndex: 'Date'
        }, {
            type: 'list',
            dataIndex: 'Flow',
            options: ['Base Flow', 'Stormwater'],
            phpMode: true
        }, {
            type: 'list',
            dataIndex: 'Test_location',
            options: ['Field', 'Lab'],
            phpMode: true
        }, {
            type: 'list',
            dataIndex: 'Source',
            options: ['Virgil Creek', 'Fall Creek','Taughannock Creek','Trumansburg Creek','Six Mile Creek','Salmon Creek','Cayuga Inlet','Cayuga Lake','Stewart Park','Direct Streams'],
            phpMode: true
        }, {
            type: 'list',
            dataIndex: 'Type',
            options: ['Synoptic', 'Partial'],
            phpMode: true
        }]
    });    
    
    // use a factory method to reduce code while demonstrating
    // that the GridFilter plugin may be configured with or without
    // the filter types (the filters may be specified on the column model
var cm = new Ext.grid.ColumnModel([
        {header: "ID", dataIndex: 'id', width: 100, hidden: true},
        {header: "Event ID", dataIndex: 'event_id', width: 50, hidden: true},
        {header: "Event", dataIndex: 'Event', width: 50, hidden: true},
        {header: "Location ID", dataIndex: 'monitoringlocation_id', width: 50, hidden: true},
        {header: "Monitoring Set", dataIndex: 'monitoringset_id', width: 50, hidden: true},
        {header: "Date", dataIndex: 'Date', width: 70,renderer: Ext.util.Format.dateRenderer('m/d/Y'), sortable: true},
        {header: "Monitoring Set", dataIndex: 'Source', width: 100, sortable: true},
        {header: "Location Name", dataIndex: 'Location_Name', width: 150, filter: {type: 'string'}},
        {header: "Analyte ID", dataIndex: 'analyte_id', width: 160, sortable: true},
        {header: "Detection Limit", dataIndex: 'Detection_Limit', width: 50},
        {header: "Value", dataIndex: 'Value', width: 50, type: 'float'},
        {header: "Units", dataIndex: 'Units', width: 100},
        {header: "Remarks", dataIndex: 'Remarks', width: 100},
        {header: "Test Location", dataIndex: 'Test_location', width: 80},
        {header: "Flow", dataIndex: 'Flow', width: 70},
				{header: "Type", dataIndex: 'Type', width: 80}
    ]);
	cm.defaultSortable = true;
    
    var grid = new Ext.grid.GridPanel({
        border: false,
        store: store,
        colModel: cm,
        loadMask: true,
        height: 650,
				width: 940,
				title: 'Query Grid',
        plugins: [filters],
        
        listeners: {
            render: {
                fn: function(){
                    store.load({
                        params: {
                            start: 0,
                            limit: 25
                        }
                    });
                }
            }
        },
        bbar: new Ext.PagingToolbar({
            store: store,
            pageSize: 25,
            displayInfo: true,
						displayMsg: 'Displaying entries {0} - {1} of {2}',
            plugins: [filters]
        })
    });

    // add some buttons to bottom toolbar just for demonstration purposes
    grid.getBottomToolbar().add([
        '->',
        /*{
            text: 'All Filter Data',
            tooltip: 'Get Filter Data for Grid',
            handler: function () {
                var data = Ext.encode(grid.filters.getFilterData());
                Ext.Msg.alert('All Filter Data',data);
            } 
        },*/{
            text: 'Clear Filter Data',
			iconCls: 'iconDelete',
            handler: function () {
                grid.filters.clearFilters();
            } 
        }/*,{
            text: 'Export to Excel',
            handler: function () {
                document.location='data:application/vnd.ms-excel;base64,' + Base64.encode(grid.getExcelXml());
            } 
        }*/,{
            text: 'Download to Excel',
			iconCls: 'dlExcel',
            handler: function () {
				var confilter = grid.filters.buildQuery(grid.filters.getFilterData());
                
				var conn = new Ext.data.Connection();
				conn.request({
					url: 'http://'+host+'/database/entries/dlgridxls',
					method: 'POST',
					params : confilter,
					success: function(responseObject) {
						document.location='http://'+host+responseObject.responseText;
						/*Ext.Msg.show({
						   title:'Query String Text',
						   msg: responseObject.responseText,						  						   
						   minWidth: 400
						});*/
					},
					 failure: function() {
						 Ext.Msg.alert('Status', 'Unable to export to Excel. Please contact CSI developer.');
					 }
				});
            } 
        }       
    ]);

    grid.render('grid-paging');
    
});