$(document).ready(function () {
    $('body').on('focus blur', ' .totrate1, .totamt2, .totrate3', calArtAmt);
    $('body').on('keyup blur', ' .meterqty', calqty);
    $('body').on('keyup blur', ' .meterrate', calrate);
    $('body').on('keyup blur', ' .qty2', calQty2);
    $('body').on('keyup blur', ' .rate2, .amount2', caltotatm2);
    $('body').on('keyup focus change', '.ordqty, .qty, .pairs', calAmt);
    $('body').on('keyup blur', ' .ratep', calRate3);
    $('body').on('keyup change', ' .subprocess', getProcess);
    $('body').on('click', ' .arImage', changeArticle);
    $("body").on('click', '.poprin', GetSuppModal);
    $("body").on('change', '.addflag', butn);
    $("body").on("click", '.remove', remove);
    $("body").on("blur", '.aadhar, .pancard', chkDupAadhar);

    
    function chkDupAadhar() {
        var aadhar = $(".aadhar").val(),
                pancard = $(".pancard").val(),
                accode = $(".accode").val();
        if (aadhar != "") {
            $.get('chkDupAadhar.php', {aadhar: aadhar, accode: accode}, function (data) {
                if (data != "") {
                    alert("Aadhar No. Already Exist on Employee Code : " + data);
                    $(".aadhar").val("");
                    $(".aadhar").focus();
                }
            });
        }
        
        if (pancard != "") {
            $.get('chkDupAadhar.php', {pancard: pancard, accode: accode}, function (data) {
                if (data != "") {
                    alert("Pan Card No. Already Exist on Employee Code : " + data);
                    $(".pancard").val("");
                    $(".pancard").focus();
                }
            });
        }
    }

    $("body").on("keyup change blur", ".basic, .da, .hra, .ta, .oa", calSalary);

    function calSalary() {
        var tot = $(".total").val(),
                basic = $(".basic").val(),
                da = $(".da").val(),
                hra = $(".hra").val(),
                ca = $(".ca").val(),
                ma = $(".ma").val(),
                oa = $(".oa").val();
        if (basic != 0) {
            basic = basic;
        } else {
            basic = 0;
        }
        if (da != 0) {
            da = da;
        } else {
            da = 0;
        }
        if (hra != 0) {
            hra = hra;
        } else {
            hra = 0;
        }
        if (ca != 0) {
            ca = ca;
        } else {
            ca = 0;
        }
        if (ma != 0) {
            ma = ma;
        } else {
            ma = 0;
        }
        if (oa != 0) {
            oa = oa;
        } else {
            oa = 0;
        }

        tot = parseFloat(basic) + parseFloat(da) + parseFloat(hra) + parseFloat(ca) + parseFloat(ma) + parseFloat(oa);

        $(".total").val(tot);
    }


    $('#chkact').change(function () {
        var flag = 0;
        if ($(this).attr("checked") == true) {
            flag = 'A';
            $.post('getkari_act.php', {flag: flag}, function (data) {
                $(".act").empty();
                $(".act").html(data);
            });
        } else {
            flag = 'N';
            $.post('getkari_act.php', {flag: flag}, function (data) {
                $(".act").empty();
                $(".act").html(data);
            });
        }
    });

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

    $("#del_all").attr("checked", true);
    show_hide_delete();
    $("#del_all").click(function () {
        show_hide_delete();
    });

    function show_hide_delete() {
        if ($("#del_all").prop("checked")) {
            $(".remove").hide();
        } else {
            $(".remove").show();
        }

    }

    butn();

    function butn() {
        var addflag = $('.addflag').val();
        if (addflag == 1) {
            $('.poprin').prop('disabled', true);
        } else {
            $('.poprin').attr('disabled', false);
        }
    }

    function GetSuppModal() {
        $('#suppModal').modal('show');
    }




    function getProcess() {
        var $row = $(this).closest("tr"),
                subproc = $row.find(".subprocess").val();

        $.post('get_process.php', {subproc: subproc}, function (data) {

            $row.find(".process").html(data);
        });
    }
    function calArtAmt() {
        var a = $('.totrate1').val();
        var b = $('.totamt2').val();
        var c = $('.totrate3').val();
        var d = parseInt(a) + parseInt(b) + parseInt(c);
        $('.totarti').val(d);
    }


    function calAmt() {
        var $row = $(this).closest("tr"),
//        var qty = $row.find('.qty2').val();
//        var rate = $row.find('.rate2').val();
                pairs = $row.find('.pairs').val(),
                mqty = $('.qty').val(),
//        var amount = qty * rate;
                ordqty = mqty / pairs;
//        $row.find('.amount2').val(amount);
        $row.find('.ordqty').val(ordqty.toFixed(2));
    }


    function calQty2() {
        var mtotqty = 0;
        $(".qty2").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                mtotqty += parseFloat(this.value);
            }
        });
        $("#totqty2").val(mtotqty);

    }

    function caltotatm2() {
        var mtotamt = 0;
        $(".amount2").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                mtotamt += parseFloat(this.value);
            }
        });
        $("#totamt2").val(mtotamt);
    }

    function calRate3() {
        var mtotrate = 0;
        $(".ratep").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                mtotrate += parseFloat(this.value);
            }
        });
        $("#totrate3").val(mtotrate);

    }


    function calqty() {
        var $row = $(this).closest("tr");
        var mqty = $row.find('.meterqty').val();

        if (mqty > 0) {
            var cqty = 39.37 / mqty;
            var sqty = cqty / 39.37;
            $row.find('.sqty').val(sqty.toFixed(4));
        }
        calculateTot();
    }
    function calrate() {
        var $row = $(this).closest("tr");
        var mqty = $row.find('.meterqty').val();
        var mrate = $row.find('.meterrate').val();

        if (mrate > 0) {
            var crate = mrate / mqty;
            $row.find('.srate').val(crate.toFixed(4));
        }
        calculaterate();
    }


    function addrows() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }

        $.post('article_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('#data');
            ctr++;
            $('#items').val(ctr);
        });
    }

    function addrows2() {
        var ctr2 = $('#items2').val();
        var hide_check = "";
        if ($("#del_all2").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }

        $.post('article2_add.php', {ctr2: ctr2, hide: hide_check}, function (data2) {
            $(data2).appendTo('#data2');
            ctr2++;
            $('#items2').val(ctr2);
        });
    }


    function addrows3() {
        var ctr3 = $('#items3').val();
        var hide_check = "";
        if ($("#del_all3").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }

        $.post('article3_add.php', {ctr3: ctr3, hide: hide_check}, function (data3) {
            $(data3).appendTo('#data3');
            ctr3++;
            $('#items3').val(ctr3);
        });
    }

    $('#addnew').click(function () {
        addrows();
    });
    $('#addnew2').click(function () {
        addrows2();
    });
    $('#addnew3').click(function () {
        addrows3();
    });

    function calculateTot() {
        var qty = 0;
        var val = 0;

        /*********Total Part************/

        $(".sqty").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val += parseFloat(this.value);
            }
        });
        qty = parseFloat(val);

        $("#totqty1").val(qty);
        calculat();
    }
    function calculaterate() {
        var rate = 0;
        var val = 0;

        /*********Total Part************/

        $(".srate").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val += parseFloat(this.value);
            }
        });
        rate = parseFloat(val);

        $("#totrate1").val(rate);
        calculat();
    }




    /////////////////////////////////Image Upload - Start/////////////////////////////////

    function _(el) {
        return document.getElementById(el);
    }
    $("#uploadbtn").click(function () {
        imageUpload();
    });
    function imageUpload() {
        var file = _("file1").files[0];
        var code = _("code").value;
        var imageno = _("imageno").value;
//        alert(file.name+" | "+file.size+" | "+file.type);
        var formdata = new FormData();
        formdata.append("file1", file);
        formdata.append("code", code);
        formdata.append("imageno", imageno);
        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;
//        setTimeout(function(){ GetImage(); },3000);
    }

    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);
    });

    showArticle();

    function showArticle() {
        var code = $(".code").val(),
                values = "";
        $.post("get_image.php", {code: code}, function (data) {
            var m = jQuery.parseJSON(data);
            $.each(m, function () {
                values += "<div class=' myImageDiv pad' >" +
                        "<label class='label-control'>Image" + this.imageno + "</label> <br>" +
                        "<img style='width:250px;height:250px;' src='" + this.imagepath + "' class='img-responsive arImage' rel='" + this.imageno + "'>" +
                        "</div>";
            });
            $(".showImages").empty();
            $(".showImages").html(values);
        });
    }

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

    $("#imageUpload").on("hidden.bs.modal", function () {
        showArticle();
    });

    function changeArticle() {
        $("#imageUpload").modal("show");
        var imageno = $(this).attr("rel"),
                image = $(this).attr("src");

        $("#imageUpload #imageno").select2().val(imageno).trigger("change");
        $("#imageUpload #imageno").prop("disabled", true);
        $("#preview").attr("src", image);
        readIMG(this);
    }

    /////////////////////////////////Image Upload - End  /////////////////////////////////

    function readIMGK(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]);
        }
    }

    $("#file3").change(function () {
        readIMGK(this);
    });
});