
var nextRowId=1;

function renumberTableRows(){
    var row_no=1;
    var table = document.getElementById("tabbody");
    for (var i = 0, row; row = table.rows[i]; i++) {
	row.cells[0].innerHTML=row_no++;
    }
}

function deleteTableRow(rowId){
    var target = document.getElementById("upload-target"+rowId);
    var children = target.children;

    // delete all uploaded elements
    for (var i = 0; i < children.length; i++) {
	var tmp = children[i].getAttribute("data-id");
	$K.ajax.post({
	    url: 'delete.php',
	    data: 'id='+tmp,
	    before: function(xhr) {},
	    success: function(response) {},
	    error: function(response) {}
	});
    }
    

    // delete the row from table
    var element = document.getElementById("trow"+rowId);
    element.parentNode.removeChild(element);
    renumberTableRows();
//    alert(rowId);
    
}

function addTableRow(){

    var $node = $K.dom('#tabbody');
    // create a new table row with id
    var element = document.createElement('tr');
    element.setAttribute("id", "trow"+nextRowId);

    var e="";

    // add column for position no
    e += '<td></td>';

    // add coluemn for description
    e += `<td><textarea name="desc[${nextRowId}]" rows="2"></textarea> </td>`;

    // add column for date
    e += `<td><input name="date[${nextRowId}]" type="date"/></td>`;

    // add column for num
    e += `<td><input name="amount[${nextRowId}]" type="num"/></td>`;

    // add column for file upload
    e+= `
	<td data-kube="">
	<div class="form-item">
	<div class="upload"
    data-kube="upload"
    data-type="file" data-multiple="true"
    data-target="#upload-target${nextRowId}"
    data-url="upload.php?row=${nextRowId}" data-url-remove="delete.php"
    data-progress="true">
	</div>
	<div id="upload-target${nextRowId}" class="upload-target"></div>
	</div>

	
    </td>
	`;
    // add delete bnutton
    e +=
	`<td><span
    onclick="deleteTableRow(${nextRowId})"
    class="close is-large">
	</span></td>`;
    
    
    $node.append(element);
    element.innerHTML=(e);
    renumberTableRows();
    nextRowId++;
}



$K.add('module', 'kaform', {
	init: function(app, context)
        {
            this.app = app;
        },
	// catch event
        onmessage: {
            tabs: {
                opened: function(sender)
                {
                    console.log('Tab box is ',sender.getActiveBox());
                }
            }
        },
	

    });

$K.init({
    observer: true
});



// startup is here



// on startup clear session on server
$K.ajax.get({
    url: 'clear.php',
    data: '', // or key=value object
    before: function(xhr) {},
    success: function(response) {},
    error: function(response) {}
});

// add on table row
//addTableRow();
