Ext.data.SortTypes.asNumeric = function(s) {
     return parseInt(String(s).replace(/<(.|\n)+?>/g, '').replace(/\(1:.*\)/g, '').replace(/[^0-9.-]/g, ''));
};

Ext.data.SortTypes.asRatio = function(s) {
    var ary = String(s).replace(/<(.|\n)+?>/g, '').split(':',2);
    if (ary[0] == 0 && ary[1] == 0)
        return 99999999999999999;
    else
        return parseInt(String(ary[1]).replace(/[^0-9.-]/g, ''));
};

/**
 * @class Ext.grid.TableGrid
 * @extends Ext.grid.Grid
 * A Grid which creates itself from an existing HTML table element.
 * @constructor
 * @param {String/HTMLElement/Ext.Element} table The table elemennt from which this grid will be created -
 * The table MUST have some type of size defined for the grid to fill. The container will be
 * automatically set to position relative if it isn't already.
 * @param {Object} config A config object that sets properties on this grid and has two additional (optional)
 * properties: fields and columns which allow for customizing data fields and columns for this grid.
 * @history
 * 2007-03-01 Original version by Nige "Animal" White
 * 2007-03-10 jvs Slightly refactored to reuse existing classes
 */
Ext.grid.TableGrid = function(table, config) {
  config = config || {};
  Ext.apply(this, config);
  var cf = config.fields || [], ch = config.columns || [], cj = config.fields || [];
  table = Ext.get(table);

  if (table == null) {
      return false;
  }

  var ct = table.insertSibling();

  var fields = [], cols = [];
  var headers = table.query("thead th");
  for (var i = 0, h; h = headers[i]; i++) {
    var htext = h.innerHTML;
    var name = 'tcol-'+i;

        var sortType = 'asString';
        if ( h.attributes.type ) {
            sortType = h.attributes.type.value;
        }

    fields.push(Ext.applyIf(cf[i] || {}, {
      name: name,
            sortType: sortType,
      mapping: 'td:nth('+(i+1)+')/@innerHTML'
    }));

        if ( sortType == 'rowNumber' ) {
            cols.push(Ext.applyIf(ch[i] || {}, new Ext.grid.RowNumberer()));
        } else {
            cols.push(Ext.applyIf(ch[i] || {}, {
              'header': htext,
              'dataIndex': name,
              'width': h.offsetWidth,
              'tooltip': h.title,
              'sortable': true,
              'menuDisabled' : true
            }));
          }
    }

    var totals = {};
    var hasTotals = false;
    var footers = table.query('tfoot td');
    if ( footers.length ) {
        hasTotals = true;
        var summary = new Ext.ux.grid.GridSummary();
        for ( var i = 0, f; f = footers[i]; i++ ) {
            totals['tcol-'+i] = f.innerHTML;
        }
    }

  var ds  = new Ext.data.Store({
    reader: new Ext.data.XmlReader({
      record:'tbody tr'
    }, fields)
  });

  ds.loadData(table.dom);

  var cm = new Ext.grid.ColumnModel(cols);

      if (config.width || config.height) {
        ct.setSize(config.width || 'auto', config.height || 'auto');
      } else {
        ct.setWidth(table.getWidth());
      }

    if (!Ext.grid.GridView.prototype.templates) {
        Ext.grid.GridView.prototype.templates = {};
    }
    Ext.grid.GridView.prototype.templates.cell = new Ext.Template(
        '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
        '<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
        '</td>'
    );

  if (config.remove !== false) {
    table.remove();
  }
  Ext.applyIf(this, {
    'ds': ds,
    'cm': cm,
    'sm': new Ext.grid.RowSelectionModel(),
    autoHeight: true,
    autoWidth: false
  });

    if ( hasTotals ) {
        Ext.applyIf(this, {
            plugins: [summary]
        });
    }

  Ext.grid.TableGrid.superclass.constructor.call(this, ct, {});

    if ( hasTotals ) {
        summary.setCustomProvider(totals);
    }
};

Ext.extend(Ext.grid.TableGrid, Ext.grid.GridPanel);

Ext.ns('Ext.ux.grid');

Ext.ux.grid.GridSummary = function(config) {
        Ext.apply(this, config);
};

