$(document).ready(function(){

    $("#st_date, #sl_date").datepicker({
        format: 'dd-mm-yyyy'
    });

    $("#gvc_sbt_btn").prop('disabled', false);
});
/************************************ Calculation ************************************/



function set_dis_amt()
{
    var pro_weight = parseFloat($("#pro_weight").val());
    if(isNaN(pro_weight)) pro_weight = 0;
    pro_weight = pro_weight.toFixed(2);

    var pro_rate = parseFloat($("#pro_rate").val());
    if(isNaN(pro_rate)) pro_rate = 0;
    pro_rate = pro_rate.toFixed(2); 

    var pro_disc_per = parseFloat($("#pro_disc_per").val());
    if(isNaN(pro_disc_per)) pro_disc_per = 0;
    pro_disc_per = pro_disc_per.toFixed(2);
    
    var pro_disc_amt = (pro_weight * pro_rate) - ((pro_weight * pro_rate) * (pro_disc_per/100));
    pro_disc_amt = pro_disc_amt.toFixed(2);

    $("#pro_disc_amt").val(pro_disc_amt);

    set_cash_dis_amt();
    set_cash_dis_per();        
}

function set_dis_per()
{
    var pro_weight = parseFloat($("#pro_weight").val());
    if(isNaN(pro_weight)) pro_weight = 0;
    pro_weight = pro_weight.toFixed(2);

    var pro_rate = parseFloat($("#pro_rate").val());
    if(isNaN(pro_rate)) pro_rate = 0;
    pro_rate = pro_rate.toFixed(2);

    var pro_disc_amt = parseFloat($("#pro_disc_amt").val());
    if(isNaN(pro_disc_amt)) pro_disc_amt = 0;
    pro_disc_amt = pro_disc_amt.toFixed(2);

    var dis_per = 100 - (pro_disc_amt / (pro_weight * pro_rate) * 100);        
    if(isNaN(dis_per)) dis_per = 0;
    dis_per = dis_per.toFixed(2)

    $("#pro_disc_per").val(dis_per);

    set_cash_dis_amt();
    set_cash_dis_per();
}

function set_cash_dis_amt()
{
    var pro_disc_amt = parseFloat($("#pro_disc_amt").val());
    if(isNaN(pro_disc_amt)) pro_disc_amt = 0;
    pro_disc_amt = pro_disc_amt.toFixed(2);

    var pro_cash_disc_per = parseFloat($("#pro_cash_disc_per").val());
    if(isNaN(pro_cash_disc_per)) pro_cash_disc_per = 0;
    pro_cash_disc_per = pro_cash_disc_per.toFixed(2);
    
    var pro_cash_disc_amt = pro_disc_amt - (pro_cash_disc_per/100 * pro_disc_amt);
    pro_cash_disc_amt = pro_cash_disc_amt.toFixed(2);

    $("#pro_cash_disc_amt").val(pro_cash_disc_amt);

    set_less_amt();
    set_less_per();     
}

function set_cash_dis_per()
{
    var pro_disc_amt = parseFloat($("#pro_disc_amt").val());
    if(isNaN(pro_disc_amt)) pro_disc_amt = 0;
    pro_disc_amt = pro_disc_amt.toFixed(2);

    var pro_cash_disc_amt = parseFloat($("#pro_cash_disc_amt").val());
    if(isNaN(pro_cash_disc_amt)) pro_cash_disc_amt = 0;
    pro_cash_disc_amt = pro_cash_disc_amt.toFixed(2);

    var dis_cash_per = 100 - (pro_cash_disc_amt / pro_disc_amt * 100);        
    if(isNaN(dis_cash_per)) dis_cash_per = 0;
    dis_cash_per = dis_cash_per.toFixed(2)

    $("#pro_cash_disc_per").val(dis_cash_per);

    set_less_amt();
    set_less_per();
}

function set_less_amt()
{
    var pro_cash_disc_amt = parseFloat($("#pro_cash_disc_amt").val());
    if(isNaN(pro_cash_disc_amt)) pro_cash_disc_amt = 0;
    pro_cash_disc_amt = pro_cash_disc_amt.toFixed(2); 

    var dollar_rate = parseFloat($("#pro_dollar_rate").val());
    if(isNaN(dollar_rate) || dollar_rate == 0) dollar_rate = 1;
    dollar_rate = dollar_rate.toFixed(2);

    var less_per = parseFloat($("#pro_less_per").val());
    if(isNaN(less_per)) less_per = 0;
    less_per = less_per.toFixed(2);

    var total = pro_cash_disc_amt * dollar_rate;

    var less_amt = (total * (less_per/100));
    less_amt = less_amt.toFixed(2);

    var total_amt = total - less_amt;
    total_amt = total_amt.toFixed(2);

    $("#pro_less_amt").val(less_amt);
    $("#pro_total").val(total_amt);        

    if(less_amt == 0.000){

        set_total();
    }
}

function set_less_per()
{
    var pro_cash_disc_amt = parseFloat($("#pro_cash_disc_amt").val());
    if(isNaN(pro_cash_disc_amt)) pro_cash_disc_amt = 0;
    pro_cash_disc_amt = pro_cash_disc_amt.toFixed(2); 

    var dollar_rate = parseFloat($("#pro_dollar_rate").val());
    if(isNaN(dollar_rate) || dollar_rate == 0) dollar_rate = 1;
    dollar_rate = dollar_rate.toFixed(2);

    var less_amt = parseFloat($("#pro_less_amt").val());
    if(isNaN(less_amt)) less_amt = 0;
    less_amt = less_amt.toFixed(2);    

    var total = pro_cash_disc_amt * dollar_rate;

    var total_amt = total - less_amt;
    total_amt = total_amt.toFixed(2);

    var less_per = less_amt / total * 100;        
    //alert(less_per);
    if(isNaN(less_per)) less_per = 0;
    less_per = less_per.toFixed(2);

    $("#pro_less_per").val(less_per);
    $("#pro_total").val(total_amt);     

    if(less_amt == 0.000){

        set_total();
    }
}

