class @CascadeDropdown

  constructor: (dropdown_id, target_id, object, extras = null) ->

    @dropdown = $ "#" + dropdown_id
    @target = $ "#" + target_id
    @object = object

    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 = "/panel/statistics/#{@dropdown.val()}/#{@object}.json"

  clear_target: ->
    @target
      .find("option")
      .remove()

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

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