<?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@magentocommerce.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.magentocommerce.com for more information.
 *
 * @category   design_default
 * @package    Mage_Bundle
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://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 Mage::helper('catalog')->__('Name') ?></th>' +
    '            <th class="type-price price-type-box"><?php echo Mage::helper('catalog')->__('Price') ?></th>' +
    '            <th class="type-type price-type-box"><?php echo Mage::helper('bundle')->__('Price Type') ?></th>' +
    '            <th class="type-price"><?php echo Mage::helper('bundle')->__('Default Qty') ?></th>' +
    '            <th class="type-uqty qty-box"><?php echo Mage::helper('bundle')->__('User Defined Qty') ?></th>' +
    '             <th class="type-order"><?php echo Mage::helper('bundle')->__('Position') ?></th>' +
    '            <th style="width:1px"><?php echo 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> {{sku}}' +
                '    </div>' +
                '</td>' +
                '<td class="price-type-box"><input 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}}"></td>' +
                '<td class="price-type-box"><?php echo $this->getPriceTypeSelectHtml() ?></td>' +
                '<td><input class="input-text required-entry 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() ?>',
    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},
            evalScripts : true
        });

        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 = {};
        }

        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 (data.selection_price_type) {
            $A($(this.idLabel + '_'+data.index+'_price_type').options).each(function(option){
                if (option.value==data.selection_price_type) option.selected = true;
            });
        }

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

        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').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();
                }
            );
        }
    },

    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.element(event);
        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>
