#= require jquery
#= require jquery_ujs
#= require cocoon
#= require ckeditor/init
#= require angular
#= require angular-resource
#= require angular-animate
#= require ng-table
#= require checklist-model
#= require handsontable.full
#= require ngHandsontable
#= require moment
#= require moment-with-locales
#= require moment-range
#= require angular-mighty-datepicker
#= require fullcalendar.min
#= require panel/app
#= require dropzone
#= require panel/foundation.min
# require google-chart-loader
#= require chartkick

#= require panel/picker
#= require panel/legacy
#= require panel/picker.date
#= require panel/translations/es_ES
# require panel/picker.time
#= require panel/jquery.livequery.min
#= require panel/cascade-dropdown
#= require panel/cascade-dropdown2v
#= require panel/cascade-dropdown-institution-filters
#= require panel/jquery.plugin.min
#= require panel/jquery.datepick.min
#= require panel/jquery.datepick-es
#= require panel/date-init

hashtable =
  hash: {}
  exists: (key) ->
    @hash.hasOwnProperty key
  get: (key) ->
    if @exists(key) then @hash[key] else null
  put: (key, value) ->
    @hash[key] = value
    return

@initMap = ->
  if document.getElementById('map')
    ele = document.getElementById('map')
    map = new google.maps.Map(ele, {
      center: {
        lat: parseFloat(ele.getAttribute('data-lat')),
        lng: parseFloat(ele.getAttribute('data-lng'))
      },
      zoom: 16,
      scrollwheel: false
    })

    marker = new google.maps.Marker({
      position: {
        lat: parseFloat(ele.getAttribute('data-lat')),
        lng: parseFloat(ele.getAttribute('data-lng'))
      },
      animation: google.maps.Animation.DROP,
      draggable: true,
      map: map
    })

    google.maps.event.addListener marker, 'dragend', ->
      document.getElementById('item_lat').value = marker.getPosition().lat()
      document.getElementById('item_lng').value = marker.getPosition().lng()

triggerAnonymousChange = ->
  if $('#item_anonymous').is(':checked')
    $('.anonymous-controls').hide('slow')
    $('.anonymous-controls input[data-anonymous]').removeAttr('required')
  else
    $('.anonymous-controls').show('slow')
    $('.anonymous-controls input[data-anonymous]').attr('required', true)

