var i = 1;
var m = 1;
var count = 1;
var editflag = 0; var copyflag = 0;
$(document).ready(function () {
    $('#hiddenrow').val('');
    $('#ToLocationIn').focus();
    $('#STIDate').val(CurDate);
    serialnoload();
    AccountLoad(2);
    loadlocation();
    $('#btntrnsfr').prop('disabled', false);   
    //$('#LocationIn').prop('disabled', true);
    $('#GrandTotal').prop('disabled', true);
    $('#GrandTotal').css('background-color', 'white');
    $//('#LocationIn').css('background-color', 'white');
    var a = '0.00';
    $('#GrandTotal').val(a);

    $("#btnsubmit").click(function (e) {       
        SaveAndUpdate(1)

    });

   
    $('#btnok').click(function () {
        PrintthisBillWindows('StockTransferOUT', i, 'MAIN');
        alertpopuprefresh();
        formrefresh();
    });
    $('#btncnclalrt').click(function () {
        alertpopuprefresh();
        formrefresh();
    });
   
   
    var data = {};
    data.UnitId = 0;
    $.ajax({
        type: "POST",
        url: "../Master/UnitGetandGets",
        data: data,
        success: function (result) {
            UnitLoad(result.oList);
        }

    });
    $('#STIDate').daterangepicker({
        minDate: minDate,
        maxDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
        singleDatePicker: true,
        showDropdowns: true,
        locale: {
            format: 'DD/MM/YYYY'
        }
    });   
    $('#LocationIn').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#ToLocationIn').focus();
        }
    });
    $('#DebitAccountIn').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            if (($('#DebitAccountIn').val() != '') && ($('#hiddendebit').val() == 0)) {
                $('#DebitAccountIn').val('');
                warningshow('Please Select A Valid Debit  Account', 'DebitAccountIn');
                return false;
            }
            else {
                $('#CreditAccountIn').focus();
            }
        }
    });
   
    $('#ToLocationIn').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#btntrnsfr').focus();
        }
    });

    $('#Comments').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#btnsubmit').focus();
        }
    });

    
    $('#CreditAccountIn').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            if (($('#CreditAccountIn').val() != '') && ($('#hiddenCredit').val() == 0)) {
                $('#CreditAccountIn').val('');
                warningshow('Please Select A Valid  Credit Account', 'CreditAccountIn');
                return false;
            }
            $('#Comments').focus();
        }
    });
    $('#Comments').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#txtproduct').focus();
        }
    });
    $('#txtquantity').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#txtrate').focus();
        }
    });
    $('#txtrate').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#btnadd').focus();
        }
    });
    $('#select_unit0').change(function () {
        $('#txtunit').val($this).find("option:selected").attr("name")
    });

   
