<?php
/**
 * Maho
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://magento.com)
 * @copyright   Copyright (c) 2018-2023 The OpenMage Contributors (https://openmage.org)
 * @copyright   Copyright (c) 2024 Maho (https://mahocommerce.com)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<script type="text/javascript">
optionTemplate = '<div id="<?= $this->getFieldId() ?>_{{index}}"  class="option-box"> ' +
'<div class="option-title"> ' +
    '<label for="<?= $this->getFieldName() ?>[{{index}}][title]"><?= $this->jsQuoteEscape(Mage::helper('bundle')->__('Default Title')) ?> <span class="required">*</span></label>' +
    <?php if ($this->isDefaultStore()): ?>
    '<input class="input-text required-entry" type="text" name="<?= $this->getFieldName() ?>[{{index}}][title]" id="id_<?= $this->getFieldName() ?>_{{index}}_title" value="{{title}}">' +
    <?php else: ?>
    '<input class="input-text required-entry" type="text" name="<?= $this->getFieldName() ?>[{{index}}][default_title]" id="id_<?= $this->getFieldName() ?>_{{index}}_default_title" value="{{default_title}}">' +
    <?php endif ?>
'<?= $this->jsQuoteEscape($this->getOptionDeleteButtonHtml()) ?>' +
'</div>' +
    '<table class="option-header" cellpadding="0" cellspacing="0">' +
        '<thead>' +
            '<tr>' +
                <?php if (!$this->isDefaultStore()): ?>
                '<th class="opt-title"><?= $this->jsQuoteEscape(Mage::helper('bundle')->__('Store View Title')) ?>  <span class="required">*</span></th>' +
                <?php endif ?>
                '<th class="opt-type"><?= $this->jsQuoteEscape(Mage::helper('bundle')->__('Input Type')) ?></th>' +
                '<th class="opt-req"><?= $this->jsQuoteEscape(Mage::helper('bundle')->__('Is Required')) ?></th>' +
                '<th class="opt-order"><?= $this->jsQuoteEscape(Mage::helper('bundle')->__('Position')) ?></th>' +
                '<th>&nbsp;</th>' +
            '</tr>' +
        '</thead>' +
        '<tbody>' +
            '<tr>' +
                '<input type="hidden" id="<?= $this->getFieldId() ?>_id_{{index}}" name="<?= $this->getFieldName() ?>[{{index}}][option_id]" value="{{option_id}}">' +
                '<input type="hidden" name="<?= $this->getFieldName() ?>[{{index}}][delete]" value="" class="delete">' +
                <?php if (!$this->isDefaultStore()): ?>
                '<td><input class="input-text required-entry" type="text" name="<?= $this->getFieldName() ?>[{{index}}][title]" id="id_<?= $this->getFieldName() ?>_{{index}}_title_store" value="{{title}}"></td>' +
                <?php endif ?>
                '<td><?= $this->getTypeSelectHtml() ?></td>' +
                '<td><?= $this->getRequireSelectHtml() ?></td>' +
                '<td><input class="input-text validate-zero-or-greater" type="text" name="<?= $this->getFieldName() ?>[{{index}}][position]" value="{{position}}"></td>' +
                '<td>&nbsp;<?= $this->jsQuoteEscape($this->getAddSelectionButtonHtml()) ?></td>' +
            '</tr>' +
        '</tbody>' +
    '</table>' +
    '<div id="<?= $this->getFieldId() ?>_search_{{index}}">' +
    '</div>' +
'</div>';
</script>

<?= $this->getSelectionHtml() ?>

<script type="text/javascript">

function changeInputType(oldObject, oType) {
    var newObject = document.createElement('input');
    newObject.type = oType;
    if(oldObject.size) newObject.size = oldObject.size;
    if(oldObject.value) newObject.value = oldObject.value;
    if(oldObject.name) newObject.name = oldObject.name;
    if(oldObject.id) newObject.id = oldObject.id;
    if(oldObject.onclick) newObject.onclick = oldObject.onclick;
    if(oldObject.className) newObject.className = oldObject.className;
    oldObject.parentNode.replaceChild(newObject,oldObject);
    return newObject;
}

Bundle.Option = Class.create();
Bundle.Option.prototype = {
    idLabel : '<?= $this->getFieldId() ?>',
    top : '',
    templateSyntax : /(^|.|\r|\n)({{(\w+)}})/,
    templateText : '',
    itemsCount : 0,
    initialize : function(template) {
        this.templateText = template;
        this.top = $('product_bundle_container_top');
    },

    add : function(data) {
        if (!data) {
            data = {};
            this.top = $('product_bundle_container_top');
        } else if (data.title) {
            data.title = data.title.replace('"', "&quot;");
        }

        data.index = this.itemsCount++;

        this.template = new Template(this.templateText, this.templateSyntax);

        Element.insert(this.top, {'after':this.template.evaluate(data)});

        this.top = $(this.idLabel + '_' + data.index);

        //set selected type
        if (data.type) {
            $A($(this.idLabel + '_'+data.index+'_type').options).each(function(option){
                if (option.value==data.type) option.selected = true;
            });
        }

        //set selected is_require
        if (typeof data.required !== 'undefined') {
            $A($(this.idLabel + '_'+data.index+'_required').options).each(function(option){
                if (option.value==data.required) option.selected = true;
            });
        }
        // rebind change notifications
        varienWindowOnload(true);

        return data.index;
    },

    remove : function(event){
        var element = $(Event.findElement(event, 'div')).parentNode;
        if(element){
            Element.select(element, '.delete').each(function(elem){elem.value='1'});
            Element.select(element, ['input', 'select']).each(function(elem){elem.hide(); elem.className = '';});
            Element.hide(element);
        }
    },

    changeType : function(event) {
        var element = Event.element(event);
        parts = element.id.split('_');
        i = parts[2];
        if (element.value == 'multi' || element.value == 'checkbox') {
            inputs = $A($$('#' + bSelection.idLabel + '_box_' + i + ' tr.selection input.default'));
            inputs.each(
                function(elem){
                    //elem.type = "checkbox";
                    changeInputType(elem, 'checkbox');
                }
            );
            /**
             * Hide not needed elements (user defined qty select box)
             */
            inputs = $A($$('#' + bSelection.idLabel + '_box_' + i + ' .qty-box'));
            inputs.each(
                function(elem){
                    elem.hide();
                }
            );

        } else {
            inputs = $A($$('#' + bSelection.idLabel + '_box_' + i + ' tr.selection input.default'));
            have = false;
            for (j=0; j< inputs.length; j++) {
                //inputs[j].type = "radio";
                changeInputType(inputs[j], 'radio');
                if (inputs[j].checked && have) {
                    inputs[j].checked = false;
                } else {
                    have = true;
                }
            }

            /**
             * Show user defined select box
             */
            inputs = $A($$('#' + bSelection.idLabel + '_box_' + i + ' .qty-box'));
            inputs.each(
                function(elem){
                    elem.show();
                }
            );
        }
    },

    priceTypeFixed : function() {
        inputs = $A($$('.price-type-box'));
        inputs.each(
            function(elem){
                elem.show();
            }
        );
    },

    priceTypeDynamic : function() {
        inputs = $A($$('.price-type-box'));
        inputs.each(
            function(elem){
                elem.hide();
            }
        );
    }
}

var optionIndex = 0;
bOption = new Bundle.Option(optionTemplate);
//adding data to templates
<?php foreach ($this->getOptions() as $_option): ?>
    <?php $_option->setDefaultTitle($this->escapeHtml($_option->getDefaultTitle())); ?>
    <?php $_option->setTitle($this->escapeHtml($_option->getTitle())); ?>
    optionIndex = bOption.add(<?= $_option->toJson() ?>);
    <?php if ($_option->getSelections()):?>
        <?php foreach ($_option->getSelections() as $_selection): ?>
        <?php $_selection->setName($this->escapeHtml($_selection->getName())); ?>
        <?php $_selection->setSku($this->escapeHtml($_selection->getSku())); ?>
        bSelection.addRow(optionIndex, <?= $_selection->toJson() ?>);
        <?php endforeach ?>
    <?php endif ?>
<?php endforeach ?>
/**
 * Adding event on price type select box of product to hide or show prices for selections
 */
function togglePriceType() {
    if ($('price_type').value == '1') {
        bOption.priceTypeFixed();
    } else {
        bOption.priceTypeDynamic();
    }
}

togglePriceType();

Event.observe('price_type', 'change', togglePriceType);

</script>
