<?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-2018 Magento, Inc. (http://www.magento.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<div class="entry-edit-head">
    <h4><?php echo Mage::helper('widget')->__('Layout Updates') ?></h4>
    <div class="right"><?php echo $this->getAddLayoutButtonHtml() ?></div>
</div>
<div class="fieldset">
    <div class="hor-scroll">
            <div id="page_group_container"></div>
    </div>
</div>
<script type="text/javascript">
//<![CDATA[

var pageGroupTemplate = '<div class="options-box page_group_container" id="page_group_container_{{id}}">'+
    '<div class="option-box">'+
        '<div class="option-title">'+
            '<?php echo $this->getRemoveLayoutButtonHtml() ?>'+
            '<label for="widget_instance[{{id}}][page_group]">Display On <span class="required">*</span></label>'+
            '<?php echo $this->getDisplayOnSelectHtml(); ?>'+
        '</div>'+
<?php foreach ($this->getDisplayOnContainers() as $container): ?>
    '<div class="no-display <?php echo $container['code'] ?> group_container" id="<?php echo $container['name'] ?>_{{id}}">'+
        '<input type="hidden" class="container_name" name="__[container_name]" value="widget_instance[{{id}}][<?php echo $container['name'] ?>]" />'+
        '<input type="hidden" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][page_id]" value="{{page_id}}" />'+
        '<input type="hidden" class="layout_handle_pattern" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][layout_handle]" value="<?php echo $container['layout_handle'] ?>" />'+
        '<table cellspacing="0" class="option-header">'+
            '<col width="200" />'+
            '<col width="220" />'+
            '<col width="320" />'+
            '<col />'+
            '<thead>'+
                '<tr>'+
                    '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('%s', $container['label'])) ?></label></th>'+
                    '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Block Reference')) ?> <span class="required">*</span></label></th>'+
                    '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Template')) ?></label></th>'+
                    '<th>&nbsp;</th>'+
                '</tr>'+
            '</thead>'+
            '<tbody>'+
                '<tr>'+
                    '<td>'+
                        '<input type="radio" class="radio for_all" id="all_<?php echo $container['name'] ?>_{{id}}" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][for]" value="all" onclick="WidgetInstance.togglePageGroupChooser(this)" checked="checked" />&nbsp;'+
                        '<label for="all_<?php echo $container['name'] ?>_{{id}}"><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('All')) ?></label>&nbsp;&nbsp;&nbsp;'+
                        '<input type="radio" class="radio for_specific" id="specific_<?php echo $container['name'] ?>_{{id}}" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][for]" value="specific" onclick="WidgetInstance.togglePageGroupChooser(this)" />&nbsp;'+
                        '<label for="specific_<?php echo $container['name'] ?>_{{id}}"><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Specific %s', $container['label'])) ?></label>'+
                    '</td>'+
                    '<td>'+
                        '<div class="block_reference_container">'+
                            '<div class="block_reference"></div>'+
                        '</div>'+
                    '</td>'+
                    '<td>'+
                        '<div class="block_template_container">'+
                            '<div class="block_template"></div>'+
                        '</div>'+
                    '</td>'+
                '</tr>'+
            '</tbody>'+
        '</table>'+
        '<div class="no-display chooser_container" id="<?php echo $container['name'] ?>_ids_{{id}}">'+
            '<input type="hidden" class="is_anchor_only" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][is_anchor_only]" value="<?php echo $container['is_anchor_only'] ?>" />'+
            '<input type="hidden" class="product_type_id" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][product_type_id]" value="<?php echo $container['product_type_id'] ?>" />'+
            '<p>' +
                '<input type="text" class="input-text entities" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][entities]" value="{{<?php echo $container['name'] ?>_entities}}" readonly="readonly" />&nbsp;' +
                '<a class="widget-option-chooser" href="javascript:void(0)" onclick="WidgetInstance.displayEntityChooser(\'<?php echo $container['code'] ?>\', \'<?php echo $container['name'] ?>_ids_{{id}}\')"  title="<?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Open Chooser')) ?>">' +
                    '<img src="<?php echo Mage::getDesign()->getSkinUrl('images/rule_chooser_trigger.gif') ?>" class="v-middle" alt="<?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Open Chooser')); ?>" />' +
                '</a>&nbsp;' +
                '<a href="javascript:void(0)" onclick="WidgetInstance.hideEntityChooser(\'<?php echo $container['name'] ?>_ids_{{id}}\')" title="<?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Apply')); ?>">' +
                    '<img src="<?php echo Mage::getDesign()->getSkinUrl('images/rule_component_apply.gif') ?>" class="v-middle" alt="<?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Apply')); ?>" />' +
                '</a>' +
            '</p>'+
            '<div class="chooser"></div>'+
        '</div>'+
    '</div>'+
