/* 
 * Author       : Jai K
 * Purpose      : Main Script for "Kattalai Archanai  - Billing"
 * Created On   : 2016-09-02 12:37
 */

function setTotal() {
    var $fnType = $('[name="fn_type"] option:selected')
    ,   total   = 0;
    if( $('.edit-page').length > 0 ) {
        $fnType = $('[name="fn_type"]');
    }
    
    // Set Total Days
    $('#days-plot .no-of-days').each(function(){
        total += parseFloat($(this).val()) || 0;
    })
    $('#total-days').html(total);
    
    // Set Total Amount
    var Amt = $('[name="total_amount"]').val() || 0
    ,   total = 0;

    $('#days-plot .days-amt').each(function(){
        total += parseFloat($(this).val()) || 0;
    });
    $('#net-amt').html(total.toFixed(2));
    
    if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');

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

    }

    //total += parseFloat( $fnType.attr('data-amt') ) || 0;
    
    if( Amt > 0 ) {
        var delAmt = parseFloat($('[name="total_amount"]').attr('data-del-amt')) || 0
        ,   addAmt = parseFloat($('[name="total_amount"]').attr('data-add-amt')) || 0;
        
        total = Amt - delAmt;
        total += addAmt;
    }
    
    $('[name="total_amount"]').removeAttr('data-del-amt data-add-amt');
    
    $('[name="total_amount"], [name="pay_amount"]').val(total.toFixed(2));
    
    
    
    /*
    var edit_id = $('input[name="hidden_edit_id"]').val();
    var total = 0;
    
    // Final Amount
    var $fnType = $('[name="fn_type"] option:selected');
    if( $('.edit-page').length > 0 ) {
        $fnType = $('[name="fn_type"]');
    }
    
    var ser_amount = parseFloat($fnType.attr('data-amt'));
    
    if( ser_amount <= 0 ) {
        // Disable Payment Btn
        $('.sbmt-btn').attr('disabled', 'disabled');
        /* if(edit_id == '') {
            $('input[name="total_amount"]').removeClass('readonly');
            $('input[name="total_amount"]').removeAttr('readonly');
            $('input[name="total_amount"]').addClass('amount num-pad'); 
        } */
    /*}else {
        $('.sbmt-btn').removeAttr('disabled');
       /*  $('input[name="total_amount"]').addClass('readonly');
        $('input[name="total_amount"]').attr('readonly');
        $('input[name="total_amount"]').removeClass('amount num-pad'); */
    /*}
    
    // Set Total Days
    $('#days-plot .no-of-days').each(function(){
        total += parseFloat($(this).val()) || 0;
    })
    $('#total-days').html(total);
    
    // Set Total Amount
    total = 0;
    $('#days-plot .days-amt').each(function(){
        total += parseFloat($(this).val()) || 0;
    });
    
    $('#net-amt').html(total.toFixed(2));
    
    if( total <= 0 ) {
        $('.sbmt-btn').attr('disabled', 'disabled');
    }else {
        $('.sbmt-btn').removeAttr('disabled');
    }

    
    total += parseFloat($fnType.attr('data-amt')) || 0;
    
    $('[name="total_amount"], [name="pay_amount"]').val(total);
    */
 
    
}

