#= require dependent-fields-toggle

$(document).ready ->
  new DependentFieldsToggle("input[name='information_request[entity_type]']", "legal", ".entity_type_dependent", "hide")
  new DependentFieldsToggle("input[name='information_request[delivery_way]']", "email", ".delivery_way_dependent", "show")

  $(".btn-group button").on "click", ->
    #$(this).closest(".btn-group").find("input").attr("checked", false)
    is_checked = $(this).find("input").is(':checked')
    $(this).find("input").attr("checked", !is_checked)
    $(this).find("input").trigger("change")

  $("#information_request_institution_id").on "change", ->
    $("#doesnt-online").remove()
    if $(this).val() != "" && $(this).find("option:selected").attr("accepts_online_requests") == "false"
      url = "http://api.gobiernoabierto.gob.sv/institutions/#{$(this).val()}/information_officer"
      #url = "http://api.localhost.com:3000/institutions/#{$(this).val()}/information_officer"
      select = $(this)
      $.getJSON url + "?callback=?", (data) =>
        $("<div />")
          .attr("id", "doesnt-online")
          .addClass("alert alert-info")
          .text("#{select.find("option:selected").text()} no acepta solicitudes de información a través del formulario en línea de Gobierno Abierto. Para realizar una solicitud de información por favor comuníquese con:")
          .append($("<br />"))
          .append($("<br />"))
          .append($("<h4 />").text(data.name))
          .append($("<span />").text(data.address))
          .append($("<br />"))
          .append($("<span />").text(data.email))
          .append($("<br />"))
          .append($("<span />").text(data.phone))
          .insertAfter(select.closest(".control-group"))

        $(".control-group").each (index, control_group) ->
          if $(control_group)[0] != select.closest(".control-group")[0]
            $(control_group).fadeOut()

        $("fieldset").each (index, fieldset) ->
          if $(fieldset)[0] != select.closest("fieldset")[0]
            $(fieldset).fadeOut()

        $(".form-actions").fadeOut()
    else
      $("fieldset:not(:visible), .control-group:not(:visible), .form-actions:not(:visible)").fadeIn()

  #nationalities
  $('#nationality_radios').on "change", "input#information_request_salvadorian", ->
    $('#information_request_nationality_name').closest('.nationality-container').hide()
    $('#information_request_nationality_name').val('')
  $('#nationality_radios').on "change", "input#information_request_foreign", ->
    $('#information_request_nationality_name').closest('.nationality-container').show()
  #entity_types
  $('#entity_types').on "change", "input#information_request_natural", ->
    $('#information_request_legal_representative').closest('.entity-container').hide()
    $('#information_request_legal_representative').val('')
    $('#information_request_legal_representative_doc').val('')
  $('#entity_types').on "change", "input#information_request_legal", ->
    $('#information_request_legal_representative').closest('.entity-container').show()

  $('#information_request_terms').trigger("change")

  $('#information_request_terms').on "change", ->
    is_checked = $(this).is(':checked')
    if is_checked == true
      $(this).attr("data-validate", false)
      $(this).attr("checked", is_checked)
    else
      $(this).attr("data-validate", true)
      $(this).attr("checked", !is_checked)

  $('[data-toggle="popover"]').popover();

