<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php
/**
 * @var $block \Magento\Catalog\Block\Adminhtml\Product\Edit
 */
?>
<div class="admin__scope-old">
    <div class="product-actions">
        <div id="product-template-suggest-container" class="suggest-expandable">
            <div class="action-dropdown">
                <button type="button" class="action-toggle" data-mage-init='{"dropdown":{}}' data-toggle="dropdown">
                    <span><?php /* @escapeNotVerified */ echo $block->getAttributeSetName()?></span>
                </button>
                <ul class="dropdown-menu">
                    <li><input type="text" id="product-template-suggest" class="search"
                           placeholder="<?php /* @noEscape */ echo __('start typing to search template'); ?>"/></li>
                </ul>
            </div>
        </div>

        <div class="switcher" onselectstart='return false;'>
            <input type="checkbox" id="product-online-switcher" name="product-online-switcher" />
            <label class="switcher-label"
                   for="product-online-switcher"
                   data-text-on="<?php /* @escapeNotVerified */ echo __('Product online'); ?>"
                   data-text-off="<?php /* @escapeNotVerified */ echo __('Product offline'); ?>"
                   title="<?php /* @escapeNotVerified */ echo __('Product online status'); ?>"></label>
        </div>

        <?php if ($block->getProductId()): ?>
            <?php echo $block->getDeleteButtonHtml() ?>
        <?php endif; ?>
        <?php if ($block->getProductSetId()): ?>
            <?php echo $block->getChangeAttributeSetButtonHtml() ?>
            <?php echo $block->getSaveSplitButtonHtml(); ?>
        <?php endif; ?>
        <?php echo $block->getBackButtonHtml() ?>
    </div>
</div>
<?php if ($block->getUseContainer()): ?>
<form action="<?php /* @escapeNotVerified */ echo $block->getSaveUrl() ?>" method="post" enctype="multipart/form-data"
      data-form="edit-product" data-product-id="<?php /* @escapeNotVerified */ echo $block->getProduct()->getId()?>">
<?php endif; ?>
    <?php echo $block->getBlockHtml('formkey')?>
    <div data-role="tabs" id="product-edit-form-tabs"></div> <?php /* @TODO: remove id after elimination of setDestElementId('product-edit-form-tabs') */?>
    <?php echo $block->getChildHtml('product-type-tabs') ?>
    <input type="hidden" id="product_type_id" value="<?php /* @escapeNotVerified */ echo $block->getProduct()->getTypeId()?>"/>
    <input type="hidden" id="attribute_set_id" value="<?php /* @escapeNotVerified */ echo $block->getProduct()->getAttributeSetId()?>"/>
    <button type="submit" class="hidden"></button>
