function setTotal(_this) {
    var service_type = $(_this).val();
    var edit_id = $('input[name="hidden_id"]').val();
    $.ajax({
        async: false,
        url: base_url + 'billing_temple_institution/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');
            /* if(edit_id == '') {
                $('input[name="amount"]').removeClass('readonly');
                $('input[name="amount"]').removeAttr('readonly');
                $('input[name="amount"]').addClass('amount num-pad');
            } */
        } else {
            //$('#payment-btn').removeAttr('disabled');
            /* $('input[name="amount"]').addClass('readonly');
            $('input[name="amount"]').attr('readonly');
            $('input[name="amount"]').removeClass('amount num-pad'); */
        }
        
        $('[name="amount"], [name="pay_amount"], [name="hidden_amount"]').val( data.amount );
        $('input[name="fee"]').trigger('keyup');
    })
    .fail(function(jqXHR, status_code, error_thrown) {
        console.log(jqXHR.responseText);
    });
}

var inter = '';
$(document).on('ready', function() {
    
    if($('input[name="transport_facility"]:checked').val() == 1) {
        $('input[name="bus_no"]').removeAttr('disabled');
    }
    
    $('input[name="transport_facility"]').on('ifChecked',function() {
        if($(this).val() == 1) {
            $('input[name="bus_no"]').removeAttr('disabled');
        } else {
            $('input[name="bus_no"]').val('').attr('disabled','disabled');
        }
    });
    
    
    $('input[name="amount"]').keyup(function() {
        $('[name="pay_amount"]').val($(this).val());
    })
    
    
    $('input[name="fee"]').keyup(function() {
        get_total_amount($(this));
    });
    
    /* $('.num-pad .ok-btn').click(function() {
        $('input[name="fee"]').trigger('keyup');
    }); */
    
    $('select[name="service_type"]').change(function(){
        setTotal(this);       
    });
    
    /* if($('input[name="service_type"]').val() != '') {
        setTotal($('input[name="service_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(){
        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');
            }
            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);
        } */
   });
   
   $('#student-btn').on('click', function(){
        var $this = $(this);
        dialog($('#student-dialog'));
        resetAll($('#student-dialog')); 
        return false;
       
    })
    
    $('#get-student-btn').on('click', function(){
        dialog($('#get-student-dialog'));
        $('#get-student-dialog input:first').val('').focus();
        $('#student-plot').html('').hide();
        return false;
    })
    
    $('#student-dialog .save-btn').on('click', function(){
        var $this = $(this)
        ,  isUpdate = ($('#student-dialog [name="db_id"]').val() !== undefined && $('#student-dialog [name="db_id"]').val() != '') ? true : false;
        
        if( autoValidate( $('#student-dialog') ) ) {

            $this.attr('disabled', 'disabled');
            $this.find('span').text((isUpdate ? 'Updating' : 'Saving') + ' ...');
            console.log($('#student-dialog form').serialize());
            var data = {
                'act'  : 'update',
                'type' : 'student',
                'id'   : $('#student-dialog [name="db_id"]').val(),
                data   : $('#student-dialog form').serialize(),
                'lang' : $('.lang-switch-btn').hasClass('active') ? 'T' : 'E',
            }

            $.post(baseURL + 'billing_temple_institution/ajax', data, function( results ) {
                $this.removeAttr('disabled');
                $this.find('span').text(isUpdate ? 'Update' : 'Save');

                results = JSON.parse(results);
                
                if( isUpdate ) {
                    msgBox('Student is updated successfully', '', 'success');
                }else {
                    //msgBox('Devotee is saved successfully', '', 'success');
                    window.setTimeout(function(){
                        msgBox('Student is saved successfully....<div>Please note the following Ref. No: <b>"'+ results +'"</b></div>','', 'success');
                    }, 1000);
                }
                //$('.lang-switch-btn').removeClass('active');
                //setKeyPad();
                resetAll($('#student-dialog'));


            });
         }

     });
     
     $('#student-dialog [name="ref_no"]').on('keyup', function(){
            setstuSaveBtn();
            msgBox();
     });
     
    $(document).on('click', '.dialog .clse-btn', function(){
        var $parent = $(this).parent().closest('.dialog');
        dialog($parent, true);
        resetAll($parent);
        msgBox();
    });
     
     $(document).on('click', '.student-search-btn', function(){

            var $dialog = $(this).parent().closest('.dialog')  
            ,   value   = $dialog.find('.student-ref-no').val()
            ,   isAddSearch = $dialog.attr('id') == 'student-dialog' ? true : false;
            var $gender = '';
            
            if(value != '') {
                var data = {
                    'act'   : 'search-student',
                    'include_contact': $dialog.find('.student-ref-no').hasClass('include-contact') ? true : false,
                    'value' : value
                };
                
                if( !isAddSearch ) {
                    $('#student-plot').html('<div class="no-results">Searching ...</div>').fadeIn('slow');
                }

                $.post(baseURL + 'billing_temple_institution/ajax', data, function( results ) {
                    results = JSON.parse(results);
                    
                    if( results == '' || results == undefined || results == null ) {
                        // No results

                        if( isAddSearch ) {
                            $('#student-dialog [name="ref_no"]').val('');
                            $('#student-dialog [name="ref_no"]').trigger('keyup');
                            msgBox('Invalid Ref. No!', -1);
                           
                            $('#student-childs .blck').not('#student-childs .blck:last').remove();
                            $('#student-dialog .db-id').remove();
                        }else {
                            $('#student-plot').fadeOut('slow', function(){
                                $(this).html('<div class="no-results">Sorry, No record found!</div>').fadeIn('slow');
                            })
                        }

                    }else {

                        // Results found
                        if( isAddSearch ) {
                            msgBox('Record is fetched successfully', 3500, 'success');
                            $('#student-childs .blck').not('#student-childs .blck:last').remove();
                            resetMultiSelect($('#student-dialog'));

                            // Fill all fields
                            Object.keys(results).map(function(ik, iv){

                                var row = results[ik];

                                if( $('#student-dialog [name="db_id"]').length == 0 ) {
                                   $('#student-dialog form').prepend('<input type="hidden" class="db-id" name="db_id" value="">');
                                }

                                $('#student-dialog [name="db_id"]').val(row[0]['id']);

                                $('#student-dialog [name="nric_no"]').val(row[0]['nric_no']);
                                $('#student-dialog [name="name"]').val(row[0]['name']);
                                $('#student-dialog [name="contact_person"]').val(row[0]['contact_person']);
                                $('#student-dialog [name="contact_no"]').val(row[0]['contact_no']);
                                $('#student-dialog [name="email"]').val(row[0]['email']);
                                $('#student-dialog [name="email"]').val(row[0]['email']);
                                $('#student-dialog [name="address"]').val(row[0]['address']);
                                $('#student-dialog [name="sex"]').val(row[0]['sex']);                                
                            });

                            $('#student-dialog [name="ref_no"]').attr('disabled', 'disabled');
                            /* $('#dev-dialog .save-btn').removeAttr('style');
                            $('#dev-dialog .dev-search-btn').css('display','none'); */
                            
                            // Set Save Btn
                            setstuSaveBtn();
                        } else {
                            // Get devotee search
                            
                            var totalNames = $('#main-content .name').length;
                            totalNames = totalNames > 0 ? totalNames : $('#main-content .tamil-name').length;
                            
                            

                            Object.keys(results).map(function(ik, iv){
                                
                                var row = results[ik]
                                ,   addr   = row[0]['address']
                                ,   html = '<div class="no-results" id="chse-mem" data-no="'+ totalNames +'"><div>You can choose <span>'+ totalNames +'</span> member(s) right now!</div></div>';
                                
                                if( addr != '' ) {
                                    addr = addr.replace('\'', '\"').replace('"', '\"');
                                }
                                
                                var details = {
                                    'contactNo' : row[0]['contact_no'],
                                    'email'     : row[0]['email'],
                                    'address'   : addr,
                                    'sex'       : row[0]['sex'],
                                };
                                
                                
                                if( $('#student-plot .hidden-details').length == 0 ) {
                                    html += '<input type="hidden" class="hidden-details" value=\''+ JSON.stringify( details ) +'\'>';
                                }
                                
                                details = {
                                    'name'      : row[0]['name']
                                }    
                                
                                var style = isTamil ? 'font-family: amudham;' : '';
                                
                                html += '<div class="cell" data-details=\''+ JSON.stringify( details ) +'\'><div><span style="'+style+'" data-lang="'+ row[0]['name'] +'">'+(row[0]['name'])+'</span></div></div>';

                                

                                //}

                                html += '<div class="row col-xs-12 ctrls"><div class="bttn primary" id="student-submit-btn"><i class="fa fa-check"></i> Submit</div></div>';

                                $('#student-plot').fadeOut('slow', function(){
                                    $(this).html(html).fadeIn('slow');
                                    $('#student-plot').data('details',details);
                                });
                            });
                        }

                    } // Yes.. Results

                });
            }

     })
     
    $(document).on('click', '#student-submit-btn', function(){
        var actLen = $('#student-plot .cell.active').length;
        
        if( actLen == 0 ) {
            msgBox('Nothing to submit in here');
            return false;
        }else {
            // Reset
            $('#main-content .contact-no, #main-content .email, #main-content .address, #main-content .name, #main-content .tamil-name, #main-content .star').val('');
            
            var details = $('#student-plot .hidden-details').val() || ""
            ,   $names  = $('#main-content .name');
                 
            
            $names      = $names.length > 0 ? $names : $('#main-content .tamil-name');
            
            if( details != '' ) {
                details = JSON.parse(details);
                
                $('#main-content .contact-no').val(details.contactNo);
                $('#main-content .email').val(details.email);
                $('#main-content .address').val(details.address);
                //$('#main-content [name="sex"]').val(details.sex);
                if(details.sex == 1) {
                    $('#main-content .sex_male').iCheck('check');
                } else if(details.sex == 2) {
                    $('#main-content .sex_female').iCheck('check');
                }
            }
        
            $names.each(function(ik, iv){
                //var text = $('#dev-plot .cell.active:eq('+ ik +') > div span').text();
                var details = $('#student-plot .cell.active:eq('+ ik +')').attr('data-details') || "";
                if( details != '' ) {
                    details = JSON.parse(details);
                    $(this).val(details.name);
                    
                    $('#main-content .tamil-name:eq('+ ik +')').val(details.tamilName);
                    
                    
                }
                
                
            });

            //msgBox('Information is submitted successfully', '', 'success');
            dialog($('#get-student-dialog'), true);
            
            var $name = $('#main-content .name:first');
            window.setTimeout(function(){
                
                if( $name.is(':hidden') ) {
                    var errTrgt = $name.attr('data-err-target') || "";
                    if( errTrgt != '' ) {
                        $(errTrgt).trigger('click');
                    }
                }
                window.setTimeout(function(){
                    scrollTo( $name );
                    $name.focus();
                }, 500);
                $('.sbmt-btn, [type="submit"]').removeAttr('disabled');
            }, 900);
            
        }
     });
     
    $(document).on('click', '#student-plot .cell', function(){ 
        var isAct = $(this).hasClass('active') ? false : true
        ,   totalAct = $('#student-plot .cell.active').length
        ,   totalNames = $('#chse-mem').attr('data-no') || 0;

        if( isAct ) {
            // Add
            ++totalAct;
            if( totalAct > totalNames ) {
                msgBox('Maximum no. of member is reached!', -1);
                return false;
            }
            $(this).addClass('active').find('> div').prepend('<i class="fa fa-check-circle"></i>');
        }else {
            --totalAct;
            $(this).removeClass('active').find('.fa').remove();
        }

        var rem = totalNames-totalAct
        ,   tW  = $(window).scrollTop()
        ,   tE  = $('#chse-mem').offset().top;

        $('#chse-mem span').text(rem);
        if( tE > tW ) {
            msgBox();
        }else {
            msgBox('You can choose '+rem+' member(s) right now!', '', 'info');
        }

     });
     
     
});


