//**********************************************************************
// setupTables: 
//**********************************************************************
Books.setupTables = function() {    
    // Fill the tables and add column sorting.
    Books.statusMessage('Filling book table');
    Books.setupTable('books');
    Books.setupTable('authors');
    Books.statusMessage(null);
};

//**********************************************************************
// setupTable: 
//**********************************************************************
Books.setupTable = function(tableName) {
    var $table = Books.fillTable(tableName);
    Books.setUpColumnSorting($table);
    
    // Initially sort by the first column
    $('th:first', $table).click();
    
    // Set up filtering and clear the filter field
    $('#'+tableName+'FilterText').keyup(function() {
        Books.filterRows($table, $(this).val());
    })
    .val('');
};

//**********************************************************************
// selectTableRow: called when the row is clicked on.
//**********************************************************************
Books.selectTableRow = function(e) {
    $this = $(this);
    var selectedRow = jQuery.data(e.data.domTable, 'selectedRow');
    if(selectedRow) selectedRow.removeClass('selected');
    jQuery.data(e.data.domTable, 'selectedRow', $this);
    $this.addClass('selected');
    
    Books.fillBookForm(e.data.rowData);
};

//**********************************************************************
// fillTable: generate the table, header and content rows.
//**********************************************************************
Books.fillTable = function(tableName)
{
    var i, j, $trow, elementArray;
    
    var tableId = '#' + tableName + '-table';
    var fields = Books.tableSpecs[tableName].fields;
    var $table = $(tableId);
    var domTable = $table.get(0);
    //jQuery.data(domTable, 'selectedRow', null);    

    // Generate the header elements and insert it into thead
    elementArray = [];
    Books.addColumnHeaders(fields, elementArray);
    
    // Get the thead, and empty it so we can call this twice if we need to.
    var $thead = $(tableId+" thead").empty();
    
    // The headers have only one row to column titles.
    $trow = $('<tr></tr>').appendTo($thead);
    $.each(elementArray, function(index, element) { $trow.append(element); });


    // Generate the data rows elements and insert it into tbody
    var dataTable = Books.bookData[tableName];
    var dataTableLength = dataTable.length;

    // Get the thead, and empty it so we can call this twice if we need to.
    var $tbody = $(tableId+" tbody").empty();
    
    for(i = 0; i < dataTableLength; ++i)
    {
        var rowData = dataTable[i];
        
        // skip inactive entries
        if(rowData.inactive) continue;
        
        // Create the table row element and bind the selection handler.
        $trow = $('<tr></tr>')
            .appendTo($tbody)
            .bind('click',
                {domTable:domTable, rowData:rowData},
                Books.selectTableRow);
        
        // Get an array of table cell elements
        elementArray = [];
        Books.addColumnData(rowData, fields, elementArray);
        
        // Append each table cell to the row
        $.each(elementArray, function(index, element) {
            $trow.append(element);
        });
    }
    
    Books.colorAlternateRows($table);
    
    return $table;
};

//**********************************************************************
// filterRows: apply a filter to the rows.
//**********************************************************************
Books.filterRows = function($table, filterText)
{
    var re = new RegExp(filterText, 'i');
    $('tbody tr', $table).each(function(index) {
        var $this = $(this);
        if($this.text().match(re))
            $this.show();
        else
            $this.hide();
    });
};

//**********************************************************************
// addColumnHeaders: generate the TH elements for a table from a template.
//**********************************************************************
Books.addColumnHeaders = function(fields, thArray) {
    var i, j;
    
    for(i=0; i<fields.length; ++i) {
        var field = fields[i];
        if(field.show) {
            switch(field.dataType) {
                case "i":
                case "ia":
                case "s":
                case "sa":
                case "authors":
                    thArray.push($("<th></th>")
                        .addClass("sort")
                        .text(field.title)
                        .append('<span class="sort-direction"></span>'));
                    break;
                
                case "r":
                case "ra":
                    var fields = Books.tableSpecs[field.table].fields;
                    Books.addColumnHeaders(fields, thArray);
                    break;
            }
        }
    }
    
};

//**********************************************************************
// addColumnData: generate the TD elements for a table from a template.
//**********************************************************************
Books.addColumnData = function(rowData, fields, tcArray) {
    var i, j;
    
    for(i=0; i<fields.length; ++i) {
        var field = fields[i];
        if(field.show) {
            var fieldData = rowData[field.name];
            switch(field.dataType) {
                case "i":
                    tcArray.push($("<td></td>").text(fieldData.toString()));
                    break;
                
                case "ia":
                    tcArray.push($("<td></td>").text(fieldData.join(' ')));
                    break;
                
                case "s":
                    if(!fieldData) fieldData = ' ';
                    tcArray.push($("<td></td>").text(fieldData));
                    break;
                
                case "sa":
                    tcArray.push($("<td></td>").text(fieldData.join(' ')));
                    break;
                
                case "r":
                    console.log("ERROR: r not implemented");
                    /*
                    var row = Books.bookData[field.table][fieldData];
                    var fields = Books.tableSpecs[field.table].fields;
                    Books.addColumnData(row, fields, tcArray);
                    */
                    break;

                case "authors":
                    var authorsArray = [];
                    for(j=0; j<fieldData.length; ++j) {
                        authorsArray.push(Books.getAuthorName(fieldData[j]));
                    }
                    tcArray.push($("<td></td>").text(authorsArray.join(' and ')));
                    break;

                case "ra":
                    console.log("ERROR: ra not implemented");
                    /*
                    var fieldValue = '';
                    var spacer = '';
                    for(j=0; j<fieldData.length; ++j) {
                        var row = Books.bookData[field.table][fieldData[j]];
                        var fields = Books.tableSpecs[field.table].fields;
                    }
                    Books.addColumnData(row, fields, tcArray);
                    */
                    break;
            }
        }
    }
};

// books data fields:
//    title: [string]: the title of the book
//    subTitle: [string]: the secondary title (the part after the ':' usually)
//    author: [string]: the author(s) of the book
//    publishedDate: [date string]: the year the book was published
//    readDate: [date string]: the date (maybe just year) I read the book
//    tags: [string]: the tags assigned to this book
//    notes: [string]: notes on the book
//    status: [string] "DidRead", "ToRead", "None", or ""
//    rating: [integer] 1 to 5

Books.tableSpecs = {
    "meetings": {
            "title": "Meetings",
            "fields": [
                {
                    "name": "date",
                    "title": "Date",
                    "dataType": "s",
                    "show": true
                },
                {
                    "name": "book",
                    "title": "Book Title",
                    "dataType": "r",
                    "table": "books",
                    "show": true
                },
                {
                    "name": "host",
                    "title": "Host",
                    "dataType": "s",
                    "show": true
                }
            ]
    },
    "books": {
            "title": "Books",
            "fields": [
                {
                    "name": "title",
                    "title": "Title",
                    "dataType": "s",
                    "show": true
                },
                {
                    "name": "author",
                    "title": "Author",
                    "dataType": "authors",
                    "table": "authors",
                    "show": true
                },
                {
                    "name": "publishedDate",
                    "title": "Published",
                    "dataType": "s",
                    "show": true
                },
                {
                    "name": "readDate",
                    "title": "Date read",
                    "dataType": "s",
                    "show": true
                },
            ]
    },
    "authors": {
            "title": "Authors",
            "fields": [
                {
                    "name": "names",
                    "title": "Name",
                    "dataType": "sa",
                    "show": true
                }
            ]
    }
};

