
var i = 1;
var editflag = 0;
var qtyflag = 0;
var copyflag = 0;
$(document).ready(function () {
    var decimail = 2;
    var a = '0.00';
    $('#GrandTotal').val(a);
    $('#ToLocation').focus();   
    serialnoload();
    AccountLoad(1);
    loadlocation();
    $('#DebitAccount').val('');
    $('#CreditAccount').val('');
    $('#Comments').val('');
    //$('#Location').prop('disabled', true);
    $('#btnaddprd').prop('disabled', false);
    $('#btnadd').prop('disabled', false);
    $('#txttotal').prop('disabled', true);
    $('#GrandTotal').prop('disabled', true);
    $('#txttotal').css('background-color', 'white');
    $('#GrandTotal').css('background-color', 'white');
    //$('#Location').css('background-color', 'white');
    $("#btnsubmit").click(function (e) {
        SaveAndUpdate(1)

    });
    
   
   
    var data = {};
    data.UnitId = 0;
    $.ajax({
        type: "POST",
        url: "../Master/UnitGetandGets",
        data: data,
        success: function (result) {
            UnitLoad(result.oList);
        }
    });

    $('#Location').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#ToLocation').focus();
        }
    });
    $('#ToLocation').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            if ($('#Location').val() == ($('#ToLocation').val())) {
                warningshow('From Location and To Location Cannot be same', 'ToLocationIn');

                return false;
            }
            else
            {
                $('#Comments').focus();
            }           
        }
    });
    $('#txtproduct0').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            if ($.trim($('#ProductId0').val() == 0) && (qtyflag == 1)) {
                warningshow('Not  Stock!', 'ProductId0');
                $('#txtproduct0').select();
                return false;
            }
        }
    });   
    $('#Comments').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#txtproduct0').focus();
        }
    });
    $('#btnok').click(function () {
        PrintthisBillWindows('StockTransferOUT', i, 'MAIN');
        alertpopuprefresh();
        formrefresh();
    });
    $('#btncnclalrt').click(function () {
        alertpopuprefresh();
        formrefresh();
    });
    $('#txtquantity').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            $('#txtrate').select();
        }
    });

    $('#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")
    });   
    $('#STODate').daterangepicker({
        minDate: minDate,
        maxDate: new Date(new Date().getFullYear(), new Date().getMonth() , new Date().getDate()),
        singleDatePicker: true,
        showDropdowns: true,
        locale: {
            format: 'DD/MM/YYYY'
        }

    });
    //$('#STODate').daterangepicker({
    //    dateFormat: 'dd/mm/yy',
    //    minDate: minDate,
    //    maxDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
    //    singleDatePicker: true,
    //    showDropdowns: true
    //});

    $('#STONo').keyup(function (e) {
        e.preventDefault();
        $('#tour1').fadeOut();
        var entrkey = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (entrkey == 8) {
            checkSTOtextempty();
        }
    });
    
});

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

    });
}
//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++) {
      
            $('#DebitAccount').val(result[k].AccCode);
            $('#hiddendebit').val(result[k].AccountId);
            $('#CreditAccount').val(result[k].CAccCode);
            $('#hiddenCredit').val(result[k].CAccountId);
            $('#txtdacnt').val(result[k].DAccountDescription);
            $('#txtcacnt').val(result[k].AccountDescription);
    }
}
//product add into grid

