////////////////////////////////////////////////////////////////////////////////
// download queue controls

$(document).ready(function() {

  // global download controller
  downloads = new function() {
  
    var self = this

    // download queue DOM elements
    self.wrap = $('#queue-wrapper')
    self.list = $('#queue-list')

    // hide/show download queue
    self.hide = function() { self.wrap.hide() }
    self.show = function() { self.wrap.show() }
    self.toggle = function() { self.wrap.is(':visible') ? self.hide() : self.show() }

    // refresh the queue
    self.refresh = function() {
      $.get('/main/queue', function(result) {
        self.list.html(result)
      })
    }

    // add download from search and substream ids to queue
    self.add = function(searchid, substreamids) {
      $.get('/downloads/enqueue?sid=' + searchid + '&ssids=' + substreamids, function(response) {
        flash(response)
        self.refresh()
      })
    }

    // remove a substream from the download queue
    self.remove = function(searchid, substreamids) {
      $.get('/downloads/dequeue?sid=' + searchid + '&ssids=' + substreamids, self.refresh)
    }

    // queue downloads with select elements in results
    self.attach = function() {
      $('div.depths select').change(function() {
        if($(this).val() != '') {
          downloads.add($('#searchid').val(), $(this).val())
          $(this).val($(this).find('option:first').val())
        }
      })
    }

  }()

  // toggle the queue when its header is clicked
  $('#queue-header').click(downloads.toggle)

  // queue download button
  $('#queue-download').click(function() {
    flash('Collecting data...')
    setTimeout(2000, flash)
    // return false
  })

  // queue clear button
  $('#queue-clear').click(function() {
    $.get('/downloads/clear', function(result) {
      flash(result)
      $('#queue-list .download').each(function() {
        $(this).fadeOut('normal')
      })
    })
  })

  downloads.attach()
  downloads.refresh()

})

