


#= require jquery
#= require jquery_ujs
#= require vendor/jquery-ui
# require turbolinks

#= require event_form
#= require bootstrap

# require vendor/jquery-sortable
#= require vendor/jquery.event.drag.js
#= require vendor/bootstrap-slider
#= require vendor/jquery.ui.widget
#= require vendor/tmpl.min
#= require vendor/jquery.iframe-transport
#= require vendor/jquery.fileupload
#= require vendor/jquery.fileupload-ui
#= require vendor/jquery.fileupload-process
#= require vendor/select2.min
#= require vendor/accounting



#= require manager
#= require image_files

#= require pane_hover


#= require redactor
#= require_tree ./redactor_plugins

#= require nested_fields
#= require Chart

#= require admin/trunk8.js


#= require vendor/Chart.bundle


#= require freeze-table

@resize = () ->
  header_size = $("#admin_nav").outerHeight() 
  
  if $(".qi_header").length > 0

    header_size = header_size + $(".qi_header").first().outerHeight() 
  
  $("body").css("padding-top", header_size+"px")

portlet_to_move = false
content_type_to_move =false
window.disable_portlet_select = false
window.portlet_change = false


@edit_watcher = (element_type, element_id, key) ->

  $.ajax
    url:"/admin/edit_watchers.js", 
    type : "POST",
    data : {edit_watcher : {'element_type' : element_type, 'element_id' : element_id, 'key' : key}}
    

@init_form_change = ->
  window.disable_portlet_select = true
  window.portlet_change = true



$(window).on 'beforeunload', ->
  if window.portlet_change == true
    return 'Les modifications que vous avez apportées ne seront peut-être pas enregistrées, avez-vous bien enregistré votre modification ?'
      

  

@reset_form_change = ->
  window.disable_portlet_select = false
  window.portlet_change = false
  
@open_collapse3 = ->
  $("#collapse3 .panel").show()
  $("#collapse3").show()
  
@reset_edit_pane = ->
  $("#element_form").html()
  $("#collapse3").hide()
  
@unselect_portlet = ->
  $(".portlet.active").removeClass("active")
  reset_edit_pane()
  
@cancel_move_portlet = ->
  $(".move_message").show()
  $(".cancel_message").hide()
  
  $(".move").removeClass("move")
  $(".portlet_placeholder").remove()
  portlet_to_move = false
  
@adjust_trunk = ->
  #$('.trunk').trunk8();




@init_video_files_drag = ->
  video_to_drag_id = null
  $( "#video_files .video_file").draggable
    containment: "document",
    appendTo: "body",
    revert : "invalid",
    cursor: "move",
    cursorAt: { top: -2, left: -8 },
    
    
    drag: ( event, ui ) ->
      multiple_ids = multiple_selection_ids()

      video_to_drag_id = $(this).data("id")
      
      nbr = 1 #multiple_ids.length
      if nbr > 1
        ui.helper.html(nbr+" videos")
      else
        ui.helper.html(nbr+" video")
    
    start: ( event, ui ) ->
      $(this).addClass("active")
      $( ".selector" ).draggable( "option", "helper", "clone" );
      $( "#video_files .active").css("opacity", "0.5");
      
    stop: ( event, ui ) ->
      $(this).addClass("active")
      $( ".selector" ).draggable( "option", "helper", "clone" );
      $( "#video_files .active").css("opacity", "1");
      
    helper: (event) -> 
      
      multiple_ids = multiple_selection_ids()
      nbr = multiple_ids.length
      
      if nbr > 1
        return $( "<div class='ui-widget-header video_file_helper'>"+nbr+" images</div>" )
      else
        return $( "<div class='ui-widget-header video_file_helper'>"+nbr+" image</div>" )
        
  $( ".video_file_receptable" ).droppable({
    accept: ".video_file",
    drop: ( event, ui ) ->
      video_folder_id = $(this).data("video_folder_id")
      
      
      $.ajax
        url:"/admin/video_folders/"+video_folder_id+"/change_video_folder.js", 
        type : "GET",
        data : {video_files_id : [video_to_drag_id]},
        success : (code_html, statut) ->
          $("#video_files .active").remove()
          update_multiple_selection_text();
      
      $("#video_files .active").remove()
      update_multiple_selection_text();
      $(this).removeClass("hover")
          

      
    over: ( event, ui ) ->
      $(this).addClass("hover")
    out: ( event, ui ) ->
      $(this).removeClass("hover")
      
  });


