
var currentRowId=1;
var banktype = "bank-eu";

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++;
	}
	return i;
}

function checkAllRows(){
	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++;
		//
		var f=1
		var v =row.cells[f].firstElementChild.value;
		if ( !v ){  // Datum
			row.cells[f].firstElementChild.focus(); 
			showAlert("Bitte gib ein g&uuml;ltiges Datum an!");
			return false;

		}
		
		f=2;
		v =row.cells[f].firstElementChild.value;
		if ( !v ){  // Datum
			row.cells[f].firstElementChild.focus(); 
			showAlert("Bitte gib ein Beschreibung ein!");
			return false;

		}

		f=3;
		v =row.cells[f].firstElementChild.value;
		if ( !v ){  // Datum
			row.cells[f].firstElementChild.focus(); 
			showAlert("Bitte gib einen g&uuml;ltigen Betrag ein!");
			return false;
		}




	
	}
	return true;
}




function isMailable(){
	var row_no=1;
	var table = document.getElementById("tabbody");
	for (var i = 0, row; row = table.rows[i]; i++) {
		var pdfs = row.cells[4].innerHTML; 
		if (pdfs==0)
			return false;
	}
	return true;
}



function isFloat(val) {
    var floatRegex = /^-?\d+(?:[.,]\d*?)?$/;
    if (!floatRegex.test(val))
        return false;

    val = parseFloat(val);
    if (isNaN(val))
        return false;
    return true;
}



/**
 * grey-out currency iselection if there is at least one document is atatched.
 */
function disableCurrency()
{
	if (countRows()>0){
		document.getElementById("a_currency").disabled=true;
	}
	else {
		document.getElementById("a_currency").disabled=false;
	}

}

function deleteTableRow(rowId){

    var target = document.getElementById("upload-target"+rowId);
//            this.message = app.message;    
//   var children = target.children;

    // delete all uploaded elements
/*    for (var i = 0; i < children.length; i++) {
	var tmp = children[i].getAttribute("data-id");
	    alert ("DEL");
	    alert (tmp);
	$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 countRows(){
	return renumberTableRows();
}


function showAlert(text) {

	$K.app.message.show( { message: `${text}`, position: 'centered', type: 'is-error' });
	return;

}


function reset2()
{
//	document.getElementById("a_type").value="";
	document.getElementById("a_description").value="";
	document.getElementById("a_amount").value="";
	setUploadField();

}


function setTableRow(id)
{
	var $node = $K.dom('#tabbody');
	var element = document.createElement('tr');
	element.setAttribute("id", "trow"+id);

	var e
	e = `<td>${a_date}
		<input type="hidden" name="date[${currentRowId}]" value="${a_date}" /></td>`;

	$node.append(element);
	element.innerHTML=(e);
 
}



function getUploadField(rid)
{
    	var e = $K.dom('#uploadfield');
	var uf =`<div class="upload"
		data-kube="upload"
		data-type="file" 
		data-multiple="true"
		data-target="#upload-target${rid}"
		data-url="upload.php?row=${rid}" data-url-remove="delete.php"
		data-progress="true"
		data-size="40"
		data-placeholder="drag!"> 
		</div>
		<div id="upload-target${rid}" class="upload-target small"></div>
		</div>
		`;
	return uf;
}



function getRow(rid,num) {
	return "" 
		+ "<td>"
		+ `${num}`
		+"</td>"
		+ "<td>"
		+ 	`<input name="date[${rid}]" value="" type="date" placeholder="Datum*"/>`
		+ "</td>"
		+ "<td>"
		+	 `<input name="desc[${rid}]" type="text" placeholder="Beschreibung"/>`
		+ "</td>"
		+ "<td>"
		+ 	`<input name="amount[${rid}] type="text" placeholder="0.00"/>`
		+ "</td>"
		+ "<td>"
		+
		`<select name="currency[${rid}]" >
			<option value="EUR">EUR</option>
			<option value="USD">USD</option>
			<option value="CHF">CHF</option>
			<option value="XBT">XBT</option>
		</select>`

		+ "</td>"
		+ "<td>"
		+ getUploadField(rid)
		+ "</td>"
		+
		`<td><span
		onclick="deleteTableRow(${rid})"
		class="close is-large">
		</span></td>`;
 

}


var nextRid = 1

function addRow() {
	var $node = $K.dom('#tabbody');
	var e = getRow(nextRid,1);
	var element = document.createElement('tr');
	element.setAttribute("id", "trow"+nextRid);
	$node.append(element);
	element.innerHTML=(e);
	renumberTableRows();
	nextRid++;
}

function xaddTableRow(){

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


/*	var a_type = document.getElementById("a_type").value;
	if (!a_type.trim().length ) {
		document.getElementById("a_type").focus();
		showAlert("Bitte gib eine Auslagenart an!");
		return;
	}
*/


	var a_date = document.getElementById("a_date").value; 
	if (!a_date.trim().length){
		document.getElementById("a_date").focus();
		showAlert("Bitte gib ein g&uuml;ltiges Datum an!");
		return;
	}


	var a_description = document.getElementById("a_description").value; 
	if (!a_description.trim().length){
		document.getElementById("a_description").focus();
		showAlert("Bitte gib eine Beschreibung ein!");
		return;
	}

	var a_amount = document.getElementById("a_amount").value; 
	if (!isFloat(a_amount)){
		document.getElementById("a_amount").focus(); 
		showAlert("Bitte gib einen g&uuml;ltigen Betrag ein!");
		return;
	}
	a_amount = parseFloat(a_amount).toFixed(2);
		

	var a_currency = document.getElementById("a_currency").value; 
/*	if (!a_currency.trim().length){
		document.getElementById("a_currency").focus();
		showAlert("Bitte gib eine W&auml;hrung an!");
		return;
	}
*/
	var target = document.getElementById("upload-target"+currentRowId);
   	var children = target.children;

	if (!children.length){
//		showAlert("Bitte lade mindestens einen Beleg hoch!");
//		return;
	}





/*	a_type = "Hello";*/

    var e="<td></td>";

    // add column for position no
//    e += `<td>${a_type}
//		<input type="hidden" name="type[${currentRowId}]" value="${a_type}" /></td>`;

    // add coluemn for a_type (Auslagenart)
//    e += `<td><textarea name="desc[${nextRowId}]" rows="2"></textarea> </td>`;
    e += `<td>${a_date}
		<input type="hidden" name="date[${currentRowId}]" value="${a_date}" /></td>`;


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


    // add column for num
    e += `<td>${a_amount} EUR
		<input type="hidden" name="amount[${currentRowId}]" value="${a_amount}" /></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>
*/
	var ulfiles = children.length;
	e += `<td>${ulfiles}</td>`;	
	
//	`;
    // add delete bnutton
    e +=
	`<td><span
    onclick="deleteTableRow(${currentRowId})"
    class="close is-large">
	</span></td>`;
    
    
    $node.append(element);
    element.innerHTML=(e);
    renumberTableRows();
    currentRowId++;
	reset2();
	
}