function set_total()
{
    
    var pro_cash_disc_amt = parseFloat($("#pro_cash_disc_amt").val());
    if(isNaN(pro_cash_disc_amt)) pro_cash_disc_amt = 0;
    pro_cash_disc_amt = pro_cash_disc_amt.toFixed(2); 

    var dollar_rate = parseFloat($("#pro_dollar_rate").val());
    if(isNaN(dollar_rate) || dollar_rate == 0) dollar_rate = 1;
    dollar_rate = dollar_rate.toFixed(2);

    var total = (pro_cash_disc_amt * dollar_rate);
    total = total.toFixed(2);

    $("#pro_total").val(total);
}


/************************************ Row Operation ************************************/

var pro_cnt = 1;
var total_amt = 0;
var broker_amt = 0;
function add_pro_row(type)
{
    var check = 1;

    if($("#pro_dm_id").val() == 0)
    {
        $("#pro_dm_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#pro_dm_id").css({
            'border-color':'#CCC'
        });
    }

    if(parseFloat($("#pro_weight").val()) == 0 || $("#pro_weight").val() == "")
    {
        $("#pro_weight").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#pro_weight").css({
            'border-color':'#CCC'
        });
    }

    if(parseInt($("#pro_rate").val()) == 0 || $("#pro_rate").val() == "")
    {
        $("#pro_rate").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#pro_rate").css({
            'border-color':'#CCC'
        });
    }

    if(parseInt($("#pro_total").val()) == 0 || $("#pro_total").val() == "")
    {
        $("#pro_total").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#pro_total").css({
            'border-color':'#CCC'
        });
    }

    if(check == 1)
    {
        var id = $("#pro_dm_id").val();

        if(type == "purchase")
            var path = base_url+"cmaster/get_daimond/"+id;   
        else    
            var path = base_url+"cmaster/get_stock_data/"+id;   

        $("#loading").show();
        $.ajax({
            type:'POST',
            url:path,
            dataType:'json',
            success:function(resp)
            {
                //console.log(resp);

                var weight = $("#pro_weight").val();
                var rate = $("#pro_rate").val();
                var disc_amt = $("#pro_disc_amt").val();
                var disc_per = $("#pro_disc_per").val();
                var disc_cash_amt = $("#pro_cash_disc_amt").val();
                var disc_cash_per = $("#pro_cash_disc_per").val();
                var dollar_rate = $("#pro_dollar_rate").val();

                if(type != "purchase")
                {
                    var less_per = $("#pro_less_per").val();
                    var less_amt = $("#pro_less_amt").val();
                }

                var total = parseFloat($("#pro_total").val());
                var broker = parseFloat($("#pro_less_amt").val());

                total_amt = total_amt + total;
                broker_amt = broker_amt + broker;

                var data = '';

                data += '<tr id="rowid_'+pro_cnt+'">';

                    data += '<td>';

                if(type == "purchase")
                {
                    data += '<input type="text" class="form-control" value="'+resp[0]['dm_name']+'" readonly/>';
                    data += '<input type="hidden" name="tr_dm_id[]" class="form-control" value="'+id+'"/>';
                    // data += '<input type="hidden" name="sale_status[]" class="form-control" value="0"/>';
                }
                else
                {
                    data += '<input type="text" class="form-control" value="'+resp[0]['se_dm_barcode']+'" readonly/>';
                    data += '<input type="hidden" name="tr_se_id[]" class="form-control" value="'+id+'"/>';
                    data += '<input type="hidden" name="sale_status[]" class="form-control" value="1"/>';
                }
                    data += '</td>';
                    
                    data += '<td>';
                    data += '<input type="text" name="tr_weight[]" class="form-control" value="'+weight+'" readonly/>';
                    data += '</td>';
                    
                    data += '<td>';
                    data += '<input type="text" name="tr_rate[]" class="form-control" value="'+rate+'"   readonly/>';
                    data += '</td>';
                    
                    data += '<td>';
                    data += '<input type="text" name="tr_disc_per[]" class="form-control" value="'+disc_per+'" readonly/>';
                    data += '<input type="text" name="tr_disc_amt[]" class="form-control" value="'+disc_amt+'" readonly/>';
                    data += '</td>';
                    
                    data += '<td>';
                    data += '<input type="text" name="tr_cash_disc_per[]" class="form-control" value="'+disc_cash_per+'" readonly/>';
                    data += '<input type="text" name="tr_cash_disc_amt[]" class="form-control" value="'+disc_cash_amt+'" readonly/>';
                    data += '</td>';
                    
                    data += '<td>';
                    data += '<input type="text" name="tr_dollar_rate[]" class="form-control" value="'+dollar_rate+'" readonly/>';
                    data += '</td>';

                if(type != "purchase")
                {
                    data += '<td>';
                    data += '<input type="text" name="tr_less_per[]" class="form-control" value="'+less_per+'" readonly/>';
                    data += '<input type="text" name="tr_less_amt[]" class="form-control" value="'+less_amt+'" id="less_total_'+pro_cnt+'" readonly/>';
                    data += '</td>';
                }

                    data += '<td>';
                    data += '<input type="text" name="tr_total[]" class="form-control" value="'+total+'" id="pro_total_'+pro_cnt+'" readonly/>';
                    data += '</td>';

                if(type == "purchase")
                {
                    data += '<td style="text-align:right;"><button type="button" class="btn btn-danger" onClick="remove_pro_row('+pro_cnt+',  \'purchase\', 0)">Remove</button></td>';
                }
                else
                {
                    data += '<td style="text-align:right;"><button type="button" class="btn btn-danger" onClick="remove_pro_row('+pro_cnt+', \'sale\','+id+')">Remove</button></td>';
                }
                data += '</tr>';

                pro_cnt++;

                $("#material_wrapper").append(data);
                // $("#final_total").html("<b>Total: </b>"+total_amt);
                $("#sl_total").val(total_amt);
                $("#sl_broker_amt").val(broker_amt);

                $("#loading").hide();

                $("#pro_weight").val("");
                $("#pro_rate").val("");
                $("#pro_disc_per").val("");
                $("#pro_disc_amt").val("");
                $("#pro_cash_disc_per").val("");
                $("#pro_cash_disc_amt").val("");
                $("#pro_total").val("");

                if(type == "sale")
                {
                    $("#pro_less_per").val("");
                    $("#pro_less_amt").val("");
                    add_sale_temp(id, 'add');
                }
            },
            error:function(resp){
                console.log(resp);
            }   
        });
    }   
}

