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');         
        } 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 edit_id = $('input[name="hidden_id"]').val();
	var $fnType = $('[name="fn_type"] option:selected');
    
	if( $('#edit-page').length > 0 ) {
        $fnType = $('[name="fn_type"]');
    }
    
    var total 		= parseFloat( $fnType.attr('data-amt') ) || 0
    ,   paidAmt 	= 0;
	
	var totPaidAmt 	= parseFloat( $('[name="paid_addit_amount"]').val() ) || 0;
	
	if( totPaidAmt > 0 ) {
		total 		= totPaidAmt;
	}
	    
    if( total <= 0 ) {
        // Disable Payment Btn
        $('[name="amount"]').removeClass('readonly').removeAttr('readonly');
        $('#payment-btn').attr('disabled', 'disabled');
    }else {
        //\$('[name="amount"]').addClass('readonly').attr('readonly', 'readonly');
        $('#payment-btn').removeAttr('disabled');
    }
	
	$('.add_amount').each(function(i, iKey){
        var value = parseFloat( $(this).val() ) || 0;		
        	total += parseFloat( value );
    });
	
	if( total > 0 ) {
        // Toatl => 60
        // Amt => 300
        // Dele => 200
        var delAmt = parseFloat($('[name="amount"]').attr('data-del-amt')) || 0;
        console.log("Del :"+delAmt);
        total -= delAmt;
    }
    
    $('[name="amount"]').removeAttr('data-del-amt');
	
	if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');
    }else {
        $('#payment-btn').removeAttr('disabled');
    }
	
    $('[name="cs_amount"]').val( total.toFixed(2) );
    $('[name="pay_amount"]').val( (parseFloat(total) - parseFloat(paidAmt)).toFixed(2) );
}

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;
		
		$.ajax({
			url: base_url + 'billing_outdoor_services/outdoor_bill_amount',
			data: {amount: parseFloat(payAmt).toFixed(2)},
			dataType: 'JSON',
			type: 'post',
			'global': false,
			'async': false,
			success: function (output) {
				//tmp = output;
			}
		});
        
        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_id == '' || 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;
    })
	
	$('[name="fn_date"]').on('change', function(){
        var dateval = $(this).val();
        $.ajax({
            async: false,
            url: base_url + 'billing_common/check_festival_date',
            type: 'POST',
            data: { fn_date: dateval},
            dataType: "json"
        }).done(function(data) {
			console.log(data);
            if(parseInt(data.id) > 0) {
                var msg = "In this date <b>"+dateval+"</b> have a <b>"+data.name+"</b> festival. Do you want to proceed to book?";
				show_festival_confirm(msg);
            }
        }).fail(function(XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
    });
   
   
    $(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>';
					html += 				'<a class="label btn btn-danger delete" href="' + base_url + 'billing_outdoor_services/delete/' + iV['id'] + '/' + iV['type_id'] + '"> <span>Delete</span></a>';
                    html += 			'</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', '.innr-table .ctrls .rm-btn', function(){
        var $this   = $(this);
        
        if( window.confirm("Are you sure and want to remove this row..?") ) {
            var $innr   = $this.parent().closest('.innr-table')
            ,   $row    = $this.parent().closest('.row-details')
			,   stotal  = $row.find('.add_amount').val();
			
			$('[name="amount"]').attr('data-del-amt', stotal);
            
            $row.slideUp('slow', function(){
                /*
                 * Take the db id of removing items
                 */
                
                $(this).remove();
                if( $('.innr-table .row-details .rm-btn').length <= 1 ) {
                    $('.innr-table .row-details:last .ctrls').html('<i class="fa fa-plus-circle add-btn"></i>');
                }else{
					 $('.innr-table .row-details:last .ctrls').html('<i class="fa fa-power-off rm-btn" style="color: #f00;"></i><i class="fa fa-plus-circle add-btn"></i>');
				}
            })
			
			setTotal();
        }
        
        return false;
        
    });
	
    $(document).on('click', '.innr-table .ctrls .add-btn', function(){
        
        var $innr   = $(this).parent().closest('.innr-table')
        ,   $row    = $(this).parent().closest('.row-details')
        ,   len     = $innr.find('.row-details').length
        ,   $clone  = $row.clone();
       
       
        // Remove ID
        $clone.find('input, textarea').each(function(){
            $(this).attr('id', $(this).attr('id')+'-'+len).val('');
			$(this).attr("readonly", false);
        });
       
	    if($row.find('.add_amount').val() != '') {          
            $row.find('.ctrls').html('<i class="fa fa-power-off rm-btn" style="color: #f00;"></i>');
            $clone.find('.ctrls').html('<i class="fa fa-power-off rm-btn" style="color: #f00;"></i><i class="fa fa-plus-circle add-btn"></i>');        
            $innr.find('.row-details:last-child').after( $clone );           
        } else {
           msgBox('Please enter additional amount!');
           $row.find('.add_amount').focus();
           $row.find('.add_desc').focus();
        }
    });
	
	// Add Additional Amount
    $(document).on('keyup', '.innr-table .add_amount', function(){
        var total = 0
        ,   $row    = $(this).parent().closest('.row-details')       
        ,   price   = $row.find('.add_amount').val() || 0;
        
        setTotal();
    });

});