var reset_total = false;
function calculate_difference() {
    //if(!reset_total) {
        $('.amtShow').attr('type','hidden');
        $('.amtHide').attr('type','text');
        var cs_amount = $('[name="cs_amount"]').val();
        var hidden_amount = parseFloat($('[name="hidden_amount"]').val());
        var total_diff = hidden_amount - parseFloat(cs_amount)  ;
        $('[name="cs_amount"]').val((hidden_amount).toFixed(2));
        reset_total = true;
        $('[name="cs_amount"]').attr('data-diff-amt',total_diff);
    //}
}

function setTotal() {
    // Calculate Prasadam Total
    var edit_id = $('input[name="hidden_id"]').val();
    var book_status = $('input[name="book_status"]').val();
    if(edit_id == '') {
        var total = parseFloat( $('[name="fn_type"] option:selected').attr('data-amt') );
    } else {
        var total = parseFloat( $('[name="fn_type"]').attr('data-amt') );
    }
    $('.stotal').each(function(i, iKey){
        var value = parseFloat( $(this).val() ) || 0;
        //console.log( 'Sub :' + value );
        
        total += parseFloat( value );
    });
    
    var csAmt = parseFloat($('[name="cs_amount"]').val()) || "";
    if( total > 0 || csAmt != '' ) {
        $('#payment-btn').removeAttr('disabled');
    }else {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');
    }

    if($('[name="cs_amount"]').attr('data-diff-amt') !== undefined)  {
        var diff = parseFloat($('[name="cs_amount"]').attr('data-diff-amt')) || 0;
        total += diff;
    }
    $('[name="cs_amount"]').val( total.toFixed(2) );
}