function remove_pro_row(id_cnt, type, id)
{
    var pro_total = parseFloat($("#pro_total_"+id_cnt).val());

    var less_total = parseFloat($("#less_total_"+id_cnt).val());

    total_amt = total_amt - pro_total;

    broker_amt = broker_amt - less_total;

    $("#rowid_"+id_cnt).detach();

    // $("#final_total").html("<b>Total: </b>"+total_amt);
    $("#sl_total").val(total_amt);
    $("#sl_broker_amt").val(broker_amt);

    pro_cnt--;

    if(type == "sale")
    {
        add_sale_temp(id, 'sub');
    }
}

/********************************* Purchase Master *********************************/

function add_stock(id)
{
    
    var check = 1;

    if(pro_cnt < 2)
    {
        $("#pro_dm_id, #pro_weight, #pro_rate, #pro_disc_per, #pro_disc_amt, #pro_cash_disc_per, #pro_cash_disc_amt, #pro_dollar_rate, #pro_total").css({
            'border-color':'red'
        });
        check = 0;   
    }
    else{

        $("#pro_dm_id, #pro_weight, #pro_rate, #pro_disc_per, #pro_disc_amt, #pro_cash_disc_per, #pro_cash_disc_amt, #pro_dollar_rate, #pro_total").css({
            'border-color':'#aaa'
        });   
    }
    if($("#st_supp_id").val() == 0)
    {
        $("#st_supp_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#st_supp_id").css({
            'border-color':'#CCC'
        });
    }

    if($("#st_broker_id").val() == 0)
    {
        $("#st_broker_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#st_broker_id").css({
            'border-color':'#CCC'
        });
    }

    if(check == 0)
    {
        var msg = 'Oh snap ! You forgot to enter some information';
        display_alert('err',msg);

        $("body, html").animate({
            'scrollTop':0
        },1000);
    }
    else
    {
        document.getElementById("sbt_btn").disabled = true;
        var path = base_url+"cmaster/stock_insert/"+id;   
        var form_data = $("#stock_form").serialize();

        $("#loading").show();
        $.ajax({
            type:'POST',
            url:path,
            data:form_data,
            success:function(resp)
            {
                alert(resp);
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully Added';
                    }
                    else
                    {
                        var msg = 'Successfully Updated';
                    }   
                    display_alert('succ',msg);

                    $("body, html").animate({
                        'scrollTop':0
                    },1000); 
                }
                else
                {
                    var msg = 'Unknown error! Please try again later.';
                    display_alert('warn',msg);

                    $("body, html").animate({
                        'scrollTop':0
                    },1000); 
                }

                $("#loading").hide();
            },
            error:function(resp){
                console.log(resp);
            }   
        });
    }   
}

function set_due_date(type)
{   
    if(type == 'purchase')
    {
        var due_days = parseInt($("#st_due_days").val());
        if(isNaN(due_days)) due_days = 0;

        var st_date = new Date($("#st_date").datepicker("getDate"));
    }
    else
    {
        var due_days = parseInt($("#sl_due_days").val());
        if(isNaN(due_days)) due_days = 0;

        var st_date = new Date($("#sl_date").datepicker("getDate"));   
    }

    if(st_date != "Invalid Date" && due_days != 0)
    {
        due_date = new Date();
        due_date.setDate(st_date.getDate()+due_days);
        
        due_date = $.format.date(due_date, 'dd-MM-yyyy');
        
        if(type == 'purchase')
            $("#st_due_date").val(due_date);
        else
            $("#sl_due_date").val(due_date);
    }
    else
    {
        if(type == 'purchase')
            $("#st_due_date").val("");
        else
            $("#sl_due_date").val("");
    }        
}

function set_due_date_purchase()
{   
    var due_days = parseInt($("#st_due_days").val());
    if(isNaN(due_days)) due_days = 0;

    var st_date = new Date($("#st_date").datepicker("getDate"));


    if(st_date != "Invalid Date" && due_days != 0)
    {
        due_date = new Date();
        due_date.setDate(st_date.getDate()+due_days);
        
        due_date = $.format.date(due_date, 'dd-MM-yyyy');
        
        $("#st_due_date").val(due_date);

    }
    else
    {
        $("#st_due_date").val("");   
    }        
}

