function setTotal(_this) {
    var service_type = $(_this).val();
    var edit_id = $('input[name="hidden_id"]').val();
    $.ajax({
        async: false,
        url: base_url + 'billing_gold_silver_offering/get_amount_by_service_id',
        type: 'POST',
        data: { service_type: service_type},
        dataType: "json"
    })
    .done(function(data) {
        
        if( parseFloat(data.amount) <= parseFloat(0) ) {
            // Disable Payment Btn
            $('#payment-btn').attr('disabled', 'disabled');
        } else {
            $('#payment-btn').removeAttr('disabled');
        }
        
        $('[name="cs_amount"], [name="pay_amount"]').val( data.amount );
    })
    .fail(function(jqXHR, status_code, error_thrown) {
        console.log(jqXHR.responseText);
    });
}

var inter = '';
$(document).on('ready', function() {
    
    $('#retrieve-dialog .reset_btn, .cancel_popup').click(function() {        
        resetAll($('#retrieve-dialog'));
        $('.p_search_by_ref').val('1');
        $('.p_search_by_con').val('0');
        $('.p_search_by_ref').iCheck('check');
        $('.resp-table').css('display','none');
        
        var reference ='';
        reference += '<option value="">-- Select Ref No --</option>';
        $('select[name="p_ref_no"]').html(reference);
        
        var contact ='';
        contact += '<option value="">-- Select Contact No --</option>';
        $('select[name="p_contact_no"]').html(contact);
    });
    
    $('input[name="cs_amount"]').keyup(function() {
        if(parseFloat($(this).val()) > 0) {
            $('#payment-btn').removeAttr('disabled');
        } else {
            $('#payment-btn').attr('disabled', 'disabled');
        }
        $('[name="pay_amount"]').val($(this).val());
    })
    
    $('select[name="fn_type"]').change(function(){
        setTotal(this);       
    });
    
    /* if($('input[name="fn_type"]').val() != '') {
        setTotal($('input[name="fn_type"]'));
    } */
    
    /* $('#sbmt-cancel-btn').on('click', function(){
        $('[name="paid_amount"], .ptype-box input').val('');
        $('#payment-btn').removeClass('dialog-btn').removeAttr('data-target');
        
    }) */
    
    $('#payment-btn').on('click', function(){
        $('[name="pay_amount"]').val($('[name="cs_amount"]').val());
        var payAmt = parseFloat( $('[name="pay_amount"]').val());
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0;
        var edit_id = $('input[name="hidden_id"]').val();
       // if(edit_id == '') {
            if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                if( paidAmt <= 0 ) {
                   $('[type="submit"]').attr('disabled', 'disabled');
                }
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }
            if( paidAmt <= 0 ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            /* $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            $('#sbmt-btn').removeAttr('disabled'); */
            if(edit_id == '') {
                $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            }
            
            if(edit_id != '') {
                var $bank_name = $('#cheque-box .hidden_bank_name').val();
                var $cheque_no = $('#cheque-box .hidden_chq_no').val();
                var $cheque_date = $('#cheque-box .hidden_chq_date').val();
                
                $('#cheque-box [name="chq_bnk_name"]').val($bank_name);
                $('#cheque-box [name="chq_no"]').val($cheque_no);
                $('#cheque-box [name="chq_date"]').val($cheque_date);
            } 
            if( edit_id != '' && parseFloat(payAmt) != parseFloat(paidAmt)) { 
                $('#sbmt-btn').attr('disabled', 'disabled');
            } else {
                $('#sbmt-btn').removeAttr('disabled');
            }

            return false;
        /* } else {
            //msgBox('Amount is already paid!','','info');
           // window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
            //}, 3500);
        } */
   });
   
    $(document).on('change', '#retrieve-dialog .p_fn_type ', function(){
        get_ref_or_contact_no(this);
    });
  
    $('input[name="p_search_by"]').on('ifChecked', function(event){
        if($(this).val() == 1) {
            $('.search_ref_no').show();
            $('.search_contact_no').hide();            
        } else if($(this).val() == 0) {
            $('.search_ref_no').hide();
            $('.search_contact_no').show();
        }
        get_ref_or_contact_no($('#retrieve-dialog .p_fn_type'));
    });
        
   $(document).on('click', '.modal .filter-btn', function(){
        if($('[name="p_fn_type"]').val() != '') {
            if($('[name="p_ref_no"]').val() != '' || $('[name="p_contact_no"]').val() != '') {
                var $appnedTo = $('#retrieve-dialog .modal-footer')
                ,   style = 'padding: 0px 2px;'
                ,   html = '';
                
                if( $appnedTo.find('#retrieve-details').length == 0 ) {
                    $appnedTo.append('<div id="retrieve-details" class="resp-table"></div>');
                }
                
                var $bookedWrapper = $appnedTo.find('#retrieve-details');
                
                $bookedWrapper.html( '<div class="col-xs-12" style="text-align: center; color: #1ba;">Please wait ...</div>' );
                
                var data = {
                    service_type: $('[name="p_fn_type"]').val(),
                    search_by: $('[name="p_search_by"]:checked').val(),
                    ref_no: $('[name="p_ref_no"]').val(),
                    contact_no: $('[name="p_contact_no"]').val()
                };
                
                $.post( base_url + controller + '/ajax/', data, function( results ){
                    results = JSON.parse( results );
                    if( results != '' ) {
                        
                        Object.keys( results ).map(function(i, iV){
                            iV = results[i];
                            var _stle = i % 2 != 0 ? 'background: rgba(17, 187, 170, 0.06);' : '';
                            $('[name="p_name"]').val(iV['name']);
                            $('[name="p_amount"]').val(iV['amount']);
                             
                            html += '<div class="col-xs-12" style="margin-top: 30px;">';

                            html +=     '<div class="col-md-2" style="'+ style +'">';
                            html +=         '<div class="form-group">';
                            html +=             '<div class="lbl"><i class="fa fa-fire"></i>Ref Id</div><div class="lbl-value" style="'+ _stle +'">'+ iV['receipt_no'] +'</div>';
                            html +=         '</div>';
                            html +=     '</div>';

                            html +=     '<div class="col-md-3" style="'+ style +'">';
                            html +=         '<div class="form-group">';
                            html +=             '<div class="lbl"><i class="fa fa-fire"></i>Type</div><div class="lbl-value" style="'+ _stle +'">'+ ( iV['service_name'] != '' ? iV['service_name'] : 'N/A' )  +'</div>';
                            html +=         '</div>';
                            html +=     '</div>';

                            html +=     '<div class="col-md-3" style="'+ style +'">';
                            html +=         '<div class="form-group">';
                            html +=             '<div class="lbl"><i class="fa fa-fire"></i>Name</div><div class="lbl-value" style="'+ _stle +';">'+ iV['name'] +'</div>';
                            html +=         '</div>';
                            html +=     '</div>';

                            html +=     '<div class="col-md-2" style="'+ style +'">';
                            html +=         '<div class="form-group">';
                            html +=             '<div class="lbl"><i class="fa fa-fire"></i>Contact  No</div><div class="lbl-value" style="'+ _stle +'">'+ iV['contact_no'] +'</div>';
                            html +=         '</div>';
                            html +=     '</div>';

                            html +=     '<div class="col-md-2" style="'+ style +'">';
                            html +=         '<div class="form-group">';
                            html +=             '<div class="lbl"><i class="fa fa-fire"></i>Amount</div><div class="lbl-value" style="'+ _stle +'; text-align: right;">'+ iV['amount'] +'</div>';
                            html +=         '</div>';
                            html +=     '</div>';

                            html += '</div>';
                        });
                        
                        

                    }else {
                        // No results
                        html += '<div class="col-xs-12" style="text-align: center; color: #1ba;">Sorry, No results found</div>';

                    }
                    
                    $bookedWrapper.fadeOut('slow', function(){
                        $(this).html(html).fadeIn('slow');
                    });

                });
           
            } else {
                msgBox('Please select Ref.No or Contact No!');
                $('[name="p_ref_no"]').focus();
                $('[name="p_contact_no"]').focus();
            }
        } else {
            msgBox('Please select Type!');
            $('[name="p_fn_type"]').focus();
        }
    });
});