<?php endforeach; ?>
'<div class="no-display all_pages group_container" id="all_pages_{{id}}">'+
    '<input type="hidden" class="container_name" name="__[container_name]" value="widget_instance[{{id}}][all_pages]" />'+
    '<input type="hidden" name="widget_instance[{{id}}][all_pages][page_id]" value="{{page_id}}" />'+
    '<input type="hidden" class="layout_handle_pattern" name="widget_instance[{{id}}][all_pages][layout_handle]" value="default" />'+
    '<input type="hidden" class="for_all" name="widget_instance[{{id}}][all_pages][for]" value="all" />'+
    '<table cellspacing="0" class="option-header">'+
        '<col width="220" />'+
        '<col width="320" />'+
        '<col />'+
        '<thead>'+
            '<tr>'+
                '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Block Reference')) ?> <span class="required">*</span></label></th>'+
                '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Template')) ?></label></th>'+
                '<th>&nbsp;</th>'+
            '</tr>'+
        '</thead>'+
        '<tbody>'+
            '<tr>'+
                '<td>'+
                    '<div class="block_reference_container">'+
                        '<div class="block_reference"></div>'+
                    '</div>'+
                '</td>'+
                '<td>'+
                    '<div class="block_template_container">'+
                        '<div class="block_template"></div>'+
                    '</div>'+
                '</td>'+
                '<td>&nbsp;</td>'+
            '</tr>'+
        '</tbody>'+
    '</table>'+
'</div>'+
'<div class="no-display ignore-validate pages group_container" id="pages_{{id}}">'+
    '<input type="hidden" class="container_name" name="__[container_name]" value="widget_instance[{{id}}][pages]" />'+
    '<input type="hidden" name="widget_instance[{{id}}][pages][page_id]" value="{{page_id}}" />'+
    '<input type="hidden" class="for_all" name="widget_instance[{{id}}][pages][for]" value="all" />'+
    '<table cellspacing="0" class="option-header">'+
        '<col width="200" />'+
        '<col width="220" />'+
        '<col width="320" />'+
        '<col />'+
        '<thead>'+
            '<tr>'+
                '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Page')) ?> <span class="required">*</span></label></th>'+
                '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Block Reference')) ?> <span class="required">*</span></label></th>'+
                '<th><label><?php echo $this->helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Template')) ?></label></th>'+
                '<th>&nbsp;</th>'+
            '</tr>'+
        '</thead>'+
        '<tbody>'+
            '<tr>'+
                '<td><?php echo $this->getLayoutsChooser() ?></td>'+
                '<td>'+
                    '<div class="block_reference_container">'+
                        '<div class="block_reference"></div>'+
                    '</div>'+
                '</td>'+
                '<td>'+
                    '<div class="block_template_container">'+
                        '<div class="block_template"></div>'+
                    '</div>'+
                '</td>'+
                '<td>&nbsp;</td>'+
            '</tr>'+
        '</tbody>'+
    '</table>'+
'</div>'+
'</div>'+
'</div>';