function set_due_date_sale()
{   
    var due_days = parseInt($("#sl_due_days").val());
    if(isNaN(due_days)) due_days = 0;

    var sl_date = new Date($("#sl_date").datepicker("getDate"));


    if(sl_date != "Invalid Date" && due_days != 0)
    {
        due_date = new Date();
        due_date.setDate(sl_date.getDate()+due_days);
        
        due_date = $.format.date(due_date, 'dd-MM-yyyy');
        
        $("#sl_due_date").val(due_date);

    }
    else
    {
        $("#sl_due_date").val("");   
    }        
}

function view_stock(st_id)
{
    var path = base_url+"cmaster/get_stock/"+st_id;  

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        dataType:'json',
        success:function(resp)
        {
            var data = "";
            var cnt = 1;
            data += '<table class="table table-bordered">';
            
            data += '<tr>';
            data += '<th>#</th>';
            data += '<th>Daimond</th>';
            data += '<th>weight</th>';
            data += '<th>Rep Rate</th>';
            data += '<th>Discount</th>';
            data += '<th>Cash Discount</th>';
            data += '<th>Dollar Rate</th>';
            //data += '<th>Less</th>';
            data += '<th>Total</th>';
            data += '</tr>';

            $.each(resp, function(index, value){

                data += '<tr>';
                data += '<td>'+cnt+'</td>';
                data += '<td>'+value['dm_name']+'</td>';
                data += '<td>'+value['tr_weight']+'</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_rate']+'</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_disc_amt']+'('+value['tr_disc_per']+' %)</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_cash_disc_amt']+'('+value['tr_cash_disc_per']+' %)</td>';
                data += '<td>'+value['tr_dollar_rate']+'</td>';
                //data += '<td><i class="fa fa-inr"></i> '+value['tr_less_amt']+'('+value['tr_less_per']+' %)</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_total']+'</td>';
                data += '</tr>';   

                cnt++;             
            });

            data += '</table>';

            $(".modal-body").html(data);
            $(".modal-title").html("Stock Details");

            var sbt_btn = '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';  

            $(".modal-footer").html(sbt_btn);

            $("#popup_modal_lg").modal('show'); 
            $("#loading").hide();
        },
        error:function(resp){
            console.log(resp);
        }   
    });
}

function view_stock_entry(st_id)
{
    var path = base_url+"cmaster/get_stock_entry/"+st_id;  

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        dataType:'json',
        success:function(resp)
        {
            var data = "";
            var cnt = 1;
            data += '<table class="table table-bordered">';
            
            data += '<tr>';
            data += '<th>#</th>';
            data += '<th>Daimond</th>';
            data += '<th>Barcode</th>';
            data += '<th>weight</th>';
            data += '<th>Rep Rate</th>';
            data += '<th>Discount</th>';
            data += '<th>Cash Discount</th>';
            data += '<th>Dollar Rate</th>';
            //data += '<th>Less</th>';
            data += '<th>Total</th>';
            data += '</tr>';

            $.each(resp, function(index, value){

                data += '<tr>';
                data += '<td>'+cnt+'</td>';
                data += '<td>'+value['dm_name']+'</td>';
                data += '<td>'+value['se_dm_barcode']+'</td>';
                data += '<td>'+value['se_weight']+'</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['se_rate']+'</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['se_disc_amt']+'('+value['se_disc_per']+' %)</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['se_cash_disc_amt']+'('+value['se_cash_disc_per']+' %)</td>';
                data += '<td>'+value['se_dollar_rate']+'</td>';
                //data += '<td><i class="fa fa-inr"></i> '+value['se_less_amt']+'('+value['se_less_per']+' %)</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['se_total']+'</td>';
                data += '</tr>';   

                cnt++;             
            });

            data += '</table>';

            $(".modal-body").html(data);
            $(".modal-title").html("Stock Entry Details");

            var sbt_btn = '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';  

            $(".modal-footer").html(sbt_btn);

            $("#popup_modal_lg").modal('show'); 
            $("#loading").hide();
        },
        error:function(resp){
            console.log(resp);
        }   
    });
}

/********************************* Sale Master *********************************/

function get_stock_data()
{
    var se_id = $("#pro_dm_id").val();

    var path = base_url+"cmaster/get_stock_data/"+se_id;  

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        dataType:'json',
        success:function(resp)
        {
            if(resp.length != 0)
            {
                $("#pro_weight").val(resp[0]['se_weight']);
                $("#pro_rate").val(resp[0]['se_rate']);
                $("#pro_disc_per").val(resp[0]['se_disc_per']);
                $("#pro_disc_amt").val(resp[0]['se_disc_amt']);
                $("#pro_cash_disc_per").val(resp[0]['se_cash_disc_per']);
                $("#pro_cash_disc_amt").val(resp[0]['se_cash_disc_amt']);
                $("#pro_dollar_rate").val(resp[0]['se_dollar_rate']);
                $("#pro_less_per").val(resp[0]['se_less_per']);
                $("#pro_less_amt").val(resp[0]['se_less_amt']);
                $("#pro_total").val(resp[0]['se_total']);
            }
            else
            {
                $("#pro_weight").val("");
                $("#pro_rate").val("");
                $("#pro_disc_per").val("");
                $("#pro_disc_amt").val("");
                $("#pro_cash_disc_per").val("");
                $("#pro_cash_disc_amt").val("");
                $("#pro_dollar_rate").val("");
                $("#pro_less_per").val("");
                $("#pro_less_amt").val("");
                $("#pro_total").val("");   
            }

            $("#loading").hide();
        },
        error:function(resp){

            console.log(resp);
        }   
    });
}

