var inter = '';
$(document).ready(function() {

    $('input[name="topup_amount"]').click(function() {
        settopupTotal();
    });
    
    $('input[name="topup_amount"]').keyup(function() {
        settopupTotal();
    });
    
    
    if($('input[name="amount"]').val() != '') {
         setTotal();
    }
    
    $('.card_val').click(function() {
        $('[name="topup_amount"]').val($(this).attr('data-value'));
    });
    $('.num-pad .ok-btn').click(function(){
        $('.check_unique').trigger('change');
    });
    
    if($('.check_unique').hasClass('email') && $(this).val() != '' && !validateEmail( $(this).val() )) {
        $(this).val('').focus();
        msgBox('Please enter valid Email Address!');
    }
    
    $('.check_unique').change(function(){
        if($(this).attr('name') == 'contact_no') {
            var field_name = 'Contact No';
        }
        else if($(this).attr('name') == 'email') {
            var field_name = 'Email';
            if($(this).hasClass('email') && !validateEmail( $(this).val() )) {
                $(this).val('').focus();
                msgBox('Please enter valid Email Address!');
            }
        }
        var id = $('input[name="hidden_id"]').val();
        if($(this).val() != '') {
            $.ajax({
                async: false,
                url: base_url + 'billing_membership_card/check_contact_email_exists',
                type: 'POST',
                data: { field_name: field_name, id: id, val: $(this).val()},
                dataType: "json"
            }).done(function(data) {
                if(data == 1) {
                    if(field_name == 'Contact No')
                       $('.contact-no').val('');
                    
                    if(field_name == 'Email')
                       $('.email').val('').focus();
                    
                    msgBox( field_name + ' is already exists!');
                    return false;
                }
                
            }).fail(function(XHR, status_code, error_thrown) {
                    console.log(error_thrown);
            });
        }
        
    });
    
    $(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('');
        });
        
        $row.find('.ctrls').html('<i class="fa fa-power-off rm-btn" style="color: #f00;"></i>');
        $clone.find('.ctrls').html('<i class="fa fa-plus-circle add-btn"></i> <i class="fa fa-power-off rm-btn" style="color: #f00;"></i>');
        
        $innr.find('.row-details:last-child').after( $clone );
        
    });
    
    $(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');
            
            $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();
            })
            
           // $row.find('.ctrls').html('<i class="fa fa-plus-circle add-btn"></i> <i class="fa fa-power-off rm-btn" style="color: #f00;"></i>');
           
            if($this.parent().closest('.row-details:last-child').prevAll().find('.ctrls').length > 1) {
                $this.parent().closest('.row-details:last-child').prev().find('.ctrls').html('<i class="fa fa-plus-circle add-btn"></i> <i class="fa fa-power-off rm-btn" style="color: #f00;"></i>');
            } else if($this.parent().closest('.row-details').prevAll().find('.ctrls').length == 0 && $this.parent().closest('.row-details').next().find('.ctrls').length > 0) {
                $this.parent().closest('.row-details').next().find('.ctrls').html('<i class="fa fa-plus-circle add-btn"></i>');
            }else {
                $this.parent().closest('.row-details:last-child').prev().find('.ctrls').html('<i class="fa fa-plus-circle add-btn"></i>');
            }
        }
        
        return false;
        
    });
    
    $('#sbmt-cancel-btn').on('click', function(){
        if(method == 'add') {
            $('[name="paid_amount"], .ptype-box input').val('');
        }
        $('#payment-btn').removeClass('dialog-btn').removeAttr('data-target');
    })
    
    $('#payment-btn').on('click', function(){
        $('input[name="password"]').trigger('change');
        var valid_pwd = check_valid_pwd($('input[name="password"]'));
        if($(this).attr('class') == 'mem_topup') {
            settopupTotal();
        } else if($(this).attr('class') == 'btn btn-danger add') {
            setTotal();
        }
        //$('.check_unique').trigger('change');
        if(valid_pwd == 1 || (valid_pwd == 0 && $(this).attr('class') == 'btn btn-danger add') ) {  
            var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
            ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
            ,   toDisable = paidAmt <= 0 ? true : false;
            
            var edit_id = $('input[name="hidden_id"]').val();
            if(edit_id == '') {
                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');
                    $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val((parseFloat(payAmt)).toFixed(2));
                    return true;
                }else if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                $('#sbmt-btn').removeAttr('disabled');
                return false;
            } else {
                //msgBox('Amount is already paid!','','info');
               // window.setTimeout(function(){
                    $('[type="submit"]').removeAttr('disabled').trigger('click');
                //}, 3500);
            }
        }
    })
    
    /* $('.ptype-box input').on('keyup', function(){
        window.clearTimeout(inter);
        var $this   = $(this);
        
        inter = window.setInterval(function(){
            window.clearTimeout(inter);
            var   value   = $this.val()
            ,   $errBlck = $this.parent().closest('.modal').find('.err-blck')
            ,   total   = 0
            ,   payAmt  = parseFloat( $('[name="pay_amount"]').val() );

            $('.ptype-box input').each(function(){

                total += parseFloat( $(this).val() ) || 0;
            })

            if( total <= 0 ) {
                $('[type="submit"]').attr('disabled', 'disabled');
            }else if( total > payAmt ) {

                total -= value;

                value = (total - (total-payAmt))-total;
                total += value;
                $this.val((value > 0 ? value : ''));

                $('[type="submit"]').attr('disabled', 'disabled');
                $errBlck.html( 'Amount can not be exceeded than payable amount!' ).slideDown('slow');
                window.setTimeout(function(){
                    $errBlck.slideUp('slow', function(){ $(this).html('') }); 
                    $('[type="submit"]').removeAttr('disabled');
                }, 3500);
                
            }else {
                
                $errBlck.slideUp('slow', function(){ $(this).html('') });
                
                if( payAmt == total ) {
                    $('[type="submit"]').removeAttr('disabled');
                }else {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
            }

            $('[name="paid_amount"]').val( total.toFixed(2));
        }, 400);    
        
    }) */
    
    $('input[name="card_no"]').keyup(function(){
        var card_no = $(this).val();
        if(card_no != '') {
            $.ajax({
                async: false,
                url: base_url + 'billing_membership_card/get_t_card_details',
                type: 'POST',
                data: { card_no: card_no},
                dataType: "json"
            }).done(function(data) {
                if(data != '') {
                    $('input[name="name"]').val(data.name).attr('readonly','readonly');
                    $('input[name="amount"]').val(data.amount);
                    $('input[name="tamil_name"]').val(data.tamil_name).attr('readonly','readonly');
                    $('input[name="email"]').val(data.email).attr('readonly','readonly');
                    $('input[name="contact_no"]').val(data.contact_no).attr('readonly','readonly');
                    $('textarea[name="address"]').val(data.address).attr('readonly','readonly');
                    $('.star_div_txt').html('<label>Star</label><input type="text" class="form-control req" name="star" value="' + data.star_name + ' / ' + data.tamil_star +'" readonly />');
                    $('.star_div_txt').show();
                    $('.star_div').hide();
                    $('input[name="hidden_id"]').val(data.id);
                    $('.member_edit').html('<button class="btn btn-primary" type="reset" id="clrbtn" onclick="setDisplay();"><i class="fa fa-trash"></i> Clear</button> <button type="submit" id="sbmt-btn1" class="btn btn-danger add" name="submit" value="Submit" ><i class="fa fa-floppy-o"></i> Submit</button>');
                    $('.blck2').show();
                } else {
                    $('input[name="name"]').val('').removeAttr('readonly','readonly');
                    $('input[name="amount"]').val('10.00');
                    $('input[name="tamil_name"]').val('').removeAttr('readonly','readonly');
                    $('input[name="email"]').val('').removeAttr('readonly','readonly');
                    $('input[name="contact_no"]').val('').removeAttr('readonly','readonly');
                    $('textarea[name="address"]').val('').removeAttr('readonly','readonly');
                    $('.star_div_txt').html('');
                    $('.star_div_txt').hide();
                    $('.star_div').show();
                    $('.star_div select').val('');
                    $('input[name="hidden_id"]').val('');
                    /* $('.member_edit .add').removeAttr('type').attr('type','button');
                    $('.member_edit .add').attr('id','payment-btn');
                    $('.member_edit .add').removeAttr('name');
                    $('.member_edit .add').removeAttr('value');
                    $('.member_edit .add').html('<i class="fa fa-credit-card"></i> Payment'); */
                    
                    $('.member_edit').html('<button class="btn btn-primary" type="reset" id="clrbtn"><i class="fa fa-trash"></i> Clear</button> <button type="button" class="btn btn-danger add" id="payment-btn" onclick="paymentOption(this);"><i class="fa fa-credit-card"></i> Payment</button>');
                    $('.blck2').hide();
                }
                
            }).fail(function(XHR, status_code, error_thrown) {
                console.log(error_thrown);
            });
        } else {
            $('input[name="name"]').val('').removeAttr('readonly','readonly');
            $('input[name="amount"]').val('10.00');
            $('input[name="tamil_name"]').val('').removeAttr('readonly','readonly');
            $('input[name="email"]').val('').removeAttr('readonly','readonly');
            $('input[name="contact_no"]').val('').removeAttr('readonly','readonly');
            $('textarea[name="address"]').val('').removeAttr('readonly','readonly');
            $('.star_div_txt').html('');
            $('.star_div_txt').hide();
            $('.star_div').show();
            $('input[name="hidden_id"]').val('');
            $('.member_edit').html('<button class="btn btn-primary" type="reset" id="clrbtn"><i class="fa fa-trash"></i> Clear</button> <button type="button" class="btn btn-danger add" id="payment-btn"><i class="fa fa-credit-card"></i> Payment</button>');
            $('.blck2').hide();
        }
    });
    
    $(document).on( 'keypress', '.t_card_no', function (e) {
        if (e.charCode==13) {
            $('input[name="t_card_no"]').trigger('change');
            return false;
        }
    });
    
    $('input[name="t_card_no"]').change(function(){
        var $this   = $(this);
        var card_no = $this.val();
        if(card_no != '') {
            $.ajax({
                async: false,
                url: base_url + 'billing_membership_card/get_t_card_details',
                type: 'POST',
                data: { card_no: card_no},
                dataType: "json"
            }).done(function(data) {
                if(data != '') {
                    $('.t_name').val(data.name);
                    $('.t_balance_amount').val(data.amount);
                    $('.mem_id').val(data.id);
                    $('.user_id').val(data.created_by);                    
                } else {
                    window.clearTimeout(inter);
                    inter = window.setInterval(function(){
                        window.clearTimeout(inter);
                        var $errBlck = $this.parents().find('.box-body .err-blck');
                            
                        $errBlck.html( 'Invalid Card No!' ).slideDown('slow');
                        window.setTimeout(function(){
                            $errBlck.slideUp('slow', function(){ $(this).html('') });
                            //$('#payment-btn').removeAttr('disabled');
                        }, 3500);
                            
                        
                    }, 400);

                    $('.t_name').val('');
                    $('.t_balance_amount').val('');
                    $('.mem_id').val('');
                    $('.user_id').val('');
                } 
                
                
            }).fail(function(XHR, status_code, error_thrown) {
                console.log(error_thrown);
            });
        } else {
            $('.t_name').html('');
            $('.t_balance_amount').html('');
            $('.mem_id').val();
            $('.user_id').val('');
        }
    });
    
    $('input[name="password"]').change(function(){
        var valid_pwd = check_valid_pwd(this);
        settopupTotal();
    });
    
});