Ext.extend(Ext.ux.grid.GridSummary, Ext.util.Observable, {
    //customProvider: {}, Moved this down a couple lines, otherwise the TOTALS line from the last grid to load was always used no-matter what grid you sorted.
    init : function(grid) {
        this.grid = grid;
        this.cm = grid.getColumnModel();
        this.view = grid.getView();
        this.customProvider = {};

        var v = this.view;

        this.customProvider.items = {};
        this.customProvider.hasData = false;

        // override GridView's onLayout() method
        v.onLayout = this.onLayout;

        v.afterMethod('render', this.refreshSummary, this);
        v.afterMethod('refresh', this.refreshSummary, this);
        v.afterMethod('syncScroll', this.syncSummaryScroll, this);
        v.afterMethod('onColumnWidthUpdated', this.doWidth, this);
        v.afterMethod('onAllColumnWidthsUpdated', this.doAllWidths, this);
        v.afterMethod('onColumnHiddenUpdated', this.doHidden, this);

        // update summary row on store's add/remove/clear/update events
        grid.store.on({
            add: this.refreshSummary,
            remove: this.refreshSummary,
            clear: this.refreshSummary,
            update: this.refreshSummary,
            scope: this
        });

        if (!this.rowTpl) {
            this.rowTpl = new Ext.Template(
                '<div class="x-grid3-summary-row x-grid3-gridsummary-row-offset">',
                    '<table class="x-grid3-summary-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
                        '<tbody><tr>{cells}</tr></tbody>',
                    '</table>',
                '</div>'
            );
            this.rowTpl.disableFormats = true;
        }
        this.rowTpl.compile();

        if (!this.cellTpl) {
            this.cellTpl = new Ext.Template(
                '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}">',
                    '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>',
                "</td>"
            );
            this.cellTpl.disableFormats = true;
        }
        this.cellTpl.compile();
    },

    setCustomProvider: function(provider) {
        this.customProvider.items = provider;
        this.customProvider.hasData = true;
        this.refreshSummary();
    },

    calculate : function(rs, cm) {
        var data = {}, cfg = cm.config;
        for (var i = 0, len = cfg.length; i < len; i++) { // loop through all columns in ColumnModel
            var cf = cfg[i], // get column's configuration
                cname = cf.dataIndex; // get column dataIndex

            // initialise grid summary row data for
            // the current column being worked on
            data[cname] = 0;

            if (cf.summaryType) {
                for (var j = 0, jlen = rs.length; j < jlen; j++) {
                    var r = rs[j]; // get a single Record
                    data[cname] = Ext.ux.grid.GridSummary.Calculations[cf.summaryType](r.get(cname), r, cname, data, j);
                }
            }
        }

        return data;
    },

    onLayout : function(vw, vh) {
        if (Ext.type(vh) != 'number') { // handles grid's height:'auto' config
            return;
        }
        // note: this method is scoped to the GridView
        if (!this.grid.getGridEl().hasClass('x-grid-hide-gridsummary')) {
            // readjust gridview's height only if grid summary row is visible
            this.scroller.setHeight(vh - this.summary.getHeight());
        }
    },

    syncSummaryScroll : function() {
        var mb = this.view.scroller.dom;

        this.view.summaryWrap.dom.scrollLeft = mb.scrollLeft;
        this.view.summaryWrap.dom.scrollLeft = mb.scrollLeft; // second time for IE (1/2 time first fails, other browsers ignore)
    },

    doWidth : function(col, w, tw) {
        var s = this.view.summary.dom;

        s.firstChild.style.width = tw;
        s.firstChild.rows[0].childNodes[col].style.width = w;
    },

    doAllWidths : function(ws, tw) {
        var s = this.view.summary.dom, wlen = ws.length;

        s.firstChild.style.width = tw;

        var cells = s.firstChild.rows[0].childNodes;

        for (var j = 0; j < wlen; j++) {
            cells[j].style.width = ws[j];
        }
    },

    doHidden : function(col, hidden, tw) {
        var s = this.view.summary.dom,
            display = hidden ? 'none' : '';

        s.firstChild.style.width = tw;
        s.firstChild.rows[0].childNodes[col].style.display = display;
    },

    renderSummary : function(o, cs, cm) {
        cs = cs || this.view.getColumnData();
        var cfg = cm.config,
            buf = [],
            last = cs.length - 1;

        for (var i = 0, len = cs.length; i < len; i++) {
            var c = cs[i], cf = cfg[i], p = {};

            p.id = c.id;
            p.style = c.style;
            p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');

            if (cf.summaryType || cf.summaryRenderer) {
                p.value = (cf.summaryRenderer || c.renderer)(o.data[c.name], p, o);
            } else if (this.customProvider.hasData) {
                p.value = o.data[c.name];
            } else {
                p.value = '';
            }

            if (p.value == undefined || p.value === "") p.value = "*";
            buf[buf.length] = this.cellTpl.apply(p);
        }

        return this.rowTpl.apply({
            tstyle: 'width:' + this.view.getTotalWidth() + ';',
            cells: buf.join('')
        });
    },

    refreshSummary : function() {
        var g = this.grid, ds = g.store;
        var cs = this.view.getColumnData();
        var cm = this.cm;
        var rs = ds.getRange();
        if ( this.customProvider.hasData ) {
            var data = this.customProvider.items;
        } else {
            var data = this.calculate(rs, cm);
        }
        var buf = this.renderSummary({data: data}, cs, cm);
        if (!this.view.summaryWrap) {
            this.view.summaryWrap = Ext.DomHelper.insertAfter(this.view.scroller, {
                tag: 'div',
                cls: 'x-grid3-gridsummary-row-inner'
            }, true);
        }
        this.view.summary = this.view.summaryWrap.update(buf).first();
    },

    toggleSummary : function(visible) { // true to display summary row
        var el = this.grid.getGridEl();

        if (el) {
            if (visible === undefined) {
                visible = el.hasClass('x-grid-hide-gridsummary');
            }
            el[visible ? 'removeClass' : 'addClass']('x-grid-hide-gridsummary');

            this.view.layout(); // readjust gridview height
        }
    },

    getSummaryNode : function() {
        return this.view.summary
    }
});
Ext.reg('gridsummary', Ext.ux.grid.GridSummary);