function add_sale_temp(id, type)
{
    var path = base_url+"cmaster/set_sale_temp/"+id+'/'+type;  

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        success:function(resp)
        {
            $("#loading").hide();
            reset_pro_dropdown();
        },
        error:function(resp){

            console.log(resp);
        }   
    });
}

function reset_pro_dropdown()
{
    var path = base_url+"cmaster/reset_pro_dropdown";  

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        dataType:'json',
        success:function(resp)
        {
            var data = '';

            if(resp.length != 0)
            {
                data += '<option value="0">Please select</option>';

                $.each(resp, function(index, value){

                    data += '<option value="'+value['se_id']+'">'+value['se_dm_barcode']+'</option>';
                });
            }
            else
            {
                data += '<option value="0">No data!</option>';                
            }

            $("#pro_dm_id").html(data);

            $("#pro_weight").val("");
            $("#pro_rate").val("");
            $("#pro_disc_per").val("");
            $("#pro_disc_amt").val("");
            $("#pro_cash_disc_per").val("");
            $("#pro_cash_disc_amt").val("");
            $("#pro_dollar_rate").val("");
            $("#pro_less_per").val("");
            $("#pro_less_amt").val("");
            $("#pro_total").val("");  

            $("#loading").hide();
        },
        error:function(resp){

            console.log(resp);
        }   
    });
}

function add_sale(id)
{
    var check = 1;

    if(pro_cnt < 2)
    {
        $("#pro_se_id, #pro_weight, #pro_rate, #pro_disc_per, #pro_disc_amt, #pro_cash_disc_per, #pro_cash_disc_amt, #pro_dollar_rate, #pro_less_per, #pro_less_amt, #pro_total").css({
            'border-color':'red'
        });
        check = 0;   
    }
    else{

        $("#pro_se_id, #pro_weight, #pro_rate, #pro_disc_per, #pro_disc_amt, #pro_cash_disc_per, #pro_cash_disc_amt, #pro_dollar_rate, #pro_less_per, #pro_less_amt, #pro_total").css({
            'border-color':'#aaa'
        });   
    }
    if($("#sl_cust_id").val() == 0)
    {
        $("#sl_cust_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#sl_cust_id").css({
            'border-color':'#CCC'
        });
    }

    if($("#sl_broker_id").val() == 0)
    {
        $("#sl_broker_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#sl_broker_id").css({
            'border-color':'#CCC'
        });
    }

    if(check == 0)
    {
        var msg = 'Oh snap ! You forgot to enter some information';
        display_alert('err',msg);

        $("body, html").animate({
            'scrollTop':0
        },1000);
    }
    else
    {
        var path = base_url+"cmaster/sale_insert/"+id;   
        var form_data = $("#sale_form").serialize();

        $("#loading").show();
        $.ajax({
            type:'POST',
            url:path,
            data:form_data,
            success:function(resp)
            {
                // alert(resp);
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully Added';
                    }
                    else
                    {
                        var msg = 'Successfully Updated';
                    }   
                    display_alert('succ',msg);

                    $("body, html").animate({
                        'scrollTop':0
                    },1000); 
                }
                else
                {
                    var msg = 'Unknown error! Please try again later.';
                    display_alert('warn',msg);

                    $("body, html").animate({
                        'scrollTop':0
                    },1000); 
                }

                $("#loading").hide();
            },
            error:function(resp){
                console.log(resp);
            }   
        });
    }   
}

function view_sale_products(sl_id)
{
    var path = base_url+"cmaster/get_sale_products/"+sl_id;  

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        dataType:'json',
        success:function(resp)
        {
            console.log(resp);
            var data = "";
            var cnt = 1;
            data += '<table class="table table-bordered">';
            
            data += '<tr>';
            data += '<th>#</th>';
            data += '<th>Daimond</th>';
            data += '<th>weight</th>';
            data += '<th>Rep Rate</th>';
            data += '<th>Discount</th>';
            data += '<th>Cash Discount</th>';
            data += '<th>Dollar Rate</th>';
            data += '<th>Less</th>';
            data += '<th>Total</th>';
            data += '</tr>';

            $.each(resp, function(index, value){

                data += '<tr>';
                data += '<td>'+cnt+'</td>';
                data += '<td>'+value['se_dm_barcode']+'</td>';
                data += '<td>'+value['tr_weight']+'</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_rate']+'</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_disc_amt']+'('+value['tr_disc_per']+' %)</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_cash_disc_amt']+'('+value['tr_cash_disc_per']+' %)</td>';
                data += '<td>'+value['tr_dollar_rate']+'</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_less_amt']+'('+value['tr_less_per']+' %)</td>';
                data += '<td><i class="fa fa-inr"></i> '+value['tr_total']+'</td>';
                data += '</tr>';   

                cnt++;             
            });

            data += '</table>';

            $(".modal-body").html(data);
            $(".modal-title").html("Sale Products");

            var sbt_btn = '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';  

            $(".modal-footer").html(sbt_btn);

            $("#popup_modal_lg").modal('show'); 
            $("#loading").hide();
        },
        error:function(resp){
            console.log(resp);
        }   
    });
}

/********************************* Voucher Master *********************************/