function get_ref_or_contact_no(_this) {
    var service_type = $(_this).val();
    var search_by = $('input[name="p_search_by"]:checked').val();
    if(service_type != '') {
        $.ajax({
            async: false,
            url: base_url + 'billing_gold_silver_offering/get_data_by_service_type',
            type: 'POST',
            data: { service_type: service_type},
            dataType: "json"
        })
        .done(function(data) {
            if(search_by == 1) {
                var reference ='';
                reference += '<option value="">-- Select Ref No --</option>';
                for(var i in data.get_data) {
                    var ref = data.get_data[i];
                    reference += '<option value="'+ ref.receipt_no +'">'+ ref.receipt_no +'</option>';
                }
                $('select[name="p_ref_no"]').html(reference);
            } else if(search_by == 0) {
                var contact ='';
                contact += '<option value="">-- Select Contact No --</option>';
                for(var i in data.get_contact) {
                    var con = data.get_contact[i];
                    contact += '<option value="'+ con.contact_no +'">'+ con.contact_no +'</option>';
                }
                $('select[name="p_contact_no"]').html(contact);
            }
            
        })
        .fail(function(jqXHR, status_code, error_thrown) {
            console.log(jqXHR.responseText);
        });
    } else {
        var reference ='';
        reference += '<option value="">-- Select Ref No --</option>';
        $('select[name="p_ref_no"]').html(reference);
        
        var contact ='';
        contact += '<option value="">-- Select Contact No --</option>';
        $('select[name="p_contact_no"]').html(contact);
    }
}