var inter = '';
$(document).on('ready', function() {
    
    $('#pr_item').change(function(){
        var sellpricetxt = $(this).find(':selected').data('sellprice');
        $('#pr_price').val(sellpricetxt);
    });
    
    $('#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_devotee_name"]').html(reference);
        
        var contact ='';
        contact += '<option value="">-- Select Contact No --</option>';
        $('select[name="p_contact_no"]').html(contact);
    });
    
    $('#booked-dialog .reset-btn').click(function() {
        // No results
        html = '<div class="col-xs-12" style="text-align: center; color: #1ba;">Sorry, No results found</div>';
        $('#booked-details').html(html).fadeIn('slow');
    });
    
    $('input[name="cs_amount"]').keyup(function() {
        var value = $(this).val() || "";
        if( value != "" ) {
            $('#payment-btn').removeAttr('disabled');
        }else {
            $('#payment-btn').attr('disabled', 'disabled');
        }
        $('[name="hidden_amount"]').val(value);
    });
    
    $('#payment-btn').on('click', function(){
        var edit_id = $('input[name="hidden_id"]').val();
        if(reset_total || (edit_id == '' || edit_id == undefined)) {
            $('[name="pay_amount"]').val($('input[name="cs_amount"]').val());
        } else {
            $('[name="pay_amount"]').val($('input[name="hidden_amount"]').val());
        }
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 || payAmt != paidAmt ? true : false;
        
        var already_paid_amt = ($('input[name="hidden_amount"]').val() !== undefined) ? $('input[name="hidden_amount"]').val() : 0;
        var cs_amount = $('input[name="cs_amount"]').val();
        
        var book_status = $('input[name="book_status"]').val();
        //if((parseFloat(already_paid_amt) < parseFloat(cs_amount)) || (edit_id == '' && (book_status == '' || book_status == 1))) {
        if((edit_id == '' && (book_status == '' || book_status == 1))) {
            if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            
            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            $('#sbmt-btn').removeAttr('disabled');
            return false;
        } /* else if((parseFloat(already_paid_amt) > parseFloat(cs_amount)) && (edit_id != '' && book_status == 1)) {
            var paying_amt = parseFloat(already_paid_amt) - parseFloat(cs_amount);
            msgBox('Amount ' + ((parseFloat(paying_amt)).toFixed(2)) + ' is Refunded!','','info');
            window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
            }, 3500);
        
        } */ else if(edit_id != '' && book_status == 2) {
           if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            $('#sbmt-btn').removeAttr('disabled');
            return false;
        
        
        } else {
            if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', '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(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);
        } */
    })
    
    $('.payment-btn').on('click', function(){
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 || payAmt != paidAmt ? true : false;
        
        if( autoValidate()) {
            return true;
        }
        
        return false;
    })
    
    $('[name="fn_type"]').on('change', function(){
        var value = $(this).val();
        if( value == '' ) {
            $('#prasadam-btn').fadeOut('slow');
        }else {
            $('#prasadam-btn').fadeIn('slow');
        }
        
        setTotal();
    });
    
    
    // Prasadam
    $(document).on('click', '.details-row .ctrl.edit-btn, .details-row .ctrl.rm-btn, .cancel-rw-edit', function(){
        
        var $wrapper = $(this).parent().closest('.modal')
        ,   $footer = $wrapper.find('.modal-footer');
        
        if( $(this).hasClass('cancel-rw-edit') ) {
            // Cancel Editing Row
            var $row = $wrapper.find('.editing');
            
            var edit_id = $('[name="hidden_id"]').val();
            if(edit_id != ""){
                var sbqty_new = $('#pr_item').find(':selected').data('sbqty');
                var row_qty = $row.find('.data-c input').val();
                var sbqty = parseFloat(sbqty_new) + parseFloat(row_qty);
                var qty = $('#pr_qty').val();
                if(parseFloat(sbqty)<parseFloat(qty)) {
                msgBox("Given quantity must be less than currently available quantity("+sbqty+")");
                return false;
                }
            } else {
                var sbqty = $('#pr_item').find(':selected').data('sbqty');
                var qty = $('#pr_qty').val();
                if(parseFloat(sbqty)<parseFloat(qty)) {
                msgBox("Given quantity must be less than currently available quantity("+sbqty+")");
                return false;
                }
            }
            
            $row.removeClass('editing');
            $wrapper.find('.details td.ctrls *').fadeIn('slow');
            $footer.find('.new-btn').fadeIn('slow');
            
            if( $(this).hasClass('save') ) {
                // Update Row
                $(this).removeClass('cancel-rw-edit save').addClass('save-btn');
                
                var price = $('#pr_price').val()
                ,   qty   = $('#pr_qty').val()
                ,   sTotal = (qty*price).toFixed(2);
                
                $row.find('.data-a input').val( $('#pr_item').val() );
                $row.find('.data-a span').html( $('#pr_item option:selected').text() );
                
                $row.find('.data-c input').val( qty );
                $row.find('.data-c span').html( qty );
                
                $row.find('.data-d input').val( price );
                $row.find('.data-d span').html( price );
                
                
                $row.find('.data-e input').val( sTotal );
                $row.find('.data-e span').html( sTotal );
                
            }
            
            
            // Clear fields
            $('#pr_item, #pr_qty, #pr_price').val('');
                       
            $footer.find('.cancel-rw-edit').addClass('cancel_popup').attr('data-dismiss', 'modal').removeClass('cancel-rw-edit');
            
        }else {
            var $row = $(this).parent().closest('.details-row');
            
            if( $(this).hasClass('rm-btn') ) {
                // Delete Row
                
                if( window.confirm("Are you sure want to remove..?") ) {
                    $row.fadeOut('slow', function(){
                        $(this).addClass('remove-me');//remove();
                        
                        var len = $('.details-row').not('.details-row.remove-me').length
                        ,   $saveBtn = $wrapper.find('.modal-footer .save-btn');
                        $saveBtn.find('span').html( ' ('+ len +')' );

                        /*if( len > 0 ) {
                            $saveBtn.removeAttr('disabled');
                        }else {
                            $saveBtn.attr('disabled', 'disabled');
                        }*/
                        
                        if( $wrapper.find('.details .details-row').length == 0 ) {
                            $wrapper.find('.details').fadeOut('slow');
                        }
                        
                    });
                }
                
                return false;
                
            }else {
            
                // Edit Row
                $row.addClass('editing');
                $wrapper.find('.details td.ctrls *').fadeOut('slow');
                $footer.find('.new-btn').fadeOut('slow');
                $footer.find('.save-btn').addClass('cancel-rw-edit save').removeClass('save-btn');
                $footer.find('.cancel_popup').removeClass('cancel_popup').removeAttr('data-dismiss').addClass('cancel-rw-edit');

                $('#pr_item').val( $row.find('.data-a input').val());
                $('#pr_qty').val( $row.find('.data-c input').val());
                $('#pr_price').val( $row.find('.data-d input').val());
            }    
        }
        add_desc();
    });
    
    $('#booked-dialog .reset_btn').click(function() {        
        //resetAll($('#booked-dialog'));
        alert('test');
        // No results
        html = '<div class="col-xs-12" style="text-align: center; color: #1ba;">Sorry, No results found</div>';
        $(this).html(html).fadeIn('slow');
    });
    
    $(document).on('click', '.new-btn, .save-btn', function() {
        
        var $this    = $(this)  
        ,   $wrapper = $this.parent().closest('.modal')
        ,   $body    = $wrapper.find('.modal-footer')   
        ,   html     = ''
        ,   isOk    = autoValidate( $wrapper ) ? true : false
        ,   isSaveOk    = $this.hasClass('save-btn') ? true : false;
        
        var edit_id = $('[name="hidden_id"]').val();
        
        if( isOk && $('.new-btn').attr('data-trigger') != 'yes' ) {
            var sbqty = $('#pr_item').find(':selected').data('sbqty');
            var qty = $('#pr_qty').val();
            if(parseFloat(sbqty)<parseFloat(qty)) {
            msgBox("Given quantity must be less than currently available quantity("+sbqty+")");
            return false;
            }
        }

        if( isOk || ( isOk && $this.hasClass('save-btn') && $('#prasadam-dialog .details-row').length == 0 ) ) {
            
        
            if( $body.find('.details').length == 0 ) {
                var table = '<table class="details">';
                    table += '<tr>';
                    table += '<th>Item</th><th>Quantity</th><th>Price</th><th>Sub Total</th>';
                   
                    table += '<th>Action</th>';
                  
                    table += '</tr>';
                    table += '</table>';
                $body.append(table);
            }

            $body.find('.details').slideDown('slow');

            var price   = $('#pr_price').val()
            ,   qty     = $('#pr_qty').val()
            ,   sTotal  = (qty*price).toFixed(2)
            ,   dbId    = $('#pr_item').attr('data-db-id') || ""
                key    = $('.data-a').length;
            

            html += '<tr class="details-row" style="display: none; border-bottom: 2px solid #fff;" data-strings="' + $('#pr_item option:selected').val() + '">';
                if( dbId != '' ) {
                    
                    html += '<input type="hidden" name="pr_id['+ key +']" class="db-id" value="'+ dbId +'">';
                }
                html += '<td><div class="data-a" style="text-align: left;"><input type="hidden" name="pr_item['+ key +']" value="'+ $('#pr_item').val() +'"><span>'+ $('#pr_item option:selected').text() +'</span></div></td>';
                html += '<td><div class="data-c"><input type="hidden" name="pr_qty['+ key +']" value="'+ qty +'"><span>'+ qty +'</span></div></td>';
                html += '<td><div class="data-d"><input type="hidden" name="pr_price['+ key +']" value="'+ price +'"><span>'+ price +'</span></div></td>';
                html += '<td><div class="data-e"><input type="hidden" name="pr_stotal['+ key +']" value="'+ sTotal +'" class="stotal"><span>'+ sTotal +'</span></div></td>';
                
                html += '<td class="ctrls" style="text-align: center;"><i class="fa fa-pencil ctrl edit-btn" title="Edit"></i> <i class="fa fa-times ctrl rm-btn" title="Remove"></i></td>';
               
            html += '</tr>';

            if( $body.find('.details tr.details-row').length == 0 ) {

                $body.find('.details').append( html );
            }else {
                $body.find('.details tr.details-row:first').before( html );
            }

            $body.find('.details tr.details-row:first').delay(500).fadeIn('slow');

            // Clear fields
            $('#pr_item, #pr_qty, #pr_price').val('');
           
        }
        
        
        if( isSaveOk && $('#prasadam-dialog .details-row').length > 0 ){
            $wrapper.find('.err-ele').trigger('click');
            
            if( $this.hasClass('save-btn') ) {
                /*
                 * Take the db id of removing items
                 */
                if( $('[name="removed-items"]').length == 0 ) {
                    $('form').append('<input type="hidden" name="removed-items" value="">');
                }
                
                var valStr = $('[name="removed-items"]').val();
                $('#prasadam-dialog .remove-me').each(function(){
                    var dbId = $(this).find('.db-id').val() || "";
                    if( dbId != '' ) {
                        valStr += '-'+dbId;
                    }
                });
                $('[name="removed-items"]').val(valStr);
                
                $('#prasadam-dialog .remove-me').remove();
                $('#prasadam-btn span').html( ' ('+ $('#prasadam-dialog .details-row').length +')' );
                setTotal();

                $('#prasadam-dialog .cancel_popup').trigger( 'click' );
                
            }
        }
        
        var len = $('.details-row').not('.details-row.remove-me').length
        ,   $saveBtn = $wrapper.find('.modal-footer .save-btn');
        $saveBtn.find('span').html( ' ('+ len +')' );
            add_desc();
            setTotal();
            
            /*if( len > 0 ) {
                $saveBtn.removeAttr('disabled');
            }else {
                $saveBtn.attr('disabled', 'disabled');
            }*/
        
        return false;
    })
    
    $('#prasadam-dialog .cancel_popup').on('click', function(){
        $('#prasadam-dialog .remove-me').removeClass('remove-me').show();
        $('#prasadam-dialog .save-btn span').html( ' ('+ $('#prasadam-dialog .details-row').length +')' );
    })
    
    
    //window.setTimeout(function(){
     if( $('#prasadam-hidden-details').length > 0 ) {
        
        var details = $('#prasadam-hidden-details').val();
        details = JSON.parse( details );
        Object.keys( details ).map(function(i, iV){
            window.setTimeout(function(){
                $('#pr_item').val(details[i]['inventory_item_id']).attr('data-db-id', details[i]['id']);
                $('#pr_qty').val(details[i]['quantity']);
                $('#pr_price').val(details[i]['price']);
                $('.new-btn').attr('data-trigger', 'yes').trigger('click');
                $('#pr_item').removeAttr('data-db-id');
            }, 1000);
        })
        
        setTimeout(function(){
            $('.new-btn').removeAttr('data-trigger');
        }, (details.length*1001));
        

        if($('[name="hidden_id"]').val()) {
            $('.amtHide').attr('type','hidden');
            $('.amtShow').attr('type','text');
        }
        setTimeout(function(){
            
            calculate_difference(); 
            
        }, (details.length+1) * 1000);
     }    
    //}, 2000);
    
    $('#prasadam-dialog #pr_item').change(function(){
        deity_prasadam_exists();
    });
    
    $(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_devotee_name').show();
            $('.search_contact_no').hide();            
        } else if($(this).val() == 0) {
            $('.search_devotee_name').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_devotee_name"]').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(),
                    devotee_name: $('[name="p_devotee_name"]').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['devotee_name1']);
                            $('[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['devotee_name1'] +'</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_devotee_name"]').focus();
                $('[name="p_contact_no"]').focus();
            }
        } else {
            msgBox('Please select Type!');
            $('[name="p_fn_type"]').focus();
        }
    });
})

