/* 
 * Author       : Jai K
 * Purpose      : Main Script for "Billing - Wedding Hall Booking"
 * Created On   : 2016-08-11 18:48
 */


function setTotal() {
    // Calculate Prasadam Total
    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 	= parseFloat( $('[name="dep_amount"]').val() ) || 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="amount"]').val( total.toFixed(2) );
    $('[name="pay_amount"]').val( (parseFloat(total) - parseFloat(paidAmt)).toFixed(2) );
    
}

/*function setTotal_add() {
       
    var total = parseFloat( $('[name="paid_addit_amount"]').val() ) || 0
	, paidAmt = parseFloat( $('[name="paid_addit_amount"]').val() ) || 0;
    
    if( total <= 0 ) {
        // Disable Payment Btn
        $('#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="addit_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="addit_amount"]').val( total.toFixed(2) );
    $('[name="pay_amount"]').val( (parseFloat(total) - parseFloat(paidAmt)).toFixed(2) );
	$('[name="paid_amount"]').val( (parseFloat(total) - parseFloat(paidAmt)).toFixed(2) );
    
}*/

function setBack(){
    $('#p-err').remove();
    $('#p-ctrls').slideDown('slow');
    $('[name="p_contact_no"], [name="p_ref_no"]').val('');
    $('[name="p_amount"], [name="p_dep_amount"], [name="p_pay_amount"]').val('');
    $('#pay-btn, [name="p_pay_amount"]').attr('disabled', 'disabled');
    $('[name="p_pay_amount"]').addClass('readonly');
}