function productadd() {
    var rowcount = CountRows();    
    var ProductFlag = 0;
    for (p = 1; p <= i; p++) {
        if ($('#ProductId' + p).val() == $("#ProductId0").val()) {
            ProductFlag = 1;
        }
    }
    var slno = parseInt($('#slnotxt').val())
    if ($.trim($('#txtproduct0').val()) == "") {
        warningshow('Please Select Product', 'txtproduct0');
        return false;
    }   
    else if ($('#Location').val() == ($('#ToLocation').val())) {
        warningshow('From Location and To Location Cannot be same', 'ToLocationIn');
        return false;
    }
    else if ($("#ProductId0").val() == 0) {
        warningshow('Please Enter a Valid Product', 'txtproduct0');
    }
    else if ($.trim($('#txtquantity').val()) == "") {
        warningshow('Please Select Quantity', 'txtquantity');
        return false;
    }
   else  if ($.trim($('#txtquantity').val()) == 0) {
       warningshow('Quantity cannot be Zero', 'txtquantity');
       $('#txtquantity').val('');
        return false;
   }
   else if ($.trim($('#txtrate').val()) == 0) {
       warningshow('Rate cannot be Zero', 'txtrate');
       $('#txtrate').val('');
       return false;
   }
   else if ($.trim($('#select_unit0').val()) =='0') {
       warningshow('Please select Unit', 'select_unit0');
       return false;
   }
   else if ($.trim($('#ProductId0').val() == 0) && (qtyflag==1)) {
       warningshow('Not  Stock!', 'ProductId0');
       return false;
   }
   else if ($.trim($('#txtrate').val()) == '') {
       warningshow('Rate Cannot Be Null', 'txtrate');
        return false;
   }
   else if ($.trim($('#txttotal').val()) == 0) {
       warningshow('Enter Valid Rate', 'txtrate');
       $('#txtrate').select();
       return false;
   }
   else {
       if (rowcount == 0) {
           i = 1;
       }
       if (ProductFlag == 1) {
           var Res = confirm('Product Already Added! Do You Want to Continue');
           if (Res == false) {
               ClearProductRow();
               return false;
           }
       }
        var slno = parseInt(i)
        var Count = $('#tblStockTransferOut tr').length;
        var serialNo = rowcount + 1;

        var ProdRowEdit = "<tr id=" + 'row' + slno + " class= jsgrid-row ><td  id=" + 'td' + slno + " class= jsgrid-cell  style= width:4%;text-align:center >"
           + serialNo + "<input type='hidden' id='SlNo" + slno + "' value=" + Count + " ></td><td class= 'jsgrid-cell jsgrid-align-left'  style='width:6%;text-align:center' ><input type='hidden' id='ProductId" + slno + "' value='" + $('#ProductId0').val() + "'/> <input typ='text' class='form-control' disabled=disabled  style='background-color:white;height:30px;' id='txtprd" + slno + "' value='"
           + $("#txtproduct0").val() + "'>  </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='"
           + $("#Description").val() + "'> </td>  <td class= 'jsgrid-cell jsgrid-align-left' style='width:6%;' ><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-left'  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='"
           + parseInt($('#txtquantity').val()) + "'><input type='hidden' id='hiddenqty" + slno + "' value='" + parseInt($('#txtquantity').val()) + "'/>  </td><td class= 'jsgrid-cell jsgrid-align-left'  style= 'width: 6%;' ><input typ='text' class='form-control text-right' disabled=disabled style='background-color:white;height:30px;' onkeyup='tot_row(" + slno + ")'  onkeypress='isNumbercheck(event,this)'  id='rate" + slno + "' value="
           + parseFloat($('#txtrate').val() || 0).toFixed(Decimal) + "></td><td class= 'jsgrid-cell jsgrid-control-field jsgrid-align-left'  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="
           + parseFloat($('#txttotal').val() || 0).toFixed(Decimal) + "></td><td id='Edit" + slno + "' class= 'jsgrid-cell jsgrid-control-field jsgrid-align-center'  style= width:4%; ><input class= 'jsgrid-button jsgrid-edit-button' onclick='Editrow(" + slno + ")' id='Edit' type=button title=Edit ><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:4%;display:none;'><input class='jsgrid-button jsgrid-update-button' onclick='Updaterow(" + slno + ")' type=button id='update' title='Update'><input class='jsgrid-button jsgrid-cancel-edit-button' onclick='CancelEditrow(" + slno + ")' type='button' id='CancelEdit' title='Cancel edit'></tr>";

        $('#tblStockTransferOut').append(ProdRowEdit);
        $('#select_unit' + slno).val($('#select_unit0').val());
        ClearProductRow();
        grandtotal(slno);
        i++;
        $('#proddiv').animate({ scrollTop: 5000 }, 900);
        productpopuprefresh();
        $("#txtproduct0").focus();
    }
}