//adding datas in grid in main form
    $("#btnaddtogrid").click(function (e) {

        
        var i = 1;
        var row = $('#RowGet1').val();
        $("#tblStockTransferIn tr").remove();
        for (m = 1; m <= row; m++) {
            if ($("#SlNoCheckgrid" + m).is(":checked")) {
             
                var Stonumber = $('#STNoRow' + m).text();
                var productIdgrid = $('#ProductIdgrid' + m).val();               
                var Product = $('#Product' + m).text();
                var unit = $('#UnitName' + m).text();
                var unitIdgrid = $('#UnitIdgrid' + m).val();                
                var qty = $('#qty' + m).text();
                var price = $('#price' + m).text();
                var total = $('#total' + m).text();
                var Des = $('#Des' + m).text();
                var STOId = $('#STOsubIdgrid' + m).val();              
                $('#iconForm').hide();
                var slno = parseInt(i);

                var ProdRow = "<tr id=" + 'row' + slno + " class= jsgrid-row ><td  id=" + 'td' + slno + " class= jsgrid-cell  style= width:4%;text-align:center >"
                  + slno + "<input type='hidden' id='SlNo" + slno + "' value=" + slno + "></td><td class= 'jsgrid-cell jsgrid-align-left'  style= 'width: 6%;text-align:center' ><input type='hidden' id='ProductId" + slno + "' value='" + productIdgrid + "'/><input type='hidden' id='STONo" + slno + "' value='" + Stonumber + "'/><input type='hidden' id='STOsubId" + slno + "' value='" + STOId + "'/>  <input typ='text' class='form-control' disabled=disabled  style='background-color:white;height:30px;' id='txtprd" + slno + "' value='"
                  + Product + "'>  </td><td class= 'jsgrid-cell jsgrid-align-left'  style= 'width:20%;text-align:center' display='none;'> <input type='text' class='form-control'  disabled  style='background-color:white;height:30px;' id='txtdesc" + slno + "' value='"
                  + Des + "'> </td><td class= jsgrid-cell jsgrid-align-center  style= 'width:6%;' text-align-center><select id=" + 'select_unit' + slno + " class='form-control' disabled=disabled style='background-color:white;height:30px;' >"
                  + UnitSelect + "</select></td><td class= 'jsgrid-cell jsgrid-align-center'  style= 'width:6%;' ><input type='text' class='form-control text-center'  disabled=disabled  style='background-color:white;height:30px;'  onkeyup='tot_row(" + slno + ")' onkeypress='return isNumber1(event)' id='txtqnty" + slno + "' value='"
                  + qty + "'><input type='hidden' id='hiddenqty" + slno + "' value='" + qty + "'/> </td><td class= 'jsgrid-cell jsgrid-align-center'  style= 'width:6%;' ><input typ='text' class='form-control text-right' disabled=disabled style='background-color:white;height:30px;' onkeyup='tot_row(" + slno + ")' onkeypress='return isNumber(event,this.id)' id='rate" + slno + "' value="
                  + price + "></td><td class= 'jsgrid-cell jsgrid-control-field jsgrid-align-center'  style= 'width:6%;' ><input typ='text' class='form-control text-right' disabled=disabled  style='background-color:white;height:30px;background-color:white'readonly onkeyup=''   id='tamnt" + slno + "' value="
                  + total + "></td><td id='Edit" + slno + "' class= 'jsgrid-cell jsgrid-control-field jsgrid-align-center'  style= width:4% ><input class= 'jsgrid-button jsgrid-delete-button'  type= button id='delete' title= Delete onclick='rowdelete(" + slno + ")' ></td><td id='Update"
                  + slno + "'  class= 'jsgrid-cell jsgrid-control-field jsgrid-align-center'  style='width:120px;display:none'><input class='jsgrid-button jsgrid-update-button' onclick='Updaterow(" + slno + ")' type=button id='update' title=Update style='' ><input class='jsgrid-button jsgrid-cancel-edit-button' onclick='CancelEditrow(" + slno + ")' type='button' id='CancelEdit' title='Cancel edit'></tr>";

                
                $('#tblStockTransferIn').append(ProdRow);
                $('#select_unit' + slno).val(unitIdgrid);
                i++;
                grandtotal(i);
                $('#btntrnsfr').focus();
                $('#hiddenrow').val(i);                         
            }
          
        }  
        count = i - 1;
        
        $('#proddiv').animate({ scrollTop: 5000 }, 900);
    });




//display data based on STO NO in popup
    $("#btnview").click(function (e) {
        var Stonumber = '';
        var DeptId = '';
        var row = $('#RowGet').val();        
        for (m = 1; m <= row; m++) {          
            if ($("#SlNoCheck"+m).is(":checked") ) 
            {
                if ( Stonumber == '') {
                    Stonumber += $('#STNoRow' + m).text();                    
                }
                else {
                    Stonumber += ',' + $('#STNoRow' + m).text();                  
                }

            }
        }       
        var data = {};
        data.Stonumber = Stonumber;
        data.DeptId = DeptId;
        $.ajax({           
            type: "POST",
            url: "../../inventory/StockTransferOutGetProduct",
            data: data,
            success: function (result) {
                if (Stonumber != 0)
                    ShowItemGet(result.oList);

            }
        });
      
    });

    $('#STINo').keyup(function (e) {
        e.preventDefault();
        $('#tour1').fadeOut();
        var entrkey = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

        if (entrkey == 8) {
            checkSTIntextempty();
        }
    });
});

function alertpopuprefresh() {
    $('#alertpopup').hide();
    $('#alertdiv').hide();
}
//acccount number load
function AccountLoad(flag) {
    var accno = {};
    accno.DeptId = ERPDeptId;
    accno.flag = flag;

    $.ajax({
        type: "POST",
        url: "../../inventory/AccountNoGetandGets",
        data: accno,
        success: function (result) {
            getacno(result.oList);
        }
    });
}
function getacno(result) {
    for (var k = 0; k < result.length; k++) {

        $('#DebitAccountIn').val(result[k].AccCode);
        $('#hiddendebit').val(result[k].AccountId);
        $('#CreditAccountIn').val(result[k].CAccCode);
        $('#hiddenCredit').val(result[k].CAccountId);
        $('#txtdacnt').val(result[k].DAccountDescription);
        $('#txtcacnt').val(result[k].AccountDescription);

    }
}
//disable grid in copy
function disable_datatable(tablename) {  
    if ($.fn.DataTable.isDataTable('#' + tablename)) {
        var table = $('#' + tablename).DataTable();
        table.destroy();
        return;
    }
}
//tot=Qty*rate
function tot() {
    var qty = parseFloat($('#txtquantity').val() || 0);
    var rate = parseFloat($('#txtrate').val() || 0);
    var total = parseFloat(qty * rate);
    $('#txttotal').val(total);
}
function tot_row(RowId) {
    if (parseFloat($('#txtqnty' + RowId).val() || 0) > parseFloat($('#hiddenqty' + RowId).val() || 0)) {
        warningshow('Transfered Quantity is:' + $('#hiddenqty' + RowId).val(), 'txtqnty' + RowId);
        $('#txtqnty' + RowId).val($('#hiddenqty' + RowId).val())
    }  
    var qty = parseFloat($('#txtqnty' + RowId).val() || 0);
    var rate = parseFloat($('#rate' + RowId).val() || 0);
    var total = parseFloat(qty * rate).toFixed(Decimal);
    $('#tamnt' + RowId).val(total).toFixed(Decimal);
   
}



