<?php
/**
 * Copyright © 2016 maijindou.com All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php echo $block->getChildHtml('grid') ?>
<?php if (count($block->getQueueAsOptions())>0 && $block->getShowQueueAdd()): ?>
<div class="form-buttons">
    <select id="queueList" name="queue">
    <?php foreach ($block->getQueueAsOptions() as $_queue): ?>
        <option value="<?php /* @escapeNotVerified */ echo $_queue['value'] ?>"><?php /* @escapeNotVerified */ echo $_queue['label'] ?> #<?php /* @escapeNotVerified */ echo $_queue['value'] ?></option>
    <?php endforeach; ?>
    </select>
    <button type="button" class="scalable" onclick="subscriberController.addToQueue();"><span><span><span><?php /* @escapeNotVerified */ echo __('Add to Queue'); ?></span></span></span></button>
</div>
<?php endif ?>
<script>
require(["prototype", "mage/adminhtml/events"], function(){
    subscriberController = {
        checkCheckboxes: function(controlCheckbox) {
            var elements = $('subscriberGrid').getElementsByClassName('subscriberCheckbox');
            elements.each(function(obj){
                obj.checked = controlCheckbox.checked;
            });
        },
        rowClick: function (e) {
            if(!Event.element(e).hasClassName('subscriberCheckbox')) {
                var elements = Event.findElement(e, 'tr').getElementsByClassName('subscriberCheckbox');
                if(elements.length != 1) {
                    return;
                }
                elements[0].checked = !elements[0].checked;
            }
        },
        addToQueue: function () {
            var elements = $('subscriberGrid').getElementsByClassName('subscriberCheckbox');
            elements.push($('queueList'));
            var serializedElements = Form.serializeElements(elements, true);
            serializedElements.add = 'subscribers';
            serializedElements.form_key = FORM_KEY;
            var url = subscriberGridJsObject.url;

            new Ajax.Updater('subscriberGrid', url + '?ajax=1',
                             {parameters:  serializedElements,
                              evalScripts: true,
                              onComplete:subscriberGridJsObject.initGrid.bind(subscriberGridJsObject)});
        }
    };

    varienGlobalEvents.attachEventHandler('gridRowClick', subscriberController.rowClick.bind(subscriberController));
});
</script>