function setDay() {
    var value = $('.day-type:checked').val()
    ,   sDate = $('#start-date').val()
    ,   eDate = $('#end-date').val()
    ,   days  = 0;  
    
    var ms = 24*60*60*1000
    ,   ss = sDate.split('-')
    ,   es = eDate.split('-')
    ,   sd = new Date(ss[2], ss[1]-1, ss[0])
    ,   ed = new Date(es[2], es[1]-1, es[0]);
    
    if( ed.getTime() < sd.getTime() ) {
        msgBox('End date can not be exceeded than start date');
        $('#end-date').val('');
        return false;
    }
    
    days = Math.round(Math.abs(sd.getTime()-ed.getTime())/ms);
    ++days; // include Start date
    
    // 1-9-2016
    /*for(i=1; i<=7; i++){
        var d = new Date(ss[2],ss[1], i+1);
        alert(d.getUTCDate()+'/'+d.getUTCMonth()+'/'+d.getUTCFullYear()+' => '+d.getUTCDay()+' '+d.getDay());
    }
    */
   
    if( value == '2' ) {
        // Weekly
        $('#week-days, #dates').slideDown('slow');
        $('#multiple-dates').slideUp('slow');
        
        if( days >= 0  ) {
        
            var asDay = sd.getDay()
            ,   aeDay = ed.getDay()
            ,   sDay    = asDay != 0 ? asDay : 7
            ,   eDay    = aeDay != 0 ? aeDay : 7
            ,   weekDay = parseInt($('#weekly-day').val()) // Monday | 1

            /*var dd = days;
           
            var df = weekDay < sDay ? sDay-weekDay : 0;
            days += df;*/

            /*var df = sDay;
            for( i = 1; i<= 7; i++ ) {


            }*/

            /*var df = weekDay < sDay ? (sDay-weekDay)-2 : 0;

            days = days-df;*/

            /*var df = sDay > weekDay ? 7-sDay : 0;
            df = df + ( weekDay % 7 );
            days = days-df;
            
           
            days = Math.ceil(days/7);
            days = days > days ? days : 0;
            
            alert('W: '+weekDay+' asDay:'+asDay+' df:'+days);
            
                days += days == 0 && ( aeDay == weekDay || asDay == weekDay ) ? 1 : 0;
                
                days += asDay != aeDay && days >= 2 && asDay == weekDay ? 1 : 0; // Include From Date day also
                */
            /*var df = (7-sDay)+weekDay;
            days = days-df;
            
            days = Math.floor(days/7);
            
            //alert('Days: '+dd+' DF:'+df+' W:'+weekDay+' sDay:'+sDay);
            
            //if( days < 7 ) {
                // Within 1 week
              //  days = 0;
                
                /*if( weekDay < df ) {
                    ++days;
                }*/
                
              /*  if( asDay == weekDay ) {
                    days += 1;
                }

                if( aeDay == weekDay && asDay != aeDay) {
                    days += 1;
                }
                
                
                
            //}*/
            
            
            var found = 0
            ,   dates = '';
            if( asDay == weekDay ) {
                found += 1;
                dates += sDate+',';
            }
            
            for(var i = 1; i<days; i++) {
                sd.setDate(sd.getDate()+1);
                
                if( sd.getDay() == weekDay ) {
                    ++found;
                    dates += getTwoDigits(sd.getDate())+'-'+getTwoDigits(sd.getMonth()+1)+'-'+sd.getFullYear()+',';
                }
            }
            
            days = found;
            dates = dates.substring(0, dates.length-1);
            $('#expanded-dates').val(dates);
            

            //days = days >= 0 ? days : 0;
        }
        
    }else {
        $('#week-days').slideUp('slow');
        
        if( value == '1' ) {
            // Daily
            $('#multiple-dates').slideUp('slow');
            $('#dates').slideDown('slow');

            var dates = sDate+',';
            for(var i = 1; i<days; i++) {
                sd.setDate(sd.getDate()+1);
                
                dates += getTwoDigits(sd.getDate())+'-'+getTwoDigits(sd.getMonth()+1)+'-'+sd.getFullYear()+',';
            }
            
            dates = dates.substring(0, dates.length-1);
            $('#expanded-dates').val(dates);
        
        }else {
            // Multiple
            days = $('#multiple-multi-date .option').length;
            
            $('#multiple-dates').slideDown('slow', function(){
                $('[name="multi_date"]').trigger('focus');
            });
            $('#dates').slideUp('slow');
        }
    }
    
    $('#no-of-days').val(days > 0 ? days : 0);
}


