class @CascadeDropdown
  
  constructor: (dropdown_id, target_id, extras = null) ->
    
    @dropdown = $ "#" + dropdown_id    
    @target = $ "#" + target_id
    
    if extras == null
      @extras = {}
    else
      eval "this.extras = #{extras};"

    @dropdown.on "change", =>
      
      @clear_target()
      @append_prompt_to_target()
      
      unless @dropdown.val() == ""
        @build_url()
        @execute_ajax()
        
  build_url: -> 
    @url = "http://api.gobiernoabierto.gob.sv/dropdowns/#{@dropdown.val()}/#{@dropdown.attr('action')}.json?callback=?"
    #@url = "http://api.localhost.com:3000/dropdowns/#{@dropdown.val()}/#{@dropdown.attr('action')}.json?callback=?"
    #@url = "http://localhost:3000/api/dropdowns/#{@dropdown.val()}/#{@dropdown.attr('action')}.json"
    
  clear_target: ->
    @target
      .find("option")
      .remove()

  append_prompt_to_target: ->
    ($("<option />").text('-- Cualquiera --').val('')).appendTo(@target)

  execute_ajax: =>
    $.getJSON @url, @extras, (data) =>
      $.each(data, (i, val) =>
        $("<option />")
          .val(i)
          .text(val)
          .appendTo(@target)
      )
