<?php
/**
 * OpenMage
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available at https://opensource.org/license/afl-3-0-php
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
 * @copyright   Copyright (c) 2021-2023 The OpenMage Contributors (https://www.openmage.org)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<script type="text/javascript">
//<![CDATA[

var bundleTemplateBox = '<table class="border" cellpadding="0" cellspacing="0">' +
    '    <thead>' +
    '        <tr class="headings">' +
    '            <th><?php echo $this->jsQuoteEscape(Mage::helper('catalog')->__('Name')) ?></th>' +
    <?php if ($this->getCanReadPrice() !== false) : ?>
    '            <th class="type-price price-type-box"><?php echo $this->jsQuoteEscape(Mage::helper('catalog')->__('Price')) ?></th>' +
    '            <th class="type-type price-type-box"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Price Type')) ?></th>' +
    <?php endif ?>
    '            <th class="type-price"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Default Qty')) ?></th>' +
    '            <th class="type-uqty qty-box"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('User Defined Qty')) ?></th>' +
    '            <th class="type-order"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Position')) ?></th>' +
    '            <th style="width:1px"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Default')) ?></th>' +
    '            <th class="last">&nbsp;</th>' +
    '        </tr>' +
    '    </thead> ' +
    '    <tbody>' +
    '    </tbody>' +
    '</table>';

var bundleTemplateRow ='<td>' +
                '    <input type="hidden" id="<?php echo $this->getFieldId() ?>_id_{{index}}" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][selection_id]" value="{{selection_id}}">' +
                '    <input type="hidden" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][option_id]" value="{{option_id}}">' +
                '    <input type="hidden" class="product" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][product_id]" value="{{product_id}}">' +
                '    <input type="hidden" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][delete]" value="" class="delete">' +
                '    {{name}}<br />' +
                '   <div  class="nobr">' +
                '        <strong><?php echo $this->helper('sales')->__('SKU') ?>:</strong> <a href="<?php echo $this->getUrl('*/catalog_product/edit', ['store' => $this->getRequest()->getParam('store')]) ?>id/{{product_id}}/">{{sku}}</a>' +
                '    </div>' +
                '</td>' +
                <?php if ($this->getCanReadPrice() !== false) : ?>
                '<td class="price-type-box"><input id="<?php echo $this->getFieldId() ?>_{{index}}_price_value" class="input-text required-entry validate-zero-or-greater" type="text" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][selection_price_value]" value="{{selection_price_value}}"<?php if($this->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif ?>></td>' +
                '<td class="price-type-box"><?php echo $this->getPriceTypeSelectHtml() ?><div><?php echo $this->getCheckboxScopeHtml() ?></div></td>' +
                <?php else: ?>
                    '<input type="hidden" id="<?php echo $this->getFieldId(); ?>_{{index}}_price_value" name="<?php echo $this->getFieldName(); ?>[{{parentIndex}}][{{index}}][selection_price_value]" value="0" />' +
                    '<input type="hidden" id="<?php echo $this->getFieldId(); ?>_{{index}}_price_type" name="<?php echo $this->getFieldName(); ?>[{{parentIndex}}][{{index}}][selection_price_type]" value="0" />' +
                    <?php if ($this->isUsedWebsitePrice()): ?>
                    '<input type="hidden" id="<?php echo $this->getFieldId(); ?>_{{index}}_price_scope" name="<?php echo $this->getFieldName(); ?>[{{parentIndex}}][{{index}}][default_price_scope]" value="1" />' +
                    <?php endif ?>
                <?php endif ?>
                '<td><input class="input-text required-entry validate-greater-zero-based-on-option validate-zero-or-greater" type="text" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][selection_qty]" value="{{selection_qty}}"></td>' +
                '<td class="qty-box"><?php echo $this->getQtyTypeSelectHtml() ?></td>' +
                '<td><input class="input-text required-entry validate-zero-or-greater" type="text" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][position]" value="{{position}}"></td>' +
                '<td class="a-center"><input onclick="bSelection.checkGroup(event)" type="{{option_type}}" class="default" name="<?php echo $this->getFieldName() ?>[{{parentIndex}}][{{index}}][is_default]" value="1" {{checked}}></td>' +
                '<td class="last"><span title="Delete Row"><?php echo $this->getSelectionDeleteButtonHtml() ?></span></td>';

