$(document).ready(function () {
    //    $(".tbody").on("blur", '.rate', autoAddRows);
    $("body").on('keyup change blur', '.adult, .child, .infant, .semiinf, .totpax', Calculat);
    $("body").on('click', '.challanupload1', uploadImgBox);
    //        $("body").on('change', '.status', getModal);
    $("body").on('change', '.status', GetReason);
    //    $("body").on('click', '.exceltest', test);
    $("body").on("click", ".snapShot", takeSnapshot);
    $("body").on("focus blur keyup", ".givename, .lastname, .passport", validatePass);
    $("body").on("keyup blur change focus", '.status', disableInwNo);
    $("body").on("keyup blur change focus", '.passcopy', getModal);
    $("tbody").on("click", '.passUploader', passUploader);

    function getModal() {
        var vouchno = $("#vouchno").val();
        var passcopy = $(".passcopy").val();
        if (passcopy == 2) {
//            $.post('get_reason.php', {vouchno: vouchno}, function (data) {
//                if (data != '') {
//                    $(".cancresn").html(data)
//                    $(".cancresn").focus();
//                }
//            });
            $("#myModal").modal("show");
            $("#tr1").hide();
            $("#tr2").show();
        }
    }

    function disableInwNo() {
        var partstats = $('.status').val();
        if (partstats == 3) {
            $(".passcopy").removeAttr("disabled");
        }
        else {
            $(".passcopy").attr("disabled", true);
        }
    }

    var partst = $('.status').val();
    if (partst == 4) {
        $(".passorig").removeAttr("disabled");
        $(".passUploader").removeAttr("disabled");
    } else {
        $(".passorig").attr("disabled", "true");
        $(".passUploader").attr("disabled", "true");
//        $(".passcopy").attr("disabled", true);
    }

    var partst1 = $('.status').val();

    if (partst1 == 3) {
        $(".passcopy").removeAttr("disabled");
    }
    else {
        $(".passcopy").attr("disabled", true);
    }


//    $(".passcopy").attr("disabled", "true");

//    $(".passorig").attr("disabled", "true");
    function validatePass() {
        var tr = $(this).closest("tr"),
                passno = tr.find(".passport").val(),
                givename = tr.find(".givename").val(),
                lastname = tr.find(".lastname").val();

        if (passno != "" && givename != "" && lastname != "") {
            tr.find(".passUploader").removeAttr("disabled");
            tr.find(".passorig").removeAttr("disabled");
        }

    }
    loadValidate();
    function loadValidate() {
        $(".passport").each(function () {

            var passno = $(".passport").val(),
                    givename = $(".givename").val(),
                    lastname = $(".lastname").val();

            if (passno != "" && givename != "" && lastname != "") {
                $(".passUploader").removeAttr("disabled");
                $(".passorig").removeAttr("disabled");
            }
        });
    }


    // ####################### Passport Upload Part (START)####################### //

    $(".snapShot").attr("disabled", "true");
    $(".snapUpload").attr("disabled", "true");

    $(".snapType").change(function () {
        var snapType = $(".snapType").val();
        if (snapType != "0") {
            $(".snapShot").removeAttr("disabled");
            $(".snapUpload").removeAttr("disabled");
        } else {
            $(".snapShot").attr("disabled", "true");
            $(".snapUpload").attr("disabled", "true");
        }
    });

    Webcam.set({
        width: 500,
        height: 500,
        image_format: 'jpeg',
        jpeg_quality: 90
    });
    Webcam.attach('#my_camera');


    function takeSnapshot() {
        // take snapshot and get image data
        Webcam.snap(function (data_uri) {
            // display results in page
            document.getElementById('results').innerHTML =
                    '<img id="mySnap"  src="' + data_uri + '"/>';
//            Webcam.upload( data_uri, "upload.php", function(code, text) {
//             $("#status").html(text);
//         });
        });
    }

    function passUploader() {
        var tr = $(this).closest("tr"),
                givename = tr.find(".givename").val(),
                lastname = tr.find(".lastname").val(),
                passport = tr.find(".passport").val(),
                vouchno = $("#vouchno").val();

        $("#snapVouch").val(vouchno);
        $("#snapGive").val(givename);
        $("#snapLast").val(lastname);
        $("#snapPass").val(passport);

        getImage();

    }

    $(".snapUpload").click(function () {
        ImgUpload();
    });
    function ImgUpload() {
        var mySnap = $("#mySnap").attr('src'),
                snapVouch = $("#snapVouch").val(),
                snapLast = $("#snapLast").val(),
                snapGive = $("#snapGive").val(),
                snapPass = $("#snapPass").val(),
                snapType = $("#snapType").val(),
                url = "passUpload.php?snapVouch=" + snapVouch + "&snapGive=" + snapGive + "&snapLast=" + snapLast + "&snapPass=" + snapPass + "&snapType=" + snapType;

        Webcam.upload(mySnap, url, function (code, text) {
            $("#mstatus").html(text);

            getImage();
        });
    }

    function getImage() {
        var snapVouch = $("#snapVouch").val(),
                snapGive = $("#snapPax").val(),
                snapLast = $("#snapLast").val(),
                snapPass = $("#snapPass").val(),
                snapType = $("#snapType").val(),
                sData = {snapVouch: snapVouch, snapPass: snapPass},
        src = "";

        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: "getPassImage.php",
            data: sData,
            success: function (response) {
                $.each(response, function () {
                    src += "<div class='col-lg-3 col-sm-3 pad'><img src='" + this.src + "' style='width:300px;height:300px;'></div>";
                });
                $(".snapImages").html("");
                $(".snapImages").html(src);
            },
            error: function (request, textStatus, errorThrown) {

            }
        });
    }
    // ####################### Passport Upload Part(END) ####################### //



    function GetReason() {
        var vouchno = $("#vouchno").val();
        var status = $("#status").val();
        if (status == "5") {
            $.post('get_reason.php', {vouchno: vouchno}, function (data) {
                if (data != '') {
                    $(".cancresn").html(data)
                    $(".cancresn").focus();
                }
            });
            $("#myModal").modal("show");
            $("#tr1").show();
            $("#tr2").hide();
        }
    }



    function Calculat() {
        var madult = parseFloat($(".adult").val());
        var mchild = parseFloat($(".child").val());
        var minfant = parseFloat($(".infant").val());
        var msemiinf = parseFloat($(".semiinf").val());
        var mtotpax = parseFloat($(".totpax").val());
        mtotpax = madult + mchild + minfant + msemiinf;
        //        $(".totpax").val(mtotpax);

        if (isNaN(mtotpax)) {
            $(".totpax").val("0");
            ;
        } else {
            $(".totpax").val(mtotpax);
            /*$row.find('.final').val(fintot.toFixed(2));-*/
        }

    }

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

        $.post('visa_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('#data');
            ctr++;
            $('#items').val(ctr);
            $(".dis_" + ctr).attr("disabled", "true");
        });
    }

    $('#addnew').click(function () {
        addrows();
    });