@init_image_files_drag = ->

  $( "#image_files .image_file").draggable
    containment: "document",
    appendTo: "body",
    revert : "invalid",
    cursor: "move",
    cursorAt: { top: -2, left: -8 },
    
    
    drag: ( event, ui ) ->
      multiple_ids = multiple_selection_ids()
      nbr = multiple_ids.length
      if nbr > 1
        ui.helper.html(nbr+" images")
      else
        ui.helper.html(nbr+" image")
    
    start: ( event, ui ) ->
      $(this).addClass("active")
      $( ".selector" ).draggable( "option", "helper", "clone" );
      $( "#image_files .active").css("opacity", "0.5");
      
    stop: ( event, ui ) ->
      $(this).addClass("active")
      $( ".selector" ).draggable( "option", "helper", "clone" );
      $( "#image_files .active").css("opacity", "1");
      
    helper: (event) -> 
      
      multiple_ids = multiple_selection_ids()
      nbr = multiple_ids.length
      
      if nbr > 1
        return $( "<div class='ui-widget-header image_file_helper'>"+nbr+" images</div>" )
      else
        return $( "<div class='ui-widget-header image_file_helper'>"+nbr+" image</div>" )
        
  $( ".image_file_receptable" ).droppable({
    accept: ".image_file",
    drop: ( event, ui ) ->
      album_id = $(this).attr("data_album_id")
      images_id = multiple_selection_ids()
      
      $.ajax
        url:"/admin/albums/"+album_id+"/change_album.js", 
        type : "GET",
        data : {image_files_id : images_id},
        success : (code_html, statut) ->
          alert("t")
          $("#image_files .active").remove()
          update_multiple_selection_text();
      
      $("#image_files .active").remove()
      update_multiple_selection_text();
      $(this).removeClass("hover")
          

      
    over: ( event, ui ) ->
      $(this).addClass("hover")
    out: ( event, ui ) ->
      $(this).removeClass("hover")
      
  });

  
$(document).ready -> 
  adjust_trunk()
  
  $(document).on 'click', 'input.datepicker', ->
    $(this).datetimepicker(
      language: 'fr'
      pickTime: false
    ).focus();
    
  $(document).on 'click', 'input.datetimepicker', ->
    $(this).datetimepicker(
      use24hours: true
      format: 'DD/MM/YYYY HH:mm'
      minuteStepping:15
      language: 'fr'
    ).focus();
    
    
  $(document).on 'click', 'input.timepicker', ->
    $(this).datetimepicker(
      use24hours: true
      format: 'DD/MM/YYYY hh:mm'
      minuteStepping:15
      pickDate: false
      language: 'fr'
    ).focus();
  
    
    

  
  
  $(document).on "click", ".portlet", (event) ->
    if !$(this).hasClass("active") and portlet_to_move == false and window.disable_portlet_select == false 
      
      $(".portlet.active").removeClass("active")
      $(this).addClass("active")
    
    
      $.ajax({url : $(this).data("edit-link"), type: "GET"});
      $("#collapse3 .trash").attr("href", $(this).data("show-link"));
    
    event.stopPropagation();
  
  $(document).on "click", ".block_portlets", (event) ->
    if portlet_to_move == false and window.disable_portlet_select == false 
      portlet_to_move = false
      content_type_to_move = false
      $("#element_form").html("")
    
      $(".portlet.active").removeClass("active")
      reset_edit_pane()
  
  
  
  
  
  $(document).on "change", "#element_form form", ->
    init_form_change()
    
  $(document).on "keydown", "#element_form form", ->
    init_form_change()
    
  
  $(document).on "keyup", "#element_form form", ->
    init_form_change()

  
  
  $(document).on "click", "#content_types .content_type", ->
    if window.portlet_change == false
      cancel_move_portlet()
      unselect_portlet()
      reset_edit_pane()
      window.disable_portlet_select = true
  
    
      type = $(this).data("type")
      content_type_to_move = type
      init_portlets_place_holder()
      $(this).addClass("move")
    false
  
    
  
  $(document).on "click", ".portlet_handle", ->
    if portlet_to_move == false
      
      $(".move_message").hide()
      $(".cancel_message").show()
      
      
      id = $(this).data("portlet-id")
      portlet_to_move = $("#portlet_"+id)
      init_portlets_place_holder()
      portlet_to_move.addClass("move")
      false
    else
      cancel_move_portlet()
      
      false
    
  $(document).on "click", ".portlet_placeholder", ->
    if portlet_to_move != false
      $(this).after portlet_to_move
      $(".move").removeClass("move")
      $(".portlet_placeholder").remove()
      update_block_portlet_order(portlet_to_move.closest(".block_portlets").data("block_id"))
      cancel_move_portlet()
    else 
      window.portlet_change = true
      #alert window.portlet_change
      block_id = $(this).closest(".block_portlets").data("block_id")
  
  
      $(this).replaceWith('<div id="new_portlet_form_inline" class="portlet"><div id="new_portlet_content_form"></div></div>');
  
      $.ajax({
        url:"/portlet/portlets/new.js", 
        type: "GET",
        data: { 
          block_id : block_id,
          position : $(this).attr("data_position"),
          content_type : content_type_to_move
          } 
      
      })
      content_type_to_move = false
      $(".portlet_placeholder").remove()
      
      
    

