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

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

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

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

    }

    $('.stotal').each(function(i, iKey){
        var value = parseFloat( $(this).val() ) || 0;
        total += parseFloat( value );
    });
    
    
    if( Amt > 0 ) {
        // Toatl => 60
        // Amt => 300
        // Dele => 200
        var delAmt = parseFloat($('[name="amount"]').attr('data-del-amt')) || 0
        ,   addAmt = parseFloat($('[name="amount"]').attr('data-add-amt')) || 0;
        
        total = Amt - delAmt;
        total += addAmt;
    }
    
    $('[name="amount"]').removeAttr('data-del-amt data-add-amt');
    
    if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');
    }else {
        $('#payment-btn').removeAttr('disabled');
    }
    
    
    
    /*var already_paid_amt = $('input[name="hidden_amount"]').val();
    var paying_amt = parseFloat(total) - parseFloat(already_paid_amt);
    var book_status = $('input[name="book_status"]').val();*/


    $('[name="amount"], [name="pay_amount"]').val( total.toFixed(2) );
     
     /*
    if(edit_id == '' || book_status === undefined) {
        // Add
        $('[name="amount"], [name="pay_amount"]').val( total.toFixed(2) );
    } else if(edit_id != '' && book_status == 2) {
        // Edit booked
        $('[name="amount"], [name="pay_amount"]').val( total.toFixed(2) );
    } else {
        // Edit
        $('[name="amount"], [name="pay_amount"]').val( total.toFixed(2) );
    }*/
    
    
}

