$(document).ready(function () {
    $("body").on('blur change', '.custcode , .custname', GetVessel);
    $("body").on('blur', '.custcode', GetCustomerFromCode);
    $("body").on('blur', '.ppno', GetPPNO);
    $("body").on('blur change', '.custname', GetCustomerFromName);
    $("body").on('blur change focus', '.item', getItemDetail);
    $("body").off('click').on("click", '.remove', remove);

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

    function remove() {
        $(this).closest("tr").remove();
    }
    function GetPPNO() {
        var ppno = $(".ppno").val();
        $.post('challan_Get_ppno.php', {ppno: ppno}, function (data) {
            if (ppno == data) {
                alert("Passport No. Already Exist");
            }
        });
    }

    function _(el) {
        return document.getElementById(el);
    }
    $("#uploadbtn").click(function () {
        ChallanImgUpload();
    });
    function ChallanImgUpload() {
        var file = _("file1").files[0];
        var series = _("series").value;
        var chalno = _("chalno").value;
//        alert(file.name+" | "+file.size+" | "+file.type);
        var formdata = new FormData();
        formdata.append("file1", file);
        formdata.append("chalno", chalno);
        formdata.append("series", series);
        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;
    }
    function errorHandler(event) {
        _("status").innerHTML = "Upload Failed";
    }
    function abortHandler(event) {
        _("status").innerHTML = "Upload Aborted";
    }
    $(".challanupload").click(function () {
        ShowUpload('upload');
    });
    $(".challanview").click(function () {
        ShowUpload('view');
    });
    $(".itemdtl").click(function () {
        GetTranDetail();
    });
    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 chalno = $("#chalno").val();
        var series = $("#series").val();
        $.post('challan_imgpath.php', {series: series, chalno: chalno}, function (data) {
            $("#mpreview").attr("src", data);
        });
    }
    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);
    });

    function AddRows() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        $.post('challan_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('#tabledata');
            ctr++;
            $('#items').val(ctr);
            $('.detailpart').select2();
        });
    }
//    $("#select2-vessel-e4-container").click(function () {
//        GetVessel();
//    });

    $('#addnew').click(function () {
        AddRows();
    });
    function GetVessel() {
        var custcode = $(".custname").val();
        var custname = $(".custname").val();
        $.post('challan_Get_Vess.php', {custcode: custcode, custname: custname}, function (data) {
            if (data != '') {
                $(".vessel").html(data);
                $(".vessel").focus();
            }
        });
    }
    function GetCustomerFromCode() {
        var custcode = $(".custcode").val();
        $.post('challan_Get_Cust.php', {custcode: custcode}, function (data) {
            if (data != '') {
                var $example = $(".fetchpart").select2();
                $example.val(data).trigger("change");
                $(".custname").focus();
            }
        });
    }
    function GetCustomerFromName() {
        var custcode = $(".custname").val();
        $.post('challan_Get_Cust.php', {custcode: custcode}, function (data) {
            if (data != '') {
                $(".custcode").val(data);
                $(".vessel").focus();
            }
        });
    }
    function GetTranDetail() {
        var custcode = $(".custcode").val();
        var rankcode = $(".rankcode").val();
        var ctr = $("#items").val();
        if (custcode == '') {
            alert("Customer Cannot Be Empty");
        } else {
            if (rankcode == '') {
                alert("Rank Cannot Be Empty");
            } else {
                $.post('challan_Get_TranDtl.php', {custcode: custcode, rankcode: rankcode}, function (data) {
                    $("#tabledata").html(data);
                    $(".getpart").select2();
                });
                $.post('challan_Get_TranDtl.php', {custcode2: custcode, rankcode2: rankcode, ctr: ctr}, function (data2) {
                    $("#items").val(data2.ctr);
                });
            }
        }


    }
    
    function getItemDetail(){
        var $row = $(this).closest("tr");
        var item = $row.find('.item').val();
        $.post('challan_Item_dtl.php', {item : item}, function(data){
            
        });
    }

    $(".loader").hide();
    $(".search-action-bar").hide();
    var mrangeFrom = 0,
            mrangeTo = 40,
            file;

    function getSearchData(pagination) {
        //   $(".loader").show();

        if (pagination == 'prev') {
            if (mrangeFrom > 0) {
                mrangeFrom = (mrangeFrom - 40);
                mrangeTo = (mrangeTo - 40);
            }
        }
        if (pagination == 'next') {
            mrangeFrom = (mrangeFrom + 40);
            mrangeTo = (mrangeTo + 40);
        }


        var series = $(".series").val(),
                chalno = $(".chalno").val(),
                searchTerm = $("#searchTerm").val(),
                field = $(".field").val(),
                data = {searchTerm: searchTerm, field: field, series: series, chalno: chalno, rangeFrom: mrangeFrom, rangeTo: mrangeTo},
        values = "";
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: "get_bigdata.php",
            data: data,
            success: function (response) {
                $.each(response, function () {
                    //"$file?mode=edit&$keyfld=$r[chalno]&series=$series\"
                    file = this.file + '?mode=edit&' + this.keyfld + '=' + this.chalno + '&series=' + this.series;

                    values += "<tr onClick='window.location.href="+"'" + file +"'"+ ";>" +
                            "<td align='left'>" + this.mdate + "</td>" +
                            "<td align='left'>" + this.chalno + "</td>" +
                            "<td align='left'>" + this.billno + "</td>" +
                            "<td align='left'>" + this.custcode + "</td>" +
                            "<td align='left'>" + this.custname + "</td>" +
                            "<td align='left'>" + this.vessel + "</td>" +
                            "<td align='left'>" + this.rankcode + "</td>" +
                            "<td align='left'>" + this.crew + "</td>" +
                            "<td align='left'>" + this.ppno + "</td>" +
                            "<td align='left'>" + this.cdcno + "</td>" +
                            "<td align='left'>" + this.remark + "</td>" +
                            "<td align='left'>" + this.action + "</td>" +
                            "</tr>";
                });
                $(".tbody").empty();
                $(".tbody").html(values);
                //  $(".loader").hide();
                if (response) {
                    $(".search-action-bar").show();
                }
            },
            error: function (request, textStatus, errorThrown) {

            }
        });
    }
    $(".load").click(function () {
        getSearchData();
    });
    $(".previous").click(function () {
        getSearchData('prev');
    });
    $(".next").click(function () {
        getSearchData('next');
    });

    getSearchData();


});