$(document).ready(function () {
    $("body").off("click").on("click", ".remove", remove);
    $(".tbody").on("blur", ".rate", autoAddRows);
    $(".tbody").on("blur keyup change", ".amount", calculations);
    $("body").on("keyup focus blur", ".remark", autoAddRows);
    $("body").on("keyup focus blur change", ".itemcode", GetItemFromCode);
    $("body").on("keyup focus blur change", ".bookno", GetMemDet);
    $("body").on("keyup focus blur change", ".item", showDetail);
    $("body").on("change blur keyup", ".calby,.trqty,.rate,.yard,.meters", calculateRow);
    $("body").on("change blur keyup focus", ".retdate", Getamount);
    $("body").on("change blur keyup focus", ".chkin, .chkout", hoursCal);
//    $("body").on("change blur keyup focus", ".advance", Maincal);
//    $("body").on("change blur keyup focus", ".extra", Maincal2);
    $("body").on("click", ".close", closemod);
    $("body").on("blur keyup focus", ".rate, .extra, .ldisc, .advance,.addoth ", Maincal);

    function Maincal() {
        var advance = parseInt($(".advance").val()),
                disc = parseInt($(".ldisc").val()),
                rate = parseInt($(".rate").val()),
                extra = parseInt($(".extra").val()),
                addoth = parseInt($(".addoth").val()),
                daysno = parseInt($(".daysno").val()),
                dayamt = parseInt(rate * daysno);


        var billamt = dayamt + extra + addoth - disc;
        var bal = billamt - advance;
        $(".amount").val(dayamt);
        $(".billamt").val(billamt);
        $('.balance').val(bal);
    }

    function closemod() {
        $(".tranmodal").hide();
    }

    function hoursCal() {
        var start = new Date($(".chkin").val()),
                end = new Date($(".chkout").val()),
                daysno = Math.round((end - start) / (1000 * 60 * 60 * 24));
        $(".daysno").val(daysno);
        Maincal();
    }

    function GetMemDet() {
        var bookno = $(".bookno").val();
        var addflg = $(".addflg").val();

        if (addflg == 1 && bookno != "") {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "getcheckout.php",
                data: {vouchno: bookno},
                success: function (response) {
                    if (response != "") {
                        var chkdt = response.chkdt,
                                name = response.name,
                                outdt = response.outdt,
                                daysno = response.daysno,
                                rate = response.rate,
                                amount = response.amount,
                                roomno = response.roomno,
                                extra = response.extra,
                                disc = response.disc,
                                advance = response.advance,
                                paytype = response.paytype,
                                billamt = response.billamt,
                                recext = response.recext,
                                r2cnt = response.r2cnt,
                                balance = response.balance;

                        if (recext > 0) {
                            alert("Record Already Exist");
                            $(".bookno").val("");
                        } else {
                            if (r2cnt > 0) {

                                $(".roomno").val(roomno);
                                $(".name").val(name);
                                $(".chkin").val(chkdt);
                                $(".chkout").val(outdt);
                                $(".daysno").val(daysno);
                                $(".billamt").val(billamt);
                                $(".rate").val(rate);
                                $(".amount").val(amount);
                                $(".extra").val(extra);
                                $(".ldisc").val(disc);
                                $(".advance").val(advance);
                                $(".balance").val(balance);
                                $(".paytype").val(paytype).trigger("change");
                            } else {
                                alert("No Record Found");
                                $(".bookno").val("");
                                $(".bookno").focus();
                            }

                        }
                    }
                },
                error: function (request, textStatus, errorThrown) {},
            });
        }
    }

    function GetItemFromCode() {
        var $row = $(this).closest("tr");
        var itemcode = $row.find(".itemcode").val();
        $.post("show_item_dtl.php", {itemcode: itemcode}, function (data) {
            if (data != "") {
                $row.find(".item").html(data).trigger("change");
            }
        });
    }