@init_portlets_place_holder = ->
  placeholder = '<div class="portlet_placeholder"><i class="fa fa-inbox" aria-hidden="true"></i></div>'
  $(".block_portlets").each ->
    $(this).find(".portlet_placeholder").remove()
    $(this).prepend(placeholder)
    $(this).find(".portlet").each ->
      $(this).after(placeholder)


  

@flash_delay = ->
  $("#flashs").find(".alert").each ->
    
    if !$(this).hasClass("delay")
      $(this).addClass("delay")
      $(this).delay(3000).fadeOut();
    
  

@init_menu_items_list = ->
  
  oldContainer = ""
  
  dropped = false;
  draggable_sibling = "";
  
  $("#sortable_menu_item").sortable
    handle : ".handle"
    containment: "document",
    tolerance: 'intersect'
    start: (event, ui)->
      dropped = false
      true
    stop: (event, ui) ->
      if dropped == false
        sortable_data = {parent_id :$("#sortable_menu_item").data("parent-id"), menu_id :$("#sortable_menu_item").data("menu-id") , menu_items_ids : []}
        
        $("#sortable_menu_item").find(".menu_item_row").each ->
          sortable_data.menu_items_ids.push $(this).data("menu-item-id")
        
        
        $.ajax({url : "/admin/menu_items/reorder", data : sortable_data, type: "POST"});
    


  
  
  $(".receptable").droppable
    #activeClass: 'active',
    hoverClass:'hovered',
    tolerance: 'pointer',
    greedy: true,
    over: (event,ui) ->
      $(".ui-sortable-placeholder").remove()
    drop: (event,ui) ->
      dropped = true;
      
      parent_id = $(this).data("parent-id")
      menu_id = $(this).data("menu-id")
      id = ui.draggable.data("menu-item-id")
      
      $.ajax({
        url:"/admin/menu_items/"+id+".js", 
        type: "PUT",
        data: { 
          reorder : true,
          menu_item : {
            parent_id : parent_id,
            menu_id : menu_id
          } 
        },
        success : ->
          #f

          
        
      })
      ui.draggable.remove()
      
      
      
      
      

@init_investigation_cats_list = ->
  
  oldContainer = ""
  
  dropped = false;
  draggable_sibling = "";
  
  $("#sortable_investigation_cat").sortable
    handle : ".handle"
    containment: "document",
    tolerance: 'intersect'
    start: (event, ui)->
      dropped = false
      true
    stop: (event, ui) ->
      if dropped == false
        sortable_data = {parent_id :$("#sortable_investigation_cat").data("parent-id"), menu_id :$("#sortable_investigation_cat").data("menu-id") , investigation_cats_ids : []}
        
        $("#sortable_investigation_cat").find(".investigation_cat_row").each ->
          sortable_data.investigation_cats_ids.push $(this).data("menu-item-id")
        
        
        $.ajax({url : "/admin/investigation_cats/reorder", data : sortable_data, type: "POST"});
    


  
  
  $(".receptable").droppable
    #activeClass: 'active',
    hoverClass:'hovered',
    tolerance: 'pointer',
    greedy: true,
    over: (event,ui) ->
      $(".ui-sortable-placeholder").remove()
    drop: (event,ui) ->
      dropped = true;
      
      parent_id = $(this).data("parent-id")
      menu_id = $(this).data("menu-id")
      id = ui.draggable.data("menu-item-id")
      
      $.ajax({
        url:"/admin/investigation_cats/"+id+".js", 
        type: "PUT",
        data: { 
          reorder : true,
          investigation_cat : {
            parent_id : parent_id,
            menu_id : menu_id
          } 
        },
        success : ->
          #f

          
        
      })
      ui.draggable.remove()
      
      
      
      
      
