$ ->
  if ($('#event-page').length > 0)


    $(".violation-buttons .btn-status").each ->
      button = $(this)
      button.click ->
        $(".btn-status", button.parent()).removeClass("btn-void")
        $(".btn-status", button.parent()).removeClass("btn-danger")
        $(".btn-status", button.parent()).removeClass("btn-warning")
        $(".btn-status", button.parent()).removeClass("btn-success")
        eventBehaviorID = button.data('event-behavior-id')
        status = button.data('status')
        button.addClass(button.data('class-color'))
        $("#event-behavior-status-"+eventBehaviorID).val(status)

    $('[data-form-action]').each ->
      $this = $(@)
      $form = $($this.data('target'))
      $this.nuclear
        alertText: $this.data('confirm-text')
        onClick: ->
          $form.attr('action', $this.data('form-action')).submit()
        delay: 0

    $('[data-set-value]').click ->
      $this = $(@)
      $target = $($this.data('set-target'))
      $target.val($this.data('set-value'))

    $('[data-filter-action]').click ->
      $this = $(@)
      onClick: ->
        alert('test')
        windows.location.href = $($this.data('filter-action'))

    $kemlerModal = $("#kemler-modal")
    $("#kemler-toggle").on "click", ->
      #$("body").modalmanager "loading"
      setTimeout (->
        $kemlerModal.load settings.baseUrl+'/kemler/create', '', ->
          $kemlerModal.modal()
          $('.chzn-select', $kemlerModal).chosen(
            allow_single_deselect: true
          )
      ), 500

    gatherCodeDescription = ($subject) ->
      code = $subject.val()
      $descriptionTarget = $($subject.data('description-target'))

      if code.length > 0
        baseUrl = $subject.data('url')
        $descriptionTarget.load(baseUrl+"?code=#{code}")
      else
        $descriptionTarget.html("")

    updateKemlerField = ($kemlerModal, $kemlerField) ->
      adr = $kemlerModal.find("#adr_code").val()
      onu = $kemlerModal.find("#onu_code").val()
      $kemlerField.val("#{adr}-#{onu}")

    $kemlerModal.on "change", "[data-description-target]", ->
      $subject = $(@)
      $kemlerModal.modal "loading"
      setTimeout (->
        $kemlerModal.modal "loading"
        gatherCodeDescription($subject)
      ), 500

    $kemlerModal.on "click", "#kemler-set", ->
      updateKemlerField($kemlerModal, $("#Event_Kemler"))

    $codeSuggestionModal = $("#modal-violation-code-suggestion")

    $codeSuggestionModal.on "click", "tr", ->
            
      $this = $(@)
      $siblings = $this.siblings()
      $siblings.removeClass 'warning'
      $this.addClass 'warning'
      $('input[name="violationCode"]', $codeSuggestionModal).val($this.data('code'))
      $('input[name="violationCodeDescription"]', $codeSuggestionModal).val($this.data('description'))
      

    $codeSuggestionModal.on "click", "#confirm-suggested-violation-code", ->
      eBehaviorID = $('input[name="eventBehaviorID"]', $codeSuggestionModal).val()
      chosenCode = $('input[name="violationCode"]', $codeSuggestionModal).val()
      chosenDescription = $('input[name="violationCodeDescription"]', $codeSuggestionModal).val()  

     
      $target = $("#eventBehavior-#{eBehaviorID}-code")
      $target.val(chosenCode).trigger("liszt:updated")
      
      $targetD = $("#eventBehavior-#{eBehaviorID}-description")

      $targetD.html(chosenDescription);
            
      $codeSuggestionModal.modal 'hide'

  $(".violation-code-select").chosen().change ->
    eventBehaviorId = $(@).data('event-behavior-id')
    codice = $(@).val();
    theEventTag = $(@).data('event-tag')
    
    $("#eventBehavior-#{eventBehaviorId}-description").html("")
          
    $.get(settings.baseUrl + "/event/codeDescription",
      code: codice
      eventTag: theEventTag
    ).success (html) ->
      $("#eventBehavior-#{eventBehaviorId}-description").html(html)
      
  $(".cacheIgnore").click (event) ->
      URL = $(this).attr('href')
      URL += '&cacheIgnore=' + (new Date()).getTime()
      event.preventDefault()
      window.location.href = URL
      return
      
  $(".ocrQualityTooltip").tooltip({
    'placement':'right'
  });
  
  $("[class*='ocrQuality']").keydown (event) ->
    $(this).tooltip 'destroy'
    $(this).removeClass (index, className) ->
      return ((className.match (/(^|\s)ocrQuality\S+/g)) || []).join(' '); 
    
    
      
  if ($('.plate-white-list').length > 0)
  
    updateWhiteListSmartTips = ->
      
     
      $.ajax
        type: "POST"
        url: settings.baseUrl+"/event/ajaxWhitelistSmartTips"
        data: $('#Plate').parents("form").serialize()
        dataType: 'json'
        success: (data) ->
          if (data.import_running)
          	openWhiteListImport()
          $("#whitelist-smart-tips").html(data.html)
          $("#whitelist-smart-tips").removeClass "invalid-data"
          $('.btn-status').prop 'disabled', false
          if (data.disable_approve_button_on_whitelisted_event)
            $('.event-behaviour.row.whitelist-event button.btn-status-approved').prop 'disabled', true
            $('.event-behaviour.row.whitelist-event button.btn-status-approved').removeClass 'active'
            $('.event-behaviour.row.whitelist-event button.btn-status-approved').removeClass 'btn-success'
            $(".event-behaviour.row.whitelist-event input[id^='event-behavior-status-']").val ""
          $('#Plate').removeClass("plate-edited")
        error: (message) ->
          alert(message)
        
    
    invalidateWhiteListSmatTips = ->
      $("#whitelist-smart-tips").addClass "invalid-data"
        
    $('#Plate').keydown ->
      invalidateWhiteListSmatTips()
      $(this).addClass("plate-edited")
      $('.btn-status').prop 'disabled', true
              
    $('#Plate').change ->
      invalidateWhiteListSmatTips()
      updateWhiteListSmartTips()
      
    $('#Event_custom_nationality').change ->
      $('.btn-status').prop 'disabled', true
      updateWhiteListSmartTips()
      
    openWhiteListImportAlert = ->
      if(!$('#whitelist-import-modal').hasClass('in'))
        setTimeout (->
          $('#whitelist-import-modal').load settings.baseUrl+'/event/whitelistImportContent', '', ->
            $('#whitelist-import-modal').modal
              escapeClose: false
              clickClose: false
              showClose: false
              backdrop: 'static'
              keyboard: false
      
        ), 
        
    closeWhiteListImportAlert = ->
     if($('#whitelist-import-modal').hasClass('in'))
       $('#whitelist-import-modal').modal('hide')
       #$("body").modalmanager "removeLoading"
       updateWhiteListSmartTips()
     

    checkWhitelistImportStatus = ->
     
      $.ajax
        type: "GET"
        url: settings.baseUrl+"/event/isWhitelistImportRunning"
        dataType: 'json'
        success: (data) ->
          if(data.import_running)
          	openWhiteListImportAlert()
          else
            closeWhiteListImportAlert()

    
    setInterval(checkWhitelistImportStatus, 5000)
    
    updateWhiteListSmartTips()
