(function () {

    $("#cm_entry_date, #search_value_entry_date, #crm_entry_date, #search_value_start_date, #search_value_end_date").datepicker({
        format: 'dd-mm-yyyy',
        todayHighlight: true,
    });

    disable_enable_background(false)
}());

// challan master
    var challan_cnt = 1;
    var item_duplicate = [];

    function get_customer_data(cust_id)
    {
    	if(cust_id != 0)
    	{

    	}
    	else
    	{
    		$("#cm_cust_id").val(0);
    		$("#cm_cust_id_flexselect").val("PLEASE SELECT");
    	}
    }

    function get_broker_data(brk_id)
    {
    	if(brk_id != 0)
    	{

    	}
    	else
    	{
    		$("#cm_broker_id").val(0);
    		$("#cm_broker_id_flexselect").val("PLEASE SELECT");
    	}
    }

    function get_diamond_data(dm_id)
    {
    	if(dm_id != 0)
    	{
    		var path        = base_url+"challan/challanctrl/get_diamond_data/"+dm_id;
            ajaxCall('POST',path,'','JSON',resp =>
            {

            	$("#dm_sh").val(resp[0]['dm_sh']);
    			$("#dm_wt").val(resp[0]['dm_wt']);
    			$("#dm_col").val(resp[0]['dm_col']);
    			$("#dm_cla").val(resp[0]['dm_cla']);
    			$("#dm_cut").val(resp[0]['dm_cut']);
    			$("#dm_pol").val(resp[0]['dm_pol']);
    			$("#dm_sym").val(resp[0]['dm_sym']);
    			$("#dm_fl").val(resp[0]['dm_fl']);
    			$("#dm_lab").val(resp[0]['dm_lab']);
                $("#dm_disc").val(resp[0]['dm_disc']);
    			$("#dm_disc").removeAttr('readonly');
                if(resp[0]['dm_rap'])
                {
                      var dm_disc = resp[0]['dm_rap'];
                      if(isNaN(dm_disc)) dm_disc = 0;
                      var dm_disc = Math.round(dm_disc);
                    $("#dm_rap").val(dm_disc);
                }
                $("#dm_dollar").val(resp[0]['dm_dollar']);
                $("#dm_ppc").val(resp[0]['dm_ppc']);
                if(resp[0]['dm_lab'] == 'IGI')
                {
                   $("#cm_notes").val('FIX PRICE BILL ONLY');
                }
                else if(resp[0]['dm_lab'] == 'GIA')
                {
                    $("#cm_notes").val('FIX PRICE NET BILL ONLY');
                }
                else
                {
                    $("#cm_notes").val('');
                }
                if(resp[0]['dm_lab'] == 'NON')
                {
                    $("#dm_cert").html('<option value="0">NO</option>');
                    $("#dm_cert").flexselect();
                    $("#dm_cert").val(0);
                    $("#dm_cert_flexselect").val('NO');
                }
                else
                {
                    $("#dm_cert").html('<option value="0">NO</option><option value="1">YES</option>');
                    $("#dm_cert").flexselect();
                    $("#dm_cert").val(0);
                    $("#dm_cert_flexselect").val('NO');
                }

    			$("#dm_disc").focus();
            },
            errmsg =>{});
    	}
    }
    
    function get_rap_amt()
    { 
        var rap = $("#dm_rap").val();
        var disc = $("#dm_disc").val();
        var wt = $("#dm_wt").val();
    
        var tot_ppc = rap * ((100 + + disc)/100);
        $("#dm_ppc").val(tot_ppc.toFixed(2));  
        
        var dollar = tot_ppc * wt;
        $("#dm_dollar").val(dollar.toFixed(2));  
    }

    function get_rap_amt_per_row(cnt)
    { 
        var rap = $("#ct_dm_rap_"+cnt).val();
        var disc = $("#ct_dm_disc_"+cnt).val();
    
        var tot_ppc = rap * ((100 + + disc)/100);
        $("#ct_dm_ppc_"+cnt).val(tot_ppc.toFixed(2));  
    }

    function add_challan_trans_row(id)
    {
        var check = 1;

        if($("#dm_id").val() == 0)
        {
            $("#dm_id_flexselect").css({'border-color':'red'});
            $("#dm_id_flexselect").addClass('shake');
            $('#dm_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#dm_id_flexselect').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#dm_id_flexselect").css({'border-color':'#757575'});
        }

        if($("#cm_entry_date").val() == '')
        {
            $("#cm_entry_date").css({'border-color':'red'});
            $("#cm_entry_date").addClass('shake');
            $('#cm_entry_date').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#cm_entry_date').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#cm_entry_date").css({'border-color':'#757575'});
        }

        if($("#cm_broker_id").val() == 0 && $("#cm_cust_id").val() == 0)
        {
            $("#cm_broker_id_flexselect").css({'border-color':'red'});
            $("#cm_broker_id_flexselect").addClass('shake');
            $('#cm_broker_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#cm_broker_id_flexselect').delay(200).removeClass('shake');
            });

            $("#cm_cust_id_flexselect").css({'border-color':'red'});
            $("#cm_cust_id_flexselect").addClass('shake');
            $('#cm_cust_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#cm_cust_id_flexselect').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#cm_broker_id_flexselect").css({'border-color':'#000'});
            $("#cm_cust_id_flexselect").css({'border-color':'#000'});
        }

        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 check_dupli_item = 0;
            if(id != 0)
            {
                var total_tr = $('#challan_material_wrapper tr').length;

                for (var i = 2; i <= total_tr; i++)
                {
                    id = $('#challan_material_wrapper tr:nth-child('+i+')').attr('id');
                    lastunderscore = id.lastIndexOf("_");
                    cnt = id.substring(lastunderscore+1);
                    item_id = $("#ct_dm_id_"+cnt).val();
                    if(item_duplicate.indexOf(item_id) < 0)
                    {
                        item_duplicate.push(item_id);
                    }
                }
            }
            var item_id = $("#dm_id").val();
            for (var i = 0; i <= item_duplicate.length; i++)
            {
                if(item_duplicate.indexOf(item_id) > -1)
                {
                    check_dupli_item = 1;
                }
            }

            if(check_dupli_item == 1)
            {
                alert("Duplicate Item Found");
            }
            else
            {
                item_duplicate.push(item_id);

                /*append row*/
                var data = '';
                data += '<tr class="floating-form" id="rowid_'+challan_cnt+'">';

                // stock id
                var item_name   = $("#dm_id option:selected").text();
                data += '<td>';
                data += '<input class="form-control floating-input" value="'+item_name+'" readonly />';
                data += '<input type="hidden" name="ct_id[]" id="ct_id_'+challan_cnt+'" value="0"/>';/*for transaction_data_update*/
                data += '<input type="hidden" name="ct_dm_id[]" id="ct_dm_id_'+challan_cnt+'" value="'+item_id+'"/>';
                data += '</td>';
                // stock id

                // diamond shape
                var dm_sh = $("#dm_sh").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_sh[]" id="ct_dm_sh_'+challan_cnt+'" value="'+dm_sh+'" readonly />';
                data += '</td>';
                // diamond shape

                // diamond weight
                var dm_wt = $("#dm_wt").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_wt[]" id="ct_dm_wt_'+challan_cnt+'" value="'+dm_wt+'" readonly />';
                data += '</td>';
                // diamond weight

                // diamond color
                var dm_col = $("#dm_col").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_col[]" id="ct_dm_col_'+challan_cnt+'" value="'+dm_col+'" readonly />';
                data += '</td>';
                // diamond color

                // diamond clarity
                var dm_cla = $("#dm_cla").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_cla[]" id="ct_dm_cla_'+challan_cnt+'" value="'+dm_cla+'" readonly />';
                data += '</td>';
                // diamond clarity

                // diamond cutting
                var dm_cut = $("#dm_cut").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_cut[]" id="ct_dm_cut_'+challan_cnt+'" value="'+dm_cut+'" readonly />';
                data += '</td>';
                // diamond cutting

                // diamond polish
                var dm_pol = $("#dm_pol").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_pol[]" id="ct_dm_pol_'+challan_cnt+'" value="'+dm_pol+'" readonly />';
                data += '</td>';
                // diamond polish

                // diamond symetry
                var dm_sym = $("#dm_sym").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_sym[]" id="ct_dm_sym_'+challan_cnt+'" value="'+dm_sym+'" readonly />';
                data += '</td>';
                // diamond symetry

                // diamond flourocent
                var dm_fl = $("#dm_fl").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_fl[]" id="ct_dm_fl_'+challan_cnt+'" value="'+dm_fl+'" readonly />';
                data += '</td>';
                // diamond flourocent

                // diamond lab
                var dm_lab = $("#dm_lab").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_lab[]" id="ct_dm_lab_'+challan_cnt+'" value="'+dm_lab+'" readonly />';
                data += '</td>';
                // diamond lab

                // diamond disc
                var dm_disc = $("#dm_disc").val();
                if(isNaN(dm_disc)) dm_disc = 0;
                // var dm_disc = Math.round(dm_disc);
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_dm_disc[]" id="ct_dm_disc_'+challan_cnt+'" value="'+dm_disc+'" readonly />';
                data += '</td>';
                // diamond disc

                 // diamond dollar
                var dm_rap = $("#dm_rap").val();
                data += '<td>';
                data += '<input type="text" class="form-control floating-input" name="ct_dm_rap[]" id="ct_dm_rap_'+challan_cnt+'" value="'+dm_rap+'" readonly />';
                data += '</td>';
                // diamond dollar

                // diamond dollar
                var dm_dollar = $("#dm_dollar").val();
                data += '<input type="hidden" class="form-control floating-input" name="ct_dollar[]" id="ct_dollar_'+challan_cnt+'" value="'+dm_dollar+'" readonly />';
                // diamond dollar

                 // diamond dollar
                var dm_ppc = $("#dm_ppc").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="ct_ppc[]" id="ct_ppc_'+challan_cnt+'" value="'+dm_ppc+'" readonly />';
                data += '</td>';
                // diamond dollar
                // certificate issue?
                var cert    = $("#dm_cert :selected").text();
                var dm_cert = $("#dm_cert").val();
                data += '<td>';
                data += '<input class="form-control floating-input" value="'+cert+'" readonly />';
                data += '<input type="hidden" name="ct_dm_cert[]" id="ct_dm_cert_'+challan_cnt+'" value="'+dm_cert+'" readonly />';
                data += '</td>';
                // certificate issue?

                // remove
                data += '<td style="text-align: center;">';
                data += '<a href="javascript:void(0)" onclick="remove_challan_trans_row('+challan_cnt+')">';
                data += '<i class="glyphicon glyphicon-trash" style="color: #dd4b39;padding-top: 9px;"></i>';
                data += '</a>';
                data += '</td>';
                //remove

                data += '</tr>';

                challan_cnt++;

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

                $("#dm_id").val(0);
    			$("#dm_id_flexselect").val("PLEASE SELECT");
    			$("#dm_sh").val('')
    			$("#dm_wt").val('')
    			$("#dm_col").val('')
    			$("#dm_cla").val('')
    			$("#dm_cut").val('')
    			$("#dm_pol").val('')
    			$("#dm_sym").val('')
    			$("#dm_fl").val('')
    			$("#dm_lab").val('')
                $("#dm_disc").val('')
    			$("#dm_disc").attr('readonly', 'readonly');
                $("#dm_rap").val('')
                $("#dm_cert").html('')
                $("#dm_cert").flexselect()
                $("#dm_cert").val('')
                $("#dm_dollar").val('')
                $("#dm_ppc").val('')
                $("#dm_cert_flexselect").val('')
    			$("#dm_id_flexselect").focus();
    			$("#sbt_btn").show();

                var cm_total_qty = parseInt($("#cm_total_qty").val());
                if (isNaN(cm_total_qty)) cm_total_qty = 0;
                var total_qty = parseInt(cm_total_qty) + parseInt(1);
                if (isNaN(total_qty)) total_qty = 0;
                $("#cm_total_qty").val(total_qty);

                var cm_total_amt = parseFloat($("#cm_total_amt").val());
                if (isNaN(cm_total_amt)) cm_total_amt = 0;
                var total_amt = parseFloat(cm_total_amt) + parseFloat(dm_rap);
                if (isNaN(total_amt)) total_amt = 0;
                $("#cm_total_amt").val(total_amt.toFixed(2));

            }
        }
    }

    function remove_challan_trans_row(remove_challan_cnt)
    {
        var cm_total_qty   	= $("#cm_total_qty").val();
        var remove_qty  	= 1;
        var total_qty      	= parseInt(cm_total_qty) - parseInt(remove_qty);
        $("#cm_total_qty").val(total_qty);


        var cm_total_amt   	= $("#cm_total_amt").val();
        var remove_amt  	= $("#ct_dm_rap_"+remove_challan_cnt).val();
        var total_amt      	= parseFloat(cm_total_amt) - parseFloat(remove_amt);
        $("#cm_total_amt").val(total_amt.toFixed(2));

        dm_id = $("#ct_dm_id_"+remove_challan_cnt).val()
        var index = item_duplicate.indexOf(dm_id);
        if (index > -1) {
          item_duplicate.splice(index, 1);
        }


        $("#rowid_"+remove_challan_cnt).detach();
        if($('#challan_material_wrapper tr').length <= 1)
        {
            $("#sbt_btn").hide();
        }
        else
        {
            $("#sbt_btn").show();
        }
    }

    function add_challan(id)
    {

     	var check = 1;

        if($("#cm_entry_date").val() == '')
        {
            $("#cm_entry_date").css({'border-color':'red'});
            $("#cm_entry_date").addClass('shake');
            $('#cm_entry_date').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#cm_entry_date').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#cm_entry_date").css({'border-color':'#000'});
        }

        if($("#cm_broker_id").val() == 0 && $("#cm_cust_id").val() == 0)
        {
            $("#cm_broker_id_flexselect").css({'border-color':'red'});
            $("#cm_broker_id_flexselect").addClass('shake');
            $('#cm_broker_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#cm_broker_id_flexselect').delay(200).removeClass('shake');
            });

            $("#cm_cust_id_flexselect").css({'border-color':'red'});
            $("#cm_cust_id_flexselect").addClass('shake');
            $('#cm_cust_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#cm_cust_id_flexselect').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#cm_broker_id_flexselect").css({'border-color':'#000'});
            $("#cm_cust_id_flexselect").css({'border-color':'#000'});
        }

        if($("#cm_total_qty").val() <= 0)
        {
            $("#cm_total_qty").css({'border-color':'red'});
            $("#cm_total_qty").addClass('shake');
            $('#cm_total_qty').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#cm_total_qty').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#cm_total_qty").css({'border-color':'#000'});
        }


        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {

            $(".btn").prop('disabled', true);
            $("#cnl_btn").attr('disabled', true);
            var path        = base_url+"challan/challanctrl/challan_insert_update/"+id;
            var form_data   = $("#challan_form").serialize();

            ajaxCall('POST',path,form_data,'JSON',resp =>
            {


                if(resp['resp'] == 1)
                {
                    if(id == 0) {
                        var msg = 'Successfully Added';
                    } else {
                        var msg = 'Successfully Updated';
                    }

                    display_alert('succ',msg);

                    $("body, html").animate({'scrollTop':0},1000);
                    window.open(base_url+"challan/challanctrl/challan_master?action=print&id="+resp['last_id'],'_blank','width=1024, height=768');

                    setInterval(function(){window.location.reload(); },2000);
                }
                else if(resp['resp'] == 2)
                {
                    var msg = 'Challan no is already exists!';
                    display_alert('err',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);
                }
                $(".btn").prop('disabled', false);
                $("#cnl_btn").removeAttr('disabled');

            },
            errmsg =>{}
            );
        }

    }
    function delete_master_item(id, path)
    {
        var ans = confirm("Are you sure? You want to delete item.");

        if(ans == true)
        {
            var update_path = base_url+"challan/challanctrl/"+path+"/"+id;

            $.ajax({
                type:'POST',
                url:update_path,
                success:resp =>
                {
                    if(resp == 2)
                    {
                        alert("You can not delete this item!");
                    }
                    else
                    {
                        $("#table_reload").load(window.location + " .table");
                        $("#count_reload").load(window.location + " #total_rows");
                        // window.location.reload();
                    }
                },
                error:resp =>{}
            });
        }
    }
