/**
 * JS for Audio Playlist
 */
jQuery(document).ready(function ($) {
  // Image Uploader Widget
  organicWidgetGallery = {

    // Call this from the upload button to initiate the upload frame.
    uploader: function(widget_id, widget_id_string) {

      var frame = wp.media({
        title: OrganicWidgetGALLERY.frame_title,
        frame: 'post',
        multiple: true,
        library: { type: 'image' },
        button: { text: OrganicWidgetGALLERY.button_title }
      })

      // Handle results from media manager.
      frame.on('close', function () {
        var attachments_arr = []
        var attachments_string = ''
        image = frame.state().get('selection')
        image.each(function(attachment) {
          attachments_arr.push(attachment.attributes.id);
        })
        attachments_string = attachments_arr.join(',')
        if (attachments_string) {
          $('#' + widget_id_string + 'gallery_ids').val(attachments_string)
          $('#' + widget_id_string + 'gallery_ids').trigger('change')
        }
      })

      // Handle results from media manager.
      frame.on('update', function () {
        var attachments_arr = []
        var attachments_string = ''
        image = frame.state().get('library')
        image.each(function(attachment) {
          attachments_arr.push(attachment.attributes.id);
        })
        attachments_string = attachments_arr.join(',')
        if (attachments_string) {
          $('#' + widget_id_string + 'gallery_ids').val(attachments_string)
          $('#' + widget_id_string + 'gallery_ids').trigger('change')
        }
      })

      frame.on('open', function () {
        var selection = frame.state().get('selection')
        var library = frame.state('gallery-edit').get('library')
        var ids_value = $('#' + widget_id_string + 'gallery_ids').val()

        if (ids_value.length > 0) {
          var ids = ids_value.split(',')

          ids.forEach(function(id) {
            attachment = wp.media.attachment(id)
            attachment.fetch()
            selection.add(attachment ? [attachment] : [])
          })
          frame.setState('gallery-edit')
          ids.forEach(function(id) {
            attachment = wp.media.attachment(id)
            attachment.fetch()
            library.add(attachment ? [attachment] : [])
          })
        }
      })

      frame.on('content:render:browse', function(browser) {
        if (!browser) return;
        // Hide Gallery Settings in sidebar
        browser.sidebar.on('ready', function() {
          browser.sidebar.unset('gallery')
        })

        // Hide filter/search as they don't work
        browser.toolbar.on('ready', function() {
          if (browser.toolbar.controller._state == 'gallery-library') {
            browser.toolbar.$el.hide()
          }
        })
      })

      frame.open()

      return false
    }

  }
})