function get_party_by_grp(){

    var ledger = $("#vc_grp_id").val();

    var path = base_url+"creport/get_party_by_ledger";
            
    $("#loading").show();  
    $.ajax({
        type:'GET',
        url:path,
        data:'ledger='+ledger,
        dataType:'json',
        success:function(resp)
        {
            var data = '';

            data += '<option value="0">Please select</option>';
            $.each(resp, function(index, value){

                data += '<option value="'+value['acc_id']+'">'+value['acc_name']+'</option>';
            });

            $("#vc_party_id").html(data);

            $("#loading").hide();
        },
        error:function(resp)
        {
            console.log(resp);
        }
    }); 
}

function get_party_list()
{
    $("#vc_payment_status").val(0);

    var grp_id = $("#vc_grp_id").val().split("-")[0];

    var path = base_url+"cmaster/get_party_list";   

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        data:'grp_id='+grp_id,
        dataType:'json',
        success:function(resp)
        {
            //console.log(resp);
            var data = '';

            if(resp.length != 0)
            {   
                data += '<option value="0">Please select</option>';

                $.each(resp, function(index, value){

                    data += '<option value="'+value['acc_id']+'-'+value['acc_name']+'">'+value['acc_name']+'</option>';
                });
            }
            else
            {
                data += '<option value="0">No data</option>';
            }

            $("#vc_party_id").html(data);
            $("#loading").hide();
        },
        error:function(resp){
            console.log(resp);
        }   
    });
}

function add_voucher(id)
{
    var check = 1;

    var acc_id = $("#vc_cash_acc_id").val().split("-")[0];

    if($("#vc_voucher_type").val() == 0)
    {
        $("#vc_voucher_type").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_voucher_type").css({
            'border-color':'#CCC'
        });
    }

    if(acc_id == 0)
    {
        $("#vc_cash_acc_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_cash_acc_id").css({
            'border-color':'#CCC'
        });
    }

    if($("#vc_ledger_type").val() == 0)
    {
        $("#vc_ledger_type").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_ledger_type").css({
            'border-color':'#CCC'
        });
    }

    if($("#vc_party_id").val() == 0)
    {
        $("#vc_party_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_party_id").css({
            'border-color':'#CCC'
        });
    }

    if($("#vc_amount").val() == 0)
    {
        $("#vc_amount").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_amount").css({
            'border-color':'#CCC'
        });
    }

    if(check == 0)
    {
        var msg = 'Oh snap ! You forgot to enter some information';
        display_alert('err',msg);

        $("body, html").animate({
            'scrollTop':0
        },1000);
    }
    else
    {     
        
        var path = base_url+"cmaster/voucher_insert/"+id;   
        var form_data = $("#voucher_form").serialize();

        $("#loading").show();
        $.ajax({
            type:'POST',
            url:path,
            data:form_data,
            success:function(resp)
            {
                alert(resp);
                if(resp == 1)
                {
                    if(id == 0)
                    {
                        var msg = 'Successfully added!';
                        display_alert('succ',msg);

                        $("html body").animate({
                            'scrollTop':0
                        },1000);

                    }
                    else
                    {
                        var msg = 'Successfully updated!';
                        display_alert('succ',msg);  

                        $("html body").animate({
                            'scrollTop':0
                        },1000);
                    }
                }
                else
                {
                    var msg = 'Unknown Error ! Please try again letter';
                    display_alert('warn',msg);

                    $("html body").animate({
                        'scrollTop':0
                    },1000);
                }
                $("#loading").hide();
            },
            error:function(resp){
                console.log(resp);
            }   
        });
    }
}

function get_party_payment_status()
{

    var party_id = $("#vc_party_id").val().split("-")[0];

    var path = base_url+"cmaster/get_party_payment_status/"+party_id;  

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        dataType:'json',
        success:function(resp)
        {
            $("#vc_payment_status").val(resp['status']);
            $("#loading").hide();
        },
        error:function(resp){

            console.log(resp);
        }   
    });
}

/******************************** General Voucher Row Operation ********************************/

var vc_cnt = 1;
function add_voucher_row()
{
    var check = 1;

    if($("#vc_grp_id").val() == 0)
    {
        $("#vc_grp_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_grp_id").css({
            'border-color':'#CCC'
        });
    }

    if($("#vc_party_id").val() == 0)
    {
        $("#vc_party_id").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_party_id").css({
            'border-color':'#CCC'
        });
    }

    if($("#vc_amount").val() == 0)
    {
        $("#vc_amount").css({
            'border-color':'red'
        });
        check = 0;
    }
    else
    {
        $("#vc_amount").css({
            'border-color':'#CCC'
        });
    }

    if(check == 1)
    {

        var grp_id = $("#vc_grp_id").val().split("-")[0];
        var grp_name = $("#vc_grp_id").val().split("-")[1];
        var acc_id = $("#vc_party_id").val().split("-")[0];  
        var acc_name = $("#vc_party_id").val().split("-")[1];
        var amt = $("#vc_amount").val();
        var trans_type = $("#vc_trans_type").val();
        var notes = $("#vc_notes").val();

        var data = '';

        data += '<tr id="rowid_'+vc_cnt+'">';

        data += '<td>';
        data += '<input type="hidden" name="vc_grp_id[]" class="form-control" value="'+grp_id+'" readonly />';
        data += '<input type="text" class="form-control" value="'+grp_name+'" readonly />';
        data += '</td>';
        data += '<td>';
        data += '<input type="hidden" name="vc_cash_acc_id[]" class="form-control" value="'+acc_id+'"/>';
        data += '<input type="text" class="form-control" value="'+acc_name+'" readonly />';
        data += '</td>';
        data += '<td>';
        data += '<input type="text" name="vc_amount[]" class="form-control" value="'+amt+'" id="amtid_'+vc_cnt+'" readonly />';
        data += '</td>';
        data += '<td>';
        data += '<input type="text" name="vc_trans_type[]" class="form-control" value="'+trans_type+'" readonly />';
        data += '</td>';
        data += '<td>';
        data += '<input type="text" name="vc_notes[]" class="form-control" value="'+notes+'" readonly />';
        data += '</td>';
        data += '<td>';
        data += '<button type="button" class="btn btn-danger" onClick="remove_voucher_row('+vc_cnt+')">Remove</button>';
        data += '</td>';

        data += '</tr>';

        vc_cnt++;

        $("#voucher_table").append(data);

        set_total_blc();

        $("#loading").hide();
    }   
}