function grandtotal(slno) {
    var grandtot = 0;   
    var row = $('#RowGet1').val();
    $('#GrandTotal').val('');
    for (var i = 1; i <= row; i++) {
        grandtot = grandtot + parseFloat($('#tamnt' + i).val() || 0);
    }
   
    $('#GrandTotal').val(grandtot.toFixed(Decimal));
}


function UnitLoad(result) {
    $("#select_unitIn").empty();
    UnitSelect = "<option value=0>-Select-</option>";
    for (var i = 0; i < result.length; i++) {
        UnitSelect += "<option value='" + result[i].UnitId + "' name=" + result[i].UnitName + ">" + result[i].UnitName + "</option>"
    }
    $("#select_unitIn").append(UnitSelect);
}
function loadlocation() {

    var datafd = {};
    datafd.LocationId = 0;
    datafd.UserId = ERPUserId;
    $.ajax({
        type: "POST",
        url: "../Master/UserLocationGetandGets",
        data: datafd,
        success: function (result) {
            LocationLoadUser(result.oList);
        }
    });
    var data4 = {};
    data4.LocationId = 0;
    $.ajax({
        type: "POST",
        url: "../Master/LocationGetandGets",
        data4: data4,
        success: function (result) {
            LocationLoad(result.oList);
        }

    });
}

function rowdelete(RowId) {
    $('#confirm').show();
    $('#confirmOk').focus();
    $('#Confirmflag').val('delete'); $('#ConfirmRowId').val(RowId);  
}
function ConfirmboxResult(Result, status, rowid) {
    if (Result == 'true' && status == 'delete') {
        deleterow(rowid)
    }
    else if (Result == 'true' && status == 'createnew') {
        formrefresh();
    }
    else if (Result == 'true' && status == 'copy') {
           enablecopy();
        }    
    $('#confirm').fadeOut();
}
function deleterow(RowId) {
    var sllno = 1;
    var h = $('#hiddenrow').val();
    var rowslno = parseInt(sllno);   
        $('#row' + RowId).remove();

        for (var j = 1; j <= h - 1; j++) {

            if ($('#txtprd' + j).val() != undefined) {
                $('#td' + j).text(sllno);

                sllno++;
            }
        }    
    $('#txttotal').val('');
    grandtotal(i)
    $('#txtproduct0').focus();
}
function enablecopy() {
    $('#tour1').fadeIn();
    copyflag = 1;
    loadlocation();
    $("#tblStockTransferIn tr").remove();
    $('.form-control').prop("disabled", true);
    $('#STINo').prop('disabled', false);
    $('#btntrnsfr').prop('disabled', true);
    $('#btnsubmit').prop('disabled', true);
    $('#btnlist').prop('disabled', true);
    $('#btnprint').show();
    $('#STINo').focus();
    $('#STINo').select();
    $('#ToLocationIn').val(0);
    $('#LocationIn').prop('disabled', true);
    $('#GrandTotal').prop('disabled', true);
    $('#GrandTotal').css('background-color', '#ECEFF1');
    //$('#LocationIn').css('background-color', '#ECEFF1');
}
function ClearProductRow()
{
    $('#txtproduct').val('');
    $('#select_unitIn').val('0');
    $('#txtquantity').val('');
    $('#txtrate').val('');
    $('#txttotal').val('');
   
}
var LocationSelect = "";
function LocationLoad(result) {
    $("#ToLocationIn").empty();
    LocationSelect = "<option value=0>-Select-</option>";
    //$("#ToLocation").append("<option value='0'>----Select Location---</option>");
    for (var i = 0; i < result.length; i++) {
        LocationSelect += "<option value='" + result[i].LocationId + "'>" + result[i].LocationName + "</option>";
    }
    $("#ToLocationIn").append(LocationSelect);
}
function LocationLoadUser(result) {
    $("#LocationIn").empty();
    LocnSelect = "<option value=0 disabled>-Select-</option>";
    for (var i = 0; i < result.length; i++) {

        LocnSelect += "<option value='" + result[i].LocationId + "'name='" + result[i].LocationName + "'>" + result[i].LocationName + "</option>";

    }
    if (copyflag == 1) {
        $("#LocationIn").append(LocationSelect);
    }
    else {
        $("#LocationIn").append(LocnSelect);
        $('#LocationIn').val(UserLocationId);
    }

}



