$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
//    $(".tbody").on("blur", '.rate', autoAddRows);
    $("body").on("keyup focus blur", '.qty, .rate', itemCal);

    $("body").on("blur", '.mobile', checkMob);
    $("body").on("blur", '.trmobile', checkMobTr);
    $("body").on("blur", '.aadhaar', checkaadhar);
    $("body").on("change", '.expired', changecolr);
    $("body").on("change", '.occupation', showbsdetail);
    $("body").on("change", '.profession', showprofession);
    $("body").on("change", '.phydisabled', showdisabled);
    $("body").on("keyup focus blur", '.qty, .rate, .amount, .subtotal .discount, .discperc, .netamt', mainbCal);
    $("body").on("keyup focus blur", '.remark', autoAddRows);
    $("body").on("click", '.familyid', getMaxFamCode);
    $("body").on("click", '#familyid', checkRequired);
    $("body").on("keyup", '.dob', getAge);
    $("tbody").on("keyup", '.trdob', getAgetr);
    $("body").on("change", ".area", getDetail);
    $("body").on("change", ".district", getDist);
    $("body").on("change", ".bsarea", getbsDetail);
    $("body").on("change", ".bsdistrict", getbsDist);

    //   $("body").on("change", '.brand', filterItem);

    var para = $(".para").val();
    if (para == "M") {
        $("#hadd").hide();
    }
    if (para == "C") {
        $("#hadd").hide();
        $("#hdelete").hide();
        $("#hprevious").hide();
        $("#hprint").hide();
        $("#hnext").hide();

    }

    function getbsDetail() {
        var bsarea = $(".bsarea").val();
        $.post('getstatedist.php', {bsarea: bsarea}, function (data) {
            $('.bsdistrict').html(data);

        });
    }

    function getbsDist() {
        var bsdistrict = $(".bsdistrict").val();
        $.post('getstatedist.php', {bsdistrict: bsdistrict}, function (data) {
            $('.bstaluka').html(data);

        });
    }

    function getDetail() {
        var area = $(".area").val();
        $.post('getstatedist.php', {area: area}, function (data) {
            $('.district').html(data);

        });
    }

    function getDist() {
        var district = $(".district").val();
        $.post('getstatedist.php', {district: district}, function (data) {
            $('.taluka').html(data);

        });
    }

    function getAge() {
        var dob = $('.dob').val();
        dob = new Date(dob);
        var today = new Date();
        var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
        $('.age').val(age + ' ');
    }
    function getAgetr() {
        var tr = $(this).closest("tr"),
                val = 0;
        var trdob = tr.find(".trdob").val();
        trdob = new Date(trdob);
        var today = new Date();
        var age = Math.floor((today - trdob) / (365.25 * 24 * 60 * 60 * 1000));
        if (age != '') {
            tr.find(".trage").val(age + ' ');
        } else {
            tr.find(".trage").val(0);

        }
    }

    function getMaxFamCode() {
        // var accode = $('.accode').val();
        // var aadhar = $('.aadhar').val();
        // if (aadhar != "") {
        //     $.ajax({
        //         type: "POST",
        //         dataType: "json",
        //         url: "check_aadhar.php",
        //         data: {accode: accode, aadhar: aadhar},
        //         success: function (response) {
        //             if (response != "") {
        //                 var name = response.name,
        //                         rowa = response.rowa;
        //                 if (rowa > 0) {
        //                     alert('Duplicate Aadhar No. Already Exist For - ' + name);
        //                     $('.aadhar').val("");
        //                 }
        //             }
        //         },
        //         error: function (request, textStatus, errorThrown) {
        //         },
        //     });
        // }
    }

    function checkaadhar() {
        var accode = $('.accode').val();
        var aadhaar = $('.aadhaar').val();
        if (aadhaar != "") {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "check_aadhar.php",
                data: {accode: accode, aadhaar: aadhaar},
                success: function (response) {
                    if (response != "") {
                        var name = response.name,
                                rowa = response.rowa;
                        if (rowa > 0) {
                            alert('Duplicate Aadhar No. Already Exist For - ' + name);
                            $('.aadhaar').val("");
                        }
                    }
                },
                error: function (request, textStatus, errorThrown) {
                },
            });
        }
    }

    function checkMob() {
        var accode = $('.accode').val();
        var mobile = $('.mobile').val();
        if (mobile != "") {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "check_mobno.php",
                data: {accode: accode, mobile: mobile},
                success: function (response) {
                    if (response != "") {
                        var name = response.name,
                                rowa = response.rowa;
                        if (rowa > 0) {
                            alert('Duplicate Mobile No. Already Exist For - ' + name);
                            $('.mobile').val("");
                        }
                    }
                },
                error: function (request, textStatus, errorThrown) {
                },
            });
        }
    }

    function checkMobTr() {
        var tr = $(this).closest("tr"),
                mmobile = $('.mobile').val(),
                mobile = tr.find('.trmobile').val(),
                accode = tr.find('.subcode').val();
        if (mobile != "") {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "check_mobno.php",
                data: {accode: accode, mobile: mobile},
                success: function (response) {
                    if (response != "") {
                        var name = response.name,
                                rowa = response.rowa;
                        if (rowa > 0) {
                            alert('Duplicate Mobile No. Already Exist For - ' + name);
                            tr.find('.trmobile').val("");
                            tr.find('.trmobile').focus();
                        }
                    }
                },
                error: function (request, textStatus, errorThrown) {
                },
            });
        }
        if (mmobile != "" && mobile != "") {
            if (mmobile == mobile) {
                alert("Same Number Already Exist for Family Head");
                tr.find('.trmobile').val("");
                tr.find('.trmobile').focus();
            }
        }

    }