function deity_prasadam_exists() {
    var return_val = true;
    var _this = $('#prasadam-dialog #pr_item').val();
    $('.details .details-row').not('.remove-me').each(function() {
        var exist_deity = ($(this).attr('data-strings')).split('-')[0];
        
        if(exist_deity != '' && exist_deity == _this) {
            $('#prasadam-dialog .modal-dialog .modal-footer .new-btn .save-btn').attr('disabled','disabled');
            $('#prasadam-dialog #pr_item, #pr_qty, #pr_price').val('');
            msgBox('Item Name already exists!');
            return_val = false;
            return false;
        }
    });
    return return_val;
}

function add_desc() {
    var desc = '';
    var text_desc = '';
    if($('#prasadam-dialog .details-row').length > 0){
        $('#prasadam-dialog .details-row').each(function() {
            var deity = $(this).find('.data-a span').text();
            var qty = $(this).find('.data-c span').text();
            var stotal = $(this).find('.data-e span').text();
            desc += deity + '-' + qty + '-' + stotal + ',';
        });
    } 
    text_desc += desc;
    var lastChar = text_desc.slice(-1);
    if(lastChar == ',') {
      text_desc = text_desc.slice(0, -1);
    }
    $('textarea[name="cs_desc"]').val(text_desc);
}

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_temple_shop_sales/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.devotee_name1 +'">'+ ref.devotee_name1 +'</option>';
                }
                $('select[name="p_devotee_name"]').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_devotee_name"]').html(reference);
        
        var contact ='';
        contact += '<option value="">-- Select Contact No --</option>';
        $('select[name="p_contact_no"]').html(contact);
    }
}