function setTotal(_this) {
    var service_type = $(_this).val();
    var edit_id = $('input[name="hidden_id"]').val();
    $.ajax({
        async: false,
        url: base_url + 'billing_outdoor_services/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="cs_amount"]').removeClass('readonly');
                $('input[name="cs_amount"]').removeAttr('readonly');
                $('input[name="cs_amount"]').addClass('amount num-pad');
            } */
        } else {
            $('#payment-btn').removeAttr('disabled');
            /* $('input[name="cs_amount"]').addClass('readonly');
            $('input[name="cs_amount"]').attr('readonly');
            $('input[name="cs_amount"]').removeClass('amount num-pad'); */
        }
        
        $('[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() {
    $('input[name="ct_email"]').change(function(){
        if($(this).hasClass('email') && !validateEmail( $(this).val() )) {
            $(this).val('').focus();
            msgBox('Please enter valid Email Address!');
        }
    });
    
    $('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());
    })
    
    $('input[name="fn_from_time"]').change(function(){
        var start_time = $(this).val();
        var hours = start_time.split(':')[0];
        var min = start_time.split(':')[1];
        var time = new Date(0,0,0,hours,min,0,0);
        var end_time = new Date(time.getTime() + (1*60*60*1000));
        var endTime = ((end_time.getHours() < 10) ? '0' + end_time.getHours() : end_time.getHours())  + ':' + ((end_time.getMinutes() < 10) ? '0' + end_time.getMinutes() : end_time.getMinutes());
        $('input[name="fn_to_time"]').val(endTime);
    });
    
    $('#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');
    });
    
    $('.timelabel_res').parent().parent().css('width','50%');
    /*$('#bkd-btn').on('click', function(){
        $('#booked-dialog .filter-btn').trigger('click'); 
    });*/

    $('select[name="fn_type"]').change(function(){
        var value = $(this).val();
        if( value == '' ) {
            $('#avail-btn').fadeOut('slow');
        }else {
            $('#avail-btn').fadeIn('slow');
        }
        setTotal(this);
    });
    
    /* if($('input[name="fn_type"]').val() != '') {
        var value = $('input[name="fn_type"]').val();
        if( value == '' ) {
            $('#avail-btn').fadeOut('slow');
        }else {
            $('#avail-btn').fadeIn('slow');
        }
        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').removeAttr('disabled');
        
    }) */
    
    $('#payment-btn').on('click', function(){
        var priest = $('select[name="priest_name"]').val()
        ,   melam  = $('select[name="melam_name"]').val()
        ,   nathaswaram  = $('select[name="nathaswaram_name"]').val();
    
        /* if((priest == '' && melam == '' && nathaswaram == '')) {
            msgBox('Please choose atleast one Priest Details!');
            return false;
        }*/

        var $this   = $(this)
        ,   paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 || payAmt != paidAmt ? true : false;
        
        var edit_id = $('input[name="hidden_id"]').val();
        var book_status = $('input[name="book_status"]').val();
        if((book_status == '' || book_status == 1) || (edit_id != '' && book_status == 2)) {
            if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Check "Already exists on this time..?"
                var data = {
                    'act'       : 'check',
                    'service_id': $('[name="fn_type"]').val(),
                    'date'      : $('[name="fn_date"]').val(),
                    'from_time' : $('[name="fn_from_time"]').val(),
                    'to_time'   : $('[name="fn_to_time"]').val(),
                }
                
                if( $('#edit-page').length > 0 ) {
                    // Ignore the current loaded page ID, while checking
                    data['load_id'] = $('[name="hidden_id"]').val();
                }
                
                $.post( base_url + controller + '/ajax/', data, function( results ){
                    results = JSON.parse( results ) || "";
                    
                    if( results == '' ) {
                        // Not exists
                        $('.err-container').slideUp('slow', function(){$(this).html('')});
                        
                        // 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');
                        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 == '' || book_status == 2) {
                            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
                        } 
                        
                        if( parseFloat(payAmt) != parseFloat(paidAmt)) { 
                            $('#sbmt-btn').attr('disabled', 'disabled');
                        } else {
                            $('#sbmt-btn').removeAttr('disabled');
                        }
                        
                        return true;
                    }else {
                        // Already exists
                        var html = 'Error: Already booked on the selected date and time. Please check availability <span class="chk-avail-btn" style="font-weight: bold; cursor: pointer; text-decoration:underline;">in here</span> ...<br />[Booked Time: '+ results.from_time +' -> '+ results.to_time +']';
                        
                        globalMsg( html );
                    }
                    
                    
                });
                
                
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            return true;
        } /* else {
            //msgBox('Amount is already paid!','','info');
            //window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
            //}, 3500);
        } */
    })

    $('.payment-btn').on('click', function(){
		$('.bookbtn').val(2);
        var priest = $('select[name="priest_name"]').val()
        ,   melam  = $('select[name="melam_name"]').val()
        ,   nathaswaram  = $('select[name="nathaswaram_name"]').val();
    
        /* if((priest == '' && melam == '' && nathaswaram == '')) {
            msgBox('Please choose atleast one Priest Details!');
            return false;
        } */
        
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 || payAmt != paidAmt ? true : false;
        
        var return_val = true;
        if( autoValidate()) {
            // Check "Already exists on this time..?"
            var data = {
                'act'       : 'check',
                'service_id': $('[name="fn_type"]').val(),
                'date'      : $('[name="fn_date"]').val(),
                'from_time' : $('[name="fn_from_time"]').val(),
                'to_time'   : $('[name="fn_to_time"]').val(),
            }
            console.log(data);
            if( $('#edit-page').length > 0 ) {
                // Ignore the current loaded page ID, while checking
                data['load_id'] = $('[name="hidden_id"]').val();
            }
            
            $.post( base_url + controller + '/ajax/', data, function( results ){
                results = JSON.parse( results ) || "";
                
                if( results == '' ) {
                    // Not exists
                    $('.err-container').slideUp('slow', function(){$(this).html('')});
                    return_val = true;
                }else {
                    // Already exists
                    var html = 'Error: Already booked on the selected date and time. Please check availability <span class="chk-avail-btn" style="font-weight: bold; cursor: pointer; text-decoration:underline;">in here</span> ...<br />[Booked Time: '+ results.from_time +' -> '+ results.to_time +']';
                    
                    globalMsg( html );
                    return_val = false;
                }
                
                
            });
            
            
        }
        return return_val;
    })
   
   
    $(document).on('click', '.chk-avail-btn', function(){
        $('.err-container').slideUp('slow', function(){$(this).html('')});
        $('#avail-btn').trigger('click');
        $('[name="a_from_date"], [name="a_to_date"]').val($('[name="fn_date"]').val());
        $('select[name="a_fn_type"]').val($('select[name="fn_type"] option:selected').val());
        window.setTimeout(function(){
            $('#chk-btn').trigger('click');
        }, 1000);
        
    });
    
    $(document).on('click', '#chk-btn', function(){
        
        var $appnedTo = $('#avail-dialog .modal-footer')
        ,   style = 'padding: 0px 2px;'
        ,   html = '';
        
        if( $appnedTo.find('#booked-details').length == 0 ) {
            $appnedTo.append('<div id="booked-details" class="resp-table"></div>');
        }
        
        var $bookedWrapper = $appnedTo.find('#booked-details');
        
        $bookedWrapper.html( '<div class="col-xs-12" style="text-align: center; color: #1ba;">Please wait ...</div>' );
        
        var data = {
            'act'       : 'availability',
            'service_id': $('[name="fn_type"]').val(),
            'from_date' : $('[name="a_from_date"]').val(),
            'to_date' : $('[name="a_to_date"]').val(),
            'load_id' : (($('input[name="hidden_id"]').val() != '') ? $('input[name="hidden_id"]').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);' : '';

                    html += '<div class="col-xs-12">';
                    
                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Rec No</div><div class="lbl-value" style="'+ _stle +'">'+ iV['receipt_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>Name</div><div class="lbl-value" style="'+ _stle +'">'+ iV['devotee_name'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';
                    
                    var d = new Date(iV['date'])
                    ,   HF = d.getHours();
                    
                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Function Date</div><div class="lbl-value" style="'+ _stle +'; text-align: right;">'+ ( getTwoDigits( d.getDate() ) +' '+ monthNames[d.getMonth()] +' '+d.getFullYear() ) +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';

                    /* var dT = new Date(iV['bh_to_date'])
                    ,   HT = dT.getHours();
                    
                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Time</div><div class="lbl-value" style="'+ _stle +'">'+ ( getTwoDigits( HF % 12 ) + ':' + getTwoDigits( d.getMinutes() ) ) +' '+ ( HF > 12 ? 'pm' : 'am' ) +' - '+ ( getTwoDigits( HT % 12 ) + ':' + getTwoDigits( dT.getMinutes() ) ) +' '+ ( HT > 12 ? 'pm' : 'am' ) +' </div>';
                    html +=         '</div>';
                    html +=     '</div>'; */
                    
                    var d = new Date(iV['created_on']);
                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Booked Date</div><div class="lbl-value" style="'+ _stle +'; text-align: right;">'+ ( getTwoDigits( d.getDate() ) +' '+ monthNames[d.getMonth()] +' '+d.getFullYear() ) +'</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>Total Amount</div><div class="lbl-value" style="'+ _stle +'; text-align: right;">'+ iV['amount'] +'</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>Action</div><div class="lbl-value" style="'+ _stle +';text-align: center;"><a class="label btn btn-primary edit" href="' + base_url + 'billing_outdoor_services/edit/' + iV['id'] + '/'+ iV['type_id'] + '"> <span>Edit</span></a></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');
            });

        });
        
        
    });

    $(document).on('click', '.modal .filter-btn', function(){
        
        var $appnedTo = $('#booked-dialog .modal-footer')
        ,   style = 'padding: 0px 2px;'
        ,   html = '';
        
        if( $appnedTo.find('#booked-details').length == 0 ) {
            $appnedTo.append('<div id="booked-details" class="resp-table"></div>');
        }
        
        var $bookedWrapper = $appnedTo.find('#booked-details');
        
        $bookedWrapper.html( '<div class="col-xs-12" style="text-align: center; color: #1ba;">Please wait ...</div>' );
        
        var data = {
            act     : 'booked',
            fromDate: $('[name="bk_from_date"]').val(),
            toDate: $('[name="bk_to_date"]').val(),
            period: $('[name="bk_period"]').val()
        };
        
        $.post( base_url + controller + '/get_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);' : '';

                    html += '<div class="col-xs-12">';

                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Devotee Name</div><div class="lbl-value" style="'+ _stle +'">'+ iV['devotee_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>Tamil Name</div><div class="lbl-value" style="'+ _stle +'">'+ ( iV['tamil_name'] != '' ? iV['tamil_name'] : 'N/A' )  +'</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 +'; text-align: right;">'+ iV['contact_no1'] +'</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>Type</div><div class="lbl-value" style="'+ _stle +'">'+ iV['service_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>Amount</div><div class="lbl-value" style="'+ _stle +'; text-align: right;">'+ iV['amount'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';

                    var d = new Date(iV['date']);

                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Function Date</div><div class="lbl-value" style="'+ _stle +';text-align: right;">'+ ( getTwoDigits( d.getDate() ) +' '+ monthNames[d.getMonth()] +' '+d.getFullYear() ) +'</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>Action</div><div class="lbl-value" style="'+ _stle +';text-align: center;"><a class="label btn btn-primary edit" href="' + base_url + 'billing_outdoor_services/edit/' + iV['id'] + '/'+ iV['type_id'] + '"> <span>Edit</span></a></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');
            });

        });
        
        
    });
});