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

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( 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;
            }
            $('[name="pay_amount"]').val(depAmt);
            $('#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]['bh_rec_no'] +'</option>';
                        cnt += '<option value="'+ results[k]['id'] +'">'+ results[k]['bh_contact_no'] + ' / ' + results[k]['bh_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"] option:first').removeAttr('selected');
        $('select[name="p_mode"] option:first').attr('selected','selected');
    });
    
    $('#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();
        }
    });
    
    $('#paynow-btn').on('click', function(){
        $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
    });
    
    
    $('#pay-btn').on('click', function(){ //payment-btn  pay-btn
        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 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 ) {
                    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;
                }
                
                $('#p-ctrls').slideUp('slow').after('<div id="p-err">'+msg+'</div>');
            }
            
            // Show payment type dialog
            
            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!');
                
            });   
        }
    })
    
    $('[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' ? 'bh_contact_no' : 'bh_rec_no'
            }

            $.post( base_url + controller + '/ajax/', data, function( results ){
                results = JSON.parse( results ) || "";
                var dbId   = ''
                ,   payAmt = results['bh_amount'] - results['bh_paid_amount'];
                
                if( results != '' ) {
                    dbId = results['id'];
                    $('[name="p_amount"]').val( results['bh_amount'] );
                    $('[name="p_dep_amount"]').val( results['bh_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){
        //alert(event.type + ' callback');
        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');
        }
        
        //alert( $(this).val() );
        
    });
    
    $(document).on('click', '.modal .filter-btn', function(){
        
        var $appnedTo = $('#booked-dialog .modal-footer')
        ,   style = 'padding: 0px 2px;'
        ,   html = '';
        
        var service_id_array = $('input[name="service_id_array"]').val();
        
        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['bh_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['ba_tamil_name_1'] != '' ? iV['ba_tamil_name_1'] : '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['bh_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['bh_amount'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';

                    var d = new Date(iV['bh_from_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 +=     '<input type="hidden" class="edit_hidden_id" name="edit_hidden_id" value="' + iV['id'] + '" />';
                    
                    
                    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 edit_booked_data" href="' + base_url + 'billing_hall_booking/edit/' + iV['id'] + '/'+ 7 + '" data-otp-ids="' + JSON.stringify(service_id_array) + '"> <span>Edit</span></a>';
                    html +=                 '<a class="label btn btn-danger delete" href="' + base_url + 'billing_hall_booking/delete/' + iV['id'] + '/'+ 7 + '" data-otp-ids="' + JSON.stringify(service_id_array) + '"> <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', '.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(){ //alert($(this));
        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) || (!isEdit && (paidAmt <= 0 || payAmt != paidAmt) ) ? true : false
        ,   isPaymentBtn = $this.attr('id') == 'payment-btn' ? true : false;
        
        var edit_id = $('input[name="hidden_edit_id"]').val();
        
        var book_status = $('input[name="book_status"]').val();
        
        
        
        if( payAmt == 0 ) {
            payAmt = parseFloat($('[name="pay_amount"]').val()) || 0;
        }
        var fntypetxt = $('[name="fn_type"] option:selected').text();
        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(),
                'period'    : $('[name="fn_period"]').val(),
                'isWedding' : ((fntypetxt == "Hall 2 and 3" || fntypetxt == "Hall 2" || fntypetxt == "Hall 3") ? 1 : 0),
            }
            
            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
						//alert(toDisable);
                        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');

                            $('[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 ';
                    html += (fntypetxt == "Hall 2 and 3" || fntypetxt == "Hall 2" || fntypetxt == "Hall 3") ? ' in <b>" Wedding Hall Booking Module "<b>' : '<span class="chk-avail-btn" style="font-weight: bold; cursor: pointer; text-decoration:underline;">in here</span> ...';
                    html += '<br />[Booked Time: '+ results.from_time +' -> '+ results.to_time +']';
                    
                    globalMsg( html );
                }
                
            });
            
            
        }else if( isPaymentBtn ){
            if( toDisable ) {
                $('[type="submit"]').attr('disabled', '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(),
            'period' : $('#avail-dialog [name="fn_period"]').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['bh_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>Name</div><div class="lbl-value" style="'+ _stle +'">'+ iV['bh_name'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';
                    
                    var d = new Date(iV['bh_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>Event 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['bh_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);
        
    
    
})


