@section('reloadable-form')
<form id="reloadable-form" method="post" class="form-horizontal" action="{{ route('catalog.hawk-reloadable.store') }}">
    {{ csrf_field() }}
    <input type="hidden" id="itemId" name="item_id" value="{{ $item->getKey() }}" />

    @if ($threshold->verify())
        <div class="form-group form-input">
            <label for="amount" class="col-xs-7 col-sm-7 control-label text-right">Load Amount $<em class="text-danger">*</em></label>
            <div class="col-xs-5 col-sm-5">
                <input type="number" class="form-control" id="amount" name="amount" value="{{ old('amount', ($threshold->amount() > 1 ? $threshold->amount() : '')) }}" />
                <span id="amount-points"></span>
                @if ($errors->has('amount'))
                    <span class="help-block" style="color: #c00;">{{ $errors->first('amount') }}</span>
                @endif
            </div>
        </div>
        @if (! $threshold->hasCreatedReloadableCard())
            <hr />
            @include('catalog.reloadable._partials.info-fields')
        @endif
        <div class="form-group text-right">
            <div class="col-xs-12">
                <button type="submit" class="btn btn-primary pull-right">Submit Order</button>
            </div>
        </div>
    @endif
</form>
@show

@section('js')
    @parent
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
    <script type="text/javascript">
    @php
    $conversion = $threshold->getDollarsPerPoint();
    @endphp
    function updatePointsAmount() {
        var value = $('#amount').val();
        @if ($conversion != 1 && $conversion != 0)
            value = value / {{ $conversion }};
        @endif
        @if ($item->price_markup > 0)
            value = value * {{ 1 + ($item->price_markup / 100) }};
        @endif
        value = Math.ceil(value);
        if (value != $('#amount').val()) {
            value = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            $('#amount-points').html('= ' + value + ' points');
        }
    };

    jQuery(document).ready(function($) {
        jQuery.validator.addMethod("isInt", function (val, element) {
            return val % 1 === 0;
        }, "This needs to be a whole number");
        jQuery.validator.addMethod("emailDomain", function(email, element) {
            if (email == '' || email.match(/@([a-z0-9\-]+\.)+[a-z]{2,}$/i)) {
                return true;
            }
            return false;
        }, "Please enter valid email address.");

        /* USA validations
         * -------------------------------------------------- */
        jQuery.validator.addMethod("state", function (state, element) {
            state = state.toUpperCase();
            return this.optional(element) || state.match(/^(A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[ANU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$/);
        }, "Please specify a valid US state");
        jQuery.validator.addMethod("phoneUS", function(phone, element) {
             return phone.length === (10 + 4);
        }, "Please enter a valid US phone.");
        jQuery.validator.addMethod("zip", function(zip, element) {
            return zip.length === 5;
        }, "Please enter a 5 digit zip code.");

        /* CA validations
         * -------------------------------------------------- */
        jQuery.validator.addMethod("phoneCA", function(phone, element) {
             return phone.length === (10 + 4);
        }, "Please enter a valid phone number.");
        jQuery.validator.addMethod("state_ca", function (state, element) {
            var provinces = ["AB", "BC", "MB", "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT"];
            state = state.toUpperCase();
            return this.optional(element) || provinces.indexOf(state) > -1;
        }, "Please specify a valid CA province");
        jQuery.validator.addMethod("postal_ca", function(zip, element) {
            // we make it flexible for US and CA, with spaces
            return (zip.length >= 5 && zip.length <= 7);
        }, "Please enter a valid zip code.");

        $('#ship-phone').mask('(000) 000-0000');

        $('#reloadable-form').validate({
            rules: {
                amount: {
                    required: true,
                    min: {{ $minRequiredAmount }},
                    max: {{ $threshold->amount() }},
                    isInt: true
                },
                "info[ship_phone]": {
                    required: true,
                },
                "info[ship_email]": {
                    email: true,
                    emailDomain: true,
                },
                "info[ship_address_1]": {
                    required: true,
                },
                "info[ship_city]": {
                    required: true,
                },
                "info[ship_state]": {
                    required: true,
                },
                "info[ship_postal]": {
                    required: true,
                },
                "info[ship_country]": {
                    required: true,
                }
            },
            errorElement: 'em',
            errorPlacement: function (error, element) {
                error.addClass('help-block');
                if (element.prop('type') === 'checkbox') {
                    error.insertAfter(element.parent('label'));
                } else if (element.hasClass('select2')) {
                    error.insertAfter(element.siblings('.select2-container'));
                } else {
                    error.insertAfter(element);
                }
            },
            invalidHandler: function(event, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    $("div.js-errors").hide();
                    $("div.js-errors").html('You have some invalid data. Please update and try again.');
                    $("div.js-errors").fadeIn();
                } else {
                    $("div.js-errors").hide();
                }
            },
            success: function (label, element) {},
            highlight: function (element, errorClass, validClass) {
                $(element).parents('.form-input').addClass('has-error');
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).parents('.form-input').removeClass('has-error');
            }
        });

        @includeFirst([
            'catalog.reloadable._partials.form-js-' . $threshold->getCardCountry(),
            'catalog.reloadable._partials.form-js-US',
        ])

        $('#amount').on('change', updatePointsAmount);
        updatePointsAmount();
    });
    </script>
@endsection