function Editrow(RowId) {
    editflag = editflag + 1;
    $('#row' + RowId).children('td,th').css('background-color', 'rgb(232,226,226)');
    $('#Edit' + RowId).hide();
    $('#Update' + RowId).show();
    grandtotal(RowId)
    desc = $('#txtdesc' + RowId).val();
    select_unit = $('#select_unit' + RowId).val();
    qty = $('#txtqnty' + RowId).val();
    rate = $('#rate' + RowId).val();
    total = $('#tamnt' + RowId).val();
    $('#txtdesc' + RowId).prop('disabled', true);
    $('#select_unit' + RowId).prop('disabled', true);
    $('#txtqnty' + RowId).prop('disabled', false);
    $('#rate' + RowId).prop('disabled', true);
    $('#tamnt' + RowId).prop('disabled', true);
}

function Updaterow(RowId) {
    if ($('#txtqnty' + RowId).val() == 0) {
        warningshow('Quantity cannot be Zero', 'txtqnty' + RowId);
        return false;
    }
    else {
        editflag = editflag - 1;
        $('#row' + RowId).children('td,th').css('background-color', 'white');
        $('#Update' + RowId).hide();
        $('#Edit' + RowId).show();
        grandtotal(RowId);
        $('#txtdesc' + RowId).prop('disabled', true);
        $('#select_unit' + RowId).prop('disabled', true);
        $('#txtqnty' + RowId).prop('disabled', true);
        $('#rate' + RowId).prop('disabled', true);
        $('#tamnt' + RowId).prop('disabled', true);
        grandtotal(i);
    }
}

function CancelEditrow(RowId) {
    editflag = editflag - 1;
    $('#row' + RowId).children('td,th').css('background-color', 'white');

    $('#Update' + RowId).hide();
    $('#Edit' + RowId).show();

    $('#txtdesc' + RowId).val(desc);
    $('#select_unit' + RowId).val(select_unit);
    $('#txtqnty' + RowId).val(qty);
    $('#rate' + RowId).val(rate);
    $('#tamnt' + RowId).val(total);
    $('#select_unit' + RowId).prop('disabled', true);
    $('#txtqnty' + RowId).prop('disabled', true);
    $('#rate' + RowId).prop('disabled', true);
    $('#tamnt' + RowId).prop('disabled', true);
    grandtotal(i);


}
//1st popupform by location select
function GetList(Id) {
   
    if ($('#LocationIn').val() == "0") {
        warningshow('Please Select Location', 'LocationIn');
        return false;
    }
    else if ($('#ToLocationIn').val() == "0") {
        warningshow('Please Select Transfer Location', 'ToLocationIn');
        return false;
    } 
    else if ($('#ToLocationIn').val() == ($('#LocationIn').val())) {     
        warningshow('Please Select Valid Location', 'ToLocationIn');
        return false;
    }
    else {
        var LocId = $('#ToLocationIn').val();
        var fromLocId = $('#LocationIn').val();      
        var data = {};
        data.ToLocation = LocId;
        data.FromLocation = fromLocId;
        data.DeptId = ERPDeptId;
        $.ajax({
            type: "POST",
            url: "../../inventory/StockDetailsGetsbyLocation",
            data: data,
            success: function (result) {
                if (LocId != 0)
                    ShowStockList(result.oList);

            }
        });
    }
}
 
//table based on location select
var l = 0;
function ShowStockList(result) {
    if (result.length == 0)
    {
warningshow('No Products Transfered')
    }
    else
    {
        $('#RowGet').val = '';
        $('#modelheader').text('Stock Details');
        $('#add').hide();
        $('#View').show();
        $('#iconForm').show();
        var responseText = "<thead><tr><th style='width:8%;'> <input type='checkbox'  checked  id= 'SlNoHeadCheck'  'custom-control-input cz-bg-image-display'  onchange='selectallinItem()' >&nbsp;&nbsp;&nbsp;Select</th><th style='width:10%;'>Slno</th><th style='width:10%;'>STONo</th><th style='width:15%;'>From Location</th><th style='width:12%;'>Date</th><th style='width:30%;'>Comments</th><th style='display:none'></th></tr></thead><tbody>";
        for (var l = 0; l < result.length; l++) {
            var slno = parseInt(l + 1);

            responseText += '<tr><td style="width:8%;" ><input type="checkbox"  checked  id= ' + 'SlNoCheck' + slno + '  "custom-control-input cz-bg-image-display" style="align:center"></td><td style="width:10%;">' + slno + '</td><td id=' + 'STNoRow' + slno + ' style="width:10%;">' + result[l].STONo + '</td><td style="width:15%;">' + result[l].FromLocationName + '</td><td style="width:12%;">' + result[l].STODate + '</td><td style="width:30%;">' + result[l].Comments + '</td><td style="display:none"   id=' + 'Dept' + slno + '  >' + result[l].DeptId + '</td></tr>';
        }
        $('#Stocklist').html(responseText + '</tbody>');



        $('#RowGet').val(result.length)
        $('#btnview').focus();
    }  
}

