{% if addresses %}
  <label class="radio radio-medium">
    <input type="radio" name="shipping_address" value="existing" id="shipping-address-existing" class="radio-entry"
           checked>
    <span class="radio-text">{{ text_address_existing }}</span>
  </label>
  <div class="field field-medium" id="shipping-existing">
    <select name="address_id" size="5" class="field-entry auto-overflow-y">
      {% for key, address in addresses %}
        <option value="{{ address.address_id }}"
          {% if address.address_id == address_id %}selected{% endif %}
          {% if address.address_2 == '' %}data-error-bairro="true"{% endif %}>
          {% set apelido     = (address.apelido != '') ? '(' ~ address.apelido ~ ')' : '' %}
          {% set complemento = (address.complemento != '') ? ', ' ~ address.complemento : '' %}
          {% if address.address_2 == '' %} [Endereço incompleto, complete agora] {% endif %}
          {{ address.firstname }} {{ address.lastname }} {{ apelido }} - {{ address.address_1 }}, {{ address.numero }},
          {{ address.address_2 }} {{ complemento }} - {{ address.city }}, {{ address.zone_code }} - {{ address.country_pt }}
        </option>
      {% endfor %}
    </select>
  </div>
  <label class="radio radio-medium">
    <input type="radio" name="shipping_address" value="new" id="shipping-address-new" class="radio-entry">
    <span class="radio-text">{{ text_address_new }}</span>
  </label>
{% endif %}
<div id="shipping-new" class="row" style="display:{{ addresses ? 'none' : 'block' }};">
  <div class="col-xs-12 col-md-4">
    <div class="content-box">
      {{ shippingAddressForm }}
    </div>
  </div>
</div>
<div class="flex middle-xs end-xs top-margin-large">
  <button type="button" id="button-shipping-address" class="btn-default btn-large">
    <span>{{ button_continue }}</span>
  </button>
</div>

<script>

  var scripts = {{ custom_scripts|json_encode() }};
  var addresses = {{ addresses|json_encode() }};

  if ($('input.numeric').length > 0) $('input.numeric').numeric();
  if ($('input.alpha').length > 0) $('input.alpha').alpha();
  if ($('input.alphanumeric').length > 0) $('input.alphanumeric').alphanumeric();

  function loadInfoForm(){

    var $THIS = $('#shipping-address select[name="address_id"]');

    if ($THIS.find('option:selected').data('error-bairro')) {
      $('#shipping-new').css('display', 'block');
      $('#shipping-address-new').prop('checked', true).siblings('.radio-text').text('Completar Endereço');

      var address_info = addresses[$THIS.val()];

      $('.js-postcode-content').removeClass('hidden');
      $('input[name="firstname"]').val(address_info['firstname']);
      $('input[name="lastname"]').val(address_info['lastname']);
      $('input[name="postcode"]').val(address_info['postcode']).trigger('input');
      $('input[name="apelido"]').val(address_info['apelido']);
      $('input[name="address_1"]').val(address_info['address_1']);
      $('input[name="numero"]').val(address_info['numero']);
      $('input[name="address_2"]').val(address_info['address_2']);
      $('input[name="tipo_logradouro"]').val(address_info['tipo_logradouro']);
      $('input[name="logradouro"]').val(address_info['logradouro']);
      $('input[name="city"]').val(address_info['city']);

      $('.js-city-search option[value='+address_info['zone_id']+']').attr('selected', 'selected').siblings().removeAttr('selected');
      $('.js-city-search').attr('data-codigo-municipio', address_info['codigo_municipio']);
      $('.js-city-search').attr('value', address_info['zone_id']);
      $('.js-city-search')[0].dispatchEvent(new Event('change'));
      $('.js-city-search').trigger('change');

      $('#form-address').append('<input type="hidden" id="address-update-id" name="address_update_id" value="'+$THIS.val()+'">');
    } else {
      $('#shipping-new').css('display', 'none');
      $('#shipping-address-existing').prop('checked', true);
      $('#shipping-address-new').siblings('.radio-text').text('Quero usar um novo endereço');
      $('#address-update-id').remove();
      $('.js-postcode-content').addClass('hidden');
      $('input[name="firstname"]').val('');
      $('input[name="lastname"]').val('');
      $('input[name="postcode"]').val('');
      $('input[name="apelido"]').val('');
      $('input[name="address_1"]').val('');
      $('input[name="numero"]').val('');
      $('input[name="address_2"]').val('');
      $('input[name="tipo_logradouro"]').val('');
      $('input[name="logradouro"]').val('');
      $('input[name="city"]').val('');
    }

  }

  loadInfoForm();

  function existePostcode() {
    if (window.initPostcode) {
      window.initPostcode($('#shipping-new')[0]);
    } else {
      setTimeout(function() {
        existePostcode();
      }, 200);
    }
  }
  existePostcode();

  $('#shipping-address select[name="address_id"]').change(loadInfoForm);

  $('#shipping-address input[name=\'shipping_address\']').live('change', function () {
    if (this.value == 'new') {
      $('#shipping-existing').hide();
      $('#shipping-new').show();
    } else {
      $('#shipping-existing').show();
      $('#shipping-new').hide();
    }
  });


  if (scripts) {
    for (var i = 0; i < scripts.length; i++) {
      if(i == scripts.length-1){

        $LAB.setOptions({AllowDuplicates: true}).script(scripts[i]).wait(function () {
          window.waitEvent('scripts_document', function () {

            $('#form-address').validate({
              onfocusout: function (element) {
                $(element).valid();
              },
              onkeyup: function (element) {
                if ($(element).valid()) {
                  $(element).removeClass('form-error');
                  $(element).siblings('span.form-error').remove();
                }
              },
              onsubmit: true,
              errorElement: 'span',
              errorClass: 'form-error',
              validClass: 'form-success',
              rules: {
                postcode: {
                  postalcodeBR: true
                }
              }
            });

          });
        });

      }else{
        $LAB.setOptions({AllowDuplicates: true}).script(scripts[i]).wait();
      }
    }
  }
</script>
