$(document).ready(
    function () {
        //popover on click user profile
        $('[data-toggle="popover"]').popover({
            placement: 'left',
            trigger: 'click',
            html: true
        });

        //function to get employee site visiting information in table-body
        $("#idForm").submit(function (e) {

            e.preventDefault(); // avoid to execute the actual submit of the form.

            var form = $(this);
            var url = form.attr('action');
            $.ajax({
                type: "POST",
                url: "fetchTableData.php",
                dataType: "JSON",
                data: form.serialize(), // serializes the form's elements.
                success: function (data) {
                    console.log(data);
                    $(".downloadExcel").attr("href", "../php/excel.php?" + form.serialize() + '&calimstatus=All');
                    $('#inserted_item_data').html(" "); //if data contains already, making empty
                    $("#nodata").hide(); //if already no data error came for last search, removing on new search
                    $("#myresult").css("visibility", "hidden");
                    var empName, empId, td_image, count = 0;
                    var len = data.length;
                    console.log("len= " + len);
                    if (len == "0") {

                        $(".table-scroll .sticky-column.col2").css("left", "42px");
                        $(".table-scroll .sticky-column.col3").css("left", "94px");
                        $(".table-scroll .sticky-column.col4").css("left", "150.7px");

                        $("#nodata").show();
                        $(".bottomdata").hide();
                    } else {
                        var gTotal = 0;
                        for (var i = 0; i < len; i++) {
                            var reportstatus1 = '',
                                reportstatus2 = '';
                            var date = data[i].date;
                            // checking employee selfy-image
                            if (data[i].employeeImages) {
                                var employeeImages = "http://www.principleacs.net/PACS_FieldTravelAllowance_RestApi/public/up/"+data[i].employeeImages;
                            } else {
                                //default image if not found
                                var employeeImages = "../defaultImages/noImageFound.png";
                            }

                            var claimstatus = data[i].claimstatus;
                            var userLocationAddress = data[i].userLocationAddress;
                            var userLat = data[i].userLat;
                            var userLng = data[i].userLng;
                            var siteVisitedOrder = data[i].siteVisitedOrder;
                            var reportSubmissionState = data[i].reportSubmissionState;
                            var modeOfTransport = data[i].modeOfTransport;
                            var supportingBillsAvailable = data[i].supportingBillsAvailable;
                            var from = data[i].from;
                            var to = data[i].to;
                            var distance = data[i].distance;
                            var fta = data[i].fta;
                            var remark = data[i].remark;
                            var sitelat = data[i].sitelat;
                            var siteLong = data[i].siteLong;
                            var siteID = data[i].siteID;
                            var site = data[i].site;
                            var project = data[i].project;
                            var customer = data[i].customer;
                            var totalDistance = data[i].totalDistance;
                            var deputation = data[i].deputation;
                            var daAmount = data[i].daAmount;
                            var hotel = data[i].hotel; //bills in UI
                            var total = data[i].total;
                            gTotal = gTotal + total;
                            empName = data[i].name;
                            empId = data[i].id;

                            //changing claiming status icon color
                            switch (claimstatus) {
                                case 1:
                                    claimstatus = 'fa fa-check-square text-warning sticky-column col3 ';
                                    reportstatus1 = 'Claim Pending';
                                    break;
                                case 2:
                                    claimstatus = 'fa fa-check-square text-primary sticky-column col3';
                                    reportstatus1 = 'Approved By TL';
                                    break;
                                case 3:
                                    claimstatus = 'fa fa-times text-danger sticky-column col3';
                                    reportstatus1 = '<span class="text-danger">Rejected By</span> ' + data[i].rejectedBy;
                                    reportstatus2 = '<span class="text-danger">Rejected Reason</span> ' + data[i].rejectedReason;
                                    break;
                                case 4:
                                    claimstatus = 'fa fa-check-square text-success sticky-column col3';
                                    reportstatus1 = 'Reimburse done';
                                    break;
                                default:
                                    claimstatus = 'fa fa-check-square text-dark sticky-column col3 ';
                                    reportstatus1 = 'Ready to claim';
                                    break;

                            }

                            var tr_str = "<tr class=data-content" + empId + date + " scop='row'>" +
                                "<td class='sticky-column col1'>" + (i + 1) + "</td>" +
                                "<td id=selfyimgId" + empId + i + " class='selfyimg sticky-column col2'><img src=" + employeeImages + " /></td>" +
                                "<td id=claimStatus" + empId + i + " class='sticky-column col3'><i class='" + claimstatus + "'></i></td>" +
                                "<td id=date" + empId + i + " class='sticky-column col4' >" + date + "</td>" +
                                "<td>" + userLocationAddress + "</td>" +
                                "<td>" + userLat + "</td>" +
                                "<td>" + userLng + "</td>" +
                                "<td>" + siteVisitedOrder + "</td>" +
                                "<td>" + reportSubmissionState + "</td>" +
                                "<td>" + modeOfTransport + "</td>" +
                                "<td>" + supportingBillsAvailable + "</td>" +
                                "<td>" + from + "</td>" +
                                "<td>" + to + "</td>" +
                                "<td>" + distance + "</td>" +
                                "<td>" + fta + "</td>" +
                                "<td>" + remark + "</td>" +
                                "<td>" + sitelat + "</td>" +
                                "<td>" + siteLong + "</td>" +
                                "<td>" + siteID + "</td>" +
                                "<td>" + site + "</td>" +
                                "<td>" + project + "</td>" +
                                "<td>" + customer + "</td>" +
                                "<td id=totalDistance" + empId + i + ">" + totalDistance + "</td>" +
                                "<td id=deputation" + empId + i + ">" + deputation + "</td>" +
                                "<td id=daAmount" + empId + i + ">" + daAmount + "</td>" +
                                "<td id=hotel" + empId + i + ">" + hotel + "</td>" +
                                "<td id=total" + empId + i + ">" + total + "</td>" +
                                "<td class='Buttonclosed' id=" + empId + i + " rowspan='1'><i class='fa fa-arrow-down' aria-hidden='true'></i></td>" +
                                "<td class='text-left' id=ReportStatus" + empId + i + ">" + reportstatus1 + "<br>" + reportstatus2 + "</td>" +
                                "</tr>" +
                                "<tr>" + //empty row for every table-row to store bill-image-proofs
                                "<td colspan='29' class='billtd' style='padding:0; border:0'><div id=tabledataDiv" + empId + i + " style='width: 2479px;display: flex;'></div></td>" + "</tr>";
                            $('#inserted_item_data').append(tr_str);

                            //To find duplicate date entry
                            if (i > 0) {
                                var date2 = data[i - 1].date;
                                if (date == date2) {
                                    count++;
                                    //removing row to merge cells
                                    //console.log(2*count+1);
                                    $("#selfyimgId" + empId + i).remove();
                                    $("#claimStatus" + empId + i).remove();
                                    $("#totalDistance" + empId + i).remove();
                                    $("#deputation" + empId + i).remove();
                                    $("#daAmount" + empId + i).remove();
                                    $("#hotel" + empId + i).remove();
                                    $("#total" + empId + i).remove();
                                    $("#ReportStatus" + empId + i).remove();
                                    $(".Buttonclosed#" + empId + i).remove();
                                    console.log("count=" + count + "value=" + i + "total" + (i - count));
                                    // adding rowspan to deleted cell
                                    $("#selfyimgId" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $("#claimStatus" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $("#totalDistance" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $("#deputation" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $("#daAmount" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $("#hotel" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $("#total" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $("#ReportStatus" + empId + (i - count)).attr("rowspan", 2 * count + 1);
                                    $(".Buttonclosed#" + empId + (i - count)).attr("rowspan", 2 * count + 1);

                                    //css border after merging
                                    $("#selfyimgId" + empId + (i - count)).css("border-left", "1px solid #dee2e6");
                                    $("#claimStatus" + empId + (i - count)).css("border-right", "1px solid #dee2e6");
                                    $("#totalDistance" + empId + (i - count)).css("border-left", "1px solid #dee2e6");

                                } else {
                                    count = 0;
                                }
                            }

                        }
                        $("#grandtotal").html(gTotal);
                        //table scrol to auto to sticky the Date, caliming visit-proof-> <td>
                        $(".table-scroll").css({
                            "overflow": "auto",
                            "height": "100vh"
                        });
                        $(".table-scroll .sticky-column.col2").css("left", "60.9px");
                        $(".table-scroll .sticky-column.col3").css("left", "140.9px");
                        $(".table-scroll .sticky-column.col4").css({
                            "left": "220.9px",
                            "border-right": "1px solid #e0e4e8"
                        });
                        $(".bottomdata").show();


                    }
                    //after click icon on "bill-images-proof" function
                    $(".Buttonclosed").click(function () {

                        var buttonStatus = $(this).attr("class");
                        var id = $(this).attr("id");
                        var rowspan = $(this).attr("rowspan");
                        var getClaimStatus = "All";
                        var LoggeduserDepartment = "Site-Engineer";
                        // geting rowspan for print bill-images below "formula:-increamnt=(rowspan-1)/2"

                        if (buttonStatus == "Buttonclosed") {
                            $(this).html("<i class='fa fa-arrow-up' aria-hidden='true'></i>");
                            $(this).addClass("ButtonOpen").removeClass("Buttonclosed"); //replacing closed to open btn
                            fetch_related_images(empId, id, rowspan, getClaimStatus, LoggeduserDepartment) //function call in images.js
                        } else {
                            $(this).html("<i class='fa fa-arrow-down' aria-hidden='true'></i>");

                            $(this).addClass("Buttonclosed").removeClass("ButtonOpen"); //replacing opened to close btn

                            var Calculateid = id.replace(empId, "");
                            if (rowspan != 1) {
                                var notFoundImageTableId = parseInt(Calculateid) + ((rowspan - 1) / 2);
                                $('#tabledataDiv' + empId + notFoundImageTableId).empty();
                                $('#tabledataDiv' + empId + notFoundImageTableId).css({
                                    "overflow": "inherit",
                                    "padding-  top": "0"
                                });

                                $('#tabledataDiv' + empId + notFoundImageTableId).parent().css("border-top", "0");
                            } else {
                                $('#tabledataDiv' + id).empty();
                                $('#tabledataDiv' + id).css({
                                    "overflow": "inherit",
                                    "padding-top": "0"
                                });
                                 $('#tabledataDiv' + empId + id).parent().css("border-top","0");
                            }

                            $("#myresult").css("visibility", "hidden"); // show the result div for image zoom preview
                        }

                    });


                    //on hover <tr>  background-color on same date:- will be same
                    $(".table-hover tbody tr").hover(function () {

                        var storename = $(this).attr("class");
                        $("." + storename).css("background-color", "rgba(0,0,0,.075)");
                        $("." + storename + " .sticky-column").css("background-color", "rgb(238 237 237 / 96%)");
                        // var k= $(this).find("td[rowspan]").attr("rowspan")

                    }, function () {

                        var storename = $(this).attr("class");
                        $("." + storename).css("background-color", "#fff");
                        $("." + storename + " .sticky-column").css("background-color", "#fff");

                    });
                }
            });




        });

        // for result image on zoom  display left if image in right to avoid overlap
        $(document).on('mousemove', function (e) {
            var cursorPoint = $(".container-fluid").outerWidth();

            if (e.pageX < (cursorPoint - 420)) {
                $('#myresult').css('left', 'inherit');
                $('#myresult').css('right', 0);

            } else {
                // alert();
                $('#myresult').css('left', 0);
                $('#myresult').css('right', 'inherit');
            }

        });
        //session time out

        //https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes


    });
;;