function UnitLoad(result) {
    $("#select_unit0").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_unit0").append(UnitSelect);   
}



var F = 1;

//find grand total of items in grid
function grandtotal(slno)
{
    var grandtot = 0;
    $('#GrandTotal').val('');
    for (var i = 1; i <=slno; i++) {               
      grandtot= grandtot+parseFloat($('#tamnt' + i).val() || 0);            
    }
    $('#GrandTotal').val(grandtot.toFixed(Decimal));  
}

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

function Updaterow(RowId) {
    var c = parseFloat($('#rate' + RowId).val());
    $('#rate' + RowId).val(isNaN(c) ? 0 : c);

    if ($('#txtqnty' + RowId).val() =='0') {
        warningshow('Quantity cannot be Zero', 'txtqnty' + RowId);
        return false;
    }
   else if ($('#txtqnty' + RowId).val() == '') {
        warningshow('Please Enter Quantity', 'txtqnty' + RowId);
        return false;
    }
    else if ($('#rate' + RowId).val() == '0') {
        warningshow('Price cannot be Zero', 'rate' + RowId);
        $('#rate' + RowId).select();
        return false;
    }
    else if ($('#rate' + RowId).val() == '') {
        warningshow('Please Enter Price', 'rate' + RowId);
        $('#rate' + RowId).select();
        return false;
    }
    else if ($('#select_unit' + RowId).val() == 0) {
        warningshow('Please select Unit', 'select_unit' + 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);
        //$('#quantity_' + RowId).prop('disabled', true);
        $('#txtqnty' + RowId).prop('disabled', true);
        $('#rate' + RowId).prop('disabled', true);
        $('#tamnt' + RowId).prop('disabled', true);
        var ratenum = parseFloat($("#rate" + RowId).val() || 0);
        $("#rate" + RowId).val(ratenum.toFixed(Decimal));
        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);
    $('#txtqnty' + RowId).prop('disabled', true);
    $('#rate' + RowId).prop('disabled', true);
    $('#tamnt' + RowId).prop('disabled', true);
    $('#select_unit' + RowId).prop('disabled', true);
    grandtotal(i);
}

//total=qty*rate
function tot() {
    var qty = parseFloat($('#txtquantity').val() || 0);
    var rate = parseFloat($('#txtrate').val() || 0);
    rate = isNaN(rate) ? 0 : rate;
    var total = parseFloat(qty * rate).toFixed(Decimal);
    $('#txttotal').val(parseFloat(total).toFixed(Decimal));
}
function tot_row(RowId) {
    if (parseFloat($('#txtqnty' + RowId).val() || 0) > parseFloat($('#hiddenqty' + RowId).val() || 0)) {
        warningshow(' Available 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);
    rate = isNaN(rate) ? 0 : rate;
    var total = parseFloat(qty * rate).toFixed(Decimal);
    $('#tamnt' + RowId).val(total).toFixed(Decimal);   
}

var LocationSelect = "";
function LocationLoad(result) {
    $("#ToLocation").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>";
    }
    $("#ToLocation").append(LocationSelect);
}

function LocationLoadUser(result) {
    $("#Location").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) {
        $("#Location").append(LocationSelect);
    }
    else {
        $("#Location").append(LocnSelect);
        $('#Location').val(UserLocationId);
    }

}

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') {
        copyflag = 1;
        for (c = 1; c <= i; c++) {
            $('#row' + c).remove();
            enablecopy();
        }       
    }
    $('#confirm').fadeOut();
}
function enablecopy()
{
    copyflag = 1;
    loadlocation();
    $('#tour1').fadeIn();
    $('#btnsubmit').prop('disabled', true);
    $('#btnlist').prop('disabled', true);
    $('#STONo').select();
    $('#ToLocation').val(0);
    $('#DebitAccount').val('');
    $('#CreditAccount').val('');
    $('#txtdacnt').val('');
    $('#txtcacnt').val('');
    $('.form-control').prop("disabled", true);
    $('#STONo').prop('disabled', false);
    $('#btnaddprd').prop('disabled', true);
    $('#btnadd').prop('disabled', true);
    $('#txttotal').prop('disabled', true);
    $('#GrandTotal').prop('disabled', true);
    $('#STONo').focus();
    $('#txttotal').css("background-color", '#ECEFF1');
    $('#GrandTotal').css("background-color", '#ECEFF1');
    //$('#Location').css('background-color', '#ECEFF1');
   // $('#Location').css('background-color', 'white');
    var a = '0.00';
    $('#GrandTotal').val(a);
}
function deleterow(RowId) {
    var sllno = 1;
    var rowslno = parseInt(sllno);
    $('#row' + RowId).remove();
    for (var j = 1; j <= i - 1; j++) {
        if ($('#txtprd' + j).val() != undefined) {
            $('#td' + j).text(sllno);
            sllno++;
        }
    }
    $('#txttotal').val('');
    grandtotal(i)
    $('#txtproduct0').focus();
}