function remove_voucher_row(id_cnt)
{
    $("#rowid_"+id_cnt).detach();

    vc_cnt--;

    if(vc_cnt < 2){

        $("#gvc_sbt_btn").prop('disabled', true);
    }
    else{

        $("#gvc_sbt_btn").prop('disabled', false);   
    }

    set_total_blc();
}

function set_total_blc(){

    var total_amt = 0;
    var total_dr_amt = 0;
    var total_cr_amt = 0;
    var amt_arr = [];
    var type_arr = [];
    $.each($('input[name="vc_amount[]"]'), function(index, value){

        var amt = parseInt($(this).val());

        amt_arr[index] = amt;
    });

    $.each($('input[name="vc_trans_type[]"]'), function(index, value){

        type_arr[index] = $(this).val();
    });

    $.each(amt_arr, function(index, value){

        if(type_arr[index] == "DR")
            total_dr_amt = total_dr_amt + value;
        else
            total_cr_amt = total_cr_amt + value;
    });

    total_amt = total_dr_amt - total_cr_amt;

    if(total_amt != 0){

        $("#gvc_sbt_btn").prop('disabled', true);
    }
    else{

        $("#gvc_sbt_btn").prop('disabled', false);   
    }

    $("#total_blc").html(total_amt);
}

function add_gvoucher(id)
{    
    var path = base_url+"cmaster/gvoucher_insert/"+id;   
    var form_data = $("#gvoucher_form").serialize();

    $("#loading").show();
    $.ajax({
        type:'POST',
        url:path,
        data:form_data,
        success:function(resp)
        {
            if(resp == 1)
            {
                if(id == 0)
                {
                    var msg = 'Successfully added!';
                    display_alert('succ',msg);

                    $("html body").animate({
                        'scrollTop':0
                    },1000);

                }
                else
                {
                    var msg = 'Successfully updated!';
                    display_alert('succ',msg);  

                    $("html body").animate({
                        'scrollTop':0
                    },1000);
                }
            }
            else
            {
                var msg = 'Unknown Error ! Please try again letter';
                display_alert('warn',msg);

                $("html body").animate({
                    'scrollTop':0
                },1000);
            }
            $("#loading").hide();
        },
        error:function(resp){
            console.log(resp);
        }   
    });
}

/********************************* status Master *********************************/

    function add_update_status_popup(status_id)
    {
        var data = '';                      
        data += '<div class="alert_msg"></div>';                      
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="status_form">';
        
        data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Status Name</label><div class="col-sm-9"><input type="text" name="status_name" class="form-control" id="status_name"></div></div>';

        data += '<div class="form-group"><label for="inputEmail3" class="col-sm-3 control-label">Status Name</label><div class="col-sm-9">';
        data += '<select name="status_type" class="form-control" id="status_type">';
                data += '<option value="1">ACTIVE</option>';
                data += '<option value="2">INACTIVE</option>';
                data += '</select></div></div>';

        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);

        var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';  
        
        if(status_id == 0){

            sbt_btn += '<button type="button" class="btn btn-success" onClick="add_status(0)">Submit</button>';

            $(".modal-title-sm").html("Add Status");
        }
        else
        {

            var update_path = base_url+"admin/cmaster/get_single_status/"+status_id;
            
            $.ajax({
                type:'POST',
                url:update_path,
                dataType:'json',
                success:function(resp)
                {
                    $("#status_name").val(resp[0]['status_name']);
                    $("#status_type").val(resp[0]['status_type']);

                },
                error:function(resp)
                {
                    console.log(resp);
                }
            });

            sbt_btn += '<button type="button" class="btn btn-success" onClick="add_status('+status_id+')">Submit</button>';

            $(".modal-title-sm").html("Update Status");
        }

        $(".modal-footer-sm").html(sbt_btn);

        $("#loading").hide();
        $("#popup_modal_sm").modal('show');  
    }

    function add_status(id)
    {

        var check = 1;

        if($("#status_name").val() == '')
        {
            $("#status_name").css({
                'border-color':'red'
            });
            check = 0;
        }
        else
        {
            $("#status_name").css({
                'border-color':'#CCC'
            });
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert('err',msg);

            $("body, html").animate({
                'scrollTop':0
            },1000);
        }
        else
        {     
            
            var path = base_url+"admin/cmaster/status_insert/"+id;   
            var form_data = $("#status_form").serialize();
            
            console.log(path);

            $("#loading").show();
            $.ajax({
                type:'POST',
                url:path,
                data:form_data,
                success:function(resp)
                {
                    console.log(resp);
                    if(resp == 1)
                    {
                        if(id == 0)
                        {
                            var msg = 'Successfully added!';
                            display_alert('succ',msg);

                            $("#status_form")[0].reset();

                            $("#popup_modal_sm").animate({
                                'scrollTop':0
                            },1000);

                        }
                        else
                        {
                            var msg = 'Successfully updated!';
                            display_alert('succ',msg);  

                            $("#popup_modal_sm").animate({
                                'scrollTop':0
                            },1000);
                        }
                    }
                    else if(resp == 2)
                    {
                        var msg = 'Status is already exists!';
                        display_alert('err',msg);

                        $("#popup_modal_sm").animate({
                            'scrollTop':0
                        },1000);
                    }
                    else
                    {
                        var msg = 'Database Error ! Please try again letter';
                        display_alert('warn',msg);

                        $("#popup_modal_sm").animate({
                            'scrollTop':0
                        },1000);
                    }
                    $("#loading").hide();
                },
                error:function(resp){
                    console.log(resp);
                }   
            });
        }
    }