// challan master

// challan return master
    var challan_return_cnt      = 1;
    var return_item_duplicate   = [];

    function get_broker_data_from_challan(cust_id)
    {
        if(cust_id != 0)
        {
            $("#dm_id").val(0);
            $("#dm_id_flexselect").val("PLEASE SELECT");
            $("#ct_id").val('')
            $("#dm_sh").val('')
            $("#dm_wt").val('')
            $("#dm_col").val('')
            $("#dm_cla").val('')
            $("#dm_cut").val('')
            $("#dm_pol").val('')
            $("#dm_sym").val('')
            $("#dm_fl").val('')
            $("#dm_lab").val('')
            $("#dm_disc").val('')
            $("#dm_rap").val('')
            $("#dm_status").html('');
            $("#dm_status").flexselect();
            $("#dm_status").val('');
            $("#dm_status_flexselect").val('');
            $("#dm_remarks").val('');
            var path = base_url+"challan/challanctrl/get_broker_data_from_challan/"+cust_id;
            ajaxCall('POST',path,'','JSON',resp =>
            {
                // populate broker drop down
                if(resp['broker_data'].length == 1)
                {
                    var broker_id   = resp['broker_data'][0]['cm_broker_id'] == '0' ? '-1' : resp['broker_data'][0]['cm_broker_id'];
                    var broker_name = resp['broker_data'][0]['cm_broker_id'] == '0' ? '-' : resp['broker_data'][0]['acc_name'];
                    $("#crm_broker_id").html("<option value='"+broker_id+"'>"+broker_name+"</option>");
                    $("#crm_broker_id").flexselect();
                    $("#crm_broker_id").val(broker_id);
                    $("#crm_broker_id_flexselect").val(broker_name);
                    $("#crm_broker_id_flexselect").focus();
                }
                else if(resp['broker_data'].length > 1)
                {
                    var data = '';

                    data += '<option value="0">PLEASE SELECT</option>';
                    $.each(resp['broker_data'], function(index, value){
                        var broker_id   = value['cm_broker_id'] == '0' ? '-1' : value['cm_broker_id'];
                        var broker_name = value['cm_broker_id'] == '0' ? '-' : value['acc_name'];
                        data += '<option value="'+broker_id+'">'+broker_name+'</option>';
                    });
                    $("#crm_broker_id").html(data);
                    $("#crm_broker_id").flexselect();
                    $("#crm_broker_id").val(0);
                    $("#crm_broker_id_flexselect").val('PLEASE SELECT');
                    $("#crm_broker_id_flexselect").focus();
                }
                else
                {
                    $("#crm_broker_id").html("<option value='0'>-</option>");
                    $("#crm_broker_id").flexselect();
                    $("#crm_broker_id").val(0);
                    $("#crm_broker_id_flexselect").val('-');
                    $("#crm_broker_id_flexselect").focus();
                }
                // populate broker drop down

                // populate through drop down
                if(resp['through_data'].length == 1)
                {
                    var through = resp['through_data'][0]['cm_through'] == '' ? '-' : resp['through_data'][0]['cm_through'];
                    $("#crm_through").html("<option value='"+through+"'>"+through+"</option>");
                    $("#crm_through").flexselect();
                    $("#crm_through").val(through);
                    $("#crm_through_flexselect").val(through);
                }
                else if(resp['through_data'].length > 1)
                {
                    var data = '';

                    data += '<option value="0">PLEASE SELECT</option>';
                    $.each(resp['through_data'], function(index, value){
                        var through = value['cm_through'] == '' ? '-' : value['cm_through'];
                        data += '<option value="'+through+'">'+through+'</option>';
                    });
                    $("#crm_through").html(data);
                    $("#crm_through").flexselect();
                    $("#crm_through").val(0);
                    $("#crm_through_flexselect").val('PLEASE SELECT');
                }
                else
                {
                    $("#crm_through").html("<option value='0'>-</option>");
                    $("#crm_through").flexselect();
                    $("#crm_through").val(0);
                    $("#crm_through_flexselect").val('-');
                    $("#crm_through_flexselect").focus();
                }
                // populate through drop down

                // populate diamond drop down
                if(resp['diamond_data'].length > 0)
                {
                    var data = '';

                    data += '<option value="0">PLEASE SELECT</option>';
                    $.each(resp['diamond_data'], function(index, value){
                        data += '<option value="'+value['dm_id']+'">'+value['dm_code']+'</option>';
                    });
                    $("#dm_id").html(data);
                    $("#dm_id").flexselect();
                    $("#dm_id").val(0);
                    $("#dm_id_flexselect").val('PLEASE SELECT');
                }
                else
                {
                    $("#dm_id").html("<option value='0'>-</option>");
                    $("#dm_id").flexselect();
                    $("#dm_id").val(0);
                    $("#dm_id_flexselect").val('-');
                }

            },
            errmsg => {}
            );
        }
        else
        {
            $("#crm_cust_id").val(0);
            $("#crm_cust_id_flexselect").val("PLEASE SELECT");

            $("#crm_broker_id").html("<option value='0'>SELECT PARTY FIRST</option>");
            $("#crm_broker_id").flexselect();
            $("#crm_broker_id").val(0);
            $("#crm_broker_id_flexselect").val('SELECT PARTY FIRST');

            $("#crm_through").html("<option value='0'>SELECT BROKER FIRST</option>");
            $("#crm_through").flexselect();
            $("#crm_through").val(0);
            $("#crm_through_flexselect").val('SELECT BROKER FIRST');

            $("#dm_id").html("<option value='0'>SELECT PARTY OR BROKER</option>");
            $("#dm_id").flexselect();
            $("#dm_id").val(0);
            $("#dm_id_flexselect").val('SELECT BROKER FIRST');

            $("#challan_return_material_wrapper").find("tr:gt(0)").remove();
        }
    }

    function get_through_data_from_challan(broker_id)
    {
        if(broker_id != 0)
        {
            $("#dm_id").val(0);
            $("#dm_id_flexselect").val("PLEASE SELECT");
            $("#ct_id").val('')
            $("#dm_sh").val('')
            $("#dm_wt").val('')
            $("#dm_col").val('')
            $("#dm_cla").val('')
            $("#dm_cut").val('')
            $("#dm_pol").val('')
            $("#dm_sym").val('')
            $("#dm_fl").val('')
            $("#dm_lab").val('')
            $("#dm_disc").val('')
            $("#dm_rap").val('')
            $("#dm_status").html('');
            $("#dm_status").flexselect();
            $("#dm_status").val('');
            $("#dm_status_flexselect").val('');
            $("#dm_remarks").val('');
            var cust_id = $("#crm_cust_id").val();
            var path = base_url+"challan/challanctrl/get_through_data_from_challan/"+broker_id+'/'+cust_id;
            ajaxCall('POST',path,'','JSON',resp =>
            {
                if(resp['through_data'].length == 1)
                {
                    var through = resp['through_data'][0]['cm_through'] == '' ? '-' : resp['through_data'][0]['cm_through'];
                    $("#crm_through").html("<option value='"+through+"'>"+through+"</option>");
                    $("#crm_through").flexselect();
                    $("#crm_through").val(through);
                    $("#crm_through_flexselect").val(through);
                    $("#crm_through_flexselect").focus();
                }
                else if(resp['through_data'].length > 1)
                {
                    var data = '';

                    data += '<option value="0">PLEASE SELECT</option>';
                    $.each(resp['through_data'], function(index, value){
                        var through = value['cm_through'] == '' ? '-' : value['cm_through'];
                        data += '<option value="'+through+'">'+through+'</option>';
                    });
                    $("#crm_through").html(data);
                    $("#crm_through").flexselect();
                    $("#crm_through").val(0);
                    $("#crm_through_flexselect").val('PLEASE SELECT');
                    $("#crm_through_flexselect").focus();
                }
                else
                {
                    $("#crm_through").html("<option value='0'>-</option>");
                    $("#crm_through").flexselect();
                    $("#crm_through").val(0);
                    $("#crm_through_flexselect").val('-');
                    $("#crm_through_flexselect").focus();
                }

                // populate diamond drop down
                if(resp['diamond_data'].length > 0)
                {
                    var data = '';

                    data += '<option value="0">PLEASE SELECT</option>';
                    $.each(resp['diamond_data'], function(index, value){
                        data += '<option value="'+value['dm_id']+'">'+value['dm_code']+'</option>';
                    });
                    $("#dm_id").html(data);
                    $("#dm_id").flexselect();
                    $("#dm_id").val(0);
                    $("#dm_id_flexselect").val('PLEASE SELECT');
                }
                else
                {
                    $("#dm_id").html("<option value='0'>-</option>");
                    $("#dm_id").flexselect();
                    $("#dm_id").val(0);
                    $("#dm_id_flexselect").val('-');
                }
            },
            errmsg =>{}
            );
        }
        else
        {
            $("#crm_broker_id").val(0);
            $("#crm_broker_id_flexselect").val("PLEASE SELECT");

            $("#crm_through").html("<option value='0'>SELECT BROKER FIRST</option>");
            $("#crm_through").flexselect();
            $("#crm_through").val(0);
            $("#crm_through_flexselect").val('SELECT BROKER FIRST');

            $("#challan_return_material_wrapper").find("tr:gt(0)").remove();
        }
    }
    function get_diamond_data_from_challan(dm_id)
    {
        if(dm_id != 0)
        {
            var path        = base_url+"challan/challanctrl/get_diamond_data/"+dm_id;
            ajaxCall('POST',path,'','JSON',resp =>
            {
                var data = '';
                $("#ct_id").val(resp[0]['ct_id']);
                $("#dm_sh").val(resp[0]['dm_sh']);
                $("#dm_wt").val(resp[0]['dm_wt']);
                $("#dm_col").val(resp[0]['dm_col']);
                $("#dm_cla").val(resp[0]['dm_cla']);
                $("#dm_cut").val(resp[0]['dm_cut']);
                $("#dm_pol").val(resp[0]['dm_pol']);
                $("#dm_sym").val(resp[0]['dm_sym']);
                $("#dm_fl").val(resp[0]['dm_fl']);
                $("#dm_lab").val(resp[0]['dm_lab']);
                $("#dm_disc").val(resp[0]['ct_dm_disc']);
                $("#dm_rap").val(resp[0]['dm_rap']);
                $("#dm_dollar").val(resp[0]['dm_dollar']);
                $("#dm_ppc").val(resp[0]['dm_ppc']);
                $("#dm_cert").val(0);
                $("#dm_cert_flexselect").val('NO');

                data += '<option value="4">Return</option>';
                data += '<option value="2">Hold</option>';
                data += '<option value="3">Sold</option>';

                $("#dm_status").html(data);
                $("#dm_status").flexselect();
                $("#dm_status").val(4);
                $("#dm_status_flexselect").val('Return');
                $("#dm_status_flexselect").focus();
            },
            errmsg =>{}
            );
        }
        else
        {
            $("#dm_id").val(0);
            $("#dm_id_flexselect").val("PLEASE SELECT");
            $("#ct_id").val('')
            $("#dm_sh").val('')
            $("#dm_wt").val('')
            $("#dm_col").val('')
            $("#dm_cla").val('')
            $("#dm_cut").val('')
            $("#dm_pol").val('')
            $("#dm_sym").val('')
            $("#dm_fl").val('')
            $("#dm_lab").val('')
            $("#dm_disc").val('')
            $("#dm_rap").val('')
            $("#dm_dollar").val('')
            $("#dm_ppc").val('')
            $("#dm_cert").val(0);
            $("#dm_cert_flexselect").val('NO');
            $("#dm_status").html('');
            $("#dm_status").flexselect();
            $("#dm_status").val('');
            $("#dm_status_flexselect").val('');
            $("#dm_remarks").val('');
        }
    }
    function add_challan_return_trans_row(id)
    {

        var check = 1;

        if($("#crm_entry_date").val() == '')
        {
            $("#crm_entry_date").css({'border-color':'red'});
            $("#crm_entry_date").addClass('shake');
            $('#crm_entry_date').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#crm_entry_date').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#crm_entry_date").css({'border-color':'#757575'});
        }

        // if($("#crm_broker_id").val() == 0 )
        // {
        //     $("#crm_broker_id_flexselect").css({'border-color':'red'});
        //     $("#crm_broker_id_flexselect").addClass('shake');
        //     $('#crm_broker_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
        //     {
        //         $('#crm_broker_id_flexselect').delay(200).removeClass('shake');
        //     });

        //     check = 0;
        // }
        // else
        // {
        //     $("#crm_broker_id_flexselect").css({'border-color':'#000'});

        // }

        if($("#crm_cust_id").val() == 0)
        {
            $("#crm_cust_id_flexselect").css({'border-color':'red'});
            $("#crm_cust_id_flexselect").addClass('shake');
            $('#crm_cust_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#crm_cust_id_flexselect').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#crm_cust_id_flexselect").css({'border-color':'#000'});
        }

        if($("#dm_id").val() == 0)
        {
            $("#dm_id_flexselect").css({'border-color':'red'});
            $("#dm_id_flexselect").addClass('shake');
            $('#dm_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#dm_id_flexselect').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#dm_id_flexselect").css({'border-color':'#757575'});
        }

        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 check_dupli_item = 0;
            if(id != 0)
            {
                var total_tr = $('#challan_return_material_wrapper tr').length;

                for (var i = 2; i <= total_tr; i++)
                {
                    id = $('#challan_return_material_wrapper tr:nth-child('+i+')').attr('id');
                    lastunderscore = id.lastIndexOf("_");
                    cnt = id.substring(lastunderscore+1);
                    item_id = $("#crt_dm_id_"+cnt).val();
                    if(return_item_duplicate.indexOf(item_id) < 0)
                    {
                        return_item_duplicate.push(item_id);
                    }
                }
            }
            var item_id = $("#dm_id").val();
            for (var i = 0; i <= return_item_duplicate.length; i++)
            {
                if(return_item_duplicate.indexOf(item_id) > -1)
                {
                    check_dupli_item = 1;
                }
            }

            if(check_dupli_item == 1)
            {
                alert("Duplicate Item Found");
            }
            else
            {
                return_item_duplicate.push(item_id);

                /*append row*/
                var data = '';
                data += '<tr class="floating-form" id="rowid_'+challan_return_cnt+'">';

                // stock id
                var item_name   = $("#dm_id option:selected").text();
                var ct_id       = $("#ct_id").val();
                data += '<td>';
                data += '<input class="form-control floating-input" value="'+item_name+'" readonly />';
                data += '<input type="hidden" name="crt_id[]" value="0"/>';/*for transaction_data_update*/
                data += '<input type="hidden" name="crt_dm_id[]" id="crt_dm_id_'+challan_return_cnt+'" value="'+item_id+'"/>';
                data += '<input type="hidden" name="ct_id[]" id="ct_id_'+challan_return_cnt+'" value="'+ct_id+'"/>';
                data += '</td>';
                // stock id

                // diamond shape
                var dm_sh = $("#dm_sh").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_sh[]" id="crt_dm_sh_'+challan_return_cnt+'" value="'+dm_sh+'" readonly />';
                data += '</td>';
                // diamond shape

                // diamond weight
                var dm_wt = $("#dm_wt").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_wt[]" id="crt_dm_wt_'+challan_return_cnt+'" value="'+dm_wt+'" readonly />';
                data += '</td>';
                // diamond weight

                // diamond color
                var dm_col = $("#dm_col").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_col[]" id="crt_dm_col_'+challan_return_cnt+'" value="'+dm_col+'" readonly />';
                data += '</td>';
                // diamond color

                // diamond clarity
                var dm_cla = $("#dm_cla").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_cla[]" id="crt_dm_cla_'+challan_return_cnt+'" value="'+dm_cla+'" readonly />';
                data += '</td>';
                // diamond clarity

                // diamond cutting
                var dm_cut = $("#dm_cut").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_cut[]" id="crt_dm_cut_'+challan_return_cnt+'" value="'+dm_cut+'" readonly />';
                data += '</td>';
                // diamond cutting

                // diamond polish
                var dm_pol = $("#dm_pol").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_pol[]" id="crt_dm_pol_'+challan_return_cnt+'" value="'+dm_pol+'" readonly />';
                data += '</td>';
                // diamond polish

                // diamond symetry
                var dm_sym = $("#dm_sym").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_sym[]" id="crt_dm_sym_'+challan_return_cnt+'" value="'+dm_sym+'" readonly />';
                data += '</td>';
                // diamond symetry

                // diamond flourocent
                var dm_fl = $("#dm_fl").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_fl[]" id="crt_dm_fl_'+challan_return_cnt+'" value="'+dm_fl+'" readonly />';
                data += '</td>';
                // diamond flourocent

                // diamond lab
                var dm_lab = $("#dm_lab").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_lab[]" id="crt_dm_lab_'+challan_return_cnt+'" value="'+dm_lab+'" readonly />';
                data += '</td>';
                // diamond lab

                // diamond disc
                var dm_disc = $("#dm_disc").val();
                if(isNaN(dm_disc)) dm_disc = 0;
                var dm_disc = Math.round(dm_disc);
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_disc[]" id="crt_dm_disc_'+challan_return_cnt+'" value="'+dm_disc+'" readonly />';
                data += '</td>';
                // diamond disc

                // diamond rapnet
                var dm_rap = $("#dm_rap").val();
                data += '<td>';
                data += '<input type ="text" class="form-control floating-input" name="crt_dm_rap[]" id="crt_dm_rap_'+challan_return_cnt+'" value="'+dm_rap+'" readonly />';
                data += '</td>';
                // diamond rapnet
                // diamond dollar
                var dm_dollar = $("#dm_dollar").val();

                data += '<input type="hidden" class="form-control floating-input" name="crt_dollar[]" id="crt_dollar_'+challan_return_cnt+'" value="'+dm_dollar+'" readonly />';



                var dm_ppc = $("#dm_ppc").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_ppc[]" id="crt_ppc_'+challan_return_cnt+'" value="'+dm_ppc+'" readonly />';
                data += '</td>';


                // diamond status
                var dm_status   = $("#dm_status").val();
                var status      = $("#dm_status option:selected").text();
                data += '<td>';
                data += '<input class="form-control floating-input" value="'+status+'" readonly />';
                data += '<input type="hidden" name="crt_dm_status[]" id="crt_dm_status_'+challan_return_cnt+'" value="'+dm_status+'"/>';
                data += '</td>';
                // diamond status

                // diamond certificate
                var dm_cert   = $("#dm_cert").val();
                var cert      = $("#dm_cert option:selected").text();
                data += '<td>';
                data += '<input class="form-control floating-input" value="'+cert+'" readonly />';
                data += '<input type="hidden" name="crt_dm_cert[]" id="crt_dm_cert_'+challan_return_cnt+'" value="'+dm_cert+'"/>';
                data += '</td>';
                // diamond certificate

                // diamond remarks
                var dm_remarks = $("#dm_remarks").val();
                data += '<td>';
                data += '<input class="form-control floating-input" name="crt_dm_remarks[]" id="crt_dm_remarks_'+challan_return_cnt+'" value="'+dm_remarks+'" readonly />';
                data += '</td>';
                // diamond remarks

                // remove
                data += '<td style="text-align: center;">';
                data += '<a href="javascript:void(0)" onclick="remove_challan_return_trans_row('+challan_return_cnt+')">';
                data += '<i class="glyphicon glyphicon-trash" style="color: #dd4b39;padding-top: 9px;"></i>';
                data += '</a>';
                data += '</td>';
                //remove

                data += '</tr>';

                challan_return_cnt++;

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

                $("#dm_id").val(0);
                $("#dm_id_flexselect").val("PLEASE SELECT");
                $("#ct_id").val('')
                $("#dm_sh").val('')
                $("#dm_wt").val('')
                $("#dm_col").val('')
                $("#dm_cla").val('')
                $("#dm_cut").val('')
                $("#dm_pol").val('')
                $("#dm_sym").val('')
                $("#dm_fl").val('')
                $("#dm_lab").val('')
                $("#dm_disc").val('')
                $("#dm_rap").val('')
                $("#dm_dollar").val('')
                $("#dm_ppc").val('')
                $("#dm_status").html('')
                $("#dm_status").flexselect()
                $("#dm_status").val('')
                $("#dm_status_flexselect").val('')
                $("#dm_cert").val(0)
                $("#dm_cert_flexselect").val('NO')
                $("#dm_remarks").val('')
                $("#dm_id_flexselect").focus();
                $("#sbt_btn").show();

                var crm_total_qty = parseInt($("#crm_total_qty").val());
                if (isNaN(crm_total_qty)) crm_total_qty = 0;
                var total_qty = parseInt(crm_total_qty) + parseInt(1);
                if (isNaN(total_qty)) total_qty = 0;
                $("#crm_total_qty").val(total_qty);

                var crm_total_amt = parseFloat($("#crm_total_amt").val());
                if (isNaN(crm_total_amt)) crm_total_amt = 0;
                var total_amt = parseFloat(crm_total_amt) + parseFloat(dm_rap);
                if (isNaN(total_amt)) total_amt = 0;
                $("#crm_total_amt").val(total_amt.toFixed(2));

            }
        }
    }
    function remove_challan_return_trans_row(remove_challan_cnt)
    {
        var crm_total_qty   = $("#crm_total_qty").val();
        var remove_qty      = 1;
        var total_qty       = parseInt(crm_total_qty) - parseInt(remove_qty);
        $("#crm_total_qty").val(total_qty);


        var crm_total_amt   = $("#crm_total_amt").val();
        //var remove_amt      = $("#ct_dm_rap_"+remove_challan_cnt).val();
        var remove_amt      = $("#crt_dm_rap_"+remove_challan_cnt).val();
        var total_amt       = parseFloat(crm_total_amt) - parseFloat(remove_amt);
        $("#crm_total_amt").val(total_amt.toFixed(2));

        dm_id = $("#crt_dm_id_"+remove_challan_cnt).val()
        var index = return_item_duplicate.indexOf(dm_id);
        if (index > -1) {
          return_item_duplicate.splice(index, 1);
        }


        $("#rowid_"+remove_challan_cnt).detach();
        if($('#challan_return_material_wrapper tr').length <= 1)
        {
            $("#sbt_btn").hide();
        }
        else
        {
            $("#sbt_btn").show();
        }
    }
    function add_challan_return(id)
    {

        var check = 1;

        if($("#crm_entry_date").val() == '')
        {
            $("#crm_entry_date").css({'border-color':'red'});
            $("#crm_entry_date").addClass('shake');
            $('#crm_entry_date').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#crm_entry_date').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#crm_entry_date").css({'border-color':'#000'});
        }

        // if($("#crm_broker_id").val() == 0 && $("#crm_cust_id").val() == 0)
        // {
        //     $("#crm_broker_id_flexselect").css({'border-color':'red'});
        //     $("#crm_broker_id_flexselect").addClass('shake');
        //     $('#crm_broker_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
        //     {
        //         $('#crm_broker_id_flexselect').delay(200).removeClass('shake');
        //     });

        //     $("#crm_cust_id_flexselect").css({'border-color':'red'});
        //     $("#crm_cust_id_flexselect").addClass('shake');
        //     $('#crm_cust_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
        //     {
        //         $('#crm_cust_id_flexselect').delay(200).removeClass('shake');
        //     });
        //     check = 0;
        // }
        // else
        // {
        //     $("#crm_broker_id_flexselect").css({'border-color':'#000'});
        //     $("#crm_cust_id_flexselect").css({'border-color':'#000'});
        // }

        if($("#crm_total_qty").val() <= 0)
        {
            $("#crm_total_qty").css({'border-color':'red'});
            $("#crm_total_qty").addClass('shake');
            $('#crm_total_qty').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
            {
                $('#crm_total_qty').delay(200).removeClass('shake');
            });
            check = 0;
        }
        else
        {
            $("#crm_total_qty").css({'border-color':'#000'});
        }


        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {
            $(".btn").prop('disabled', true);
            $("#cnl_btn").attr('disabled', true);
            var path        = base_url+"challan/challanctrl/challan_return_insert_update/"+id;
            var form_data   = $("#challan_return_form").serialize();

            ajaxCall('POST',path,form_data,'JSON',resp =>
            {


                if(resp['resp'] == 1)
                {
                    if(id == 0) {
                        var msg = 'Successfully Added';
                    } else {
                        var msg = 'Successfully Updated';
                    }

                    display_alert('succ',msg);

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

                    setInterval(function(){window.location.reload(); },2000);
                }
                else if(resp['resp'] == 2)
                {
                    var msg = 'Return no is already exists!';
                    display_alert('err',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);
                }
                $(".btn").prop('disabled', false);
                $("#cnl_btn").removeAttr('disabled');

            },
            errmsg =>{}
            );
        }

    }
// challan return master