//  
//    $('.expired').change(function() {
//      var expired = $('.expired').val();
//      if (expired == 'Y') {
//          $('.expiredlb').css('color','red');
//      }else{
//          $('.expiredlb').css('color','black');
//      }
//   });


    function changecolr() {
        var expired = $('.expired').val();
        if (expired == 'Y') {
            $('.expiredlb').css('color', 'red');
        } else {
            $('.expiredlb').css('color', 'black');
        }
    }

    function showbsdetail() {
        var occupation = $('.occupation').val();
        if (occupation == "Govt Service") {
            $('#occudept').css({'display': 'block'});
            $('#businessdtl').css({'display': 'none'});
        } else if (occupation == "") {
            $('#occudept').css({'display': 'none'});
            $('#businessdtl').css({'display': 'none'});
        } else if (occupation == "Business") {
            $('#businessdtl').css({'display': 'block'});
            $('#occudept').css({'display': 'none'});
        } else if (occupation != "Business") {
            $('#businessdtl').css({'display': 'none'});

        }
    }

    function showprofession() {
        var profession = $('.profession').val();
        if (profession == "Other") {
            $('#profsdtl').css({'display': 'block'});
        } else {
            $('#profsdtl').css({'display': 'none'});
        }
    }
    function showdisabled() {
        var phydisabled = $('.phydisabled').val();
        if (phydisabled == "YES") {
            $('#phydis').css({'display': 'block'});
        } else {
            $('#phydis').css({'display': 'none'});
        }
    }

    function checkRequired() {
        var check;
        check = $("#familyid").prop("checked");
        if (check) {
//         alert("Family Head Aadhaar is Manadatory.");
            $(".aadhaar").attr("required", "true");
            $(".mobile").attr("required", "true");
        }
    }


//   var check;
//   $("#familyid").on("click", function(){
//    if(check) {
////         alert("Family Head Aadhaar is Manadatory.");
//         $(".aadhaar").attr("required", "true");
//    } 
//  }); 

//    function checkaadhar() {
//        var accode = $('.accode').val();
//        var aadhar = $('.aadhar').val();
//        $.post('check_aadhar.php', {accode: accode, aadhar: aadhar}, function (data) {
//            
//            success: function (response) {
//          if (response != "") {
//            var vpassport = response.passport,
//              vcno = response.myvouch,
//              vcdt = response.vouchdt;
//            if (vcno != "") {
//              alert(
//                "This Mofa No. Exist for Passport No  " +
//                  vpassport +
//                  " on File No  " +
//                  vcno +
//                  "  dated on   " +
//                  vcdt +
//                  ""
//              );
//              $(".mofano").val("");
//            }
//          }
//        },
////                  var oldname = data.name;
////              if (data !=  '' ) {
////                    alert(oldname );
////                    alert('Duplicate Aadhar No. Already Exist For' + oldname );
////                    $('.aadhar').val('');
////                    valid = false;
////                }       
//        });
//    }

//    function filterItem(){
//        var brand = $(".brand").val();
//        $.post('get_fitem.php', {brand: brand}, function (data) {
//            $(".item").html(data);
//        });
//    }

//    function showdtl() {
//        var $row = $(this).closest("tr");
//        var name = $row.find('.item').val();
//        $.ajax({
//            type: 'GET',
//            dataType: 'json',
//            url: "show_item_dtl.php",
//            data: "name=" + name + "",
//            success: function (response) {
////                    var barcode = response.barcode;
//                var rate = response.cost;
////                    $($row.find('.barcode')).val(barcode);
//                $($row.find('.rate')).val(rate);
//
//            },
//            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('member_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }


    function itemCal() {
        var tr = $(this).closest("tr"),
                val = 0;
//        var taka = tr.find(".taka").val();
        var qty = tr.find(".qty").val();
        var rate = tr.find(".rate").val();
        var amount = qty * rate;
        tr.find(".amount").val(amount);

//        $(".amount").each(function () {
//            if (!isNaN(this.value) && this.value.length != 0) {
//                val += parseFloat(this.value);
//            }
//        });
//        var tot = parseFloat(val);
//        $('.subtotal').val(tot);
        mainbCal();
    }

    function mainbCal() {
        var tot = 0;
        var val = 0;

        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val += parseFloat(this.value);
            }
        });
        tot = parseFloat(val);
        $('.subtotal').val(tot);

        var discperc = $(".discperc").val();
        var subtotal = $(".subtotal").val();
        var totdisc = subtotal * discperc / 100;
        $(".discount").val(totdisc);


        var netamt = subtotal - totdisc;
        if (isNaN(netamt)) {
            var netamt = subtotal - totdisc;
            $(".netamt").val(netamt);
        } else {
            $(".netamt").val(netamt);
        }
    }

    $(document).keydown(function (event) {
        if (!(String.fromCharCode(event.which).toLowerCase() == 'd' && event.altKey) && !(event.which == 19))
            return true;
        $(".discperc").focus();
        event.preventDefault();
        return false;
    });


    $(".image").change(function () {
        readURL1(this);
    });



    function readURL1(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.view1').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
//    $(document).keydown(function (event) {
//        //19 for Mac Command+S
//        if (!(String.fromCharCode(event.which).toLowerCase() == 's' && event.altKey) && !(event.which == 19))
//            return true;
//        //alert("Ctrl-s pressed");
//        $("#submit").click();
//        event.preventDefault();
//        return false;
//    });
});