﻿function TableBuilder(Container,Hoverable,Selectable) {
    this.Container = Container;

    this.Table = document.createElement('table');
    this.Table.className = 'mGrid';
    Container.appendChild(this.Table);

    this.CurrentRow = null;
    this.HeaderRowStyle = '';
    this.EvenRowStyle = '';
    this.OddRowStyle = 'alt';
    this.RowHoverStyle = '';
    this.Hoverable = Hoverable;
    if (this.Hoverable) this.RowHoverStyle = 'hover';

    this.Selectable = Selectable;
    this.SelectedRowStyle = '';
    if (this.Selectable) this.SelectedRowStyle = 'selected';

    this._CurrentRowIndex = -1;
    this._CurrentColIndex = 0;

    this.RowClick = null;
}

TableBuilder.prototype = {
    SetTitle: function(Title) {
        var caption = document.createElement('caption');
        caption.innerHTML = Title;
        this.Table.appendChild(caption);
    },
    NewRow: function() {

        var tr = this.Table.insertRow()

        this._CurrentColIndex = 0;
        this._CurrentRowIndex++;

        if (this._CurrentRowIndex == 0)
            tr.className = this.HeaderRowStyle;
        else {

            if (this.Hoverable) tr.className = this.RowHoverStyle;

            if (this._CurrentRowIndex % 2 == 0)
                tr.className += ' ' + this.EvenRowStyle;
            else
                tr.className += ' ' + this.OddRowStyle;

            if (this.RowClick != null) {
                var c = new this._Context(this, tr);
                var d = Function.createDelegate(c, this._RowClicked);
                $addHandler(tr, 'click', d);
            }
        }

        this.CurrentRow = tr;
        return tr;
    },

    AddHeader: function(HeaderText, HeaderCellStyle) {

        var th = document.createElement('th');
        th.innerHTML = HeaderText;
        if (typeof (HeaderCellStyle) != "undefined") th.className = HeaderCellStyle;
        this.CurrentRow.appendChild(th);
        return th;
    },

    AddCell: function(Text, CellStyle) {
        var td = this.CurrentRow.insertCell();
        td.innerHTML = Text;
        if (typeof (CellStyle) != "undefined") td.className = CellStyle;

        return td;
    },

    _RowClicked: function() {
        this.Sender.RowClick(this.Sender, this.Argument);
    },

    _Context: function(sender, argument) {
        this.Sender = sender;
        this.Argument = argument;
    }
}

