jQuery(function($){
  $(document).on('click', '.wae-select-image', function(e){
    e.preventDefault();
    var box = $(this).closest('.wae-image-picker');
    var frame = wp.media({ title: 'Bild auswählen', button: { text: 'Bild verwenden' }, multiple: false });
    frame.on('select', function(){
      var attachment = frame.state().get('selection').first().toJSON();
      box.find('.wae-image-id').val(attachment.id);
      var url = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
      box.find('.wae-image-preview').html('<img src="'+url+'" alt="" />');
    });
    frame.open();
  });
  $(document).on('click', '.wae-remove-image', function(e){
    e.preventDefault();
    var box = $(this).closest('.wae-image-picker');
    box.find('.wae-image-id').val('');
    box.find('.wae-image-preview').empty();
  });
});

jQuery(function($){
  $(document).on('click', '.wae-geocode-button', function(e){
    e.preventDefault();
    var $btn = $(this);
    var $status = $('.wae-geocode-status');
    var zip = $('#zip').val() || '';
    var city = $('#city').val() || '';
    $status.text('Adresse wird geprüft ...');
    $.post(WAE_ADMIN.ajaxUrl, {
      action: 'wae_geocode_address',
      nonce: WAE_ADMIN.geocodeNonce,
      zip: zip,
      city: city
    }).done(function(resp){
      if(resp && resp.success && resp.data){
        $('#latitude').val(resp.data.lat || '');
        $('#longitude').val(resp.data.lng || '');
        $status.text('Koordinaten übernommen. Bitte Schritt 1 speichern.');
      } else {
        $status.text((resp && resp.data && resp.data.message) ? resp.data.message : 'Keine Koordinaten gefunden.');
      }
    }).fail(function(xhr){
      var detail = xhr && xhr.status ? ' HTTP ' + xhr.status : '';
      $status.text('Die Adresse konnte gerade nicht geprüft werden.' + detail);
    });
  });
});
