jQuery(document).ready(function() {
  var groupClasses = new Array();
  jQuery('.search-result.solr-grouped').each(function(index, item){
    item = jQuery(item)
    currentGroupClass = item.attr('class').substr(item.attr('class').lastIndexOf('solr-group-'));
    if(jQuery.inArray(currentGroupClass, groupClasses) < 0) {
      groupClasses.push(currentGroupClass);
    }
  });

  jQuery.each(groupClasses, function(index, item) {
    currentGroup = jQuery('.search-result.solr-grouped.' + item);
    currentGroup.wrapAll('<li id="' + item + '-all" />');
    currentGroup.wrapAll('<ol class="apachesolr_search-results-grouped search-results-grouped">');
    jQuery('#' + item + '-all').prepend('<span>Group: ' + item.replace('solr-group-', '') +'</span>');
  });
});
;
/**
 * AJAX command to remove deleted rows from given view.
 */
if (Drupal.ajax) {
  Drupal.ajax.prototype.commands.popline_aas_remove_rows = function(ajax, response, status) {
    var selector = response.selector;
    var values = response.values;
    jQuery.each(values, function(index, value) {
      jQuery(selector + ' input.vbo-select[value=' + value + ']').parents('.views-row').remove();
    });
  };
}
;
/**
 * A button that can add and remove documents from a users folders.
 * To enable this functionality add an HTML element to the page with an
 * attribute of popline-mydocument="nid" where nid is the nid of the
 * document. The button will be appended to this element.
 *
 * @file MyDocumentsButton
 */
