/* 
 * 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;
    
    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');
    }
    
    $('[name="amount"]').val( total.toFixed(2) );
    $('[name="pay_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!');
                
            });
        }        
        
    })
    
    $('#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 ) {
            $('#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'];
                
                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;
        }
        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
        ,   toDisable = (isEdit && payAmt != paidAmt ) || (!isEdit && (paidAmt <= 0 || payAmt != paidAmt) ) ? true : false
        ,   isPaymentBtn = $this.attr('id') == 'payment-btn' ? true : false;
        
        if( payAmt == 0 ) {
            payAmt = parseFloat($('[name="pay_amount"]').val()) || 0;
        }
        
        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 ) || "";
                
                if( results == '' ) {
                    
                    if( isPaymentBtn ) {
                        // Not exists
                        $('.err-container').slideUp('slow', function(){$(this).html('')});

                        // Go to payment
                        if( toDisable ) {
                            $('[type="submit"]').attr('disabled', 'disabled');
                        }

                        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 [name="pay_amount"], [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
                            $('#sbmt-btn').removeAttr('disabled');
                            return true;
                        } 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);
        
    
    
})