@update_block_portlet_order = (block_portlet_id) ->
  return_order = []
  
  block_portlet = $("#block_portlet_"+block_portlet_id)
  
  block_data = {block_id : block_portlet.data('block_id'), block_portlet_ids : []}

  block_portlet.children('.portlet').each ->
    if $(this).data('portlet_id')
      block_data.block_portlet_ids.push($(this).data('portlet_id'))
      

  
  return_order.push(block_data);



  $.ajax({url : "/portlet/portlets/reorder", data : {blocks:return_order}, type: "POST"})
 
  
jQuery ->
  
  $(".inline-contenteditable").keypress (e) ->
    if e.which == 13
      false
    else
      $(this).html($(this).text())
      return true
      
  
  $(document).on 'click', ".portlet_title_content .inline-contenteditable", () ->
    
    $.ajax
      url : "/portlet/title_contents/"+$(this).data("title-id")+"/edit.js", 
      type: "GET",
  
  $(document).on 'blur keyup paste', ".portlet_title_content .inline-contenteditable", () ->
    $(this).html($(this).text())
    $.ajax
      url : "/portlet/title_contents/"+$(this).data("title-id"), 
      type: "PUT",
      data : 
        title_content : 
          content : $(this).html()
  
    
    
    
  $(".sortable").sortable({

    containerSelector :".block",
    itemSelector:".portlet",
    handle: ".handle",
    nested:true,
    placeholder:"<div class='placeholder'></div>"
    
    })
    
  
  
    
    
  flash_delay();
  

  item_catched = ""
  
    
  adjustment = ""
  
  $("#menu_item_inspector_container").sortable({


    itemSelector:"#menu_item_informations",
    pullPlaceholder :false,
    placeholder : "",
    handle: ".inspector_handle",
    onDragStart: ($item, container, _super) ->
      $item.css({
        height: $item.height(),
        width: $item.width()
        })
      
      $("body").addClass("dragging")
      
      offset = $item.offset()
      pointer = container.rootGroup.pointer
      adjustment = {
        left: pointer.left - offset.left,
        top: pointer.top - offset.top
        }      
      
    onCancel : ($item, container, _super) ->
      $item.css(position)
      $item.removeClass("dragged")
      $("body").removeClass("dragging")
      
    onDrag: ($item, position, _super) ->

      $item.css({
        left: position.left - adjustment.left,
        top: position.top - adjustment.top - $(window).scrollTop()
      })




    
    })
                   


  
$ ->
  $(window).on "resize", ->
    resize()


  
  resize()

$(document).on "scroll", () ->

  if( $(this).scrollTop() <= 52 ) 
    top = 52 - $(this).scrollTop()
  else
    top = 0

  $("#toolbar-text, #menu_item_informations").css
    top : top
    
$(document).on "click", "#menu_item_informations .save", ->
  $(this).closest(".panel").find("form").submit()
  return false
  
$(document).on "click", "#menu_item_informations h4", ->
  $(this).next(".panel").toggle()
  return false




@qi_autocomplete = (autocomplete_object) ->
  
  $('.' + autocomplete_object + '_autocomplete_input').autocomplete
    source: (request, response) ->
      $.ajax
        url: '/admin/' + autocomplete_object + 's/autocomplete.json'
        dataType: 'json'
        data: search: request.term
        success: (data) ->
          arr = jQuery.map(data, (item) ->
            {
              label: item.member_label
              value: item.member_label
              id: item.id
            }
          )
          response arr
          return
      return
    minLength: 2
    select: (event, ui) ->
      $(this).next('.' + autocomplete_object + '_id').val ui.item.id
      return
  return


