ready = ->
if $.isFunction($.fn.nestable)
$('.dd').nestable
maxDepth: "<%= Spina.config.max_page_depth %>"
$('.sortable-grid').sortable().bind 'sortupdate', (e) ->
position_array = []
$(e.target).find('li.image').each (index) ->
position_array.push $(this).data('image-id')
$(e.target).parents('.horizontal-form-content').find('.image-positions').val(position_array.join(","))
$(document).on 'turbolinks:load', ready
# Dynamically add and remove structures
$(document).on 'click', 'form .add_structure_item_fields', (event) ->
$structureForm = $(this).parents('.structure-form')
time = new Date().getTime()
regexp = new RegExp("#{$(this).data('id')}|new_association", 'g')
$fields = $($(this).data('fields').replace(regexp, time))
$structureForm.find('.structure-form-content').append($fields)
$link = $("
")
$structureForm.find('.structure-form-menu ul').append($link)
$fields.attr('id', "structure_form_pane_#{time}")
$link.find('a').click()
# Fire event
$structureForm.trigger('spina:structure_added')
event.preventDefault()
$(document).on 'click', 'form .remove_structure_item_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$pane = $(this).closest('.structure-form-pane')
$link = $("a[href='##{$pane.attr('id')}']").parents('li')
$previousLink = $link.siblings('li:visible')
$previousLink.find('a').trigger('click')
$link.hide()
$pane.hide()
$link.remove()
$pane.remove()
event.preventDefault()
$(document).on 'change', '.structure-form-pane .structure-form-part:first-child input', (event) ->
value = $(this).val()
$pane = $(this).parents('.structure-form-pane')
$link = $("a[href='##{$pane.attr('id')}']")
$link.html(" #{value}")
# Sort pages
$(document).on 'click', '.sort-switch', (event) ->
$($(this).attr('href') + ' .dd-item-inner').toggleClass('dd-handle')
if $(this).hasClass('button-success')
$(this).removeClass('button-success')
$(this).text($(this).data('change-order'))
$(this).prepend('')
else
$(this).addClass('button-success')
$(this).text($(this).data('done-changing-order'))
$(this).prepend('')
return false