function get_total_amount(_this){
    var entry_fee = parseFloat($(_this).val()) || 0;
    var amount = parseFloat($('[name="hidden_amount"]').val()) || 0;
    
    var total = parseFloat(entry_fee) + parseFloat(amount);
    if(parseFloat(total) > parseFloat(0)) {
        //$('#payment-btn').removeAttr('disabled', 'disabled');
    } else {
       // $('#payment-btn').attr('disabled', 'disabled');
    }
    $('input[name="amount"], input[name="pay_amount"]').val((parseFloat(total)).toFixed(2));
}

function setstuSaveBtn() {
    var value = $('#student-dialog [name="ref_no"]').val();
    if( value != '' && $('#student-dialog [name="db_id"]').val() === undefined) {
        // Search
        $('#student-dialog .save-btn').hide().find('span').text('Save');
        $('#student-dialog .student-search-btn').fadeIn('slow');

        $('#student-dialog .req-mark').remove();
    }else {
        // Save | Update
        var lbl = 'Save';
        if( $('#student-dialog [name="db_id"]').length > 0 ) {
            // Update
            lbl = 'Update';
        }

        $('#student-dialog .student-search-btn').hide();
        $('#student-dialog .save-btn').fadeIn('slow').find('span').text(lbl);

        $('#student-dialog .req').each(function(){
            if( $(this).prev('label').find('.req-mark').length == 0 ) {
                $(this).prev('label').append('<span class="req-mark"> * </span>');
            }
        });
    }
}


