        function isValidEmail(email) {
            // Regular expression to validate email format
            var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(email);
        }

        function isNumber(value) {
         //   console.log("Is number: "+value);
         //   console.log("Type: "+typeof value);
            return typeof value === 'number' && !isNaN(value);
        }

        $(document).ready(function(){
            console.log("ready!");


            //requestnewpassform
            $("#requestnewpassform").submit(function(e){
                e.preventDefault();
             //   console.log("New pass for email...");
                let email = $("#email").val();
             //   console.log("Email: "+email);
                if (!isValidEmail(email)) {
                    $('#mailsent').removeClass("alert-outline-primary");
                    $('#mailsent').addClass("alert-outline-danger");
                    $('#mailsent').show();
                    $('#mailsent').text("Antamasi sahkoposti on virheellinen. Yritä uudelleen.");
                    return;
                }
                else
                {
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "sendnewpass.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                        //    console.log(xhr.responseText);
                            // Handle the response from the server
                            $('#mailsent').removeClass("alert-outline-danger");
                            $('#mailsent').addClass("alert-outline-primary");
                            $('#mailsent').show();
                            $('#mailsent').text("Lähetimme sinulle sähköpostiisi 6-merkkisen koodin salasanan vaihtamista varten. Tarkista sähköpostisi.");

                            // Reditect to page newpass.php after 3 seconds
                            setTimeout(function(){
                                window.location.href = "./newpass.php";
                            }, 3000);

        
                        }
                    };
                    xhr.onerror = function() {
                        console.log("Error occurred during the request");
                        // Handle the error
                    };
                    xhr.send("email=" + encodeURIComponent(email));
                }
                // Continue with the rest of the code
            });

            $("#newpass").click(function(){

                let email = $("#email").val();
                let token = '';
                token = $("#c1").val() + $("#c2").val() + $("#c3").val() + $("#c4").val() + $("#c5").val() + $("#c6").val();
                token = token.trim();
                token = token.toUpperCase();
              //  console.log("Token: " + token);
                $('#mailsent').text("");
                $('#mailsent').hide();
                $('#mailsent').removeClass("alert-outline-danger");
                $('#mailsent').addClass("alert-outline-primary");


                let pass1 = $("#pass1").val();
                let pass2 = $("#pass2").val();

                //mailsent
                if(pass1.length < 8){
                    $('#mailsent').removeClass("alert-outline-primary");
                    $('#mailsent').addClass("alert-outline-danger");
                    $('#mailsent').show();
                    $('#mailsent').text("Salasasi on liian lyhyt. Minimi 8 merkkiä.");
                    return;
                }

                else if(pass1 != pass2){
                    $('#mailsent').removeClass("alert-outline-primary");
                    $('#mailsent').addClass("alert-outline-danger");
                    $('#mailsent').show();
                    $('#mailsent').text("Salasasanat eivät täsmää. Yritä uudelleen.");
                    return;
                }

                else{

                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "setpass.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            console.log(xhr.responseText);
                            // Handle the response from the server
                            $('#mailsent').removeClass("alert-outline-danger");
                            $('#mailsent').addClass("alert-outline-primary");
                            $('#mailsent').show();
                            $('#mailsent').text("Salasana vaihdettu onnistuneesti. Kirjaudu sisään uudella salasanalla. Siirrämme sinut kirjautumissivulle 3 sekunnin kuluttua.");
                            
                            setTimeout(function(){
                                window.location.href = "./login.php?checkmail=true";
                            }, 3000);
                        }
                    };
                    var password = $("#pass1").val();
                    xhr.send("email=" + encodeURIComponent(email) + "&pass=" + encodeURIComponent(pass1) + "&token=" + encodeURIComponent(token));
                    xhr.onerror = function() {
                        console.log("Error occurred during the request");
                        // Handle the error
                    };
                }

            });

            $(".monthbutton").click(function(){

                let month = $(this).attr("data-month");
                let year = $(this).attr("data-year");
                let page = $(this).attr("data-page");

               // console.log("Month: "+month);
                //Test that variables year and month are correct and contain only digits
                if(!isNaN(year) && !isNaN(month)){

                    //Remove leading zero from variables month and year
                   // month = month.replace(/^0+/, '');
                    //year = year.replace(/^0+/, '');

                    //Go throught all button elements with class monthbutton and remove class active    
                    $(".monthbutton").each(function(){
                        $(this).removeClass("active");
                    });

                    window.location.href = "./"+page+"?year="+year+"&month="+month;
                }

            });

            $('#addfiles #price').on('input', function() {

                let price =   $('#addfiles #price').val();


                price =  parseFloat(price.replace(/,/g, '.'));

               // console.log("Price: "+price);

                if (!isNumber(price)) {
                    console.log("Price is not a number"); 
                    $('#addfiles #price').css('border', '1px solid red');
                    $('#kuittiPriceAlert').show();
                }
                else
                {
                    $('#addFiles #price').css('border', '0px solid red');
                    $('#kuittiPriceAlert').css('border', '0px solid lightgrey');
                    $('#kuittiPriceAlert').hide();

                }



            });

            $('#addfiles #selite').on('input', function() {
                var seliteInput = $('#addfiles #selite');
                var seliteError = $('#addfiles #seliteError');
                if (seliteInput.val().length >= 50) {
                    seliteError.show();
                } else {
                    seliteError.hide();
                }
            });            

            $('#kuittiDetailsForm #selite').on('input', function() {
                var seliteInput = $('#kuittiDetailsForm #selite');
                var seliteError = $('#kuittiDetailsForm #seliteError');
                if (seliteInput.val().length >= 50) {
                    seliteError.show();
                } else {
                    seliteError.hide();
                }
            });            


            $("#submitKuittiButton").click(function(e){
                e.stopPropagation();
               // console.log("Pikakuitti button clicked");

                let price =   $('#kuittiDetailsForm #price').val();

                let selite = $('#kuittiDetailsForm #selite').val();

                price =  parseFloat(price.replace(/,/g, '.'));

                console.log("Price: "+price);

                if (!isNumber(price)) {
                    console.log("Price is not a number"); 
                    $('#kuittiDetailsForm #price').css('border', '1px solid red');
                    $('#priceAlertQuick').show();

                    return;
                }
                else
                {
                    $('#kuittiDetailsForm #price').css('border', '1px solid lightgrey');
                    $('#priceAlertQuick').css('border', '1px solid lightgrey');
                    $('#priceAlertQuick').hide();

                }
            
                price = parseFloat(price);

                console.log("Price: "+price);
                console.log("Selite: "+selite);

                //cameraInput
                var file1 = document.getElementById("cameraInput").files[0];

                var formData = new FormData();
                if (file1) formData.append("image", file1);
                formData.append("price", price);
                if (selite) formData.append("selite", selite);
                formData.append("utype", 1);
                
                $.ajax({
                    url: "ajaxtiedosto.php", // URL of the backend PHP file
                    type: "POST",
                    data: formData,
                    processData: false, // Prevent jQuery from automatically transforming the data into a query string
                    contentType: false, // Prevent jQuery from setting the Content-Type header
                    success: function(response) {
                        // Handle the response from the server
                      //  console.log("Response from server: ", response);

                        if (response === '1') {
                            $("#errorAlertQuickPic").hide();
                            $("#successAlertQuickPic").show();    

                            setTimeout(function() {
                                $("#successAlertQuickPic").fadeOut();
                
                                // Hide the modal
                                $('#kuittiDetailsModal').modal('hide');
                
                                // Wait for 500 milliseconds before reloading the page
                                setTimeout(function() {
                                    location.reload();
                                }, 500);
                
                            }, 2000);

                        }
                        else {
                            $("#errorAlertQuickPic").show();
                            $("#successAlertQuickPic").hide();    

                        }        
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        // Handle any errors
                        console.error("Error: ", textStatus, errorThrown);
                    }
                });


            });


            $(".addfile").click(function(e){
                e.stopPropagation();

                
                console.log("Add file clicked");


                let tid = $(this).data('tid');
                console.log("Tid: "+tid);


                let type = $(this).data('type');
                console.log("Type: "+type);

                
                let counter = document.getElementById('spancounter_'+tid);
                console.log("Counter: "+counter.tagName);
                let count = counter.getAttribute('data-count');
                console.log("Count: "+count);


                if ( $('.file2_'+tid).not(":visible") && count == 1)
                {
                    console.log("File2 visible");
                    $('.plus2_'+tid).hide();

                    let con2 = $('.file2_'+tid).html();
                    localStorage.setItem('.file2_'+tid, con2);

                    $('.file2_'+tid).show();
                    counter.setAttribute('data-count', 2);
                    $('.plus3_'+tid).show();
                    return
                }
                else if ( $('.file3_'+tid).not(":visible")  && count == 2)
                {
                    console.log("File3 visible");
                    $('.plus3_'+tid).hide();
                   

                    $('.file3_'+tid).show();
                    counter.setAttribute('data-count', 3);
                    $('.plus4_'+tid).show();
                    return
                }
                else if ( $('.file4_'+tid).not(":visible")  && count == 3)
                {
                    console.log("File4 visible");
                    $('.plus4_'+tid).hide();
                    $('.file4_'+tid).show();
                    counter.setAttribute('data-count', 4);

                    $(this).hide();
                    return
                }
            

            });

            //upload-image
            $(".upload-image").click(function(e){
                e.stopPropagation();

                let tid = $(this).data('tid');
                console.log("Tid: "+tid);

                let type = $(this).data('type');
                console.log("Type: "+type);

                if (type == "upload") {

                    console.log("Upload clicked");
                    let eve = $(this).data('event');
                    console.log("Event: "+eve);

                    $(eve).click();
                }
                

            });



            //upload-close
            
            $(".upload-close").click(function(e){

                console.log("Upload-close clicked");
                e.stopPropagation();

                let tid = $(this).data('tid');
                console.log("Tid: "+tid);

                let type = $(this).data('type');
                console.log("Type: "+type);

                let num = parseInt($(this).data('num'));
                console.log("Num: "+num);

                if (type == "close") {

                    console.log("Upload clicked");
                    let fileElement = $(this).data('event');
                    console.log("Event remove: "+fileElement);
                    $(fileElement).hide();

                    let oldContent = '.file'+num+'_'+tid;
                    if (localStorage.getItem(oldContent) ) 
                    {
                        console.log("Old content: "+oldContent);
                        let content = localStorage.getItem(oldContent);
                        $(oldContent).html(content);
                        localStorage.removeItem(oldContent);
                      }

                    let counter = document.getElementById('spancounter_'+tid);
                    console.log("Counter: "+counter.tagName);
                    let count = counter.getAttribute('data-count');
                    console.log("Count: "+count);

                    if (num > 1) num = num - 1;

                    counter.setAttribute('data-count', num);

    
                }

            });

            //kuvauploadbtn
            $(".kuvauploadbtn").click(function(){

                let tid = $(this).attr("data-tid");
                if ($('#kuva_'+tid).is(":visible"))  $('#kuva_'+tid).hide();
                else   $('#kuva_'+tid).show();
              
            });

            //showselite
            $(".showselite").click(function(){

                let tid = $(this).attr("data-tid");
                $('#selite_'+tid).show();
                $('#selite_'+tid).focus();
                $('#selitelink_'+tid).hide();
              
            });


            $(".selitetext").on('keyup paste', function(){

                let tid = $(this).attr("data-tid");

                var Characters = $(this).val().replace(/(<([^>]+)>)/ig,"").length; // '$' is missing from the selector
    
                if (Characters >= 5) {
                    document.getElementById("sendpic_"+tid).disabled = false;
                }
                else
                {
                    document.getElementById("sendpic_"+tid).disabled = true;
                }
    
            });

            //selitebtn
            $(".selitebtn").click(function(){
                console.log("Selitebtn clicked");
                let tid = $(this).attr("data-tid");
                console.log("Tid: "+tid);
                if ($('#selite_'+tid).is(":visible"))  $('#selite_'+tid).hide();
                else   $('#selite_'+tid).show();
              
            });

            $('.sendpic').click(function(){
                let tid = $(this).attr("data-tid");
                let entrynro = $(this).attr("data-entrynro");
                let tran = $(this).attr("data-trans");
                let selite = $("#seliteteksti_"+tid).val();

                let kuitti1 = '';
                let kuitti2 = '';
                let kuitti3 = '';
                let kuitti4 = '';
                
                for(let i = 1; i <= 4; i++)
                {
                    let kuitti = $("#kuitti_"+i+"_"+tid).val();
                 //   console.log("Kuitti "+i+" :"+kuitti);
                    if (kuitti) {
                        if (i == 1) kuitti1 = kuitti;
                        if (i == 2) kuitti2 = kuitti;
                        if (i == 3) kuitti3 = kuitti;
                        if (i == 4) kuitti4 = kuitti;
                    }
                }
                
               

                //uploadfile_1_112

                //console.log("Send pic clicked: "+tid+" "+tran+" "+selite);
                if (document.getElementById("uploadfile_1_"+tid))
                {
                    console.log("Uploaded files: "+document.getElementById("uploadfile_1_"+tid).files.length);

                }
                var file1 = '';
                var file2 = '';
                var file3 = '';
                var file4 = '';

                if (document.getElementById("uploadfile_1_"+tid) && document.getElementById("uploadfile_1_"+tid).files[0]) file1 = document.getElementById("uploadfile_1_"+tid).files[0];
                if (document.getElementById("uploadfile_2_"+tid) && document.getElementById("uploadfile_2_"+tid).files[0]) file2 = document.getElementById("uploadfile_2_"+tid).files[0];
                if (document.getElementById("uploadfile_3_"+tid) && document.getElementById("uploadfile_3_"+tid).files[0]) file3 = document.getElementById("uploadfile_3_"+tid).files[0];
                if (document.getElementById("uploadfile_4_"+tid) && document.getElementById("uploadfile_4_"+tid).files[0]) file4 = document.getElementById("uploadfile_4_"+tid).files[0];

                if (file1 && file1.name) console.log("File1: "+file1.name);
                if (file2 && file2.name) console.log("File2: "+file2.name);
                if (file3 && file3.name) console.log("File3: "+file3.name);
                if (file4 && file4.name) console.log("File4: "+file4.name);

                //Kuvapankki files

                

                var formdata = new FormData();
                if (file1) formdata.append("file1", file1);
                if (file2) formdata.append("file2", file2);
                if (file3) formdata.append("file3", file3);
                if (file4) formdata.append("file4", file4);

                formdata.append("tid", tid);
                formdata.append("tran", tran);
                formdata.append("selite", selite);
                formdata.append("entrynro", entrynro);
                formdata.append("kuitti1", kuitti1);
                formdata.append("kuitti2", kuitti2);
                formdata.append("kuitti3", kuitti3);
                formdata.append("kuitti4", kuitti4);

                // Log all form data
                for (var pair of formdata.entries()) {
                  //  console.log(pair[0] + ': ' + pair[1]);
                }

                var xhr = new XMLHttpRequest();
                xhr.open("POST", "eventimage.php", true);
                xhr.send(formdata);
                xhr.onload = function() {
                    if (xhr.status == 200) {
                       // console.log("Got response");
                        //console.log(xhr.responseText);
                        document.getElementById("sendpic_"+tid).disabled = true;

                        if (document.getElementById("uploadfile_1_"+tid)) document.getElementById("uploadfile_1_"+tid).disabled = true;
                        if (document.getElementById("uploadfile_2_"+tid)) document.getElementById("uploadfile_2_"+tid).disabled = true;
                        if (document.getElementById("uploadfile_3_"+tid)) document.getElementById("uploadfile_3_"+tid).disabled = true;
                        if (document.getElementById("uploadfile_4_"+tid)) document.getElementById("uploadfile_4_"+tid).disabled = true;
                        // kuittisended_
                        document.getElementById("kuittisended_"+tid).style.display = "block";
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    }
                    else {
                        console.log("Error: "+xhr.status);
                    }
                }

            });

            //formFileMultiple
            $(".formFileMultiple").change(function(){
                //console.log("Jep...");
                //console.log($(this).prop('files'));
                var files = $(this).prop('files');
                console.log("F:"+files);
                var names = $.map(files, function(val) { return val.name; });
                //console.log(names);
                //Loop names array and append to filelist

                let image_count = files.length;

                console.log("Image count 1: "+image_count);

                if (image_count > 3) {
                    image_count = 3;
                }
                else{
                    image_count = files.length;
                }

               // console.log("Image count 2: "+image_count);

                for(var i=0; i < image_count; i++){
                    let ix = i+1;
                    $('#kuva'+ix).empty();


                    console.log(names[i]);
                    let img = document.createElement("img");
                    //img.src = URL.createObjectURL(files[i]);

                    let src = URL.createObjectURL(files[i]);


                   // console.log("SRC: "+src);

                    if (names[i].includes(".pdf")) {
                        img.src = "./img/pdf-upload.png";
                    }
                    else {
                        img.src = src;
                    }

                    img.width = 100;
                    img.height = 150;
                    img.property = "margin: 10px; background-size: cover;";
                    //img.src = files[i];
                    
    
                    $('#kuva'+ix).append(img);
                    $('#trash_'+ix).show();

                    $('#trash_'+ix).click(function(){
                        console.log("Trash clicked");
                        $('#kuva'+ix).empty();
                        $('#kuva'+ix).text(" Kuittikuva tai pdf-tiedosto.");
                        $('#formFileMultiple').val('');
                        $('#trash_'+ix).hide();

                    });
                

                }
                

            });

            
            $('form #companyselect').on('change', function (e) {
                let puid = $('form #companyselect').val();
                console.log("Company selected: "+puid);
    
                $.ajax({
                    url: 'acc-set-company.php',
                    type: 'post',
                    data: {puid: puid},
                    success: function(response){
                        console.log("R:"+response);
                        if (response === 'true')
                        {
                            location.reload();
                        }
                        else
                        {
                            console.log("Login failed");
                        }
                    }
                });
    
            });
    

        });



