$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
//    $(".tbody").on("blur", '.rate', autoAddRows);
    $("body").on("keyup change blur", '.amount, .discperc, .gsttype,.tcsperc', mainbCal);
    $("body").on("focus", '.amount', autoAddRows);
    $("body").on("blur change", ".vouchdt", getvoucher);
    $("body").on("change", ".oms", editoms);
    $("body").on("change", ".gstperc, .oms", gstperc);


    function gstperc() {
        var gstp = $(".gstperc").val();
        if (gstp != '') {
            if ($(".oms").prop('checked')) {
                $(".igstrate").val(gstp)
            } else {
                var cgstp = gstp / 2;
                $(".sgstrate").val(cgstp)
                $(".cgstrate").val(cgstp)
            }
        }

    }



    $(".showUploader").click(function () {
        $("#imageUpload").modal('show');
        $("#imageno").prop("disabled", false);
    });

    function _(el) {
        return document.getElementById(el);
    }

    $("#uploadbtn").click(function () {
        imageUpload();
    });

    function imageUpload() {
        var file = _("file1").files[0];
        var vouchno = _("vouchno").value;
        var source = _("source").value;
        var formdata = new FormData();
        formdata.append("file1", file);
        formdata.append("vouchno", vouchno);
        formdata.append("source", source);
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress", progressHandler, false);
        ajax.addEventListener("load", completeHandler, false);
        ajax.addEventListener("error", errorHandler, false);
        ajax.addEventListener("abort", abortHandler, false);
        ajax.open("POST", "upload_image.php");
        ajax.send(formdata);
    }


    function progressHandler(event) {
        _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
        var percent = (event.loaded / event.total) * 100;
        _("progressBar").value = Math.round(percent);
        _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
    }

    function completeHandler(event) {
        _("status").innerHTML = event.target.responseText;
        _("progressBar").value = 0;
    }

    function errorHandler(event) {
        _("status").innerHTML = "Upload Failed";
    }

    function abortHandler(event) {
        _("status").innerHTML = "Upload Aborted";
    }

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

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

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imageUpload").find("#file1").change(function () {
        readIMG(this);
    });

    $(".showUploader").click(function () {
        $("#imageUpload").modal('show');
        $("#imageno").prop("disabled", false);
    });

    function editoms() {
        var igstamt = $('.igstamt').val(),
                cgstamt = $('.cgstamt').val();
        if ($(".oms").prop('checked')) {
            if (igstamt == 0) {
                var val = cgstamt * 2;
                $('.igstamt').val(val);
                $('.cgstamt').val(0);
                $('.sgstamt').val(0);
            }
        } else {
            if (cgstamt == 0) {
                var val2 = igstamt / 2;
                $('.cgstamt').val(val2);
                $('.sgstamt').val(val2);
                $('.igstamt').val(0);
            }
        }
        mainbCal();

    }

    function getvoucher() {
        var date = new Date($(".vouchdt").val()),
                month = (date.getMonth() + 1).toString(),
                vouchno = $('.vouchno').val(),
                voucher = '0' + month + vouchno;

        $('.monno').val(month);
        $('.voucher').val(voucher);

    }


    $('#hedit').click(function () {
        var addflag = $('.addflag').val();
        if (addflag != 1) {
            $('.oms').prop("disabled", true);
        } else {
            $('.oms').prop("disabled", false);
        }
    });


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

    $('#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('purcoth_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
//            $(detail).select2();
        });
    }

    function mainbCal() {

        var grosstot = 0,
                totbillamt = 0,
                rtotbillamt = 0,
                igst = 0,
                cgst = 0,
                gsttype = $('.gstperc').val(),
                igstrate = $('.igstrate').val(),
                cgstrate = $('.cgstrate').val();


        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                grosstot += parseFloat(this.value);
            }
        });
        var discperc = $('.discperc').val(),
                discamt = discperc * grosstot / 100,
                taxable = parseFloat(grosstot) - parseFloat(discamt);
        $(".grossamt").val(grosstot.toFixed(2));
        $(".totdiscamt").val(discamt.toFixed(2));
        $(".taxableamt").val(taxable.toFixed(2));
        if (gsttype != '') {
            if ($(".oms").prop('checked')) {
                igst = taxable * igstrate / 100;
                $('.igstamt').val(igst);
            } else {
                cgst = taxable * cgstrate / 100;
                $('.cgstamt').val(cgst);
                $('.sgstamt').val(cgst);
            }
        }


        totbillamt = parseFloat(taxable) + parseFloat(cgst) + parseFloat(cgst) +  parseFloat(igst);

        var tcsperc = $('.tcsperc').val(),
                tcsamt = parseFloat(totbillamt) * parseFloat(tcsperc) / 100,
                acttotal = parseFloat(totbillamt) + parseFloat(tcsamt);
        $('.tcsamt').val(tcsamt);
        var rtotbillamt = Math.round(acttotal);

        $('.amtbftax').val(totbillamt);
        $('.rtotbillamt').val(rtotbillamt);


//        $(".totbillamt").val(totbillamt);

    }
});