Bundle.Selection = Class.create();
Bundle.Selection.prototype = {
    idLabel : '<?php echo $this->getFieldId() ?>',
    scopePrice : <?php echo (int)$this->isUsedWebsitePrice() ?>,
    templateSyntax : /(^|.|\r|\n)({{(\w+)}})/,
    templateBox : '',
    templateRow : '',
    itemsCount : 0,
    row : null,
    gridSelection : new Hash(),

    initialize : function() {
        this.templateBox = '<div class="grid tier form-list" id="' + this.idLabel + '_box_{{parentIndex}}">' + bundleTemplateBox + '</div>';

        this.templateRow = '<tr class="selection" id="' + this.idLabel + '_row_{{index}}">' + bundleTemplateRow + '</tr>';
    },

    showSearch : function(event) {
        var element = Event.findElement(event, 'div');
        var parts = element.id.split('_');

        var products = new Array();

        var inputs = $A($$('#' + element.id + ' tr.selection input.product'));
        for (i=0; i<inputs.length; i++) {
            products.push(inputs[i].value);
        }

        this.gridSelection.set(parts[2], $H({}));

        new Ajax.Updater(bOption.idLabel + '_search_' + parts[2], '<?php echo $this->getSelectionSearchUrl() ?>', {
            method: 'post',
            parameters : {'index' : parts[2], 'products[]' : products, 'form_key': FORM_KEY},
            evalScripts : true
        });

        if (Event.element(event).tagName.toLowerCase() != 'button') {
            var button = Event.element(event).up('button');
        } else {
            var button = Event.element(event);
        }
        button.hide();
    },

    addRow : function (parentIndex, data) {
        var box = null;
        if (!(box = $(this.idLabel + '_box_' + parentIndex))) {
            this.addBox(parentIndex);
            box = $(this.idLabel + '_box_' + parentIndex);
        } else {
            box.show();
        }

        var option_type = $(bOption.idLabel + '_' + parentIndex + '_type');

        if (!data) {
            var data = {};
        }

        if (data.selection_qty) {
            data.selection_qty = parseFloat(data.selection_qty);
        }

        if (data.can_read_price != undefined && !data.can_read_price) {
            data.selection_price_value = '';
        } else {
            data.selection_price_value = Number(data.selection_price_value).toFixed(2);
        }

        data.index = this.itemsCount++;
        data.parentIndex = parentIndex;

        if (option_type.value == 'multi' || option_type.value == 'checkbox') {
            data.option_type = 'checkbox';
        } else {
            data.option_type = 'radio';
        }

        if (data.is_default == 1) {
            data.checked = 'checked="checked"';
        }

        this.template = new Template(this.templateRow, this.templateSyntax);
        var tbody = $$('#' + this.idLabel + '_box_' + parentIndex + ' tbody');

        Element.insert(tbody[0], {'bottom':this.template.evaluate(data)});

        if (typeof data.selection_price_type !== 'undefined') {
            $A($(this.idLabel + '_'+data.index+'_price_type').options).each(function(option){
                if (option.value==data.selection_price_type) option.selected = true;
            });
        }

        if (typeof data.selection_price_type !== 'undefined') {
            $A($(this.idLabel + '_'+data.index+'_can_change_qty').options).each(function(option){
                if (option.value==data.selection_can_change_qty) option.selected = true;
            });
        }

        var checkbox = $(this.idLabel + '_'+data.index+'_price_scope');
        if (checkbox && this.scopePrice) {
            if (data.price_scope === undefined) {
                checkbox.up().hide();
            } else if(!data.price_scope) {
                checkbox.checked = true;
                this.addScope(null, checkbox);
            }
        }

        this.bindScopeCheckbox();

        if (option_type.value == 'multi' || option_type.value == 'checkbox') {
            /**
             * Hide not needed elements (user defined qty select box)
             */
            inputs = $A($$('#' + this.idLabel + '_box_' + data.parentIndex + ' .qty-box'));
            inputs.each(
                function(elem){
                    elem.hide();
                }
            );
        }

        if (!$('price_type') || $('price_type').value != '1') {
            /**
             * Hide not needed elements (price type select and price input)
             */
            inputs = $A($$('#' + this.idLabel + '_box_' + data.parentIndex + ' .price-type-box'));
            inputs.each(
                function(elem){
                    elem.hide();
                }
            );
        }

        var inputs = $$('#bundle_option_' + data.parentIndex + ' input');
        inputs.each(function(el) { Event.observe(el, 'change', el.setHasChanges.bind(el));  } )
        var inputs = $$('#bundle_option_' + data.parentIndex + ' button.delete');
        inputs.each(function(el) { Event.observe(el, 'click', el.setHasChanges.bind(el));  } )
    },

    bindScopeCheckbox : function(){
        var checkboxes = $$('.bundle-option-price-scope-checkbox');
        for (var i=0;i<checkboxes.length;i++) {
            if (!$(checkboxes[i]).binded) {
                $(checkboxes[i]).binded = true;
                Event.observe(checkboxes[i], 'click', this.addScope.bind(this));
            }
        }
    },

    addScope : function(event, element){
        if (element == undefined) {
            element = $(Event.element(event));
        }
        var priceValue = $(element.id.sub('scope', 'value'));
        var priceType = $(element.id.sub('scope', 'type'));

        if (element.checked) {
            priceValue.disable();
            priceType.disable();
        } else {
            priceValue.enable();
            priceType.enable();
        }
    },

    addBox : function (parentIndex) {
        var div = $(bOption.idLabel + '_' + parentIndex)
        this.template = new Template(this.templateBox, this.templateSyntax);
        var data = {'parentIndex' : parentIndex};
        Element.insert(div, {'bottom':this.template.evaluate(data)});
    },

    remove : function(event) {
        var element = Event.findElement(event, 'tr');
        var container = Event.findElement(event, 'div');

        if (element) {
            Element.select(element, '.delete').each(function(elem){elem.value='1'});
            Element.select(element, ['input', 'select']).each(function(elem){elem.hide()});
            Element.removeClassName(element, 'selection');
            Element.hide(element);

            if (container) {
                if ($$('#' + container.id + ' tr.selection')) {
                    if (!$$('#' + container.id + ' tr.selection').length) {
                        container.hide();
                    }
                }
            }
        }
    },

    checkGroup : function(event) {
        var element = Event.element(event);
        if (element.type == 'radio') {
            var box = element.up('div');

            var inputs = $$('div#' + box.id + ' input.default');
            if (inputs) {
                for (i=0; i< inputs.length; i++) {
                    if (inputs[i].name != element.name) {
                        inputs[i].checked = false;
                    }
                }
            }
        }
    },

    productGridAddSelected : function(event) {
        var element = Event.findElement(event, 'button');
        var parts = element.id.split('_');

        $(bOption.idLabel + '_search_' + parts[2]).innerHTML = '';
        $(bOption.idLabel + '_' + parts[2] + '_add_button').show();

        this.gridSelection.get(parts[2]).each(
            function(pair) {
                var qty = pair.value.get('qty');
                var data = {
                    'name' : pair.value.get('name'),
                    'selection_price_value' : 0,
                    'selection_qty' : (qty == '' ? 1 : qty),
                    'sku' : pair.value.get('sku'),
                    'position' : 0,
                    'product_id' : pair.key,
                    'option_id' : $(bOption.idLabel + '_id_' + parts[2]).value
                };
                bSelection.addRow(parts[2], data);
            }
        );
    },

    productGridRowInit : function(grid, row){
        var checkbox = $(row).getElementsByClassName('checkbox')[0];
        var inputs = $(row).getElementsByClassName('input-text');
        for (var i = 0; i < inputs.length; i++) {
            inputs[i].checkbox = checkbox;
            Event.observe(inputs[i], 'keyup', this.productGridRowInputChange.bind(this));
            Event.observe(inputs[i], 'change', this.productGridRowInputChange.bind(this));
        }
    },

    productGridCheckboxCheck : function(grid, element, checked) {
        var id = element.up('table').id.split('_')[4];
        if (element.value > 0) {
            if (element.checked) {
                var tr = element.parentNode.parentNode;
                if (!this.gridSelection.get(id)) {
                    this.gridSelection.set(id, new Hash());
                }
                this.gridSelection.get(id).set(element.value, $H({}));
                this.gridSelection.get(id).get(element.value).set('name', tr.select('td.name')[0].innerHTML);
                this.gridSelection.get(id).get(element.value).set('qty', tr.select('input.qty')[0].value);
                this.gridSelection.get(id).get(element.value).set('sku', tr.select('td.sku')[0].innerHTML);
            } else {
                this.gridSelection.get(id).unset(element.value);
            }
        }
    },

    productGridRowClick : function(grid, event) {
        var trElement = Event.findElement(event, 'tr');
        var isInput = Event.element(event).tagName == 'INPUT';
        if (trElement) {
            var checkbox = Element.select(trElement, 'input');
            if (checkbox[0]) {
                var checked = isInput ? checkbox[0].checked : !checkbox[0].checked;
                grid.setCheckboxChecked(checkbox[0], checked);
            }
        }
    },

    productGridRowInputChange : function(event) {
        var element = Event.element(event);
        if (!element.checkbox.checked) {
            return;
        }
        var id = element.up('table').id.split('_')[4];
        this.gridSelection.get(id).get(element.checkbox.value).set('qty', element.value);
    }
}

bSelection = new Bundle.Selection();
//]]>
</script>