/*
 * all Calculation methods are called on each Record in the Store
 * with the following 5 parameters:
 *
 * v - cell value
 * record - reference to the current Record
 * colName - column name (i.e. the ColumnModel's dataIndex)
 * data - the cumulative data for the current column + summaryType up to the current Record
 * rowIdx - current row index
 */
Ext.ux.grid.GridSummary.Calculations = {
    sum : function(v, record, colName, data, rowIdx) {
        return data[colName] + Ext.num(parseInt(v), 0);
    },

    count : function(v, record, colName, data, rowIdx) {
        return rowIdx + 1;
    },

    max : function(v, record, colName, data, rowIdx) {
        return Math.max(Ext.num(v, 0), data[colName]);
    },

    min : function(v, record, colName, data, rowIdx) {
        return Math.min(Ext.num(v, 0), data[colName]);
    },

    average : function(v, record, colName, data, rowIdx) {
        var t = data[colName] + Ext.num(v, 0), count = record.store.getCount();
        return rowIdx == count - 1 ? (t / count) : t;
    }
}


Ext.onReady(function(){
    if (Ext.get("submit")) {
        Ext.get("submit").on('click', function() {doSubmit(this)});
    }

    var tables = document.getElementsByTagName("table");
    for (var i = 0; i < tables.length; i++) {
        if (tables[i].className.indexOf('niceTable') != -1) {
            currId = tables[i].id;
            var gridNew = new Ext.grid.TableGrid(currId, {
                stripeRows: true,
                sortable: true
            });
            //gridNew.render();
        }
    }

     if (Ext.get('startDate')) {
        var startDate = Ext.get('startDate').dom.innerHTML;
        var endDate = Ext.get('endDate').dom.innerHTML;

        // Clear out div's to make room for calendar controls
        Ext.get('startDate').update('');
        Ext.get('endDate').update('');

        //document.write(sd.format('Y-m-d'));
        startDateField = new Ext.form.DateField({
            fieldLabel: 'Start Date',
            name: 'start_date',
            width: 90,
            allowBlank: false,
            format: 'Y-m-d',
            minDate: new Date(),
            minText: 'Nope',
            showWeekNumber: false
        });

        endDateField = new Ext.form.DateField({
            fieldLabel: 'End Date',
            name: 'end_date',
            width: 90,
            allowBlank: false,
            format: 'Y-m-d',
            minDate: new Date(),
            minText: 'Nope',
            showWeekNumber: false
        });
        startDateField.setValue(startDate);
        endDateField.setValue(endDate);

        startDateField.render('startDate');
        endDateField.render('endDate');
    }

}); // End onReady

function doSubmit(elem) {
    if (typeof(submitMsg) == "undefined") {
        submitMsg = 'Saving Changes....';
    }
    Ext.get(document.body).mask('Working.......','x-mask-loading');
    return true;
}

function openWindow(titleText,statUrl)
{
    ulDialog = new Ext.Window({
        width:          650,
        modal:          true,
        shadow:         true,
        collapsible:    true,
        closable:       true,
        animate:        true,
        autoScroll:		true,
        autoHeight:		true,
        items: [new Ext.ux.ManagedIframePanel(
                    { 	defaultSrc:statUrl,
                        loadMask: true,
                        fitToFrame: true
                    }
                  )],
        title:          titleText,
        resizable:      true,
        bodyBorder:     true,
        buttons:        [{text: "Close", handler: function() {ulDialog.hide();ulDialog.destroy();} }],
        keys:           [{key: 27, fn: function() {ulDialog.hide();ulDialog.destroy();}, scope: this}]
        });
   ulDialog.show();
}