$(document).on('ready', function(){
    var inter = '';
    /* $('#sbmt-cancel-btn').on('click', function(){
        $('#payment-btn').removeClass('dialog-btn').removeAttr('data-target');
    }) */
    
    
    $('input[name="total_amount"]').keyup(function() {
        // Set Total Amount
        $('input[name="total_amount"], [name="pay_amount"]').val($(this).val());
    })
    
    $('.sbmt-btn').on('click', function(){
        var $this = $(this)
        ,   cs_amount = payAmt = $('input[name="total_amount"]').val()
        ,   paidAmt   = parseFloat($('#payment-btn').attr('data-paid-amt')) || 0;
        
        $('[name="pay_amount"]').val( cs_amount );
        
        //var already_paid_amt = ($('input[name="hidden_amount"]').val() !== undefined) ? $('input[name="hidden_amount"]').val() : 0;
        
        var edit_id = $('input[name="hidden_edit_id"]').val();
        var book_status = $('input[name="book_status"]').val();
        
        if((edit_id == '' && (book_status == '' || book_status == 1))) {
            if( !$this.hasClass('dialog-btn') ) {
                if( autoValidate() ) {
                    $('.sbmt-btn').removeAttr('disabled');
                    
                    if( $this.attr('id') == 'payment-btn') {
                        // Payment
                        $('.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="paid_amount"]').val((parseFloat(payAmt)).toFixed(2)); 
                    $('#sbmt-btn').removeAttr('disabled');                    
                    return true;
                }else {
                    
                    $('.sbmt-btn').attr('disabled', '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( autoValidate() ) {
                if( $this.attr('id') == 'payment-btn' && !$this.hasClass('dialog-btn')) {
                    // Payment
                    $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                    $this.addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                    return false;
                }
                
                var toPay = (payAmt - paidAmt).toFixed(2);
                if(edit_id == '') {
                    // Add Page
                    $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val( toPay );
                
                }else {    
                    $('[name="paid_amount"]').val('');
                    var $bank_name = $('#cheque-box .hidden_bank_name').val();
                    var $cheque_no = $('#cheque-box .hidden_chq_no').val();
                    var $cheque_date = $('#cheque-box .hidden_chq_date').val();
                    
                    $('#cheque-box [name="chq_bnk_name"]').val($bank_name);
                    $('#cheque-box [name="chq_no"]').val($cheque_no);
                    $('#cheque-box [name="chq_date"]').val($cheque_date);
                }
                
                if( toPay == 0 || toPay == parseFloat( $('[name="paid_amount"]').val() ) ) {
                    $('#sbmt-btn').removeAttr('disabled');
                }else {
                    $('#sbmt-btn').attr('disabled', 'disabled');
                }
                
                return true;
            }else {
                
                $('.sbmt-btn').attr('disabled', 'disabled');
            }
            
            return false;
            
            
        } 
        /* else {
            //msgBox('Amount is already paid!','','info');
            //window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
           // }, 3500);
        } */
    })
    
    
    $('#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');
    });
    
    $('.day-type').on('ifClicked', function(){
        setTimeout(function(){
            setDay();
            
        })
        
    });
    
    $('#start-date, #end-date, #weekly-day').on('change', function(){
        setDay();
    })
    
    $('#days-wrapper .add-btn').on('click', function(){
        var msg = '';
        if( $('[name="fn_type"]').val() == '' ){
            msg = 'Please choose the archanai type!';
        }else if( $('[name="fn_deity"]').val() == '' ){
            msg = 'Please choose the deity!';
        }else if( $('#no-of-days').val() <= 0 ) {
            msg = 'Please choose the days!';
        }
        
        if( msg != '' ) {
            // Errors
            msgBox(msg);
            return false;
        }
        
        //if( $('#days-wrapper').parent().find('#days-plot').length == 0 ) {
        if( $('#days-wrapper #days-plot').length == 0 ) {
            var html = '<table>' 
                +  '<thead>'
                 +  '<tr>'
                    +  '<th width="17%">Type</th>'
                    +  '<th width="23%">Deity(s)</th>'
                    +  '<th width="30%">Date(s)</th>'
                    +  '<th width="14%">No. of Days</th>'
                    +  '<th>Amount</th>'
                    +  '<th>Action</th>'
                 +  '</tr>'
                 +  '</thead>'
                 +  '<tbody></tbody>'
                 +  '<tfoot>'
                    +  '<td colspan="3"></td>'
                    +  '<td id="total-days" align="center">0</td>'
                    +  '<td id="net-amt" align="right">0.00</td>'
                    +  '<td>&nbsp;</td>'
                 +  '</tfoot>'
                 + '</table>';
            $('#days-wrapper').append('<div id="days-plot">'+html+'</div>');
        }
        
        var type    = $('.day-type:checked').val()
        ,   typeLbl = $('.day-type:checked').parent().closest('.input-group').find('label').text()
        ,   days    = $('#no-of-days').val() || 0
        ,   dateVal = weekDay = startDate = endDate = dates = '';
        
        if( type == '3' ) {
            // Multiple
            dates = dateVal = $('[name="multi_date"]').val(); 
            
            var split   = dates.split(',');
            startDate   = split[0];
            endDate     = split[split.length-1];
                 
        }else {
            startDate   = $('#start-date').val(); 
            endDate     = $('#end-date').val();
            dates = $('#expanded-dates').val();
            
            if( type == 2 ) {
                weekDay = $('#weekly-day').val();
                typeLbl += ' - <b style="font-size: 12px; color: #1ba;">'+$('#weekly-day option:selected').text()+'</b>';
                
                dateVal = dates ;//startDate+' <b style="color: #999;">to</b> '+endDate;
            }else {
                // Daily
                dateVal = startDate+' <b style="color: #999;">to</b> '+endDate;
            }
    
        }
        
        var len = $('#days-plot table tr').length
        ,   deityLbl = ''
        ,   amt = 0
		
		var fn_type = $('[name="fn_type"] option:selected').attr('data-amt');
		
		if(typeof fn_type == 'undefined' || fn_type == '' || fn_type == null){
			 var fn_type = $('[name="fn_type"]').attr('data-amt');
		}
        
        $('[name="multi-fn_deity"] option:selected').each(function(ik, iv){
            var price = $(this).attr('data-price') || 0;//$('[name="multi-fn_deity"] option:selected:eq('+ik+')').attr('data-price');
            //alert('Price: '+price+' k:'+ik+$(this).val());
            if( price != 0 ) {
                deityLbl += $(this).text()+',';
                if (parseFloat(fn_type) > 0) {
					amt += parseFloat(fn_type);
				} else {
					amt += parseFloat(price);
				}
            }
            
        })
        deityLbl = deityLbl.substring(0, deityLbl.length-1);
        
        amt *= days;
        
        html = '<tr '+(len % 2 != 0 ? 'style="background: #fff;"' : '')+'>'
                +  '<td>'+typeLbl+'<input type="hidden" name="day_type[]" value="'+$('.day-type:checked').val()+'"><input type="hidden" name="weekly_day[]" value="'+weekDay+'"></td>'
                +  '<td>'+deityLbl+'<input type="hidden" name="deity[]" value="'+$('[name="fn_deity"]').val()+'"><input type="hidden" name="expand_dates[]" value="'+dates+'"></td>'
                +  '<td>'+dateVal+'<input type="hidden" name="start_date[]" value="'+startDate+'"><input type="hidden" name="end_date[]" value="'+endDate+'"></td>'
                +  '<td align="center">'+days+'<input type="hidden" name="no_of_days[]" class="no-of-days" value="'+days+'"></td>'
                +  '<td align="right">'+amt.toFixed(2)+'<input type="hidden" name="days_amt[]" class="days-amt" value="'+amt+'"></td>'
                +  '<td class="ctrls"><i class="fa fa-times rm-btn"></i></td>'
             +  '</tr>';
     
        $('#days-plot table tbody').append(html);
        
        $('[name="total_amount"]').attr('data-add-amt', amt.toFixed(2));
        
        setTotal();
        
    })
    
    $(document).on('click', '#days-plot table .rm-btn', function(){
        var $parent = $(this).parent().closest('tr');
        
        if( window.confirm( "Are you sure about to remove?" ) ) {
            var stotal  = $parent.find('.days-amt').val();
            $('[name="total_amount"]').attr('data-del-amt', stotal);
            
            if( $parent.find('.db-id').length > 0 ) {
                /*
                 * Take the db id of removing items
                 */
                if( $('[name="removed-items"]').length == 0 ) {
                    $('form').append('<input type="hidden" name="removed-items" value="">');
                }

                var valStr = $('[name="removed-items"]').val();
                valStr += '-'+$parent.find('.db-id').val();
                $('[name="removed-items"]').val(valStr);
             }

            $parent.fadeOut('slow', function(){
                $(this).remove();
                if($('#days-plot table .ctrls').length == 0) {
                    $('#days-plot').fadeOut(400, function(){$(this).remove()});
                }
                setTotal();
            })
        }
    })
    
    $('[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(),
        };
        
        $.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>Name</div><div class="lbl-value" style="'+ _stle +'">'+ iV['bk_name_1'] +'</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['bk_tamil_name_1'] != '' ? iV['bk_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>Archanai 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['bk_amount'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';

                    var d = new Date(iV['bk_begin_date']);

                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Begin 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 d = new Date(iV['bk_end_date']);

                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>End 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_kattalai_archanai/edit/' + iV['id'] + '/'+ iV['type_id'] + '"> <span>Edit</span></a></div>';
                    html +=         '</div>';
                    html +=     '</div>';

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

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

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

        });
        
    }); // filter-btn    
    
})