function ClearProductRow()
{
    $('#txtproduct0').val('');   
    $('#txtquantity').val('');
    $('#txtrate').val('');    
    $('#ProductId').val('');
    $('#txttotal').val('');
    $('#select_unit0').val('0');
    $('#GrandTotal').val('');
    $('#ProductId0').val('');
    $('#hiddenquantitycheck').val('0');
}

function warningshow(message, Id) {
    $('#popupmessage').text(message);
    $('#Warningpopup').show();
    $('#' + Id).focus();
    window.setTimeout(function () {
        $('#Warningpopup').fadeOut();
    }, 3000);
}

   
//floating point
function isNumber(evt,Id) {
    $(this).val($(this).val().replace(/[^0-9\.]/g, ''));
    if (e.which != 8 && e.which != 0 && (e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
        warningshow('Digits Only')
        return false;
    }
}

//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 formrefresh() {
    if (editflag != 0) {
        warningshow('You are in Edit Mode');
    }
    else {
        copyflag = 0;
        $('#STONo').prop('disabled', true);
        $('#btnsubmit').prop('disabled', false);
        $('#btnlist').prop('disabled', false);        
        $('#STODate').prop('disabled', false);
        $('#ToLocation').prop('disabled', false);
        $('#DebitAccount').prop('disabled', false);
        $('#Comments').prop('disabled', false);
        $('#CreditAccount').prop('disabled', false);
        $('#txtproduct0').prop('disabled', false);
        $('#select_unit0').prop('disabled', false);
        $('#txtquantity').prop('disabled', false);
        $('#txtrate').prop('disabled', false);
        $('#DebitAccount').val('');
        $('#STONo').val('');      
        $('#ToLocation').val('0');
        $('#DebitAccount').val('');
        $('#CreditAccount').val('');
        $('#Comments').val('');
        $('#GrandTotal').val('');
        $('#hiddendebit').val('');
        $('#hiddenCredit').val('');        
        productpopuprefresh();
        $('#btnaddprd').prop('disabled', false);
        $('#btnadd').prop('disabled', false);
        $('#txttotal').css("background-color", 'white');
        $('#Location').prop('disabled', false);
        //$('#Location').css('background-color', 'white');
        $('#GrandTotal').css("background-color", 'white');
        $('#hiddenquantitycheck').val('0');
        var a = '0.00';
        $('#GrandTotal').val(a);        
        for (var c = 1; c < i; c++) {
            $('#row' + c).remove();
        }
        serialnoload();
        AccountLoad(1);
        loadlocation();
        $('#Location').val(UserLocationId);
        $('#STODate').val(CurDate);
        $('#ToLocation').focus();
        $('#tour1').fadeOut();
        $('#txtproduct0').val('');
        $('#txtquantity').val('');
        $('#txtrate').val('');
        $('#select_unit0').val('0');
        $('#txttotal').val('0.00');
    }
}