(function($) {
  $(function() {
    var DEBUG = true;

    var $docs = $('[popline-my-document]');
    // A global to store the users folders state in memory.
    var folders;

    // Here is some new functionality for special times when there is no content in folders.
    $('.page-node-add-popline-folder input#edit-preview.form-submit').hide();
    if ($('.node-type-popline-folder .views-row').length==0 && $('.vbo-views-form-empty').length!=0) {
      $('.node-type-popline-folder #edit-select').hide();
      var foldername=$('.node-type-popline-folder h1.page-title').text();
      $('.node-type-popline-folder .region-content .content:first').append('<i>'+foldername+'</i> contains no items. To add citations, click the "Add to My Documents" button when viewing your search results.');
    }
    /**
     * Make a request for all of the users current folders and store them in
     * memory as to avoid multiple requests.
     */
    $.get('/popline_my_documents/folders', function(folds) {
      folders = folds;
      log('Remembered folders:', folders);

      $docs.each(function() {
        var $doc = $(this);

        // Append a button to each document.
        $('<button/>')
          .appendTo($doc)
          // .text('Add to My Documents')
          .addClass('popline-document-button')
          .attr("title","Add this title to your saved list of documents for future access and export.")
          .click(function() {
            log('popline-documents-button click init.');
           /**
            * Toggle for the folder adding.
            * TODO:
            *   This successfully prevents printing the folders to the DOM
            *   more than once but, for reasons I've yet to discover, does NOT
            *   remove the list.
            */
            if ($doc.find('ul').length > 0) {
              return $doc.remove('ul');
            }
            /**
             * The button will insert all of the folders and their options into
             * the DOM. These can be clicked to carryout the action they
             * represent. After they are clicked the options are removed from
             * the DOM
             */
            var nid = $doc.attr('popline-my-document');
            var foldersWith = foldersWithDocument(nid, folders);
            var foldersWithout = folders.filter(function(folder) {

              if (foldersWith.length === 0) {
                return folder;
              }
              if (foldersWith.length === folders.length) {
                return false;
              }
              return foldersWith.every(function(folderWith) {
                return Number(folderWith.nid) !== Number(folder.nid);
              });
            });

            /**
             * Folders are injected into the DOM this can be any HTML element.
             */
            var $folders = $('<ul/>')
              .addClass('popline-folders')
              .insertAfter($(this));

            var $addBtn = $('<button/>',{class: 'add-to-folders', text: 'Add'});
            $folders.after($addBtn);

            log('These folders don\'t have', nid, ':', foldersWithout);

            /**
             * The documents that aren't in the folder are injected into the DOM
             * with the class popline-document-add. The element used could be
             * any HTML element.
             */
            foldersWithout.forEach(function(folder) {
              $('<li/>')
                .appendTo($folders)
                .attr('doc-nid', folder.nid)
                .html('<label><input type="checkbox" value="' + folder.nid + '" /><strong>' + folder.title + '</strong></label>')
                .addClass('popline-document-add');
            });

            if (folders.length <= 1) {
              $(this).siblings('.popline-folders').hide();
              $(this).siblings('.add-to-folders').hide();
            }

            /**
             * Add a click handler for addind addable documents.
             */
             var count = 0;
             $addBtn.click(function(e) {
                e.preventDefault();
                $folders.find('input[type="checkbox"]:checked').each(function(i, e){
                  var $this = $(this);
                  var $poplineBtn = $this.parents('div').children('.popline-document-button');
                  addDocTo($(e).attr('value'), nid, function(err, result) {
                    $('confirm-message').remove();
                    if (err) {
                      log('There appears to have been an issue');
                      $poplineBtn.after($('<span class="confirm-message">There appears to have been an issue</span>').addClass('issue'));
                    } else {
                      $poplineBtn.after($('<span class="confirm-message">Item added to ' + result + '</span>').addClass('success'));
                    }
                    count++;
                    log('count', count);
                    $folders.remove();
                    $addBtn.remove();
                  });
                });

              });

              if (folders.length === 1) {
                $('.popline-document-add input').attr('checked', true);
                $addBtn.click();
              }
            if (foldersWith.length > 0) {
              var f='';
              $.each(foldersWith,function( index, value ) {
               if (index!=0) {f+=",";}
               f+=" " + value.title;
              });
             $('<span class="docs_added">This document has already been added to your folder(s):'+ f + '</span>').insertAfter($(this).siblings('.add-to-folders'));
            }
            if (foldersWithout.length === 0) {
              $(this).siblings('.add-to-folders').hide();
            }

            /**
             * REMOVED:
             *   We don't currently want the ability to remove documents from
             *   folders via this button. Commented out in case minds are
             *   changed.
             */
            /**
             * The documents that are in the folder are injected into the DOM
             * with the class popline-document-remove The element used could be
             * any HTML element.
             */
            // foldersWith.forEach(function(folder) {
            //   $('<li/>')
            //     .appendTo($folders)
            //     .attr('doc-nid', folder.nid)
            //     .text(folder.title + ' remove')
            //     .addClass('popline-document-remove');
            // });

            /**
             * Add a click handler for removing removable documents.
             */
            // $folders.find('.popline-document-remove')
            //   .click(function() {
            //     var $this = $(this)
            //     removeDocFrom($this.attr('doc-nid'), nid, function(err) {
            //       // TODO error handling
            //       $folders.remove();
            //     });
            //   });
          });
      });
    });

    /**
     * Given a document and a list of folders returns all the folders that
     * have the document.
     * @param doc - the document to search the folders for.
     * @param folders - the list of folders to search.
     * @return foldersWith - folders containing the document.
     */
    function foldersWithDocument(doc, folders) {
      return folders.filter(function(folder) {
        return folder.documents.some(function(d) {
          return Number(d) === Number(doc);
        });
      });
    }

    /**
     * Adds documents to folders.
     * @param node - the nid of the folder to add the document to.
     * @param nid - the nod of the document to add to the folder
     * @param callback - an optional callback to run upon failure or completion.
     *                   if successful the first argument of the callback will be
     *                   falsey.
     */
    function addDocTo(node, nid, callback) {
      log('adding', node, 'to', nid);
      $.get('/popline_my_documents/' + node + '/add/' + nid, function(res) {
        if (res.error) {
          log('adding failed');
          return callback(res.error);
        }

        var folderName = [];
        folders = folders.map(function(folder) {
          if (folder.nid === node) {
            log('remembering', node, 'is in', folder);
            folder.documents.push(nid);
            folderName.push(folder.title);
          }
          return folder;
        });
        callback(false, folderName);
      });
    }

    /**
     * Debug aware logging.
     */
    function log(/* ...args */) {
      if (!DEBUG) { return; }
      var args = [].slice.call(arguments);
      console.log.apply(console, ['My Documents =>'].concat(args));
    }

    /**
     * Removes documents from folders.
     * @param node - the nid of the folder to remove the document to.
     * @param nid - the nod of the document to remove to the folder
     * @param callback - an optional callback to run upon failure or completion.
     *                   if successful the first argument of the callback will be
     *                   falsey.
     */
    // function removeDocFrom(node, nid, callback) {
    //   $.get('/popline_my_documents/' + node + '/remove/' + nid, function(res) {
    //     // error = JSON.parse(error);
    //     if (res.error) {
    //       return callback(res.error);
    //     }

    //     folders = folders.map(function(folder) {
    //       if (folder.nid !== node) {
    //         return folder;
    //       }
    //       folder.documents = folder.documents.filter(function(doc) {
    //         return Number(doc) !== Number(nid);
    //       });
    //       return folder;
    //     });


    //     callback(false);
    //   });
    // }

  });
}(jQuery));
;