function selectallinItem() {

    var rowCount = $('#Stocklist tr').length;
    var flag = $("#SlNoHeadCheck").is(":checked")


    for (var i = 1; i <= rowCount + 1; i++) {
        document.getElementById("SlNoCheck" + i).checked = flag;
    }
}
//table based on STONo
function ShowItemGet(result) {
    var l = 0;
    $('#myModalLabel17').text('Stock List');
    $('#View').hide();
    $('#add').show();
    $('#iconForm').show();
    disable_datatable('ListItem');
    var responseText = "<thead><tr><th style='width:10%;'> <input type='checkbox'  checked  id= 'SlNoHeadCheckItem' onchange='selectall()' 'custom-control-input cz-bg-image-display'></th><th style='width:5%;text-align:center'>SlNo</th><th style='width:7%;text-align:center'>STONo</th><th style='display:none;'></th><th style='display:none;'></th><th style='width:20%;'>Product</th><th style='display:none;'></th><th style='width:12%;'>Unit</th style='width:25%;'><th>Description</th><th style='width:10%;'>Quantity</th><th style='width:15%;'>Price</th><th style='width:15%;' style='width:15%;'>Total</th></tr>" +
        "<tr ><th style='width:10%;'> </th><th style='width:5%;'>SlNo</th><th style='width:7%;'>STONo</th><th style='display:none;'></th><th style='display:none;'></th><th style='width:20%;'>Product</th><th style='display:none;'></th><th style='width:12%;'>Unit</th><th style='width:25%;'>Description</th><th style='width:10%;'>Quantity</th><th style='width:15%;'>Price</th><th style='width:15%;'>Total</th></tr></thead><tbody>";
    for (var l = 0; l < result.length; l++) {
        var slno = parseInt(l + 1);
        responseText += '<tr><td style="width:10%;"><input type="checkbox"  checked  id= ' + 'SlNoCheckgrid' + slno + ' ></td><td style="width:5%;text-align:center">' + slno + '</td><td  id=' + 'STNoRow' + slno + ' style="width:7%;text-align:center">' + result[l].STONo + '</td><td style=display:none;><input type="text" id= ' + 'ProductIdgrid' + slno + ' value= ' + result[l].ProductId + '></td><td style=display:none;><input type="hidden" id= ' + 'STOsubIdgrid' + slno + ' value= ' + result[l].STOSubId + '></td><td id=' + 'Product' + slno + ' style="width:20%;">' + result[l].ItemCode + '</td><td style=display:none;><input type="text" style="display:none;" id= ' + 'UnitIdgrid' + slno + ' value= ' + result[l].UnitId + '></td><td id=' + 'UnitName' + slno + ' style="width:12%;">' + result[l].UnitName + '</td><td id=' + 'Des' + slno + ' style="width:25%;">' + result[l].Description + '</td><td id=' + 'qty' + slno + ' style="width:10%;text-align:center">' + result[l].Quantity + '</td><td id=' + 'price' + slno + ' style="width:15%;text-align:right">' + (result[l].Price.toFixed(Decimal)) + '</td><td id=' + 'total' + slno + ' style="width:15%;text-align:right">' + (result[l].Total.toFixed(Decimal)) + '</td></tr>';
    }
    $('#ListItem').html(responseText + '</tbody>');
    datatableWithsearch('ListItem', 'Multiple');
    $('#RowGet1').val(result.length)
    $('#btnaddtogrid').focus();
}
//selecting checkbox
function selectall() {
    var rowCount = $('#RowGet1').val();
    var flag = $("#SlNoHeadCheckItem").is(":checked")    
    for (var i = 1; i <= rowCount; i++)
    {
        if (document.getElementById("SlNoCheckgrid" + i) != null) {
            document.getElementById("SlNoCheckgrid" + i).checked = flag;
        }
    }  
}

