jQuery(document).ready(function ($) {

    $('#tabs').each(function() {
        var disabled = $( this ).data('disabled') || '';

        $( this ).tabs({
            disabled: [ disabled ]
        });
    });

    $('#wiaas_add_cl_customer_extras').click(function(e) {
        e.preventDefault();

        var customer_id = $('#wiaas_cl_customers').val();

        if (!customer_id || customer_id === '0') {
            return;
        }

        $.post(window.ajaxurl, {
            action: 'wiaas_create_cl_customer_extras',
            _ajax_nonce: $('#wiaas_create_cl_customer_extras_nonce').val(),
            customer_id: customer_id,
            package_id: $('#wiaas_cl_package_id').val()
        }).done( function (result) {
            $('#tabs-2').append(result);

            $('#wiaas_cl_customer_' + customer_id).prop( 'disabled', true );
        });

        $('#wiaas_cl_customers').val('0');
    });

    $('#wiaas_package_extras').delegate('.wiaas_remove_cl_extras', 'click', function(e) {
        e.preventDefault();

        var customer_id  = $( this ).data('customer_id');

        $('#extras_customer_' + customer_id).remove();

        $('#wiaas_cl_customer_' + customer_id).prop( 'disabled', false );

        $('#wiaas_cl_customers').val('0');
    });

    $('#wiaas_package_extras').delegate('.wiaas-cl-extra-input', 'change', function(e) {
        e.preventDefault();

        var val = parseFloat($( this ).val());
        var target = '#' + $( this).data('target');

        if (isNaN(val)) {

            $(target).val('Invalid!');

            return;
        }

        var type = $( this).data('type');

        if (type === 'fixed') {
            $(target).text( $(target).data('base') + val);
        }

        if (type === 'recurrent' || type === 'services') {
            $(target).data(type, val);

            $(target).text( $(target).data('base') + $(target).data('recurrent') + $(target).data('services'));
        }
    });
});