/* 
 * 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));

    //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;
    }*/
    
	$('.stotal').each(function(i, iKey){
        var value = parseFloat( $(this).val() ) || 0;
        //console.log( 'Sub :' + value );
        
        total += parseFloat( value );
    });
	
    if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');

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

    }
	
    $('[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;  
    
	if(value != 3){
		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);
	
	var pr_dates = (dates) ? dates : $('[name="multi_date"]').val(); 
	//var select_dates = $('#expanded-dates').val();
	$('.row-details-clone').remove();	
	$('.innr-table').find('select').each(function(){
		$(this).attr('id', $(this).attr('id')).val('');
	});
	$('.innr-table .row-details:last .ctrls').html('<i class="fa fa-plus-circle add-btn"></i>');
	$('.pr-day').val(value);
	$('.pr-dates').val(pr_dates);
	$('.pr-week-day').val(weekDay);
	$('.pr-no-day').val(days);
	$('.pr-qty').val(1);
	$('.stotal').val('');
	$('.pr-price').val('');
	$('.rm-btn').hide();
	//console.log("HERE");
}


$(document).on('ready', function(){
    var inter = '';
    /* $('#sbmt-cancel-btn').on('click', function(){
        $('#payment-btn').removeClass('dialog-btn').removeAttr('data-target');
    }) */
	
	 // Add Items
    $(document).on('keyup', '.innr-table .pr-qty, .innr-table .pr-price', function(){
        var total = 0
        ,   $row    = $(this).parent().closest('.row-details')
		,   days   = $('#no-of-days').val() || 0
        ,   qty   = $row.find('.pr-qty').val() || 0
        ,   price   = $row.find('.pr-price').val() || 0
        ,   $stotal = $row.find('.stotal')
        ,   pstotal  = $stotal.val() || 0
        ,   nstotal = (days * qty * price).toFixed(2);
        
        $stotal.val( nstotal );
        
		//console.log(days);return false;
		
        $('[name="amount"]').attr('data-add-amt', ( pstotal > 0 ? nstotal - pstotal : nstotal ));
        
        setTotal();
    });
	
    
    $('input[name="amount"]').keyup(function() {
        $('[name="hidden_amount"]').val($(this).val());
    });
    
  
    $(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();
               // add_desc();
            })
        }
        
        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-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').addClass('row-details-clone');
            
            $clone.find('.pr-deity').val(deity);
			$clone.find('.pr-qty').val("1");

        } else {
           msgBox('Please Choose Deity and Prasadam!');
           $row.find('.pr-deity').focus();
           $row.find('.pr-prasadam').focus();
        }
        //add_desc();
        
    });
    
    $('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 );
        
		$.ajax({
			url: base_url + 'billing_kattalai_archanai/kattalai_bill_amount',
			data: {amount: parseFloat(payAmt).toFixed(2)},
			dataType: 'JSON',
			type: 'post',
			'global': false,
			'async': false,
			success: function (output) {
				//tmp = output;
			}
		});
		
        //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();
            })
        }
    })
	
	if($('[name="type_name"]').val() == 'Kattalai Prasatham' ) {
		$('#deity_input').hide();
		$('#calculate_btn').hide();
		$('#prasadam-section').show();
		$('#prasadam_period').show();
		$('.pr_period').addClass('req');
		$('#days-plot').hide();
	}else{         
		$('[name="pr_period"]').val('');   
		$('#deity_input').show();
		$('#calculate_btn').show();
		$('#prasadam-section').hide();
		$('#prasadam_period').hide();
		$('.pr_period').removeClass('req');
		$('.pr_period').val('');
		$('#days-plot').show();
	}
    
    $('[name="fn_type"]').on('change', function(){
        //setTotal();
		var value = $('[name="fn_type"] option:selected').text();
				
		if( value == 'Kattalai Prasatham' ) {
            $('#deity_input').hide();
			$('#calculate_btn').hide();
			$('#prasadam-section').show();
			$('#prasadam_period').show();
			$('.pr_period').addClass('req');
			$('.pr_period').val(1);
        }else{         
			$('[name="pr_period"]').val('');   
			$('#deity_input').show();
			$('#calculate_btn').show();
			$('#prasadam-section').hide();
			$('#prasadam_period').hide();
			$('.pr_period').removeClass('req');
			$('.pr_period').val('');
        }
    });
    
    
    $(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    
    
})

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_kattalai_archanai/get_prasadam_price',
            type: 'POST',
            data: { id: prasadam},
            dataType: "json"
        }).done(function(data) {
            if(parseFloat(data.price) > parseFloat(0)) {
              var price = $(_this).parent().closest('.row-details').find('.pr-price').val(data.price);
                //$(_this).parent().closest('.row-details').find('.pr-price').attr('readonly','readonly');
				
				 var total = 0
				,   $row    = $(_this).parent().closest('.row-details')
				,   days   = $('#no-of-days').val() || 0
				,   qty   	= $row.find('.pr-qty').val() || 0
				,   price   = $row.find('.pr-price').val() || 0
				,   $stotal = $row.find('.stotal')
				,   pstotal = $stotal.val() || 0
				,   nstotal = (days * qty * price).toFixed(2);
				
				$stotal.val( nstotal );
				
				$('[name="amount"]').attr('data-add-amt', ( pstotal > 0 ? nstotal - pstotal : nstotal ));
				
				setTotal();
            } else {
                $(_this).parent().closest('.row-details').find('.pr-price').val('');
                //$(_this).parent().closest('.row-details').find('.pr-price').removeAttr('readonly');
            }
        }).fail(function(XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
    }
    
    deity_prasadam_exists(_this,2);
    
}

function deity_prasadam_exists(_this,name) {
   // add_desc();
    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;
}