function createnew() {   
    var rowcount = document.getElementById('tblStockTransferIn').rows.length;
        if (rowcount > 0 && copyflag == 0) {
            $('#Confirmflag').val('createnew'), $('#ConfirmRowId').val(1)
            $('#confirmmessage').text('Data Will be Lost.Do you want to Continue?')
            $('#confirm').show();
            $('#confirmOk').focus();
        }
        else  {
            formrefresh();
            $('#btnprint').hide();
            $('#tour1').fadeOut();

        }
}

function formrefresh() {
    if (editflag != 0) {
        warningshow('You are in Edit Mode');
    }
    else {
        serialnoload();
        AccountLoad(2);
        copyflag = 0;
        $('#STINo').prop('disabled', true);
        $('#btnsubmit').prop('disabled', false);
        $('#btnlist').prop('disabled', false);
        $('#ToLocationIn').prop('disabled', false);
        $('#STIDate').prop('disabled', false);
        $('#DebitAccountIn').prop('disabled', false);
        $('#Comments').prop('disabled', false);
        $('#CreditAccountIn').prop('disabled', false);
        $('#DebitAccountIn').prop('disabled', false);
        $('#DebitAccountIn').val('');
        $('#ToLocationIn').val('0');
        $('#CreditAccountIn').val('');
        $('#Comments').val('');
        $('#txtproduct').val('');
        $('#select_unitIn').val('0');
        $('#txtquantity').val('');
        $('#txtrate').val('');
        $('#txttotal').val('');
        $('#hiddenrow').val('');
        $('#hiddendebit').val('');
        $('#hiddenCredit').val('');
        $('#btntrnsfr').prop('disabled', false);
        $("#tblStockTransferIn tr").remove();
        $('#LocationIn').prop('disabled', false);
        $('#GrandTotal').prop('disabled', true);
        $('#GrandTotal').css('background-color', 'white');
        //$('#LocationIn').css('background-color', 'white');
        var a = '0.00';
        $('#GrandTotal').val(a);
        $('#ToLocationIn').focus();
        loadlocation();
        $('#LocationIn').val(UserLocationId);
    }
}


function serialnoload() {
    var srlno = {};
    srlno.DeptId = ERPDeptId;
    $.ajax({
        type: "POST",
        url: "../../Common/SlNoGetandGets",
        data: srlno,
        success: function (result) {
            getslno(result.oList);

        }
    });

}
function getslno(result) {
    for (var k = 0; k < result.length; k++) {
        $('#STINo').val(result[k].StockInNo);
    }
}