var inter = '';
$(document).on('ready', function() {
    
    $('[name="amount"], [name="dep_amount"]').on('keyup', function(){
        var totAmt = parseFloat($('[name="amount"]').val()) || 0
        ,   depAmt = parseFloat($('[name="dep_amount"]').val()) || 0;
        
        if( depAmt > 0 ) {
            if( depAmt > totAmt ) {
                msgBox('Deposit amount can not be exceeded than total amount to pay!');
                $('[name="dep_amount"]').val(totAmt.toFixed(2));
                return false;
            }
            $('#payment-btn').removeAttr('disabled');
        }else {
            $('#payment-btn').attr('disabled', 'disabled');
        }
    })
    
    $('[name="p_fn_type"]').on('change', function(){
        var value = $(this).val() ||""
        ,   ref = '<option value="">-- Select Ref. No --</option>'
        ,   cnt = '<option value="">-- Select Contact. No --</option>';
        
        msgBox();
        
        if( value != '' ) {
            var data = {
                'act'   : 'nos',
                'typeId': value,
                
            };
            
            $.post( base_url + controller + '/ajax/', data, function( results ){
                results = JSON.parse( results ) || "";
                
                if( results != '' ) {
                    Object.keys( results ).map(function(k, val){
                        ref += '<option value="'+ results[k]['id'] +'">'+ results[k]['bwh_rec_no'] +'</option>';
                        cnt += '<option value="'+ results[k]['id'] +'">'+ results[k]['bwh_contact_no'] + ' / ' + results[k]['bwh_rec_no'] +'</option>';
                        
                    })
                }
                
                $('[name="p_ref_no"]').html(ref);
                $('[name="p_contact_no"]').html(cnt);
                
            });    
        }else {
            // No type selected
            $('[name="p_ref_no"]').html(ref);
            $('[name="p_contact_no"]').html(cnt);
        }
        
    })
    
    $('#pay-details-dialog .reset-btn, .cancel_popup').click(function() {
        $('#payment-cheque').hide();
        //$('select[name="p_mode"]').val('');
        $('select[name="p_mode"] option:first').removeAttr('selected');
        $('select[name="p_mode"] option:first').attr('selected','selected');
    });
    
    $('#pay-btn').on('click', function(){
        var cheque = $('select[name="p_mode"] option:selected').attr('data-id');
        
        if(cheque == 'pay-cheque' && $('[name="bnk_name"]').val() == '') {
            msgBox('Please enter the Bank Name!');
            return false;
        } else if(cheque == 'pay-cheque' && $('[name="cheque_no"]').val() == '') {
            msgBox('Please enter the Cheque No!');
            return false;
        
        } else {
            var $this = $(this);
            var msg  = 'Please wait ...'
            ,   dbId = parseInt($('#pay-btn').attr('data-id')) || "";
            $('#p-err').remove();
            
            if( dbId == '' ) {
                alert('Oops: Something went wrong.. Please try again!');
            
                setBack();
                return false;
            }else {
                
                var payAmt    = parseFloat( $('[name="p_pay_amount"]').attr('data-amt') ) || 0
                ,   payingAmt = parseFloat( $('[name="p_pay_amount"]').val() ) || 0;
                /* if(payAmt > 0 && (('#ptypes-dialog.partial').length > 0 || $('input[name="hidden_edit_id"]').val() == '')) {
                    $('.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 {
                    $('[type="submit"]').trigger('click');
                    return true;
                } */
                if( payAmt <= 0 ) {
                    msgBox('Nothing to pay!');
                    return false;
                }else if( parseFloat(payingAmt.toFixed(2)) > parseFloat(payAmt.toFixed(2)) ) {
                    // Greater than to pay
                    msgBox('Payable Amount must be less than total amount to be paid!');
                    $('[name="p_pay_amount"]').val(payAmt.toFixed(2)).focus();
                    return false;
                } /* else {
                    $(this).parents().find('#pay-details-dialog .cancel_popup').trigger('click');
                    $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                    $('#ptypes-dialog .pay-type:first, [name="pay_amount"], [name="paid_amount"]').val((parseFloat(payingAmt)).toFixed(2));
                    $this.addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                    $('#pay-btn').trigger('click');
                    return true;
                } */
                
                $('#p-ctrls').slideUp('slow').after('<div id="p-err">'+msg+'</div>');
            }
            
            var data = {
                'act'       : 'pay',
                'id'        : dbId,
                'val'       : $('[name="p_pay_amount"]').val(),
                'mode'      : $('select[name="p_mode"]').val(),
                'bank_name' : $('[name="bnk_name"]').val(),
                'cheque_no' : $('[name="cheque_no"]').val(),
                'cheque_date' : $('[name="cheque_date"]').val(),
                'cheque' : cheque,
            }

            $.post( base_url + controller + '/ajax/', data, function( results ){                
                results = JSON.parse( results ) || "";
                $('[name="p_pay_amount"]').attr('data-amt', '0');
                $('#p-err').html('Paid successfully!');
                location.reload();
            });
        }        
        
    })
    
    $('#pay-details-dialog select[name="p_mode"]').change(function() {
        var cheque = $('select[name="p_mode"] option:selected').attr('data-id');
        if(cheque == 'pay-cheque') {
            $('#payment-cheque').show();
        } else {
            $('#payment-cheque').hide();
        }
    });
    
    $('[name="p_pay_amount"]').on('keyup', function(){
        if( $(this).val() > 0 ) {
			$.ajax({
				url: base_url + 'billing_wedding_booking/wedding_bill_amount',
				data: {amount: (parseFloat($(this).val())).toFixed(2)},
				dataType: 'JSON',
				type: 'post',
				'global': false,
				'async': false,
				success: function (output) {
					//tmp = output;
				}
			});
            $('#pay-btn').removeAttr('disabled');
        }else {
            $('#pay-btn').attr('disabled', 'disabled');
        }
    })
    
    $('[name="p_contact_no"], [name="p_ref_no"]').on('change', function(){
        var value = $(this).val();
        $('#p-err').remove();
        $('#p-ctrls').slideDown('slow');
    
        if( value != '' ) {
            
            var data = {
                'act'       : 'balance',
                'service_id': $('[name="p_fn_type"]').val(),
                'val'       : value,
                'col'       : $(this).attr('name') == 'p_contact_no' ? 'bwh_contact_no' : 'bwh_rec_no'
            }

            $.post( base_url + controller + '/ajax/', data, function( results ){
                results = JSON.parse( results ) || "";
                var dbId   = ''
                ,   payAmt = results['bwh_amount'] - results['bwh_paid_amount'];
                
				$.ajax({
					url: base_url + 'billing_wedding_booking/wedding_bill_amount',
					data: {amount: (parseFloat(payAmt)).toFixed(2)},
					dataType: 'JSON',
					type: 'post',
					'global': false,
					'async': false,
					success: function (output) {
						//tmp = output;
					}
				});
				
                if( results != '' ) {
                    dbId = results['id'];
                    $('[name="p_amount"]').val( results['bwh_amount'] );
                    $('[name="p_dep_amount"]').val( results['bwh_paid_amount'] );
                    $('[name="p_pay_amount"]').val( ( payAmt ).toFixed(2) ).attr('data-amt', payAmt.toFixed(2) );
                }
                
                $('#pay-btn').attr('data-id', dbId);
                if( payAmt > 0 ) {
                    $('#pay-btn, [name="p_pay_amount"]').removeAttr('disabled');
                    $('[name="p_pay_amount"]').removeClass('readonly').focus();
                }else {
                    $('#pay-btn, [name="p_pay_amount"]').attr('disabled', 'disabled');
                    $('[name="p_pay_amount"]').addClass('readonly');
                }    
            });    
        }else {
            // Clear fields
            setBack();
        }    
                
    })
    
    $('[name="p_search_by"]').on('ifChecked', function(event){
        var typeId = $('[name="p_fn_type"]').val() || "";
        if( typeId == '' ) {
            msgBox('Please choose the Type');
            return false;
        }
        var value = $(this).val();
        
        setBack();
        
        if( value == "1" ) {
            // Show Ref No
            $('#p-ref-no-wrap').slideDown('slow');
            $('#p-cnt-no-wrap').slideUp('slow');
            
            
        }else {
            $('#p-cnt-no-wrap').slideDown('slow');
            $('#p-ref-no-wrap').slideUp('slow');
        }
        
    });
    
    
    $(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());
        window.setTimeout(function(){
            $('#chk-btn').trigger('click');
        }, 1000);
        
    });
    
    
    /* $('#sbmt-cancel-btn').on('click', function(){
        
        $('#payment-btn').removeClass('dialog-btn').removeAttr('data-target');
        
    }) */
    
    
    
    $('#payment-btn').on('click', function(){
        submit($(this));
    });
    
    $('[name="fn_type"]').on('change', function(){
        if( $(this).val() != '' && $(this).hasClass('check-avail') ){
            $(this).removeClass('check-avail');
            submit($(this));
        }
    });
    $('[name="fn_date"], [name="fn_from_time"], [name="fn_to_time"], [name="fn_period"]').on('change', function(){
        if( $('[name="fn_type"]').val() == '' ) {
            msgBox('Please choose the type first!');
            $('[name="fn_type"]').addClass('check-avail').focus();
            return false;
        }
		
		if( $('[name="fn_date"]').val() != '' ) {
			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);
			});
		}
        submit($(this));
    })
    
    function submit($this){
        var isEdit = $('#edit-page').length > 0 ? true : false
        ,   paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="dep_amount"]').val()) || 0
		, 	addPay = parseFloat($('[name="paid_amount"]').val()) || 0
        ,   toDisable = (isEdit && payAmt != paidAmt ) || (!isEdit && (paidAmt <= 0 || payAmt != paidAmt) ) ? true : false
        ,   isPaymentBtn = $this.attr('id') == 'payment-btn' ? true : false
		,   flagval		  = 1;
        
		
        if( payAmt == 0 ) {
            payAmt = parseFloat($('[name="pay_amount"]').val()) || 0;
        }
		
		if(addPay > 0){
			if (!$this.hasClass('dialog-btn')) {
				$.ajax({
					url: base_url + 'billing_wedding_booking/wedding_bill_amount',
					data: {amount: (parseFloat(paidAmt)).toFixed(2)},
					dataType: 'JSON',
					type: 'post',
					'global': false,
					'async': false,
					success: function (output) {
						//tmp = output;
					}
				});
				
				$('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
				$this.addClass('dialog-btn').attr('data-target', '#ptypes-dialog').trigger('click');
				$('#ptypes-dialog .pay-type:first, input[name="pay_amount"], [name="paid_amount"]').val((parseFloat(paidAmt)).toFixed(2));
				$('#sbmt-btn').removeAttr('disabled');
				return true;
			}
		}
        
        if( !isPaymentBtn || (isPaymentBtn && 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( isEdit ) {
                // 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) || "";
				console.log(results);				
				if( results == '' ) {
					if( isPaymentBtn ) {
						// Not exists
						$('.err-container').slideUp('slow', function(){$(this).html('')});

						// Go to payment
						if( toDisable ) {
							$('[type="submit"]').attr('disabled', 'disabled');
						}
						
						if (!$this.hasClass('dialog-btn')) {
							$.ajax({
								url: base_url + 'billing_wedding_booking/wedding_bill_amount',
								data: {amount: (parseFloat(payAmt)).toFixed(2)},
								dataType: 'JSON',
								type: 'post',
								'global': false,
								'async': false,
								success: function (output) {
									//tmp = output;
								}
							});
							
							if (!isEdit && payAmt > 0 && (('#ptypes-dialog.partial').length > 0 || $('input[name="hidden_edit_id"]').val() == '')) {
								$('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
								$this.addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
								$('#ptypes-dialog .pay-type:first, [name="pay_amount"], [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
								//$('#ptypes-dialog [name="pay_amount"], [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
								$('#sbmt-btn').removeAttr('disabled');
								
							} else {
								if( isEdit ) {
									$('[name="submit"]').removeAttr('name');
									$this.addClass('dialog-btn').removeAttr('disabled');
								}
	
								$('[type="submit"]').trigger('click');
								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( isPaymentBtn ){
            if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            if($('input[name="hidden_edit_id"]').val() == '') {
                $('#ptypes-dialog [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            }
            $('#sbmt-btn').removeAttr('disabled');
            return true;
        }
        
    }
    
    $('[name="fn_type"]').on('change', function(){
        var value = $(this).val();
        if( value == '' ) {
            $('#avail-btn').fadeOut('slow');
        }else {
            $('#avail-btn').fadeIn('slow');
        }
        setTotal();
    });
   
    
    $(document).on('click', '#chk-btn', function(){
        
        var $appnedTo = $('#avail-dialog .modal-footer')
        ,   style = 'padding: 0px 2px;'
        ,   html = '';
        
        $('#book-type-lbl').remove();
        
        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(),
        };
        
        $.post( base_url + controller + '/ajax/', data, function( results ){
            results = JSON.parse( results );
            if( results != '' ) {
                
                html += '<div id="book-type-lbl" style="margin: -15px 0px; text-align: right; padding: 0px 17px; color: #999; font-size: 11px; font-weight: bold;">';
                html += '<span>Type: '+ results[0]['service_name'] +'</span>';
                html += '</div>';
                $('#booked-details').before( html );
                
                html = '';
                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['bwh_rec_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>Groom Name</div><div class="lbl-value" style="'+ _stle +'">'+ iV['bwh_groom_name'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';
                    
                    var d = new Date(iV['bwh_from_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>Wedding 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['bwh_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['bwh_amount'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';
                    

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

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

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

        });        
    });
    
    //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_deity').val(details[i]['god_id']).attr('data-db-id', details[i]['id']);
                $('#pr_prasadam').val(details[i]['prasadam_id']);
                $('#pr_qty').val(details[i]['qty']);
                $('#pr_price').val(details[i]['price']);
                $('.new-btn').trigger('click');
                $('#pr_deity').removeAttr('data-db-id');
            }, 1000);
        })
     }    
    //}, 2000);
        
    $(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();
    });

    
})