$ ->

  $('select[data-dependent]').each (index) ->
    dependent = $('.' + $(@).data('target'))
    console.log dependent
    hashtable.put $(@).data('child'), dependent.html()
    $('optgroup', dependent).remove()
    $(@).on 'change', ->
      type = $('option:selected', this).text()
      options = hashtable.get($(@).data('child'))
      values = $(options).filter('optgroup[label=\'' + type + '\']').html()
      dependent.find('option:gt(0)').remove()
      if values
        dependent.append values
      return
    $(this).trigger 'change'
    return

  $('[data-toggable-from-select]').hide()
  $.each $('[data-toggable-from-select]'), (i, e) ->
    toggable = $(e)
    toggler  = $("##{toggable.data('toggler-id')}")
    hide_on  = $.map toggable.data('toggable-hide-on').split(','), (value) ->
      return value.replace(/ /g, '')

    toggler.on 'change', ->
      if $.inArray($(this).val(), hide_on) != -1
        toggable.hide()
      else
        toggable.show()
    toggler.trigger('change')


  $('[data-xhrpopup]').on 'ajax:complete', (event, xhr, settings) ->
    html = $(xhr.responseText).hide()
    $('body').append(html).addClass('overlayed')
    html.fadeIn 'fast'

    $('[data-close]').on 'click', (e) ->
      e.preventDefault()
      $(this).closest('.overlay').fadeOut 'fast', ->
        $(this).remove()
        $('.overlayed').removeClass('overlayed')

  $.each $('[data-tab]'), (i, t) ->
    $(t).on 'click', (e) ->
      e.preventDefault()

      $.each $('[data-tab]'), (j, x) ->
        $($(x).data('tab')).hide()

      $('[data-tab]').removeClass('active')
      $(this).addClass('active')
      $($(this).data('tab')).show()

    $($(t).data('tab')).hide() unless $(t).hasClass('active')

  ##
  # Dropzone configure
  Dropzone.autoDiscover = false
  $('.dropzone').each ->
    dropUrl = $(this).attr('action')
    previewContainer = $(this).data('preview')
    $(this).dropzone
      autoProcessQueue: false
      uploadMultiple: true
      parallelUploads: 100
      maxFiles: 100
      previewsContainer: previewContainer
      url: dropUrl
      addRemoveLinks: true
      init: ->
        myDropzone = this
        # First change the button to actually tell Dropzone to process the queue.
        @element.querySelector('button[type=submit]').addEventListener 'click', (e) ->
          if myDropzone.getQueuedFiles().length > 0
            # Make sure that the form isn't actually being sent.
            e.preventDefault()
            e.stopPropagation()
            myDropzone.processQueue()
          return
        @on 'sendingmultiple', ->
          return
        @on 'successmultiple', (files, response) ->
          if response.code == 200
            window.location = response.redirect_url
            setTimeout (->
              window.location.reload()
            ), 500
          return
        @on 'errormultiple', (files, response) ->
          return
        return
  # Dropzone.options.dropzoneExpedients =
  #   autoProcessQueue: false
  #   uploadMultiple: true
  #   parallelUploads: 100
  #   maxFiles: 100
  #   previewsContainer: '.dropzone-previews'
  #   addRemoveLinks: true
  #   init: ->
  #     myDropzone = this
  #     # First change the button to actually tell Dropzone to process the queue.
  #     @element.querySelector('button[type=submit]').addEventListener 'click', (e) ->
  #       if myDropzone.getQueuedFiles().length > 0
  #         # Make sure that the form isn't actually being sent.
  #         e.preventDefault()
  #         e.stopPropagation()
  #         myDropzone.processQueue()
  #       return
  #     @on 'sendingmultiple', ->
  #       return
  #     @on 'successmultiple', (files, response) ->
  #       if response.code == 200
  #         window.location.href = response.redirect_url
  #       return
  #     @on 'errormultiple', (files, response) ->
  #       return
  #     return

  $(document).foundation()

  $('.input-times').select2
    multiple: false

  $('.input-tags').select2
    multiple: true

  $('.input-tokens').select2
    tags: true
    tokenSeparators: [',']
    placeholder: 'adultos,salud,zona metropolitana'
    createTag: (tag) ->
      {
        id: tag.term
        text: tag.term
        tag: true
      }
  .on 'select2:select', (evt) ->
    $.ajax
      type: 'POST'
      url: $(@).closest('form').attr('action')
      data: $(@).closest('form').serialize()
    return
  .on 'select2:unselect', (evt) ->
    $.ajax
      type: 'POST'
      url: $(@).closest('form').attr('action')
      data: $(@).closest('form').serialize()
    return



  $('#item_anonymous').on 'change', (e) ->
    triggerAnonymousChange()
  triggerAnonymousChange()

$(document).ready ->
  #dates
  $('.datepicker').pickadate
    format: 'yyyy-mm-dd'
    formatSubmit: 'yyyy-mm-dd'
    hiddenSuffix: ''
  return




$(document).ready ->
  # Cascade dropdowns
  $(".ajaxable").livequery ->
    new CascadeDropdown($(this).attr("id"), $(this).attr("target"), $(this).attr("object"), $(this).attr("extras"))

  $(".2v").livequery ->
    new CascadeDropdown2v($(this).attr("id"), $(this).attr("target"), $(this).attr("object"), $(this).attr("extras"))

  $(".institution_to_filters").livequery ->
    new CascadeDropdownInstitutionFilters($(this).attr("id"))