//save
function SaveAndUpdate(Flag) {
    rowcount = CountRows();
    if(editflag!=0)
    {
        warningshow('You are in Edit Mode');
    }
  else  if ($('#Location').val() == 0) {
      warningshow('Please Select From Location', 'Location');
      return false;
    }
    else if ($('#ToLocation').val() == 0) {
        warningshow('Please Select To Location', 'ToLocation');
        return false;
    }
    else if (($('#DebitAccount').val() != '') && ($('#hiddendebit').val() == 0)) {
        warningshow('Please Select A Valid Debit Account', 'DebitAccount');
        return false;
    }
    else if (($('#CreditAccount').val() != '') && ($('#hiddenCredit').val() == 0)) {
        warningshow('Please Select A Valid Credit Account', 'CreditAccount');
        return false;
    }   
    else if ($('#DebitAccount').val() == '') {
        warningshow('Please Select A  Debit Account', 'DebitAccount');
        return false;
    }
    else if ($('#CreditAccount').val() == "") {
        warningshow('Please Select A Credit Account', 'CreditAccount');
        return false;
    }   
    else if ($('#Location').val() == ($('#ToLocation').val())) {
        warningshow('From Location and To Location Cannot be same', 'ToLocationIn');
        return false;
    }
    else if(rowcount==0)
    {
        warningshow('No Products Added', 'txtproduct0');
        return false;
    }
    else {
        $('#btnsubmit').prop("disabled", true);
        var oArray = new Array();
        for (var k = 1; k < i; k++) {
            var ProductId = $('#ProductId' + k).val();
            var Description = $('#txtdesc' + k).val();
            var UnitId = $('#select_unit' + k).val();
            var Quantity = $('#txtqnty' + k).val();
            var Price = $('#rate' + k).val();
            var Total = $('#tamnt' + k).val();
            var FromLocation = $('#Location').val();
            var ToLocation = $('#ToLocation').val();
            var STONo = $('#STONo').val();
            var STODate = $('#STODate').val();
            var DebitAccount = $('#hiddendebit').val();
            var CreditAccount = $('#hiddenCredit').val();
            var Comments = $('#Comments').val();
            var UId = ERPUserId;
            var DeptId = ERPDeptId;
            DelFlag = 1;
            if (typeof(Description != "undefined")) {
                oArray.push({
                    'ProductId': ProductId,
                    'Description': Description,
                    'UnitId': UnitId,
                    'Quantity': Quantity,
                    'Price': Price,
                    'Total': Total,
                    'STONo': STONo,
                    'FromLocation': FromLocation,
                    'ToLocation': ToLocation,
                    'STODate': STODate,
                    'DebitAccount': DebitAccount,
                    'CreditAccount': CreditAccount,
                    'Comments': Comments,
                    'UId': UId,
                    'DeptId': DeptId,
                    'DelFlag': DelFlag
                })
            }
        }
        if (oArray != "") {
            var data = { 'StockTransferOutModel': oArray };
            $.ajax({
                type: "POST",
                url: "../../inventory/StocktransferOutInsertandUpdate",
                data: data,
                success: function (result) {
                    for (var i = 0; i < result.oList.length; i++) {
                        var status = result.oList[i].Status;
                        var Billno = result.oList[i].STONo;
                        //$('#btnsubmit').prop("disabled", false);
                        if (status != 0) {
                            Showalerts(status, Billno);                            
                        }
                        else {
                            $('#btnsubmit').prop("disabled", false);
                            $('#tblAlert tr').remove();
                            $('#alertpopup').show();
                            $('#alertdiv').show();
                            for (var i = 0; i <= result.oList.length; i++) {
                                var Prod =
                                     "<tr class='jsgrid-row'><td colspan=3><h2>Not enough quantity on Stock!</h2></td></tr>" +
                                "<tr class='jsgrid-row'><td class='jsgrid-cell jsgrid-control-field jsgrid-align-center'>ProductCode</td><td class='jsgrid-cell jsgrid-control-field jsgrid-align-center'>Description</td><td class='jsgrid-cell jsgrid-control-field jsgrid-align-center'>Quantity</td></tr>" +
                                "<tr class='jsgrid-row'>" +
                                "<td class='jsgrid-cell jsgrid-control-field jsgrid-align-center'>" + result.oList[i].ProductCode + "</td>" +
                                "<td class='jsgrid-cell jsgrid-control-field jsgrid-align-center'>" + result.oList[i].ProductDescr + "</td>" +
                                "<td class='jsgrid-cell jsgrid-control-field jsgrid-align-center'>" + result.oList[i].Quantity + "</td></tr>";
                                $('#tblAlert').append(Prod);
                                $('#btntermssave').focus();
                            }
                        }
                    }
                }
            });
        }
    }    
}


