<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * 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 through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<script type="text/javascript">
optionTemplate = '<div id="<?php echo $this->getFieldId() ?>_{{index}}"  class="option-box"> ' +
'<div class="option-title"> ' +
    '<label for="<?php echo $this->getFieldName() ?>[{{index}}][title]"><?php echo $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="<?php echo $this->getFieldName() ?>[{{index}}][title]" id="id_<?php echo $this->getFieldName() ?>_{{index}}_title" value="{{title}}">' +
    <?php else: ?>
    '<input class="input-text required-entry" type="text" name="<?php echo $this->getFieldName() ?>[{{index}}][default_title]" id="id_<?php echo $this->getFieldName() ?>_{{index}}_default_title" value="{{default_title}}">' +
    <?php endif; ?>
'<?php echo $this->jsQuoteEscape($this->getOptionDeleteButtonHtml()) ?>' +
'</div>' +
    '<table class="option-header" cellpadding="0" cellspacing="0">' +
        '<thead>' +
            '<tr>' +
                <?php if (!$this->isDefaultStore()): ?>
                '<th class="opt-title"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Store View Title')) ?>  <span class="required">*</span></th>' +
                <?php endif; ?>
                '<th class="opt-type"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Input Type')) ?></th>' +
                '<th class="opt-req"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Is Required')) ?></th>' +
                '<th class="opt-order"><?php echo $this->jsQuoteEscape(Mage::helper('bundle')->__('Position')) ?></th>' +
                '<th>&nbsp;</th>' +
            '</tr>' +
        '</thead>' +
        '<tbody>' +
            '<tr>' +
                '<input type="hidden" id="<?php echo $this->getFieldId() ?>_id_{{index}}" name="<?php echo $this->getFieldName() ?>[{{index}}][option_id]" value="{{option_id}}">' +
                '<input type="hidden" name="<?php echo $this->getFieldName() ?>[{{index}}][delete]" value="" class="delete">' +
                <?php if (!$this->isDefaultStore()): ?>
                '<td><input class="input-text required-entry" type="text" name="<?php echo $this->getFieldName() ?>[{{index}}][title]" id="id_<?php echo $this->getFieldName() ?>_{{index}}_title_store" value="{{title}}"></td>' +
                <?php endif; ?>
                '<td><?php echo $this->getTypeSelectHtml() ?></td>' +
                '<td><?php echo $this->getRequireSelectHtml() ?></td>' +
                '<td><input class="input-text validate-zero-or-greater" type="text" name="<?php echo $this->getFieldName() ?>[{{index}}][position]" value="{{position}}"></td>' +
                '<td>&nbsp;<?php echo $this->jsQuoteEscape($this->getAddSelectionButtonHtml()) ?></td>' +
            '</tr>' +
        '</tbody>' +
    '</table>' +
    '<div id="<?php echo $this->getFieldId() ?>_search_{{index}}">' +
    '</div>' +
'</div>';
</script>

<?php echo $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 : '<?php echo $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 {
            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 (data.required) {
            $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): ?>
optionIndex = bOption.add(<?php echo $_option->toJson() ?>);
<?php if ($_option->getSelections()):?>
    <?php foreach ($_option->getSelections() as $_selection): ?>
    <?php $_selection->setName($this->escapeHtml($_selection->getName())); ?>
bSelection.addRow(optionIndex, <?php echo $_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>