function warningshow(message, Id) {
    $('#popupmessage').text(message);
    $('#Warningpopup').show();
    $('#' + Id).focus();
    window.setTimeout(function () {
        $('#Warningpopup').fadeOut();
    }, 3000);
}
//save
function SaveAndUpdate(Flag) {
    var rowCount = $('#tblStockTransferIn tr').length; 
    if (editflag != 0) {
        warningshow('You are in Edit Mode');
    }   
      else  if ($.trim($('#ToLocationIn').val()) == '0') {
            warningshow('Please select Transfer From Location', 'ToLocationIn');
        return false;
      }
      else if ($.trim($('#LocationIn').val()) == '0') {
          warningshow('Please select Transfer From Location', 'LocationIn');
          return false;
      }
      else if (($('#DebitAccountIn').val() != '') && ($('#hiddendebit').val() == 0)) {
          warningshow('Please Select A Valid Debit Account', 'DebitAccountIn');
          return false;
      }
          else  if (($('#CreditAccountIn').val() != '') && ($('#hiddenCredit').val() == 0)) {
                warningshow('Please Select A Valid Credit Account', 'CreditAccountIn');
                return false;
          }         
          else if ($('#DebitAccountIn').val() == '') {
              warningshow('Please Select A  Debit Account', 'DebitAccountIn');
              return false;
          }
          else if ($('#CreditAccountIn').val() == "") {
              warningshow('Please Select A Credit Account', 'CreditAccountIn');
              return false;
          }        
          else if ($('#ToLocationIn').val() == ($('#LocationIn').val())) {
              warningshow('Please Select Valid Location', 'ToLocationIn');
              return false;
          }
          else if(rowCount==0)
          {
              warningshow('No Products Added', 'btntrnsfr');
              return false;              
          }
          else {
              $('#btnsubmit').prop("disabled", true);
        var oArray = new Array();

        for (var k = 1; k <= count; k++) {
            var ProductId = $('#ProductId' + k).val();
            var UnitId = $('#select_unit' + k).val();
            var Quantity = $('#txtqnty' + k).val();
            var Price = $('#rate' + k).val();
            var Total = $('#tamnt' + k).val();
            var LoginLocation = $('#LocationIn').val();
            var ToLocation = $('#ToLocationIn').val();
            var STONo = $('#STONo' + k).val();
            var STInNo = $('#STINo').val();
            var STInDate = $('#STIDate').val();
            var DebitAccount = $('#hiddendebit').val();
            var CreditAccount = $('#hiddenCredit').val();
            var Comments = $('#Comments').val();
            var STOId = $('#STOsubId' + k).val();
            var UId = ERPUserId;
            var DeptId = ERPDeptId;
            DelFlag = 1;
            var outstatus = 1;
            if (ProductId != undefined) {
                oArray.push({
                    'ProductId': ProductId,
                    'UnitId': UnitId,
                    'Quantity': Quantity,
                    'Price': Price,
                    'Total': Total,
                    'STONo': STONo,
                    'STInNo': STInNo,
                    'LoginLocation': LoginLocation,
                    'TransferLocation': ToLocation,
                    'STInDate': STInDate,
                    'DebitAccount': DebitAccount,
                    'CreditAccount': CreditAccount,
                    'Comments': Comments,
                    'STOId':STOId,
                    'UId': UId,
                    'DeptId': DeptId,
                    'DelFlag': DelFlag,
                    'outstatus': outstatus
                })
            }
        }
        if (oArray != "") {
            var data = { 'StockTransferOutModel': oArray };

            $.ajax({
                type: "POST",
                url: "../../inventory/StocktransferInInsert",
                data: data,
                success: function (result) {
                    for (var a = 0; a <= result.oList.length; a++) {
                        var status = result.oList[a].Status;
                        var stinnum = result.oList[a].STInNo;
                        //$('#btnsubmit').prop("disabled", false);
                        Showalerts(status, stinnum);                      
                    }
                }
            });
        }
    }
}
function Showalerts(Status,stinnum) {
    if (Status == 1) {
        //formrefresh();
        //swal('STIn Number: ' + stinnum , " Saved Successfully", "success");
        //$('.swal-button swal-button--confirm').focus();
        $('#alertpopup').show();
        $('#alertdiv').show();
        $('#savealert').text('');
        $('#savealert').append('Saved Successfully!<br>Do you want to print this bill?');
        $('#btnok').focus();
    }
}
function disabletext() {
    var rowCount = $('#tblStockTransferIn tr').length;
    if (rowCount > 0) {
        $('#Confirmflag').val('copy'), $('#ConfirmRowId').val(1)
        $('#confirmmessage').text('Data Will be Lost.Do you want to Continue?')
        $('#confirm').show();
        $('#confirmOk').focus();
    }
    else if (rowCount == 0)
    {
        enablecopy();
    }   
}
//copy 
var rowCount = 1;
function ShowStockTransferInGet(result) {
        var rowCount = $('#tblStockTransferIn tr').length;
        if (rowCount == 0)
        {
            i = 1;
        }       
        $('#btnsubmit').prop('disabled', true);
        $('#txtprd').val(result[0].ItemCode);
        $('#select_unit').val(result[0].UnitId);
        var Unit = result[0].UnitId;
        var description = result[0].Description;
        for (var m = 0; m < result.length; m++) {
            var slno = parseInt(i);
            var ProdRow = "<tr id=" + 'row' + slno + " class= jsgrid-row ><td  id=" + 'row' + slno + " class= jsgrid-cell  style= width:4%;text-align:center >"
              + slno + "<input type='hidden' id='SlNo" + slno + "' value=" + slno + "></td><td class= 'jsgrid-cell jsgrid-align-left'  style= 'width:6%;text-align:center' ><input type='hidden' id='ProductId" + slno + "' value='" + result[m].ProductId + "'/> <input typ='text' class='form-control' disabled=disabled  style='background-color:white;height:30px;' id='txtprd" + slno + "' value='"
              + result[m].ItemCode + "'>  </td><td class= 'jsgrid-cell jsgrid-align-left'  style= 'width:20%;text-align:center' display='none;'> <input type='text' class='form-control'  disabled  style='background-color:white;height:30px;' id='txtdesc" + slno + "' value='"
              + result[m].Description + "'> </td><td class= jsgrid-cell jsgrid-align-center  style= width:6%;text-align-center><select id=" + 'select_unit' + slno + " class='form-control' disabled=disabled style='background-color:white;height:30px;' value='"
              + result[m].UnitId + "'>" + UnitSelect + "</td><td class= 'jsgrid-cell jsgrid-align-center'  style= width:6%; ><input type='text' class='form-control text-center'  disabled=disabled  style='background-color:white;height:30px;'  id='txtqnty" + slno + "' value='"
              + result[m].Quantity + "'> </td><td class= 'jsgrid-cell jsgrid-align-center'  style= width:6%; ><input typ='text' class='form-control text-center' disabled=disabled style='background-color:white;height:30px;'   id='rate" + slno + "' value="
              + (result[m].Price.toFixed(Decimal)) + "></td><td class= 'jsgrid-cell jsgrid-control-field jsgrid-align-center'  style=width:6%;><input typ='text' class='form-control text-center' disabled=disabled  style='background-color:white;height:30px;background-color:white'readonly onkeyup=''   id='tamnt" + slno + "' value="
              + (result[m].Total.toFixed(Decimal)) + "></td><td id='Edit" + slno + "' class= 'jsgrid-cell jsgrid-control-field jsgrid-align-center'  style= ' background-color:white;width:4%;' ><input class= 'jsgrid-button jsgrid-edit-button' style='display:none;' onclick='Editrow(" + slno + ")' id='Edit' type=button title=Edit ><input class= 'jsgrid-button jsgrid-delete-button'  style='display:none;' type= button id='delete' title= Delete onclick='rowdelete(" + slno + ")' ></td><td id='Update"
           + slno + "'  class= 'jsgrid-cell jsgrid-control-field jsgrid-align-center'  style='background-color:white;width:120px;display:none;'><input class='jsgrid-button  style='display:none;' jsgrid-update-button' onclick='Updaterow(" + slno + ")' type=button id='update' title=Update style='' ><input class='jsgrid-button jsgrid-cancel-edit-button' style='display:none;' style='display:none;' onclick='CancelEditrow(" + slno + ")' type='button' id='CancelEdit' title='Cancel edit' value='Cancel Edit' ></tr>";
            $('#tblStockTransferIn').append(ProdRow);
            $('#select_unit' + slno).val(result[m].UnitId);           
            i++;
            $('#GrandTotal').val(result[0].Total.toFixed(Decimal));
        }
    }
    //allow decimal
    function isNumber1(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        else {
            return true;
        }
    }

    function checkSTIntextempty() {
        $('#DebitAccountIn').val('');
        $('#CreditAccountIn').val('');
        $('#Comments').val('');       
        $('#ToLocationIn').val(0);
        $("#tblStockTransferIn tr").remove();
    }
    function checkexistSTInNumber() {
        if ($("#stono").val() == 0) {
            warningshow('Please Enter a Valid Product', 'stono');
        }
    }
    function checkDebitAccounttextempty(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 13 && charCode != 9) {
            $('#hiddendebit').val(0);
            $('#txtdacnt').val('');
        }
    }
    function checkCreditAccounttextempty(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 13 && charCode != 9) {
            $('#txtcacnt').val('');
            $('#hiddenCredit').val(0);
        }
    }

    

    $(document).keydown(function (e) {
        if (e.altKey && e.keyCode == 83) {  //Alt+S

            if ($("#btnsubmit").is(":disabled") == false) {
                SaveAndUpdate(1)
            }
           
           
        }
        else if (e.altKey && e.keyCode == 76) {                 //Alt+L        
            disabletext()
        }
        else if (e.altKey && e.keyCode == 67) {                  //Alt+C
            createnew();
        }
        else if (e.keyCode == 27) {                           //esc
            $('#iconForm').hide();
            $('#iconForm').hide();

        }
    });
    function datatableWithsearch(tablename, Type) {
        var a = '#' + tablename + ' tr:eq(1) th'

        $(a).each(function () {
            var title = $(this).text();
            if (title != ' ')
                if (title == 'Description' || title == 'Unit' || title == 'STONo' || title == 'Product' || title == 'Quantity' || title == 'Price' || title == 'Total' || title == 'SlNo') {
                    $(this).html('<input type="text" class="form-control"  style="width:120px"  placeholder="' + title + '"/>')
                }                
                else {
                $(this).html('<input type="text" class="form-control" style="font-weight:100"   placeholder="' + title + '"/>')
                }
        });
        var table = null;

        if (Type == 'Single') {

            table = $('#' + tablename).DataTable({
                dom: 'tipr',
                orderCellsTop: true,
                //"order": false,
            });
        }
        else if (Type == 'Multiple') {

            table = $('#' + tablename).DataTable({
                dom: 'tir',
                orderCellsTop: true,
                //"order": false,
                "pageLength": -1
            });
        }
        table.columns().every(function (index) {
            $('#' + tablename + ' thead tr:eq(1) th:eq(' + index + ') input').on('keyup change', function () {
                table.column($(this).parent().index() + ':visible')
                    .search(this.value)
                    .draw();
            });
        });
    }



    function disable_datatable(tablename) {
        $('#Warningpopup').fadeOut();
        if ($.fn.DataTable.isDataTable('#' + tablename)) {
            var table = $('#' + tablename).DataTable();
            table.destroy();
            return;
        }
    }