//new
function createnew() {
    if (editflag != 0) {
        warningshow('You Are In Edit Mode');
    }
    else {
        var rowcount = document.getElementById('tblStockTransferOut').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();
        }               
    }

}

function alertpopuprefresh() {
    $('#alertpopup').hide();
    $('#alertdiv').hide();
}

function Showalerts(Status,Billno) {
    if (Status == 1) {        
        //formrefresh();        
        //swal('STO Number :' + Billno ," 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();

    }
}
    



$(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        
        enablenobox()
    }
    else if (e.altKey && e.keyCode == 67) {                  //Alt+C
        createnew();
    }
    else if (e.keyCode == 27) {                           //esc    
        $('#productpopupdiv').hide();
    }
});


//copy into grid

function ShowStockTransferOutGet(result) {   
    $('#btnsubmit' ).prop('disabled',true);
        $('#Location').prop('disabled', true);
        $('#STODate').prop('disabled', true);
        $('#ToLocation').prop('disabled', true);
        $('#DebitAccount').prop('disabled', true);
        $('#Comments').prop('disabled', true);
        $('#CreditAccount').prop('disabled', true);
        $('#txtproduct0').prop('disabled', true);
        $('#select_unit0').prop('disabled', true);
        $('#txtquantity').prop('disabled', true);
        $('#txtrate').prop('disabled', true);
        $('#btnprint').show();
        $('#txtprd').val(result[0].ItemCode);
        $('#select_unit').val(result[0].UnitId);
        var Unit = result[0].UnitId;
        var description = result[0].Description;
        var rowcount = CountRows();
        if (rowcount == 0) {
            i = 1;
        }
        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  disabled 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>";
            $('#tblStockTransferOut').append(ProdRow);
            $('#select_unit' + slno).val(result[m].UnitId);
            grandtotal(slno);
            i++;
        }
}





//load STO No
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++) {
        $('#STONo').val(result[k].StockOutNo);
    }    
}

function CountRows() {
    var totalRowCount = 0;
    var rowCount = 0;
    var table = document.getElementById("tblStockTransferOut");
    var rows = table.getElementsByTagName("tr")
    for (var i = 0; i < rows.length; i++) {
        totalRowCount++;
        if (rows[i].getElementsByTagName("td").length > 0) {
            rowCount++; $('.form-control').pro
        } $('.form-control').pro
    }
    var message = "Total Row Count: " + totalRowCount;
    message += "\nRow Count: " + rowCount;
    return rowCount;
}

//copy
function enablenobox() {
    var rowcount = CountRows();
    if (editflag != 0) {
        warningshow('You are in Edit Mode');
        return false;
    }
   else 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();
   }
   
    }