//    function Maincal() {
//        var advance = parseInt($(".advance").val()),
//                disc = parseInt($(".disc").val());
//        totamt = parseInt($(".totamt").val());
//
//        var billamt = totamt - disc - advance;
//        $(".totamt").val(billamt);
//    }
//
//    function Maincal2() {
//        var extra = parseInt($(".extra").val());
//        totamt = parseInt($(".totamt").val());
//
//        var billamt = totamt + extra;
//        $(".totamt").val(billamt);
//    }

    function Getamount() {
        var totamt = $(".totamt").val(),
                start = new Date($(".vouchdt").val()),
                end = new Date($(".retdate").val()),
                diff = new Date(end - start) / (1000 * 60 * 60 * 24);
        $(".days").val(diff);
        if (diff == "0") {
            $(".billamt").val(totamt);
        } else {
            var days = Math.round(diff);
            var getbillamt = totamt * days;
            $(".billamt").val(getbillamt);
        }
    }

    function calculateRow() {
        var $row = $(this).closest("tr");

        var calby = $row.find(".calby").val();
        // var meters = $row.find('.meters').val();
        var rate = $row.find(".rate").val();

        var meters = parseFloat($row.find(".meters").val());
        var yard = parseFloat($row.find(".yard").val());
        var trqty = parseFloat($row.find(".trqty").val());

        // var pair = packing * carton;
        // $row.find('.pair').val(pair.toFixed(2));
        var calm = parseFloat(meters),
                caly = parseFloat(yard),
                calq = parseFloat(trqty),
                amount = 0;

        // var totdoz = pair / 12;
        if (calby == "M" || meters > 0) {
            //            var m = 'meter';
            // $row.find('.calby').val(m)
            (amount = (parseFloat(calm) * parseFloat(rate)).toFixed(2)),
                    $row.find(".amount").val(amount);
        } else if (calby == "Y" || yard > 0) {
            (amount = (parseFloat(caly) * parseFloat(rate)).toFixed(2)),
                    $row.find(".amount").val(amount);
        } else {
            (amount = (parseFloat(calq) * parseFloat(rate)).toFixed(2)),
                    $row.find(".amount").val(amount);
        }

        // var amt =  $row.find('.amount').val("");
        //         if (isNaN(amt)) {
        //             $row.find('.amount').val("0");
        //         } else {
        //             $row.find('.amount').val(amt);
        //         }
        // calculateTot();
    }

    function calculations() {
        var totamt = 0;

        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.lenght !== 0) {
                totamt += parseFloat(this.value);
            }
        });
        $(".totamt").val(totamt);
    }

    //getting rate from item
    function showDetail() {
        var tr = $(this).closest("tr");
        var name = tr.find(".item").val();
        $.ajax({
            type: "GET",
            dataType: "json",
            //                url         : "get_itemrate_dtl.php",
            url: "get_itemrate_dtl.php",
            data: "name=" + name + "",
            success: function (response) {
                var code = response.code;
                var rate = response.rate;
                var msp = response.msp;
                var mrp = response.mrp;
                $(tr.find(".itemcode")).val(code);
                $(tr.find(".rate")).val(rate);
                $(tr.find(".msp")).val(msp);
                $(tr.find(".mrp")).val(mrp);
            },
            error: function (request, textStatus, errorThrown) {
                alert(errorThrown);
            },
        });
    }

    $("#addnew").click(function () {
        AddRows();
    });

    function autoAddRows() {
        var ctr = $("#items").val();
        var tr = $(this).closest("tr");
        var srno = tr.find(".srno").val();
        if (srno == ctr) {
            AddRows();
        }
    }

    function remove() {
        $(this).closest("tr").remove();
    }

    function AddRows() {
        var ctr = $("#items").val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var detail = ".fetchpart_" + ctr;
        $.post("hotel_add.php", {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo(".tbody");
            ctr++;
            $("#items").val(ctr);
            $(detail).select2();
        });
    }
});