//        var currentEle = '';
    function uploadImgBox() {
        var $row = $(this).closest("tr");
        var vouchno = $("#vouchno").val();
        var passno = $row.find('#passport').val();


        ShowUpload('upload');
        $('#evouchno').val(vouchno);
        $('#epassno').val(passno);
        setTimeout(function () {
            GetImage();
        }, 2000);
//            });
        $(".challanview").click(function () {
            ShowUpload('view');
        });
        function ShowUpload(para) {
            $('#formModal').modal('show');
            if (para == 'upload') {
                $("#formModal").find(".upload").show();
                $("#formModal").find(".mview").hide();
            } else {
                GetImage();
                ShowView();
            }
        }
        function ShowView() {
            $("#formModal").find(".mview").show();
            $("#formModal").find(".upload").hide();
        }
        function GetImage() {
            var $row = $(this).closest("tr");
//            var vouchno = $row.find("#vouchno").val();
//            var passno = $row.find("#passno").val();
            var vouchno = $("#vouchno").val();
            var passno = $('#epassno').val();
//            $('#epassno').focus();
            $.post('challan_imgpath.php', {evouchno: vouchno, epassno: passno}, function (data) {
                $("#mpreview").attr("src", data);
                $("#preview").attr("src", data);
//                $(".print_image").attr("href", "print_chal_img.php?path=" + data);
                readIMG(this);
            });
        }

        function _(el) {
            return document.getElementById(el);
        }
        $("#uploadbtn").click(function () {
            ChallanImgUpload();
        });
        function ChallanImgUpload() {
            var file = _("file1").files[0];
//            var $row = $(this).closest("tr");
            var epassno = _("epassno").value;
            var evouchno = _("vouchno").value;
//        alert(file.name+" | "+file.size+" | "+file.type);
            var formdata = new FormData();
            formdata.append("file1", file);
            formdata.append("evouchno", evouchno);
            formdata.append("epassno", epassno);
            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", "challan_upd_img.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]);
            }
        }


        $("#formModal").find("#file1").change(function () {
            readIMG(this);
        });
        $('#formModal').off("shown.bs.modal").on("shown.bs.modal", function () {
            $("#status").css({'background-image': 'none'});
        });
    }
});