function checkpdcttextempty(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 13) {
        $('#ProductId0').val(0);
        $('#select_unit0').val(0);
        $('#txtquantity').val('');
        $('#txttotal').val('');
        $('#txtrate').val('');
        productpopuprefresh();
    }
}
//validating account
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) {
        $('#hiddenCredit').val(0);
        $('#txtcacnt').val('');
    }
}
function checkSTOtextempty() {
    $('#DebitAccount').val('');
    $('#CreditAccount').val('');
    $('#Comments').val('');
    $("#tblStockTransferOut tr").remove();
}
function checkquantity()
{
    if ( parseInt($('#txtquantity').val())>parseInt($('#hiddenquantitycheck').val()) ) {
        $('#txtquantity').val('');
        warningshow(' Available Stock is:'   + $('#hiddenquantitycheck').val()+ '');
    }
}


function isNumbercheck(evt, selectedvalue) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    $(selectedvalue).val($(selectedvalue).val().replace(/[^0-9\.]/g, ''));
    if (charCode != 8 && (charCode != 46 || $(selectedvalue).val().indexOf('.') != -1) && charCode != 13 && (charCode < 48 || charCode > 57)) {
        evt.preventDefault();
        warningshow('Digits Only')
        return false;
    }
    return true;

}

function changetoupper(Id) {
    $('#' + Id).val($('#' + Id).val().toUpperCase())
}

//list product details in popup
var custstats = "Last Selling Price";


function CustPrdctLoad(result) {
    for (var n = 0; n < result.length; n++) {
        var custstat;
        if (result[n].LastSellingPrice == 0) {
            custstat = "Last Selling Price";
        }
        else {
            custstat = result[n].custstats;
        }
        $('#productpopupdiv').show();
        $('#prodheader').text('Location Stock Details');
        $('#productdiv').show();
        var strr = result[n].Locationstock;
        var strr1 = strr.replace(/&/gi, "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;");
        var strr2 = strr1.replace(/#/gi, "&emsp;");
        var strr3 = strr2.replace(/,/gi, "&nbsp;");
        var ProdRow =
               "<tr class='jsgrid-row' id='pdctrow'>" +
               "<td style='border:none;'><b>Average Cost :</b> <input type='text' disabled='' class='text-center' value=" + (parseFloat(result[n].AvgCost || 0).toFixed(Decimal)) + " style='height:30px;background-color:white;border:none'></td>" +
               "<td style='border:none;'><b>Last Purchase Cost :</b> <input type='text' disabled='' class='text-center' value=" + (parseFloat(result[n].LPCost || 0).toFixed(Decimal)) + " style='background-color:white;height:30px;border:none'></td>" +
               "<td style='border:none;'><b>" + custstat + " :</b> <input type='text' disabled='' class='text-center' value=" + (parseFloat(result[n].LastSellingPrice || 0).toFixed(Decimal)) + "  style='background-color:white;height:30px;border:none'></td>" +
               "<td style='border:none;'><b>Total Stock :</b> <input type='text' disabled='' class='text-center' value=" + (result[n].Sumtotqty || 0) + " style='background-color:white;height:30px;border:none'></td>" +
               "<td class='jsgrid-cell jsgrid-control-field jsgrid-align-center' style='display:none;width:15px'><input style='height:30px' class='jsgrid-button jsgrid-update-button' id='Update' type='button' title='Update'><input class='jsgrid-button jsgrid-cancel-edit-button' style='height:30px' type='button' id='canceledit'  title='Cancel edit'></td></tr>" +
               "<tr class='jsgrid-row' id='pdctrow1'><td colspan=4 class='text-left' style='border:none'> " + strr3 + "</td ></tr>";
        $('#tblproductdetails').append(ProdRow);
    }

}
function productpopuprefresh() {
    $('#productpopupdiv').hide();
    $('#pdctrow').remove();
    $('#pdctrow1').remove();
    $('#custlsp').hide();
}

function alertpopuprefresh(e) {
    $('#alertpopup').hide();
    $('#alertdiv').hide();

}