var inter = '';
$(document).on('ready', function() {
	
	$('.contact-no').keyup(function () {
		var name_1 = $('[name="dev_name_1"]').val();
		var name_2 = $('[name="dev_name_2"]').val();
		var tname_1 = $('[name="tamil_name_1"]').val();
		var tname_2 = $('[name="tamil_name_2"]').val();
		var star_1 = $('[name="star_1"]').val();
		var star_2 = $('[name="star_2"]').val();
		var email = $('[name="email"]').val();
		
        $.ajax({
            async: false,
            url: base_url + 'billing_prasadam/get_basic_details',
            type: 'POST',
            data: {contact_no: $(this).val()},
            dataType: "json"
        }).done(function (data) {
            if (data.prasadam != '') {
                (name_1 == '' && data.prasadam.bp_dev_name_1) ? $('[name="dev_name_1"]').val(data.prasadam.bp_dev_name_1):'';
                (name_2 == '' && data.prasadam.bp_dev_name_2) ? $('[name="dev_name_2"]').val(data.prasadam.bp_dev_name_2):'';
                (tname_1 == '' && data.prasadam.tamil_name_1) ? $('[name="tamil_name_1"]').val(data.prasadam.bp_tamil_name_1):'';
                (tname_2 == '' && data.prasadam.tamil_name_2) ? $('[name="tamil_name_2"]').val(data.prasadam.bp_tamil_name_2):'';
                (star_1 == '' && data.prasadam.star_1) ? $('[name="star_1"]').val(data.prasadam.star_id_1):'';
                (star_2 == '' && data.prasadam.star_2) ? $('[name="star_2"]').val(data.prasadam.star_id_2):'';
				(email == '' && data.prasadam.bp_email) ? $('[name="email"]').val(data.prasadam.bp_email):'';
            }
        }).fail(function (XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
    });
    
    $('#booked-dialog .reset-btn').click(function() {
        // No results
        html = '<div class="col-xs-12" style="text-align: center; color: #1ba;">Sorry, No results found</div>';
        $('#booked-details').html(html).fadeIn('slow');
    });
    
    // Add Items
    $(document).on('keyup', '.innr-table .pr-qty, .innr-table .pr-price', function(){
        var total = 0
        ,   $row    = $(this).parent().closest('.row-details')
        ,   qty   = $row.find('.pr-qty').val() || 0
        ,   price   = $row.find('.pr-price').val() || 0
        ,   $stotal = $row.find('.stotal')
        ,   pstotal  = $stotal.val() || 0
        ,   nstotal = (qty * price).toFixed(2);
        
        $stotal.val( nstotal );
        
        $('[name="amount"]').attr('data-add-amt', ( pstotal > 0 ? nstotal - pstotal : nstotal ));
        
        setTotal();
    });
    
    $('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');
            
            $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();
        
    });
    
    
    /*$('#bkd-btn').on('click', function(){
        $('#booked-dialog .filter-btn').trigger('click'); 
    });*/
    
    /* $('#sbmt-cancel-btn').on('click', function(){
        //$('[name="paid_amount"], .ptype-box input').val('');
        $('#payment-btn').removeClass('dialog-btn').removeAttr('data-target');
        
    }) */
    
    $('#payment-btn').on('click', function(){
        //\get_desc();
        //event.stopImmediatePropagation(event);
		
        var cs_amount = $('input[name="amount"]').val();
        $('[name="pay_amount"]').val(cs_amount);
        
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 ? true : false;
		
		$.ajax({
			url: base_url + 'billing_prasadam/prasadam_bill_amount',
			data: {amount: 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((parseFloat(already_paid_amt) < parseFloat(cs_amount)) || (edit_id == '' && (book_status == '' || book_status == 1))) {
        if((edit_id == '' && (book_status == '' || book_status == 1))) {    
            if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            
            return false;
        } /* else if((parseFloat(already_paid_amt) > parseFloat(cs_amount)) && (edit_id != '' && book_status == 1)) {
            var paying_amt = parseFloat(already_paid_amt) - parseFloat(cs_amount);
            msgBox('Amount ' + ((parseFloat(paying_amt)).toFixed(2)) + ' is Refunded!','','info');
            window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
            }, 3500);
        
        }  */else if(edit_id != '' && book_status == 2) {
           if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }
            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            $('#sbmt-btn').removeAttr('disabled');
            return false;
        
        
        } else{
           if( autoValidate() && !$(this).hasClass('dialog-btn') ) {
                // Go to payment
                if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                
                $('.ptype-box input:first').parent().closest('.modal').find('.err-blck').html('');
                $(this).addClass('dialog-btn').attr('data-target','#ptypes-dialog').trigger('click');
                return true;
            }else if( toDisable ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }

            if(edit_id == '') {
                $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
            }

            if(edit_id != '') {
                var $bank_name = $('#cheque-box .hidden_bank_name').val();
                var $cheque_no = $('#cheque-box .hidden_chq_no').val();
                var $cheque_date = $('#cheque-box .hidden_chq_date').val();
                
                $('#cheque-box [name="chq_bnk_name"]').val($bank_name);
                $('#cheque-box [name="chq_no"]').val($cheque_no);
                $('#cheque-box [name="chq_date"]').val($cheque_date);
            }
            //$('#sbmt-btn').removeAttr('disabled');
            return false;
        
        
        } /*  else {
            //msgBox('Amount is already paid!','','info');
            //window.setTimeout(function(){
                $('[type="submit"]').removeAttr('disabled').trigger('click');
           // }, 3500);
        } */
    })
    
    $('.payment-btn').on('click', function(){
        //\get_desc();
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
        ,   toDisable = paidAmt <= 0 || payAmt != paidAmt ? true : false;
        
        if( autoValidate()) {
            return true;
        }
        return false;
    })
    
    $('[name="fn_type"]').on('change', function(){
		var fnType = $(this).find("option:selected").text();
		if(fnType == "Indoor Prasadam"){
			$('#required').show();
			$('.pr-deity').addClass("req");
		}else{
			$('#required').hide();
			$('.pr-deity').removeClass("req");
		}		
        setTotal();
    });
    
    $(document).on('click', '.modal .filter-btn', function(){
        
        var $appnedTo = $('#booked-dialog .modal-footer')
        ,   style = 'padding: 0px 2px;'
        ,   html = '';
        
        if( $appnedTo.find('#booked-details').length == 0 ) {
            $appnedTo.append('<div id="booked-details" class="resp-table"></div>');
        }
        
        var $bookedWrapper = $appnedTo.find('#booked-details');
        
        $bookedWrapper.html( '<div class="col-xs-12" style="text-align: center; color: #1ba;">Please wait ...</div>' );
        
        var data = {
            act     : 'booked',
            fromDate: $('[name="bk_from_date"]').val(),
            toDate: $('[name="bk_to_date"]').val(),
            period: $('[name="bk_period"]').val()
        };
        
        $.post( base_url + controller + '/ajax/', data, function( results ){
            results = JSON.parse( results );
            if( results != '' ) {
                
                Object.keys( results ).map(function(i, iV){
                    iV = results[i];
                    var _stle = i % 2 != 0 ? 'background: rgba(17, 187, 170, 0.06);' : '';

                    html += '<div class="col-xs-12">';

                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Devotee Name</div><div class="lbl-value" style="'+ _stle +'">'+ iV['bp_dev_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['bp_tamil_name_1'] != '' ? iV['bp_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['bp_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['bp_amount'] +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';

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

                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Function Date</div><div class="lbl-value" style="'+ _stle +'; text-align: right;">'+ ( getTwoDigits( d.getDate() ) +' '+ monthNames[d.getMonth()] +' '+d.getFullYear() ) +'</div>';
                    html +=         '</div>';
                    html +=     '</div>';
                    
                    html +=     '<div class="col-md-2" style="'+ style +'">';
                    html +=         '<div class="form-group">';
                    html +=             '<div class="lbl"><i class="fa fa-fire"></i>Action</div><div class="lbl-value" style="'+ _stle +';text-align: center;"><a class="label btn btn-primary edit" href="' + base_url + 'billing_prasadam/edit/' + iV['id'] + '/' + 15 +'"> <span>Edit</span></a>';
				    html += 				'<a class="label btn btn-danger delete" href="' + base_url + 'billing_prasadam/delete/' + iV['id'] + '/' + 15 + '"> <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');
            });

        });
        
        
    });
    
})


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_prasadam/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')
				,   qty   	= $row.find('.pr-qty').val() || 0
				,   price   = $row.find('.pr-price').val() || 0
				,   $stotal = $row.find('.stotal')
				,   pstotal = $stotal.val() || 0
				,   nstotal = (qty * price).toFixed(2);
				
				$stotal.val( nstotal );
				
				$('[name="amount"]').attr('data-add-amt', ( pstotal > 0 ? nstotal - pstotal : nstotal ));
				
				setTotal();
            } 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;
}

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

/*\function get_desc() {
    var desc = '';
    var text_desc = '';
    if($('.row-details').length > 0){
        $('.row-details').each(function() {
            var deity = $(this).find('.pr-deity option:selected').text();
            var prasadam = $(this).find('.pr-prasadam option:selected').text();
            var qty = parseFloat($(this).find('.pr-qty').val()) || 0;
            var stotal = parseFloat($(this).find('.stotal').val()) || 0;
            desc += deity + '-' + prasadam + '-' + qty + '-' + stotal + ',';
        });
    } 
    text_desc += desc;
    var lastChar = text_desc.slice(-1);
    if(lastChar == ',') {
      text_desc = text_desc.slice(0, -1);
    }
    $('textarea[name="desc"]').val(text_desc);
}*/