#########################
$(document).ready ->

  @controls = 'http://localhost.com:3000/api/information_requests/controls.json'
  #@controls = 'http://solicitudes.gobiernoabierto.gob.sv/api/information_requests/controls.json'

  $.getJSON @controls, @extras, (data) =>
    #institutions
    @d_institutions = $ '#information_request2_institution_id'
    ($("<option />").text('-- Seleccione una opción --').val('')).appendTo(@d_institutions)
    @institutions = data['institutions']
    $.each(@institutions, (i, val) =>
      $("<option />")
        .val(i)
        .text(val)
        .appendTo(@d_institutions)
    )

    #nationalities
    @r_nationalities = $ '#nationality_radios'
    @nationality_radios = data['nationality_radios']
    $.each(@nationality_radios, (i, a) =>
      $("<label class='radio-inline' for='information_request_" + a[0] + "'><input id='information_request_" + a[0] + "' name='information_request[nationality]' type='radio' value='" + a[0] + "' " + a[2] + " >" + a[1] + "</label>")
        .appendTo(@r_nationalities)
    )

    @d_nationalities = $ '#information_request_nationality_name'
    ($("<option />").text('-- Seleccione una opción --').val('')).appendTo(@d_nationalities)
    @nationality_dropdown = data['nationality_dropdown']
    $.each(@nationality_dropdown, (i, val) =>
      $("<option />")
        .val(i)
        .text(val)
        .appendTo(@d_nationalities)
    )

    #residences
    @r_residences = $ '#residence_radios'
    @residence_radios = data['residences']

    $.each(@residence_radios, (i, a) =>
      $("<label class='radio-inline' for='information_request_" + a[0] + "'><input id='information_request_" + a[0] + "' name='information_request[residence]' type='radio' value='" + a[0] + "' " + a[2] + " >" + a[1] + "</label>")
       .appendTo(@r_residences)
    )

    #entity_types
    @r_entity_types = $ '#entity_types'
    @entity_types = data['entity_types']

    $.each(@entity_types, (i, a) =>
      $("<label class='radio-inline' for='information_request_" + a[0] + "'><input id='information_request_" + a[0] + "' name='information_request[entity_type]' type='radio' value='" + a[0] + "' " + a[2] + " >" + a[1] + "</label>")
       .appendTo(@r_entity_types)
    )

    #genders
    @r_genders = $ '#genders'
    @genders = data['genders']

    $.each(@genders, (i, a) =>
      $("<label class='radio-inline' for='information_request_" + a[0] + "'><input id='information_request_" + a[0] + "' name='information_request[gender]' type='radio' value='" + a[0] + "' " + a[2] + " >" + a[1] + "</label>")
       .appendTo(@r_genders)
    )

    #educational_level
    @d_educational_levels = $ '#information_request_educational_level'
    ($("<option />").text('-- Seleccione una opción --').val('')).appendTo(@d_educational_levels)
    @educational_levels = data['educational_levels']
    $.each(@educational_levels, (i, val) =>
      $("<option />")
        .val(val[0])
        .text(val[1])
        .appendTo(@d_educational_levels)
    )

    #occupations
    @d_occupations = $ '#information_request_occupation_id'
    ($("<option />").text('-- Seleccione una opción --').val('')).appendTo(@d_occupations)
    @occupations = data['occupations']
    $.each(@occupations, (i, val) =>
      $("<option />")
        .val(val)
        .text(i)
        .appendTo(@d_occupations)
    )

    #states
    @d_states = $ '#information_request_state_id'
    ($("<option />").text('-- Seleccione una opción --').val('')).appendTo(@d_states)
    @states = data['states']
    $.each(@states, (i, val) =>
      $("<option />")
        .val(val)
        .text(i)
        .appendTo(@d_states)
    )

    #notification_modes
    @c_notification_modes = $ '#notification_modes'
    @notification_modes = data['notification_modes']
    $.each(@notification_modes, (i, val) =>
      $("<label class='checkbox-inline' for='notification_mode_#{i}'>
         <input id='notification_mode_' name='notification_mode[]' type='checkbox' value='#{i}' data-validate='true' />
      #{val}</label>").appendTo(@c_notification_modes)
    )

    #delivery_ways
    @d_delivery_ways = $ '#information_request_delivery_way'
    ($("<option />").text('-- Seleccione una opción --').val('')).appendTo(@d_delivery_ways)
    @delivery_ways = data['delivery_ways']
    $.each(@delivery_ways, (val, i) =>
      $("<option />")
        .val(val)
        .text(i)
        .appendTo(@d_delivery_ways)
    )

    #document_types
    @d_document_types = $ '#information_request_document_type'
    ($("<option />").text('-- Seleccione una opción --').val('')).appendTo(@d_document_types)
    @document_types = data['document_types']
    $.each(@document_types, (i, val) =>
      $("<option />")
        .val(i)
        .text(val)
        .appendTo(@d_document_types)
    )
###############
$(document).ready ->

  $('#new_information_request').on 'ajax:success', (xhr, data, response) ->
    #result = jQuery.parseJSON(data.responseText)
    window.location.href = confirmationURL

  $('#new_information_request').on 'ajax:error', (xhr, data, response) ->
    self = $(this)
    result = jQuery.parseJSON(data.responseText)
    self.find('.field-error').remove()

    $.each(result.error, (control, errors) ->
      $.each errors, (_, error) ->

        if(control == 'notification_mode')
          position = $('#notification_modes')
        else if(control in ["institution_id", "nationality_name", "educational_level","occupation_id", "state_id", "city_id", "delivery_way", "document_type"])
          position = self.find("select[name*='[#{control}]']")
        else if(control == 'address')
          position = $('#information_request_address')
        else if(control == 'requirements.requested_information')
          position = $('#requirements')
        else
          position = self.find("input[name*='[#{control}]']")

        $('<div />')
          .addClass('field-error')
          .text(error)
          .insertAfter(position)
    )
