<script type="text/javascript">
    $(document).ready(function () {

$('#frmstockdiary').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

    });


    $(document).on('keydown', '.inputs', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        $('.inputs').removeClass('editfield');
        $(this).addClass('editfield');
        var txtindex = $('.editfield').attr("data-ind");
        var curclassname = this.className;
        var arr = curclassname.split(' ');
        if (code == 13) {
        if (arr[1] == 'itemprice') {
        newLineInsert(txtindex);
        }
        else if (arr[1] == 'itemcode') {
            var itemcode = $("#itemcode_" + txtindex).val();
        getItemFromCode(itemcode, txtindex);
        }
        
        }
        else{
        if(arr[1] == 'itemname')
        {
            var b = parseInt(txtindex);
        itemNameAutocomplete(b);
        }
    }
        
    });


    function newLineInsert(txtindex) {

        //itemNameAutocomplete(txtindex);
        var b  =	parseInt(txtindex)+1;
        var itemid = $("#itemid_" + b).val();

        if (itemid != 'undefined' || itemid != null || itemid != '') {
            var curitemid = $("#itemid_" + txtindex).val();
            if (curitemid != '') {
                var htmlcontent = incrememttablerow(b);
                $('#mainTable').append(htmlcontent);
            }
        }


    }

    function itemNameAutocomplete(index)
    {
        $("#itemname_" + index).autocomplete({
            source: "<?php echo base_url('inventory/purchaseinvoice/getproductsautocomplete/'); ?>",
            minLength: 1,
            select: function (event, ui) {
                $("#item_" + index).val("");
                $('#itemid_' + index).val(ui.item.ID);
                $('#itemcode_' + index).val(ui.item.CODE);
                $('#itemname_' + index).val(ui.item.NAME);
                $('#itemprice_' + index).val(parseFloat(ui.item.PRICEBUY).toFixed(2));


            }
        });
    }
    
    function getItemFromCode(itemcode, txtindex)
    {
        
        $.ajax({
                    method: "GET",
                    url: "<?php echo base_url('inventory/Products/getproductsfromcode/'); ?>",
                    data: {term: itemcode},
                    dataType: "json"
                }).done(function (msg) {
                    if (msg.length == 0) {
                        $('.inputs').removeClass('editfield');
                        alert("Product not found!");
                    } else {
                        $.each(msg, function (index, element) {

                            $("#item_" + txtindex).val("");
                            $('#itemid_' + txtindex).val(element.ID);
                            $('#itemcode_' + txtindex).val(element.CODE);
                            $('#itemname_' + txtindex).val(element.NAME);
                            $('#itemprice_' + txtindex).val(parseFloat(element.PRICEBUY).toFixed(2));
                        });
                        
                        
                    }
                });
    }

    function incrememttablerow(i) {
        html = '<tr id="tablerow_' + i + '">';
        html += '<td class="nopaddingtd"><input style="width: 150px;" type="text" class="inputs itemcode" name="itemcode[]" id="itemcode_' + i + '" data-ind="' + i + '" /><input type="hidden" name="itemid[]" id="itemid_' + i + '" value="" /></td>';
        html += '<td class="nopaddingtd"><input style="width: 400px;" type="text" class="inputs itemname" name="itemname[]" id="itemname_' + i + '" data-ind="' + i + '" /></td>';
        html += '<td class="nopaddingtd"><input type="number" class="inputs itemqty text-center" name="itemqty[]" id="itemqty_' + i + '" data-ind="' + i + '" value="1" /></td>';
        html += '<td class="nopaddingtd"><input type="number" class="inputs itemprice text-right" name="itemprice[]" id="itemprice_' + i + '" data-ind="' + i + '" value="0" /></td>';
        html += '<td class="text-center" width="50"><a class="btn btn-danger btn-xs delete" onclick="tablerowremove(' + i + ')"><i class="fa fa-trash-o"></i></a></td>';
        html += '</tr>';
        return html;
    }

// Delete table row
    function tablerowremove(rowid = '', recId = '') {
        if (rowid) {
            
            $('#tablerow_' + rowid + '').remove();
            
        }
        
        var tbody = $("#mainTable tbody");
        if (tbody.children().length == 0) {
            var htmlcontent = incrememttablerow(1);
            $('#mainTable').append(htmlcontent);
        }
    }

</script>

