//**********************************************************************
// setupForms: 
//**********************************************************************
Books.setupForms = function() {    
    var $form = $('#books-edit-form');
    
    Books.clearForm($form);
            
    $('#bookSaveButton').click(function() {
        Books.saveBookForm();
    });
        
    $('#bookCreateButton').click(function() {
        Books.clearForm($form);
        Books.formBookRowData = null;
    });

    var ratingClickHandler = function() {
        $('#ratingField').val($.data(this, "rating").toString());
    };
    for(var i=1; i<6; ++i) {
        var $ratingButton = $('#rating'+i.toString()+'Button');
        $ratingButton.click(ratingClickHandler);
        $.data($ratingButton.get(0), "rating", i);
    }
    
    $('#addTagsButton').click(function() {
        
        // LATER: be clever and remove duplicates.
        // split(' ') both existing tags and tags to be added.
        // Start from empty and add in all the tags, skipping duplicates,
        // and empty tags (from two spaces in a row).
        
        var $tagsField = $('#tagsField');
        var tags = $tagsField.val();
        if(tags.length > 0) tags += ' ';
        tags += $(this).next().val();
        //log("newTags="+tags);
        $tagsField.val(tags);
    });
    
    // Save book data
    $('#saveBookDataButton').click(function() {
        var filename = $("#saveFilename").next().val();
        Books.statusMessage('Saving book data to file "'+filename+'"');
        $.ajax({
            type: "POST",
            url: "save.php",
            data: {
                filename: filename,
                filedata: JSON.stringify(Books.bookData, null, 4)
            },
            complete: function(){Books.statusMessage(null);},
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log("ERROR saving book data to file "+filename+", msg: "+textStatus);
            },
            success: function(data) {
                console.log('SAVED book data to file "'+filename+'"');
            }
        });
    });

    // Import book data
    $('#importButton').click(function() {
        var filename = $("#importFilename").next().val();
        Books.statusMessage('Importing book data from file "'+filename+'"');
        $.ajax({
            url: filename,
            complete: function(){Books.statusMessage(null);},
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log("ERROR fetching import file "+filename+", msg: "+textStatus);
            },
            success: Books.importData
        });
    });
};

//**********************************************************************
// saveBookForm:
//**********************************************************************
Books.saveBookForm = function()
{
    // Record this so we can save the changes if it is edited.
    var rowData = Books.formBookRowData;
    if(!rowData) {
        // We are creating a new book record.
        rowData = {};
        // Save in the book array.
        Books.bookData.books.push(rowData);
        log("Adding book :"+o2s(rowData));
    }
    
    var $form = $('#books-edit-form');
    var $inputs = $('input', $form);
    
    // Fill in the fields of the form
    rowData.title = $inputs.eq(0).val();
    rowData.titleLowerCase = rowData.title.toLowerCase();
    rowData.subtitle = $inputs.eq(1).val();
    rowData.publishedDate = $inputs.eq(2).val();
    rowData.readDate = $inputs.eq(3).val();
    rowData.rating = $inputs.eq(4).val();
    rowData.status = $inputs.eq(5).val();
    // $inputs.eq(6) is the "Add author" button.
    rowData.author = Books.bookFormAuthorList;    
    rowData.tags = $inputs.eq(7).val();
    rowData.notes = $inputs.eq(8).val();
};

//**********************************************************************
// fillBookForm:
//**********************************************************************
Books.fillBookForm = function(rowData)
{
    // Record this so we can save the changes if it is edited.
    Books.formBookRowData = rowData;
    
    //console.log('fillBookForm: rowData='+o2s(rowData));
    var $form = $('#books-edit-form');
    var $inputs = $('input', $form);
    
    var fillField = function(index, name) {
        var v = rowData[name];
        if(!v) v = '';
        $inputs.eq(index).val(v);
    };
    
    // Fill in the fields of the form
    fillField(0, 'title');
    fillField(1, 'subtitle');
    fillField(2, 'publishedDate');
    fillField(3, 'readDate');
    fillField(4, 'rating');
    fillField(5, 'status');
    // $inputs.eq(6) is the "Add author" button, handled below.
    fillField(7, 'tags');
    fillField(8, 'notes');
    
    // Handle the authors field, which comes from another table.
    var authors = '';
    var spacer = '';
    var authorList = rowData.author;
    // Save the author list for later changes.
    Books.bookFormAuthorList = authorList;
    if(authorList) {
        $.each(authorList, function(index, value) {
            authors += spacer + Books.getAuthorName(value);
            space = ', ';
        });
    }
    $('#authors-span').text(authors);    
};

//**********************************************************************
// Form convenience functions: 
//**********************************************************************
Books.clearForm = function($form) {
    //log("clear form " + $form + " size="+$form.size());
    if(!$form) return;
    //log("# of :text=" + $(':text', $form).size());
    $(':text', $form).val('');
    $('#authors-span').text('');
};



