/* 
 * Author       : Jai K
 * Purpose      : Main Script for "Madappalli - Billing"
 * Created On   : 2016-08-13 13:13
 */

function setTotal() {
    var edit_id = $('input[name="hidden_edit_id"]').val();
    var $fnType = $('[name="fn_type"] option:selected');
    var isEdit = $('#edit-page').length > 0 ? true : false;
    
    if( isEdit ) {
        $fnType = $('[name="fn_type"]');
    }
    
    var Amt = $('[name="amount"]').val() || 0
    ,   total = parseFloat( $fnType.attr('data-amt') ) || 0;

    if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');

    }else {
        $('#payment-btn').removeAttr('disabled');

    }

    $('.stotal').each(function(i, iKey){
        var value = parseFloat( $(this).val() ) || 0;
        total += parseFloat( value );
    });
    
    
    if( Amt > 0 ) {
        var delAmt = parseFloat($('[name="amount"]').attr('data-del-amt')) || 0
        ,   addAmt = parseFloat($('[name="amount"]').attr('data-add-amt')) || 0;
        
        total = Amt - delAmt;
        total += addAmt;
    }
    
    $('[name="amount"]').removeAttr('data-del-amt data-add-amt');
    
    if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');
    }else {
        $('#payment-btn').removeAttr('disabled');
    }
    
    $('[name="amount"], [name="pay_amount"]').val( total.toFixed(2) );
    
    
}

var inter = '';
$(document).on('ready', function() {
    
    $('#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');
    });
    
    // Add Items
    $(document).on('keyup', '.innr-table .pr-qty, .innr-table .pr-price', function(){
        var total = 0
        ,   $row    = $(this).parent().closest('.row-details')
        ,   qty   = $row.find('.pr-qty').val() || 0
        ,   price   = $row.find('.pr-price').val() || 0
        ,   $stotal = $row.find('.stotal')
        ,   pstotal  = $stotal.val() || 0
        ,   nstotal = (qty * price).toFixed(2);
        
        $stotal.val( nstotal );
        
        $('[name="amount"]').attr('data-add-amt', ( pstotal > 0 ? nstotal - pstotal : nstotal ));
        
        setTotal();
        
    });
    
    $(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('.stotal').val();
            
            $('[name="amount"]').attr('data-del-amt', stotal);
            
            $row.slideUp('slow', function(){
                
                /*
                 * Take the db id of removing items
                 */
                var dbId = $(this).find('.db-id').val() || "";
                if( dbId != '' ) {
                    if( $('[name="removed-items"]').length == 0 ) {
                        $('form').append('<input type="hidden" name="removed-items" value="">');
                    }
                
                    var valStr = $('[name="removed-items"]').val();
                    valStr += '-'+dbId;
                    $('[name="removed-items"]').val(valStr);
                }
                
                $(this).remove();
                if( $('.innr-table .row-details .add-btn').length <= 1 ) {
                    $('.innr-table .row-details:last .ctrls').html('<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, select').each(function(){
            $(this).attr('id', $(this).attr('id')+'-'+len).val('');
        });
        
        if($row.find('.pr-deity').val() != '' && $row.find('.pr-prasadam').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 );
            var deity = $row.find('.pr-deity').val();
            var prasadam = $row.find('.pr-prasadam').val();
            $row.attr('data-strings',deity + '-' + prasadam);
            $clone.removeAttr('data-strings').attr('cloend', 'ok');
            
            $clone.find('.pr-deity').val(deity);
        } else {
           msgBox('Please Choose Deity and Prasadam!');
           $row.focus();
           //$row.focus();
        }
    });
    
    /*$('#bkd-btn').on('click', function(){
        $('#booked-dialog .filter-btn').trigger('click'); 
    });*/
    
    /* $('#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 paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 ? true : false;
        
        var already_paid_amt = ($('input[name="hidden_amount"]').val() !== undefined) ? $('input[name="hidden_amount"]').val() : 0;
        var cs_amount = $('input[name="amount"]').val();
        
        var edit_id = $('input[name="hidden_edit_id"]').val();
        var book_status = $('input[name="book_status"]').val();
        //if((parseFloat(already_paid_amt) < parseFloat(cs_amount)) || (edit_id == '' && (book_status == '' || book_status == 1))) {
        if((edit_id == '' && (book_status == '' || book_status == 1))) {
            if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            
            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            $('#sbmt-btn').removeAttr('disabled');
            return false;
        } /* else if((parseFloat(already_paid_amt) > parseFloat(cs_amount)) && (edit_id != '' && book_status == 1)) {
            var paying_amt = parseFloat(already_paid_amt) - parseFloat(cs_amount);
            msgBox('Amount ' + ((parseFloat(paying_amt)).toFixed(2)) + ' is Refunded!','','info');
            
            window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
            }, 3500);
        
        }  */else if(edit_id != '' && book_status == 2) {
           if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            
            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            $('#sbmt-btn').removeAttr('disabled');
            return false;
        
        } else { 
            if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            
            if(edit_id == '') {
                $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            }
            
            if(edit_id != '') {
                var $bank_name = $('#cheque-box .hidden_bank_name').val();
                var $cheque_no = $('#cheque-box .hidden_chq_no').val();
                var $cheque_date = $('#cheque-box .hidden_chq_date').val();
                
                $('#cheque-box [name="chq_bnk_name"]').val($bank_name);
                $('#cheque-box [name="chq_no"]').val($cheque_no);
                $('#cheque-box [name="chq_date"]').val($cheque_date);
            }
            
            //$('#sbmt-btn').removeAttr('disabled');
            return false;
        }        
        /*  else {
            //msgBox('Amount is already paid!','','info');
            //window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
           // }, 3500);
        } */
    })
    
    
    $('.payment-btn').on('click', function(){
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 || payAmt != paidAmt ? true : false;
        
        if( autoValidate()) {
            return true;
        }
        return false;
    })
    
    $('[name="fn_type"]').on('change', function(){
        setTotal();
    });
    
    $(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 + '/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['bm_dev_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['bm_tamil_name'] != '' ? iV['bm_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['bm_contact_no'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';

                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>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['bm_amount'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';

                    var d = new Date(iV['bm_fn_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_madappalli/edit/' + iV['id'] + '/'+ 9 + '"> <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');
            });

        });
        
        
    });
    
})