$(document).ready(function() {
    var $draggables = $(".draggable");
    var totalDivs = $draggables.length;
    var currentVisibleIndex = 1; // Start with the second div (index 1)
    var  addButton = '';

    // Drag and drop functionality
    $draggables.on("dragstart", function() {
        $(this).addClass("dragging");
    });

    $draggables.on("dragend", function() {
        $(this).removeClass("dragging");
    });

    $(".billhandle").on("dragover", function(e) {
        e.preventDefault();
        var $afterElement = getDragAfterElement($(this), e.clientX);
        var $dragging = $(".dragging");

        if (!$afterElement.length) {
            $(this).append($dragging);
        } else {
            $afterElement.before($dragging);
        }
    });

    function getDragAfterElement($container, x) {
        var $draggableElements = $container.find(".draggable").not(".dragging");

        return $draggableElements.toArray().reduce(function(closest, child) {
            var box = child.getBoundingClientRect();
            var offset = x - box.left - box.width / 2;

            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: $(child) };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element || $();
    }

    // Show hidden elements one by one when "+" button is clicked
    $(".addButton").on("click", function() {

        let tid = $(this).data('tid');
        let id = $(this).attr('id');

        addButton = $('#'+id);
        let container = $('#container_'+tid);   

        //Reset draggables
       // console.log("Reset draggables: ");
        $draggables = $('#container_'+tid+' .draggable');
        totalDivs = $draggables.length;

        //recountDivs();
         
      //  console.log("Current visible index: " + currentVisibleIndex);
      //  console.log("Current totalDivs: " + totalDivs);

        if (currentVisibleIndex < totalDivs) {
          // console.log("Testing Add ");

            //Loop through the divs and show the next hidden div
            for (var i = 0; i < totalDivs; i++) {
                if ( $($draggables[i]).is(":hidden") ) {
                    $($draggables[i]).show();
                    currentVisibleIndex++;
                    console.log("Added one: " + currentVisibleIndex);
                    break;
                }
            }

        }

        // Hide the "+" button once all divs except the first are visible
        if (currentVisibleIndex === totalDivs) {
            $(this).hide();
        }

        recountDivs(tid);
    });

    // Hide element functionality, but not the first element
    $(".hide-button").on("click", function(e) { 
        e.preventDefault();
        e.stopPropagation(); // Prevent triggering drag event
        let selector = $(this).attr('id');
        let tid = $(this).data('tid');
        let nro = $(this).data('nro');

        //console.log("Hide button clicked: " + selector);
        var $this = $('#'+selector);

        let parentDiv = $('#kuitti_'+nro+'_'+tid);
        //console.log("Parent div: " + '#kuitti_'+nro+'_'+tid);
        parentDiv.hide();
        currentVisibleIndex--;

        //console.log("Current visible index: " + currentVisibleIndex);
        //console.log("Current parentDiv: " + parentDiv.attr('id'));

        // Show the "+" button again if it's hidden
        if (currentVisibleIndex < totalDivs) {
            $('#addButton_'+tid).show();
        } 
        //Lets clear the input of the element
        let card = parentDiv.find('.card-body:first');
        card.css('background-image', 'none');


            //Buttons
            let buttons = card.children('button');
            for (let i = 0; i < buttons.length; i++) {
                $(buttons[i]).addClass('btn-outline-primary');
                $(buttons[i]).removeClass('btn-success');
            }

            let inputFile = parentDiv.find('input:first');
            inputFile.val('');
            let kuittiInput = parentDiv.find('input:last');
            kuittiInput.val('');



        recountDivs(tid);

        setSendStatus(tid);

    });

    // Generate function that wuíll recount the total number of divs and counts the currentVisbleIndex
    function recountDivs(tid) {

        $draggables = $('#container_'+tid+' .draggable');

        totalDivs = $draggables.length;
        currentVisibleIndex = 1;

        $draggables.each(function(index) {
            if (index > 0 && $(this).is(":visible")) {
               // $draggables[currentVisibleIndex].textContent = "Div " + (currentVisibleIndex + 1);
                currentVisibleIndex++;
            }
        });

        if (currentVisibleIndex === totalDivs) {
            addButton.hide();
        } else {
            addButton.show();
        }

       // console.log("Recount visible index: " + currentVisibleIndex);
       // console.log("Recount totalDivs: " + totalDivs);
    }

    $('.uploadfile').on("click", function(e) { 
        e.stopPropagation(); // Prevent triggering drag event
        var tid = $(this).data('tid');
        var nro = $(this).data('nro');

       // console.log("Upload file for nro: " + nro + " tid: " + tid);

        let uploadElement = $('#uploadfile_' + nro + '_' + tid);
        uploadElement.click();

    });
    

    //$('.kuittiholder').on("change", function(e) {
    function kuittiHolderChange() {
       
      //  console.log("Kuitti holder changed");
        let tid = $(this).data('tid');
        //var nro = $(this).data('nro');
        setSendStatus(tid);
    }
    

    $('.uploadinput').on("change", function(e) {
      //  console.log("File changed"); 

        var file = e.target.files[0];
        var fileType = file.type;
        let pdf = false;
        if (fileType === 'application/pdf') {
            // File is a PDF
           // console.log('File is a PDF');
            pdf = true;
        } 

        var tid = $(this).data('tid');
        var nro = $(this).data('nro');
        let name = '#card_' + nro + '_' + tid;
        let card = null;

        if (file) {
            console.log("Step 1"); 

            var reader = new FileReader();
            reader.onload = function(e) {
              //  console.log("Step 2 : " + e.target.result); 

              //  console.log("Name: " + name);
                card = $('#card_' + nro + '_' + tid);
                let kuva = e.target.result;
                if (pdf) {
                    kuva = './img/pdf-upload.png';
                }

                card.css('background-image', 'url("' + kuva + '")');
                card.css('background-size', 'cover');
                card.css('background-position', 'center');
                card.css('background-repeat', 'no-repeat');

                //Buttons
                let buttons = card.children('button');
                for (let i = 0; i < buttons.length; i++) {
                    $(buttons[i]).removeClass('btn-outline-primary');
                    $(buttons[i]).addClass('btn-success');
                }

                $('#kuitti_' + nro + '_' + tid).val();

            };
           // console.log("Step 3"); 

            reader.readAsDataURL(file);
           // console.log("Step 4"); 
            setButtons(card);
        }

        setSendStatus(tid);
    });

    function setSendStatus(tid)
    {
            sendButton = '';
            enableSendButton = false;

            if ($('#sendpic_'+tid)) {
                sendButton = $('#sendpic_'+tid);
                //Test for content
                for (let i = 1; i <= 4; i++) {
                    let fileInput = $('#uploadfile_'+i+'_'+tid);
                    if (fileInput && fileInput.val()) {
                    //    console.log("File input: " + '#uploadfile_'+i+'_'+tid +  " val: "+fileInput.val());
                        enableSendButton = true;
                    }

                    let fileHolder = $('#kuitti_'+i+'_'+tid);

                  //  console.log("File holder: " + '#kuitti_'+i+'_'+tid +  " val: "+fileHolder.val());

                    if (fileHolder && fileHolder.val()) {
                     //   console.log("File holder: " + '#kuitti_'+i+'_'+tid +  " val: "+fileInput.val());

                        enableSendButton = true;
                    }
                }

                if (enableSendButton) {
                    sendButton.prop('disabled', false);
                }
                else {
                    sendButton.prop('disabled', true);
                }


            }

    }

    function setButtons(card)
    {
        //Buttons
        if (!card) {
            return;
        }
        let buttons = card.children('button');
        for (let i = 0; i < buttons.length; i++) {
            $(buttons[i]).addClass('btn-outline-primary');
            $(buttons[i]).removeClass('btn-success');
        }
    }

    $('.setkuitti').on("click", function(e) { 
        e.stopPropagation(); // Prevent triggering drag event
        var tid = $(this).data('tid');
        var nro = $(this).data('nro');
        var kuittiid = $(this).data('kuittiid');
        var card = $(this).data('card');
        var amount = $(this).data('amount');


      //  console.log("Set kuitti for nro: " + nro + " tid: " + tid + " kuittiid: " + kuittiid + " card: " + card + " amount: " + amount);
        $('#tid-to-set').val(tid);
        $('#nro-to-set').val(nro);
        $('#kuittiid-to-set').val(kuittiid);
        $('#card-to-set').val(card);    
        $('#amount-to-set').val(amount);    
        $('#amount-to-set').change();


    });

    $('#actionSheetDefaultInset').on('show.bs.modal', function () {
        console.log('Modal has been opened');
       

    });



    $('#actionSheetDefaultInset').on('hidden.bs.modal', function () {
        console.log('Modal has been closed');
    });


});