function setUploadField()
{
    	var e = $K.dom('#uploadfield');
	var uf =`<div class="upload"
		data-kube="upload"
		data-type="file" data-multiple="true"
		data-target="#upload-target${currentRowId}"
		data-url="upload.php?row=${currentRowId}" data-url-remove="delete.php"
		data-progress="true">Beleg(e) hochladen 
		</div>
		<div id="upload-target${currentRowId}" class="upload-target small"></div>
		</div>
		`;
	document.getElementById("uploadfield").innerHTML=uf; 
}

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

		banktype = sender.getActiveBox().nodes[0].attributes.id.value;

			console.log(banktype);


			
//			console.log(sender);	
//		  this.message.show({ message: 'My message' });
		}
            }
        },
	

    });

$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) {}
});

setUploadField();


function check_field(fieldid,message){
	var f = document.getElementById(fieldid).value;
	if (! f.trim().length ) {
		document.getElementById(fieldid).focus();
		showAlert(message)
		return false;
	}
	return true;
}

// add on table row
//addTableRow();
//
//
//
//
function downloadDocument2(){
	downloadDocument(true);
}

function downloadDocument1(){
	downloadDocument(false);
}


function downloadDocument(mail)
{


	if (!checkAllRows())
		return;


	if (!check_field("projectid", "Bitte gib einen Projektnamen/Zweck der Reise an!"))
		return;

	if (!check_field("realname", "Bitte gib deinen Realnamen an!"))
		return;

	if (!check_field("email", "Bitte gib deinen E-Mail-Adresse an!"))
		return;

	if (banktype == "bank-eu"){
		iban = document.getElementById('iban');
		if (!IBAN.isValid(iban.value)){
			document.getElementById("iban").focus();
			showAlert("Bitte gib eine korrekte IBAN ein!");
			return;
		}
/*		if (!document.getElementById('bic').value.trim().length){
			document.getElementById("bic").focus();
			showAlert("Bitte gib einen korrekte BIC an!");
			return;
		}

*/
	}
	
	if (banktype == "bank-paypal"){
		ii = document.getElementById('paypal');
		if (!document.getElementById('paypal').value.trim().length){
			document.getElementById("paypal").focus();
			showAlert("Bitte gib einen PayPal Account an!");
			return;
		}
	}
	

	if (countRows()==0){
		document.getElementById("add_issue").focus();
		showAlert("Bitte f&uuml;ge mind. eine Auslage hinzu!");
		return;
	}


	if (mail){
		if (!isMailable()){
			showAlert("Um den Antrag elektronisch direkt an WMDE zu schicken, muss jeder Position ein Beleg beigef&uuml;gt sein.");
			return;

		}

		document.getElementById('sendmail').value="yes";
		
	}
	else{
		document.getElementById('sendmail').value="no";
	}


	document.getElementById('banktype').value=banktype;
	document.getElementById("theform").submit(); 	

	if (!document.getElementById("agree").checked){
		document.getElementById("agree").focus();
		showAlert("Bitte best&auml;tige, dass du alle Angaben nach bestem Wissen und Gewissen gemacht hast!");
		return;
	};


	
}


/*
function checkIban()
{
	iban = document.getElementById('iban');
	if(IBAN.isValid(iban.value))
	
	if( document.getElementById('eu').checked ) {

		if(IBAN.isValid(iban.value))
		{
                	if(iban.classList.contains('invalid')) iban.classList.remove('invalid');
                                        iban.classList.add('valid');
		}
                else {
			if(iban.classList.contains('valid')) iban.classList.remove('valid');
                                        iban.classList.add('invalid');
                                }
                        } else {
                                if(iban.classList.contains('invalid')) iban.classList.remove('invalid');
                                if(iban.classList.contains('valid')) iban.classList.remove('valid');
                        }
                }
*/