var WidgetInstance = {
    pageGroupTemplate    : pageGroupTemplate,
    pageGroupContainerId : 'page_group_container',
    templatePattern : /(^|.|\r|\n)({{(\w+)}})/,
    count : 0,
    activePageGroups : $H({}),
    selectedItems : {},

    addPageGroup : function(data) {
        if (this.pageGroupTemplate && (pageGroupContainer = $(this.pageGroupContainerId))) {
            if (!data.page_id) {
                data = {};
                data.page_id = 0;
                data.entities = '';
            }
            data.id = this.count++;
            if (data[data.group + '_entities']) {
                var selected_entities = data[data.group + '_entities'].split(',');
                if (selected_entities.length > 0) {
                    for (var i = 0; i < selected_entities.length; i++) {
                        this.addProductItemToSelection(data.group + '_ids_' + data.id, selected_entities[i]);
                    }
                }
            }
            pageGroupTemplateObj = new Template(this.pageGroupTemplate, this.templatePattern);
            Element.insert(pageGroupContainer, {'top':pageGroupTemplateObj.evaluate(data)});
            if (data.group) {
                pageGroup = $(data.group+'_'+data.id);
                additional = {};
                additional.selectedBlock = data.block;
                additional.selectedTemplate = data.template;
                additional.position = data.position;
                additional.for_value = data.for_value;
                additional.template = '';
                if (data.group == 'pages') {
                    layoutSelect = pageGroup.down('select#layout_handle');
                    if (layoutSelect) {
                        for (var i = 0; i < layoutSelect.options.length; i++) {
                            if (layoutSelect.options[i].value == data.layout_handle) {
                                layoutSelect.options[i].selected = true;
                                break;
                            }
                        }
                    }
                }
                if ($(this.pageGroupContainerId+'_'+data.id)) {
                    selectGroupElm = $(this.pageGroupContainerId+'_'+data.id).down('select.page_group_select');
                    for (var i = 0; i < selectGroupElm.options.length; i++) {
                        if (selectGroupElm.options[i].value == data.group) {
                            selectGroupElm.options[i].selected = true;
                            break;
                        }
                    }
                }
                forElm = pageGroup.down('input.for_'+data.for_value);
                if (forElm) {
                    /**
                    * IE browsers fix: remove default checked attribute in radio form element
                    * to check others radio form elements in future
                    */
                    pageGroup.down('input.for_all').defaultChecked = false;
                    forElm.defaultChecked = true;
                    forElm.checked = true;
                    this.togglePageGroupChooser(forElm);
                }
                this.displayPageGroup(pageGroup, additional);
            }
        }
    },
    removePageGroup : function(element) {
        container = element.up('div.page_group_container');
        if (container) {
            container.remove();
        }
    },
    addProductItemToSelection: function(groupId, item) {
        if (undefined == this.selectedItems[groupId]) {
            this.selectedItems[groupId] = $H({});
        }
        if (!isNaN(parseInt(item))) {
            this.selectedItems[groupId].set(item, 1);
        }
    },
    removeProductItemFromSelection: function(groupId, item) {
        if (undefined !== this.selectedItems[groupId]) {
            this.selectedItems[groupId].unset(item);
        }
    },
    showBlockContainer : function(container) {
        container = $(container);
        if (container) {
            container.removeClassName('no-display');
            container.removeClassName('ignore-validate');
            container.show();
        }
    },
    hideBlockContainer : function(container) {
        container = $(container);
        if (container) {
            container.addClassName('no-display');
            container.addClassName('ignore-validate');
            container.hide();
        }
    },
    displayPageGroup : function(container, additional) {
        container = $(container);
        if (!container) {
//            if (activePageGroupId = this.activePageGroups.get(container.up('div.page_group_container').id)) {
//                this.hideBlockContainer(activePageGroupId);
//            }
        }
        if (!additional) {
            additional = {};
        }
        if (activePageGroupId = this.activePageGroups.get(container.up('div.page_group_container').id)) {
            this.hideBlockContainer(activePageGroupId);
        }
        this.activePageGroups.set(container.up('div.page_group_container').id, container.id);
        this.showBlockContainer(container);
        blockContainer = container.down('div.block_reference');
        if (blockContainer && blockContainer.innerHTML == '') {
            layoutHandle = '';
            if (layoutHandleField = container.down('input.layout_handle_pattern')) {
                layoutHandle = layoutHandleField.value;
            }
            this.loadSelectBoxByType('block_reference', container, layoutHandle, additional);
        }
        this.loadSelectBoxByType('block_template', container, additional.selectedBlock, additional);
    },
    displayEntityChooser : function(type, chooser, additional) {
        if (!additional) {
            additional = {};
        }
        if (type == 'categories') {
            additional.url = '<?php echo $this->getCategoriesChooserUrl() ?>';
            additional.post_parameters = $H({'is_anchor_only':$(chooser).down('input.is_anchor_only').value});
        } else if (type == 'products') {
            additional.url = '<?php echo $this->getProductsChooserUrl() ?>';
            additional.post_parameters = $H({'product_type_id':$(chooser).down('input.product_type_id').value});
        }
        if (chooser && additional) {
            this.displayChooser(chooser, additional);
        }
    },
    hideEntityChooser : function(chooser) {
        chooser = $(chooser).down('div.chooser');
        if (chooser) {
            chooser.addClassName('no-display');
            chooser.hide();
        }
    },
    displayChooser : function(chooser, additional) {
        chooser = $(chooser).down('div.chooser');
        entities = chooser.up('div.chooser_container').down('input[type="text"].entities').value;
        postParameters = $H({selected:entities});
        url = '';
        if (additional) {
            if (additional.url) url = additional.url;
            if (additional.post_parameters) {
                additional.post_parameters.each(function(pair){
                    postParameters.set(pair.key,pair.value);
                });
            }
        }
        if (chooser && url) {
            if (chooser.innerHTML == '') {
                new Ajax.Request(url, {
                    method: 'post',
                    parameters: postParameters,
                    onSuccess: function(transport) {
                        try {
                            if (transport.responseText) {
                                Element.insert(chooser, transport.responseText);
                                chooser.removeClassName('no-display');
                                chooser.show();
                            }
                        } catch (e) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Error occurs during loading chooser.')) ?>');
                        }
                    }
                });
            } else {
                chooser.removeClassName('no-display');
                chooser.show();
            }
        }
    },
    checkProduct : function(event) {
        var elm = event.memo.element,
            container = event.target.up('div.chooser').up('div.chooser_container'),
            selectionId = container.id,
            entitiesElm = container.down('input[type="text"].entities');
        if (elm.checked) {
            this.addProductItemToSelection(selectionId, elm.value);
        } else {
            this.removeProductItemFromSelection(selectionId, elm.value);
        }
        if (entitiesElm) {
            entitiesElm.value = this.selectedItems[selectionId].keys().join(',');
        }
    },
    checkCategory : function(event) {
        node = event.memo.node;
        container = event.target.up('div.chooser_container');
        value = container.down('input[type="text"].entities').value.strip();
        if (node.attributes.checked) {
            if (value) ids = value.split(',');
            else ids = [];
            if (-1 == ids.indexOf(node.id)) {
                ids.push(node.id);
                container.down('input[type="text"].entities').value = ids.join(',');
            }
        } else {
            ids = value.split(',');
            while (-1 != ids.indexOf(node.id)) {
                ids.splice(ids.indexOf(node.id), 1);
                container.down('input[type="text"].entities').value = ids.join(',');
            }
        }
    },
    togglePageGroupChooser : function(element) {
        element = $(element);
        if (element && (chooser = element.up('div.group_container').down('div.chooser_container'))) {
            if (element.value == 'all') {
                chooser.addClassName('no-display');
                chooser.hide();
            } else {
                chooser.removeClassName('no-display');
                chooser.show();
            }
        }
    },
    loadSelectBoxByType : function (type, element, value, additional) {
        if (!additional) {
            additional = {};
        }
        if (element && (containerElm = element.down('div.'+type))) {
            url = '';
            selected = '';
            parameters = {};
            if (type == 'block_reference') {
                url = '<?php echo $this->getBlockChooserUrl() ?>';
                if (additional.selectedBlock) {
                    selected = additional.selectedBlock;
                }
                parameters.layout = value;
            } else if (type == 'block_template') {
                url = '<?php echo $this->getTemplateChooserUrl() ?>';
                if (additional.selectedTemplate) {
                    selected = additional.selectedTemplate;
                }
                parameters.block = value;
            }
            parameters.selected = selected;
            if (url) {
                new Ajax.Request(url, {
                    method: 'post',
                    parameters: parameters,
                    containerElm: containerElm,
                    onSuccess: function(transport) {
                        containerElm = transport.request.options.containerElm;
                        try {
                            if (transport.responseText) {
                                containerElm.update(transport.responseText);
                                formElm = containerElm.down('select, input[type="hidden"]');
                                if (formElm) {
                                    formElm.name = element.down('input.container_name').value+'['+formElm.name+']';
                                }
                            }
                        } catch (e) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('widget')->__('Error occurs during loading chooser.')) ?>');
                        }
                    }
                });
            }
        }
    }
};

Ext.onReady(function(){
    <?php foreach ($this->getPageGroups() as $pageGroup): ?>
        WidgetInstance.addPageGroup(<?php echo Zend_Json::encode($pageGroup) ?>);
    <?php endforeach; ?>
    Event.observe(document, 'product:changed', function(event){
        WidgetInstance.checkProduct(event);
    });
    Event.observe(document, 'node:changed', function(event){
        WidgetInstance.checkCategory(event);
    });
});
//]]>
</script>