function setTotal() {
    // Calculate Prasadam Total
    var total = ($('[name="amount"]').val() != '') ? parseFloat($('[name="amount"]').val()) : 0;
    if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');
    }else {
        $('#payment-btn').removeAttr('disabled');
    }
    
    $('[name="pay_amount"]').val( total.toFixed(2) );
    
    
}

function settopupTotal() {
    // Calculate Prasadam Total
    var total = ($('[name="topup_amount"]').val() != '') ? parseFloat($('[name="topup_amount"]').val()) : 0;
    if( total <= 0 ) {
        // Disable Payment Btn
        $('#payment-btn').attr('disabled', 'disabled');
    }else {
        $('#payment-btn').removeAttr('disabled');
    }
    $('[name="pay_amount"]').val( total.toFixed(2) );
    
    
}

function setDisplay() {
    $('input[name="name"]').val('').removeAttr('readonly','readonly');
    $('input[name="amount"]').val('10.00');
    $('input[name="tamil_name"]').val('').removeAttr('readonly','readonly');
    $('input[name="email"]').val('').removeAttr('readonly','readonly');
    $('input[name="contact_no"]').val('').removeAttr('readonly','readonly');
    $('textarea[name="address"]').val('').removeAttr('readonly','readonly');
    $('.star_div_txt').hide();
    $('.star_div').show();
}