/********************************* status Master End *********************************/

/*********************** staff Master *********************************/

    function add_update_staff_popup(staff_id)
    {
        var data = '';                      
        data += '<div class="alert_msg"></div>';                      
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="staff_form">';
        
        data += '<div class="form-group"><label for="inputEmail3" class="col-sm-4 control-label">Name of Employee</label><div class="col-sm-8"><input type="text" name="staff_name" class="form-control" id="staff_name"></div></div>';
        
        data += '<div class="form-group"><label for="inputEmail3" class="col-sm-4 control-label">Academic Qualification</label><div class="col-sm-8"><input type="text" name="staff_qualification" class="form-control" id="staff_qualification"></div></div>';
        
        
        data += '<div class="form-group"><label for="inputEmail3" class="col-sm-4 control-label">Professional Qualification</label><div class="col-sm-8"><input type="text" name="staff_prof_qualification" class="form-control" id="staff_prof_qualification"></div></div>';
                
                
        data += '<div class="form-group"><label for="inputEmail3" class="col-sm-4 control-label">Designation</label><div class="col-sm-8">';
        data += '<select name="staff_designation" class="form-control" id="staff_designation">';
                data += '<option value="0">Please Select</option>';
                data += '<option value="1">Principal</option>';
                data += '<option value="2">Asst. Teacher</option>';
                data += '<option value="3">Lab Asst</option>';
                data += '<option value="4">Librarian</option>';
                data += '</select></div></div>';
                
        data += '<div class="form-group"><label for="inputEmail3" class="col-sm-4 control-label">Status</label><div class="col-sm-8">';
        data += '<select name="staff_type" class="form-control" id="staff_type">';
                data += '<option value="1">ACTIVE</option>';
                data += '<option value="2">INACTIVE</option>';
                data += '</select></div></div>';

        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);

        var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';  
        
        if(staff_id == 0){

            sbt_btn += '<button type="button" class="btn btn-success" onClick="add_staff(0)">Submit</button>';

            $(".modal-title-sm").html("Add Staff");
        }
        else
        {

            var update_path = base_url+"admin/cmaster/get_single_staff/"+staff_id;
            
            $.ajax({
                type:'POST',
                url:update_path,
                dataType:'json',
                success:function(resp)
                {
                    $("#staff_name").val(resp[0]['staff_name']);
                    $("#staff_qualification").val(resp[0]['staff_qualification']);
                    $("#staff_prof_qualification").val(resp[0]['staff_prof_qualification']);
                    $("#staff_designation").val(resp[0]['staff_designation']);
                    $("#staff_type").val(resp[0]['staff_type']);

                },
                error:function(resp)
                {
                    console.log(resp);
                }
            });

            sbt_btn += '<button type="button" class="btn btn-success" onClick="add_staff('+staff_id+')">Submit</button>';

            $(".modal-title-sm").html("Update Staff");
        }

        $(".modal-footer-sm").html(sbt_btn);

        $("#loading").hide();
        $("#popup_modal_sm").modal('show');  
    }

    function add_staff(id)
    {

        var check = 1;

        if($("#staff_name").val() == '')
        {
            $("#status_name").css({
                'border-color':'red'
            });
            check = 0;
        }
        else
        {
            $("#staff_name").css({
                'border-color':'#CCC'
            });
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert('err',msg);

            $("body, html").animate({
                'scrollTop':0
            },1000);
        }
        else
        {     
            
            var path = base_url+"admin/cmaster/staff_insert/"+id;   
            var form_data = $("#staff_form").serialize();
            
            console.log(path);

            $("#loading").show();
            $.ajax({
                type:'POST',
                url:path,
                data:form_data,
                success:function(resp)
                {
                    console.log(resp);
                    if(resp == 1)
                    {
                        if(id == 0)
                        {
                            var msg = 'Successfully added!';
                            display_alert('succ',msg);

                            $("#staff_form")[0].reset();

                            $("#popup_modal_sm").animate({
                                'scrollTop':0
                            },1000);

                        }
                        else
                        {
                            var msg = 'Successfully updated!';
                            display_alert('succ',msg);  

                            $("#popup_modal_sm").animate({
                                'scrollTop':0
                            },1000);
                        }
                    }
                    else if(resp == 2)
                    {
                        var msg = 'Staff is already exists!';
                        display_alert('err',msg);

                        $("#popup_modal_sm").animate({
                            'scrollTop':0
                        },1000);
                    }
                    else
                    {
                        var msg = 'Database Error ! Please try again letter';
                        display_alert('warn',msg);

                        $("#popup_modal_sm").animate({
                            'scrollTop':0
                        },1000);
                    }
                    $("#loading").hide();
                },
                error:function(resp){
                    console.log(resp);
                }   
            });
        }
    }

/********************************* status Master End *********************************/