<?php if ($block->getUseContainer()): ?>
</form>
<?php endif; ?>
<script>
require([
    "jquery",
    "Magento_Catalog/catalog/type-events",
    "underscore",
    "mage/mage",
    "mage/backend/tabs",
    "domReady!"
], function($, TypeSwitcher){
    var $form = $('[data-form=edit-product]');
    $form.data('typeSwitcher', TypeSwitcher.init());

    var scriptTagManager = (function($) {
        var hiddenPrefix = 'hidden',
            scriptTypeRegExp = /((java|ecma)script)/gi,
            hiddenScriptType = 'text/' + hiddenPrefix + 'javascript',
            changeScriptsType = function(source, callback) {
                var isString = (typeof source === 'string'),
                    div = document.createElement('div'),
                    scripts,
                    scriptsLength;
                div.innerHTML = isString ? source : $(source).clone().wrap('<p>').parent().html();
                scripts = div.getElementsByTagName('script');
                scriptsLength = scripts.length;
                for (var i = 0; i < scriptsLength; i++) {
                    scripts[i].type = callback(scripts[i].type);
                }
                return isString ? div.innerHTML : $(div.innerHTML);
            },
            disableScripts = function(source) {
                enableScripts(source);
                return changeScriptsType(source, function(type) {
                    return type ? type.replace(scriptTypeRegExp, hiddenPrefix + '$1') : hiddenScriptType;
                });
            },
            enableScripts = function(source) {
                return changeScriptsType(source, function(type) {
                    return type.replace(hiddenPrefix, '');
                });
            };
        return {
            'disableScripts' : disableScripts,
            'enableScripts' : enableScripts
        }
    })($);

    $('#meta_description').on('change keyup paste', function () {
        var maxLength = $(this).data('maxLength') || 255;
        if ($(this).val().length >= maxLength) {
            $(this).val($(this).val().substr(0, maxLength));
        }
    });
    $form.mage('form', {
        handlersData: {
            save: {},
            saveAndContinueEdit: {
                action: {
                    args: {back: 'edit'}
                }
            },
            saveAndNew: {
                action: {
                    args: {back: 'new'}
                }
            },
            saveAndDuplicate: {
                action: {
                    args: {back: 'duplicate'}
                }
            }
        }
    });
    $form.mage('validation', {validationUrl: '<?php /* @escapeNotVerified */ echo $block->getValidationUrl() ?>'});

    var masks = <?php /* @escapeNotVerified */ echo $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($block->getFieldsAutogenerationMasks())?>;
    var availablePlaceholders = <?php /* @escapeNotVerified */ echo $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($block->getAttributesAllowedForAutogeneration())?>;
    var Autogenerator = function(masks) {
        this._masks = masks || {};
        this._fieldReverseIndex = this._buildReverseIndex(this._masks);
        this.form = $('[data-form=edit-product], #drawer-form');
    };

    $.extend(Autogenerator.prototype, {
        varRegexp: /{{([\w_]+?)}}/,
        varsRegexp: new RegExp('{{(' + availablePlaceholders.join('|') + ')}}', 'g'),
        data: {
            disabled: 'autogenerator-disabled'
        },
        bindAll: function(events) {
            var self = this;
            var elementSelector = _(this._masks).keys().map(function(key) {
                return '#' + key;
            }).join(',');
            var disabler = function() {
                this.form.on(
                    'change init',
                    elementSelector,
                    $.proxy(function(event) {
                        var $element = $(event.target);
                        if (event.type == 'init' && $element.data('disablerInited')) {
                            return;
                        } else {
                            $element.data('disablerInited', true);
                        }
                        $element.data(this.data.disabled, $element.val().replace(/\s/g, '') != '');
                    }, this)
                ).find(elementSelector).trigger('init');
            };
            disabler.call(this);
            $("#product_info_tabs").on("tabscreate tabsactivate", $.proxy(disabler, this));

            $.each(this._masks, function(field, mask) {
                var $field = $('#' + field);
                if (!$field.val() && mask && mask.length > 0 && !self.varRegexp.test(mask)) {
                    $field.val(mask);
                }
                $field.trigger('change');
            });

            $.each(self._fieldReverseIndex, function(field) {
                var fields = this, $field = $('#' + field);
                var filler = function(onlyText) {
                    $.each(fields, function() {
                        var $el = $('#' + this);
                        if ($el.data(self.data.disabled)) {
                            return;
                        }
                        if (onlyText === true && self.varRegexp.test(self._masks[this])) {
                            return;
                        }
                        var value = self._masks[this].replace(self.varsRegexp, function(maskfieldName) {
                            return $('#' + maskfieldName.slice(2, -2)).val();
                        });
                        $el.val(value);
                    });
                };
                if ($field.length) {
                    self.form.on('keyup change blur click paste', '#' + field, filler);
                    $field.trigger('change');
                }
            });
        },
        _buildReverseIndex: function(masks) {
            var self = this;
            var fieldReverseIndex = {};
            $.each(masks, function(field, mask) {
                if (mask) {
                    $.each(mask.toString().match(self.varsRegexp) || [], function (key, maskName) {
                        var fieldName = maskName.slice(2, -2);
                        if (!(fieldName in fieldReverseIndex)) {
                            fieldReverseIndex[fieldName] = [];
                        }
                        fieldReverseIndex[fieldName].push(field);
                    })
                }
            });
            return fieldReverseIndex;
        }
    });

    $form.data('autogenerator', new Autogenerator(masks).bindAll());

    $('.widget-button-save .item-default').parent().hide();

    $('#product-online-switcher')
        .prop('checked', $('#status').val() == '1')
        .trigger('change');

    $('#product-online-switcher').on('change', function(event) {
        $('#status').val($(this).prop('checked') ? '1' : '2');
    });

    $form.on('changeAttributeSet', function(event, data) {
        if (data.label) {
            $('#product-template-suggest-container .action-toggle>span').text(data.label);
            $('[data-role=affected-attribute-set-selector] [data-role=name-container]').text(data.label);
        }
        $('#product-template-suggest').suggest('option', "currentlySelected", data.id).val('');

        var uri = document.location.href.replace(/(\/|&|\?)?\bset(\/|=)\d+/g, '').replace(/#[^#]*$/, '');
        uri += /\?/.test(uri) ? '&' : '?';
        uri += 'set=' + window.encodeURIComponent(data.id);

        var $form = $('[data-form=edit-product]');
        $form.attr('action', $form.attr('action').replace(/(\/|&|\?)?\bset(\/|=)\d+/g, ''));
        $form.find('#attribute_set_id').attr('name', 'set').val(data.id);
        $.ajax({
            url: uri.replace('/edit/', '/new/') + '&popup=1',
            type: 'post',
            data: $form.serializeArray(),
            dataType: 'html',
            context: $('body'),
            showLoader: true
        }).done(function(data) {
            //Hide all js scripts to prevent removing them during jQuery object creation
            data = scriptTagManager.disableScripts(data);
            var removedElementClass = 'removed';

            var $page = $('body');
            var $newPage = $(data);

            var nameMapper = function() {
                return $(this).attr('name');
            };
            var activeTabId = $('.ui-tabs-active>a').attr('id');
            //add new tab tabs or reorder
            $page.find('#product_info_tabs .tabs').each(function(i, tabContainer) {
                $newPage.find('#product_info_tabs .tabs').each(function(j, newTabContainer) {
                    if (i != j) {
                        return;
                    }
                    var $tabContainer = $(tabContainer);
                    $(tabContainer).find('li').removeClass(removedElementClass);
                    var $tabs = $(tabContainer)
                        .find('li:not(.' + removedElementClass + ')  .tab-item-link.user-defined:not(.ajax)');
                    var $newTabs = $(newTabContainer).find('.tab-item-link.user-defined:not(.ajax)'),
                        tabsNames = $tabs.map(nameMapper).toArray();

                    //hide not exists elements
                    $.each(
                        _.difference(tabsNames, $newTabs.map(nameMapper).toArray()),
                        function(index, tabName) {
                            $tabContainer.find('[name=' + tabName + ']').closest('li')
                                .addClass(removedElementClass);
                            $page.find('#' + tabName)
                                .addClass(removedElementClass)
                                .addClass('ignore-validate');
                        }
                    );

                    $(newTabContainer).find('.tab-item-link.user-defined:not(.ajax)').each(function(index, tab) {
                        var $tab = $(tab),
                            tabName = nameMapper.apply($tab),
                            $tabsContent = $tab.closest('li').clone();
                        $tabsContent.find('.fieldset>.field').remove();
                        if (nameMapper.apply($tabs.eq(index)) == tabName) {
                            return true;
                        }
                        var $tabToMove = $.inArray(tabName, tabsNames) !== -1
                            ? $tabs.filter(function() {
                            return nameMapper.apply(this) === tabName;
                        }).closest('li')
                            : $tabsContent;
                        if (index === 0) {
                            $tabToMove.prependTo($tabContainer);
                        } else {
                            $tabToMove.insertAfter($tabs.eq(index - 1).closest('li'));
                        }
                        $tabToMove.removeClass(removedElementClass).removeClass('ignore-validate');
                        $tabs = $tabContainer.find('li:not(.' + removedElementClass + ')  .tab-item-link.user-defined:not(.ajax)');
                    });
                });
            });

            //add new fieldsets or reorder
            $newPage.find('#product_info_tabs .fieldset.user-defined').each(function(index, newFieldset) {
                var fieldsetContainer, newFieldsetContainer, sourceContainer, destinationContainer;
                newFieldsetContainer = $(newFieldset).parents('[data-ui-id*=-tab-content-]').first();
                if ($page.find('[data-ui-id=' + newFieldsetContainer.data('uiId') + ']').length === 0) {
                    fieldsetContainer = newFieldsetContainer
                        .clone()
                        .removeClass(removedElementClass)
                        .removeClass('ignore-validate');
                    //Enable hidden js scripts in node. These scripts will be performed after inserting into page
                    fieldsetContainer = scriptTagManager.enableScripts(fieldsetContainer);
                } else {
                    fieldsetContainer = $page.find('[data-ui-id=' + newFieldsetContainer.data('uiId') + ']').first();
                }
                sourceContainer = newFieldsetContainer.parents('[data-ui-id*=-tab-content-]').first();
                destinationContainer = $page.find('[data-ui-id=' + sourceContainer.data('uiId') + ']').first();
                fieldsetContainer.appendTo(destinationContainer);
            });

            var nameDataMapper = function() {
                return $(this).data('attributeCode');
            };
            //add new element elements or reorder
            $page.find('[data-form=edit-product] [data-role=tabs] .fieldset, #product_info_tabs .fieldset')
                .removeClass('ignore-validate')
                .removeClass(removedElementClass)
                .each(function(i, fieldSet) {
                var updateFieldsetElements = function(index, newFieldSet) {
                    if ($(fieldSet).attr('id') != $(newFieldSet).attr('id')) {
                        return
                    }
                    var $elements = $(fieldSet).find('>.field:not(.' + removedElementClass + ')');
                    var $newFieldSet = $(newFieldSet);
                    var $newElements = $newFieldSet.find('>.field');

                    $elements.removeClass(removedElementClass);

                    var elementNames = $elements.map(nameDataMapper).toArray();

                    //hide not exists elements
                    $.each(
                        _.difference(elementNames, $newElements.map(nameDataMapper).toArray()),
                        function(index, elementId) {
                            $page.find('#attribute-' + elementId + '-container')
                                .addClass(removedElementClass)
                                .addClass('ignore-validate');
                        }
                    );

                    $newElements.each(function(index, element) {
                        var $element = $(element),
                            elementId = nameDataMapper.apply($element);
                        if (nameDataMapper.apply($elements.get(index)) == elementId) {
                            return true;
                        }
                        var $elementToMove = $('.fieldset>.field[data-attribute-code="' + elementId + '"]');
                        if ($elementToMove.length === 0) {
                            $elementToMove = $element.clone();
                        }
                        if (index === 0) {
                            $elementToMove.prependTo(fieldSet);
                        } else {
                            $elementToMove.insertAfter($elements.get(index - 1))
                        }
                        $elementToMove.trigger('contentUpdated');
                        $elementToMove.removeClass(removedElementClass).removeClass('.ignore-validate');
                        $elements = $(fieldSet).find('>.field:not(.' + removedElementClass + ')');
                    });
                };

                $newPage.find('#product_info_tabs .fieldset').each(updateFieldsetElements);

                fieldsetContainer = $(fieldSet).parents('[data-ui-id*=-tab-content-]').first();
                var newFieldsetContainer = $newPage.find('[data-ui-id=' + $(fieldsetContainer).data('uiId') + ']');
                if (newFieldsetContainer.length == 0) {
                    $(fieldsetContainer).find('fieldset .field')
                        .addClass('ignore-validate')
                        .addClass(removedElementClass);
                    $(fieldsetContainer).addClass(removedElementClass);
                } else {
                    $(newFieldsetContainer).find('fieldset').each(updateFieldsetElements);
                    $(fieldsetContainer).removeClass(removedElementClass);
                }
            });
            $('#product_info_tabs').tabs('refresh');
            if (!$('#' + activeTabId).closest('li').hasClass(removedElementClass)) {
                $('#' + activeTabId).trigger('click');
            } else {
                $('#product_info_tabs').tabs("option", "active", 0);
            }
        });

    });
});
</script>
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Catalog/js/product/weight-handler": {},
            "Magento_Catalog/catalog/apply-to-type-switcher": {}
        }
    }
</script>