function get_deity_name(_this) {
    deity_prasadam_exists(_this,1);
}

function get_prasadam_name(_this){
    var prasadam = $(_this).val();
    if(prasadam != '') {
        $.ajax({
            async: false,
            url: base_url + 'billing_madappalli/get_prasadam_price',
            type: 'POST',
            data: { id: prasadam},
            dataType: "json"
        }).done(function(data) {
            $(_this).parent().closest('.row-details').find('.pr-price').val(data.price);
        }).fail(function(XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
    }
    deity_prasadam_exists(_this,2);
}

function deity_prasadam_exists(_this,name) {
    var return_val = true;
    if(name == 1) {
        var deity = $(_this).val();
        var prasadam = $(_this).parent().closest('.row-details').find('.pr-prasadam').val();
    } else if(name == 2) {
        var deity = $(_this).parent().closest('.row-details').find('.pr-deity').val();
        var prasadam = $(_this).val();
    }
    
    
    $('.row-details').each(function() {
        var exist_deity = ($(this).attr('data-strings')).split('-')[0];
        var exist_prasadam = ($(this).attr('data-strings')).split('-')[1];
       
        if(exist_deity != '' && exist_prasadam != '' && (exist_deity == deity && prasadam == exist_prasadam)) {
            if(name == 1) {
               $(_this).val('');
               $(_this).parent().closest('.row-details').find('.pr-prasadam').val('');
            } else if(name == 2) {
               $(_this).parent().closest('.row-details').find('.pr-deity').val('');
               $(_this).val('');
            }
            $(_this).parent().closest('.row-details').find('.pr-price').val('');
            msgBox('Deity Name and Prasadam are already exists!');
            return_val = false;
            return false;
        }
    });
    return return_val;
}

/* function add_desc() {
    var desc = '';
    $('textarea[name="desc"]').val('');
    $('.innr-table .row-details').each(function() {
        var deity = $(this).find('.pr-deity option:selected').text();
        var prasadam = $(this).find('.pr-prasadam option:selected').text();
        var de_val = $(this).find('.pr-deity option:selected').val();
        var prasadam_val = $(this).find('.pr-prasadam option:selected').val();
        var qty = parseFloat($(this).find('.pr-qty').val()) || 0;
        var stotal = parseFloat($(this).find('.stotal').val()) || 0;
        if(de_val != '' && prasadam_val != '' && qty) {
           desc += deity + '-' + prasadam + '-' + qty + '-' + stotal + ',';
        }
    });
    $('textarea[name="desc"]').val(desc);
} */


