- input_class = large_inputs ? 'input-lg' : ''
- btn_class = large_inputs ? 'btn-lg' : ''

%p Écrivez une ville de départ et/ou une ville d'arrivée.

= simple_form_for @search, url: search_url, method: :get, html: { class: 'form-inline' } do |f|
  = f.input :from_city, as: :string, input_html: { class: "#{input_class} geoname" }, label: false, placeholder: 'De'
  = f.input :from_lon, as: :hidden
  = f.input :from_lat, as: :hidden
  .form-group
    = link_to '<span class="glyphicon glyphicon-transfer" aria-hidden="true"></span>'.html_safe, '#', { class: 'btn btn-default btn-search-inverse-cities' }
  = f.input :to_city, as: :string, input_html: { class: "#{input_class} geoname" }, label: false, placeholder: 'À'
  = f.input :to_lon, as: :hidden
  = f.input :to_lat, as: :hidden
  = f.input :date, as: :string, input_html: { class: "datepicker #{input_class}" }, label: false, placeholder: 'Date'
  .form-group
    = f.button :submit, 'Partez !', class: "btn btn-primary #{btn_class} btn-search"

- content_for :javascript_footer do
  :javascript
    $(".geoname").geonameAutocomplete();

    $(".datepicker").datepicker({
      dateFormat: "DD dd MM yy",
      minDate: 0
    });

    $(".btn-search-inverse-cities").click(function() {
      ["city", "lon", "lat"].forEach(function(fieldName) {
        var $fromInput = $("#search_from_" + fieldName);
        var $toInput = $("#search_to_" + fieldName);

        var fromValue = $fromInput.val();
        $fromInput.val($toInput.val());
        $toInput.val(fromValue);
      });

      return false;
    });

    $("#new_search").submit(function() {
      var emptyCityGeoCount = 4;
      $(this).find("input.hidden").each(function() {
        var value = $(this).val();
        if (value && value !== "") {
          emptyCityGeoCount -= 1;
        }
      });
      if (emptyCityGeoCount > 2) { // No city fully selected with geo
        var input = $("#search_to_city");

        // Display error
        input.parent().addClass("has-error");
        var inputHelpBlock = input.next(".help-block");
        if (inputHelpBlock.length > 0) {
          inputHelpBlock.show();
        } else { // Create it
          $("<span>", {
            class: "help-block",
            text: "Sélectionnez une ville dans la liste"
          }).insertAfter(input);
        }

        return false; // Prevent submission
      }

      return true;
    });
