$(document).ready(function() {
    //load number functions if they are not loaded yet
    if (typeof window["FormatNumber"] === 'undefined') {
        $.ajax({
            async : false,
            url : "include/ECM/EcmNumberFunctions.js",
            dataType : "script"
        });
    }
    $('#invSelectAll').click(function(event) {  //on click 
        if(this.checked) { // check select status
            $('.invcheckbox').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox1"    
                calculate();
            });
        }else{
            $('.invcheckbox').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox1"   
                calculate();
            });         
        }
    });
    
    $('#discount').on('blur', function() {
        calculate();
     });
});

var calculate = function() {
    var discount = UnformatNumber($('#discount').val())/100;
    $('#discount').val(FormatNumber(UnformatNumber($('#discount').val())));
    console.log(discount);
    var sum_disc = 0;
    $('#invTable tr').each(function (i, row) {
        if (i == 0 || i == $('#invTable tr').lenght) return;
        if ($(row).find('.invcheckbox').is(':checked') == false) return;
        var val = parseFloat($(row).find('.netto').html());
        sum_disc += val * discount;
    });
    $('#total_info').html('-'+FormatNumber(sum_disc));
}

var prepareData = function() {
    var inv = "";
    $('.invcheckbox:checked').each(function (){
       inv+=this.value+'|'; 
    });
    inv = inv.slice(0,-1);
    var link = "index.php?module=EcmInvoiceOuts&action=EditView&mdci=1&account_id="+$('#account_id').val();
    link +="&account_name="+$('#account_name').val()+'&invoices='+inv+'&discount='+UnformatNumber($('#discount').val());
    window.location = link;
    
} 