function check_valid_pwd(_this) {
    var $this = $(_this);
    var pwd = $this.val();
    var return_val = 1;
    if(pwd != '') {
        $.ajax({
            async: false,
            url: base_url + 'billing_membership_card/check_valid_pwd',
            type: 'POST',
            dataType: "json"
        }).done(function(data) {
            if(data.password !== pwd) {
                window.clearTimeout(inter);
                inter = window.setInterval(function(){
                    window.clearTimeout(inter);
                    var $errBlck = $this.parents().find('.box-body .err-blck');
                        
                    $errBlck.html( 'Invalid Password!' ).slideDown('slow');
                    $this.val('').focus();
                    window.setTimeout(function(){
                        $errBlck.slideUp('slow', function(){ $(this).html('') });                            
                    }, 3500);
                        
                    $('#payment-btn').attr('disabled','disabled');
                }, 400);
                return_val = 0;
            } else {
                $('#payment-btn').removeAttr('disabled');
                return_val = 1;
            }
        }).fail(function(XHR, status_code, error_thrown) {
            console.log(error_thrown);
        });
    }
    return return_val; 
}

function paymentOption(_this) {
    $('input[name="password"]').trigger('change');
        var valid_pwd = check_valid_pwd($('input[name="password"]'));
        if($(_this).attr('class') == 'mem_topup') {
            settopupTotal();
        } else if($(_this).attr('class') == 'btn btn-danger add') {
            setTotal();
        }
        //$('.check_unique').trigger('change');
        if(valid_pwd == 1 || (valid_pwd == 0 && $(_this).attr('class') == 'btn btn-danger add') ) {  
            var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
            ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0
            ,   toDisable = paidAmt <= 0 ? true : false;
            
            var edit_id = $('input[name="hidden_id"]').val();
            if(edit_id == '') {
                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');
                    $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val($('input[name="amount"]').val());
                    return true;
                }else if( toDisable ) {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
                return false;
            } else {
                //msgBox('Amount is already paid!','','info');
               // window.setTimeout(function(){
                    $('[type="submit"]').removeAttr('disabled').trigger('click');
                //}, 3500);
            }
        }
}