<script type="text/javascript">
    function myFunction(id) {
        // id = $(this).attr('id');
        $.ajax({
            url: base_url + 'inventory/stock/editstockdiary/' + id,
            success: function (data) {
                var json = $.parseJSON(data);
                for (var i = 0; i < json.length; ++i) {
                    $("#id").val(json[i].ID);
                    $("#DATE").val(json[i].DATE);
                    $("#REASON").val(json[i].REASON);
                    $("#LOCATION").val(json[i].LOCATION);
                    $("#CODE").val(json[i].CODE);
                    $("#PRODUCT").val(json[i].PRODUCT);
                    $("#UNITS").val(json[i].UNITS);
                    $("#PRICE").val(json[i].PRICE);
                    $("#SUPPLIER").val(json[i].SUPPLIER);
                }
            }
        });
    }


    function confirmFunction(id) {
        $("#okid").val(id);
    }

    function deleteFunction() {
        id = $("#okid").val();
        $.ajax({
            url: base_url + 'inventory/stock/deletestockdiary/' + id,
            success: function (data) {
                location.reload(true);
                $("#confirmmodal").hide();
                $("#modal-success").show();

            }
        });
    }
</script>
<style>
    .select2-container {
        width: 100% !important;
    }
</style>
<!-- Page Content -->
<div class="page-content">

    <!-- Page Header -->
    <div class="page-header position-relative">
        <div class="header-title">
            <h1>
                Update Stock
            </h1>
        </div>
        <!--Header Buttons-->
        <div class="header-buttons">
            <a class="sidebar-toggler" href="#">
                <i class="fa fa-arrows-h"></i>
            </a>
            <a class="refresh" id="refresh-toggler" href="">
                <i class="glyphicon glyphicon-refresh"></i>
            </a>
            <a class="fullscreen" id="fullscreen-toggler" href="#">
                <i class="glyphicon glyphicon-fullscreen"></i>
            </a>
        </div>
        <!--Header Buttons End-->
    </div>
    <!-- /Page Header -->
    <!-- Page Body -->
    <div class="page-body">
        <div class="row">
            <div class="col-xs-12 col-md-12">
                <div class="widget">
                    <div class="widget-body">



                        <form id="frmstockdiary" action="" method="post">

                            <div class="modal-body">
                                <div class="row">
                                    <div class="alert alert-success" id="successmessagealert" style="display: none;">
                                        <a href="#" class="close" data-dismiss="alert">&times;</a>
                                        <?php echo $this->lang->line("SAVEDSUCCESSFULLY"); ?>
                                    </div>
                                    <div class="col-md-12">
                                        <input type="hidden" id="id" name="id">
                                        <div class="form-group">
                                            <label><?php echo $this->lang->line("DATE"); ?></label>
                                            <input type="text" class="form-control date-picker" name="DATENEW" id="DATENEW"
                                                   placeholder="<?php echo $this->lang->line("SELECT") . " " . $this->lang->line("DATE"); ?>"
                                                   data-date-format="dd-mm-yyyy" readonly value="<?php echo date("d-m-Y"); ?>" />
                                        </div>
                                        <div class="form-group">
                                            <label><?php echo $this->lang->line("SELECTREASON"); ?></label>
                                            <select id="REASON" name="REASON" class="form-control" onchange="reasonselect(this.value)">
                                                <option value=""><?php echo $this->lang->line("SELECTREASON"); ?></option>
                                                <option role="option" value="1"><?php echo $this->lang->line("INPURCHASE"); ?></option>
                                                <option role="option" value="2"><?php echo $this->lang->line("INREFUND"); ?></option>
                                                <option role="option" value="4"><?php echo $this->lang->line("INMOVEMENT"); ?></option>
                                                <option role="option" value="5"><?php echo $this->lang->line("INPRODUCTION"); ?></option>
                                                <option role="option" value="-1"><?php echo $this->lang->line("OUTSALE"); ?></option>
                                                <option role="option" value="-2"><?php echo $this->lang->line("OUTREFUND"); ?></option>
                                                <option role="option" value="-3"><?php echo $this->lang->line("OUTBREAK"); ?></option>
                                                <option role="option" value="-4"><?php echo $this->lang->line("OUTMOVEMENT"); ?></option>
                                                <option role="option" value="-5"><?php echo $this->lang->line("OUTPRODUCTION"); ?></option>
                                                <option role="option" value="1000"><?php echo $this->lang->line("CROSSING"); ?></option>
                                                <option role="option" value="999"><?php echo $this->lang->line("REQUEST"); ?></option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label><?php echo $this->lang->line("SELECTWAREHOUSE"); ?></label>
                                            <select role="select" id="LOCATION" name="LOCATION" class="form-control">
                                                <option value=""><?php echo $this->lang->line("SELECTWAREHOUSE"); ?></option>
                                                <?php foreach ($locations as $locations_list) { ?>
                                                    <option value="<?php echo $locations_list->ID; ?>"><?php echo $locations_list->NAME; ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label id="lbllocationto" style="display: none;"><?php echo $this->lang->line("TOWAREHOUSE"); ?></label>
                                            <select role="select" id="LOCATION1" name="LOCATION1" class="form-control" style="display: none;">
                                                <option value=""><?php echo $this->lang->line("TOWAREHOUSE"); ?></option>
                                                <?php foreach ($locations as $locations_list) { ?>
                                                    <option value="<?php echo $locations_list->ID; ?>"><?php echo $locations_list->NAME; ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>





                                        <div class="table-scrollable">
                                            <table id="mainTable" class="table table-bordered table-striped">
                                                <thead>
                                                    <tr>
                                                        <th style="width: 70px;"><?php echo $this->lang->line("ITEMCODE"); ?></th>
                                                        <th style="width: 300px;"><?php echo $this->lang->line("ITEMNAME"); ?></th>
                                                        <th class="labelcenteralign" id="orgqtyid" style="width: 70px;"><?php echo $this->lang->line("QTY"); ?></th>
                                                        <th class="labelrightalign" style="width: 100px;"><?php echo $this->lang->line("PRICE"); ?></th>
                                                        <th></th>
                                                    </tr>
                                                </thead>

                                                <tr id="tablerow_1" data-invitemid="">
                                                    <td class="nopaddingtd">
                                                        <input style="width: 150px;" autocomplete="off" type="text" class="inputs itemcode" name="itemcode[]" id="itemcode_1" data-ind="1" value="" />
                                                        <input autocomplete="off" type="hidden" name="itemid[]" id="itemid_1" value="" />
                                                    </td>
                                                    <td class="nopaddingtd">
                                                        <input style="width: 400px;" autocomplete="off" type="text" class="inputs itemname" name="itemname[]" id="itemname_1" data-ind="1" value="" />
                                                    </td>
                                                    <td class="nopaddingtd">
                                                        <input autocomplete="off" type="number" class="inputs itemqty text-center" name="itemqty[]" id="itemqty_1" data-ind="1" value="1" />
                                                    </td>
                                                    <td class="nopaddingtd">
                                                        <input autocomplete="off" type="number" name="itemprice[]" id="itemprice_1" class="inputs itemprice text-right" data-ind="1" value="0" />
                                                    </td>
                                                    <td class="text-center" width="50">
                                                        <a class="btn btn-danger btn-xs delete" onclick="tablerowremove('1', '')"><i class="fa fa-trash-o"></i></a>
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>



                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="submit" class="btn btn-success shiny" id="saveandnewbtn"> Save </button>
                            </div>
                        </form>

                    </div>

                </div>
            </div>

        </div>
        <!-- /Page Body -->
    </div>
    <!-- /Page Content -->
</div>
<!-- /Page Container -->
<!-- Main Container -->



</div>
<script src="<?php echo base_url(); ?>assets/js/dropzone/dropzone.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/select2/select2.js"></script>
<!--    <script src="<?php echo base_url(); ?>assets/js/validation/bootstrapValidator.js"></script>-->
<script src="<?php echo base_url() ?>assets/js/jquery.validate.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#frmstockdiary').validate({// initialize the plugin
            rules: {
                REASON: {
                    required: true
                },
                LOCATION: {
                    required: true
                },
                CODE: {
                    required: true
                },
                PRODUCT: {
                    required: true
                },
                UNITS: {
                    required: true
                },
                PRICE: {
                    required: true
                },
                LOCATION1: {
                    required: true
                }
            },
            submitHandler: function (form) {
                //$("#saveandnewbtn").prop("disabled", true);
                var REASON = $("#REASON").val();
                var LOCATION = $("#LOCATION").val();
                var LOCATION1 = $("#LOCATION1").val();
                var DATE = $("#DATENEW").val();
                
                
                formVals = $("#mainTable").serialize();
$('#mainTable').find('input').each(function(){
    formVals += '&' + this.id + '=' + this.value;
});
                $.ajax({
                    method: "POST",
                    url: "<?php echo base_url('inventory/stock/addstockdiary2'); ?>",
                    data: formVals+"&DATENEW="+DATE+"&REASON="+REASON+"&LOCATION="+LOCATION+"&LOCATION1="
                        +LOCATION1
                }).done(function (msg) {
                    //alert(msg);
                    window.location.replace("../stockdiary");
                });
                return false;
            }
        });
    });

    

    function reasonselect(reasonId) {
        if (reasonId == '1000') {
            $("#LOCATION1").show();
            $("#lbllocationto").show();
        } else {
            $("#LOCATION1").hide();
            $("#lbllocationto").hide();
        }
    }

    $(document.body).on("change", "#PRODUCT", function () {
        if ($(this).val() != '') {
            $.ajax({
                method: "GET",
                url: base_url + "inventory/Products/getproductsfromid/",
                data: {id: $(this).val()},
                dataType: "json"
            }).done(function (msg) {
                $(".loading-container").addClass("loading-inactive");
                $.each(msg, function (index, element) {
                    $('#CODE').val(element.CODE);
                    $('#PRICE').val(element.PRICEBUY);
                });
            });
        } else {
            $('#CODE').val('');
            $('#PRICE').val('');
        }
    });
    function resetform() {
        $("#frmstockdiary")[0].reset();
    }

    $('#myModal').on('shown.bs.modal', function () {
        $('#REASON').focus();
    });

    

</script>