<?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
 * @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)
 */
?>

<div class="content-header">
<table cellspacing="0">
    <tr>
        <td><h3 class="icon-head head-categories"><?php echo $this->getHeader() . ($this->getCategoryId() ? ' (' . Mage::helper('catalog')->__('ID: %s', $this->getCategoryId()) . ')' : '') ?></h3></td>
        <td class="form-buttons">
            <?php echo $this->getResetButtonHtml() ?>
            <?php if($this->getCategoryId()): ?>
                    <?php echo $this->getDeleteButtonHtml() ?>
            <?php endif; ?>
            <?php echo $this->getAdditionalButtonsHtml(); ?>
            <?php echo $this->getSaveButtonHtml() ?>
        </td>
    </tr>
</table>
</div>
<?php if($this->hasStoreRootCategory()): ?>
    <?php echo $this->getTabsHtml() ?>
<?php else: ?>
<div class="messages warning-msg">
    <?php echo Mage::helper('catalog')->__('Set root category for this store in the <a href="%s">configuration</a>', $this->getStoreConfigurationUrl()) ?>
</div>
<?php endif; ?>
<iframe name="iframeSave" style="display:none; width:100%;" src="<?php echo $this->getJsUrl() ?>blank.html"></iframe>
<form target="iframeSave" id="category_edit_form" action="<?php echo $this->getSaveUrl() ?>" method="post" enctype="multipart/form-data">
    <input type="hidden" name="isIframe" value="1" />
    <input name="form_key" type="hidden" value="<?php echo $this->getFormKey() ?>" />
    <div class="no-display">
        <input type="hidden" name="category_products" id="in_category_products" value="" />
        <input type="hidden" name="active_tab_id" id="active_tab_id" value="" />
    </div>
    <div id="category_tab_content"></div>
</form>
<script type="text/javascript">
//<![CDATA[
    categoryForm = new varienForm('category_edit_form');

    categoryForm.submit= function (url) {
        this.errorSections = $H({});
        this.canShowError = true;
        this.submitUrl = url;
        if (this.validator && this.validator.validate()) {
            if(this.validationUrl){
                this._validate();
            }
            else{
                this._submit();
            }
            displayLoadingMask();
            return true;
        }
        return false;
    };

    function categorySubmit(url) {
        var activeTab = $('active_tab_id');
        if (activeTab) {
            if (activeTab.tabsJsObject && activeTab.tabsJsObject.activeTab) {
                activeTab.value = activeTab.tabsJsObject.activeTab.id;
            }
        }

        var params = {};
        var fields = $('category_edit_form').getElementsBySelector('input', 'select');
        for(var i=0;i<fields.length;i++){
            if (!fields[i].name) {
                continue;
            }
            params[fields[i].name] = fields[i].getValue();
        }

        if (tree && tree.storeId==0 && !tree.addNodeTo) {
            var currentNode = tree.getNodeById(tree.currentNodeId);

            if (currentNode) {
                if (params['general[is_active]']) {
                    var oldClass = 'no-active-category';
                    var newClass = 'active-category';
                } else {
                    var oldClass = 'active-category';
                    var newClass = 'no-active-category';
                }

                Element.removeClassName(currentNode.ui.wrap.firstChild, oldClass);
                Element.addClassName(currentNode.ui.wrap.firstChild, newClass);

          /*      var name = currentNode.text;

                if (!name.match(/(\(\d+\))/)) {
                   name = params['general[name]'];
                } else {
                    name = name.replace(/(.+)\(/,params['general[name]']+' (');
                }
                currentNode.setText(name);*/
            }
        }

        /**
         * We submit first loaded form
         */
        if (!tree.currentNodeId) {
            tree.currentNodeId = tree.root.id;
            tree.addNodeTo = tree.currentNodeId;
        }
        categoryForm.submit();
    }

<?php if(($block = $this->getLayout()->getBlock('category.product.grid')) && ($_gridJsObject=$block->getJsObjectName())): ?>

    var categoryProducts = $H(<?php echo $this->getProductsJson() ?>);
    $('in_category_products').value = categoryProducts.toQueryString();

    function registerCategoryProduct(grid, element, checked){
        if(checked){
            if(element.positionElement){
                element.positionElement.disabled = false;
                categoryProducts.set(element.value, element.positionElement.value);
            }
        }
        else{
            if(element.positionElement){
                element.positionElement.disabled = true;
            }
            categoryProducts.unset(element.value);
        }
        $('in_category_products').value = categoryProducts.toQueryString();
        grid.reloadParams = {'selected_products[]':categoryProducts.keys()};
    }
    function categoryProductRowClick(grid, event){
        var trElement = Event.findElement(event, 'tr');
        var isInput   = Event.element(event).tagName == 'INPUT';
        if(trElement){
            var checkbox = Element.getElementsBySelector(trElement, 'input');
            if(checkbox[0]){
                var checked = isInput ? checkbox[0].checked : !checkbox[0].checked;
                <?php echo $_gridJsObject ?>.setCheckboxChecked(checkbox[0], checked);
            }
        }
    }
    function positionChange(event){
        var element = Event.element(event);
        if(element && element.checkboxElement && element.checkboxElement.checked){
            categoryProducts.set(element.checkboxElement.value, element.value);
            $('in_category_products').value = categoryProducts.toQueryString();
        }
    }

    var tabIndex = 1000;
    function categoryProductRowInit(grid, row){
        var checkbox = $(row).getElementsByClassName('checkbox')[0];
        var position = $(row).getElementsByClassName('input-text')[0];
        if(checkbox && position){
            checkbox.positionElement = position;
            position.checkboxElement = checkbox;
            position.disabled = !checkbox.checked;
            position.tabIndex = tabIndex++;
            Event.observe(position,'keyup',positionChange);
        }
    }


    <?php echo $_gridJsObject ?>.rowClickCallback = categoryProductRowClick;
    <?php echo $_gridJsObject ?>.initRowCallback = categoryProductRowInit;
    <?php echo $_gridJsObject ?>.checkboxCheckCallback = registerCategoryProduct;
    <?php echo $_gridJsObject ?>.rows.each(function(row){categoryProductRowInit(<?php echo $_gridJsObject ?>, row)});

<?php endif; ?>
<?php if($this->isAjax() && ($block = $this->getLayout()->getBlock('tabs')) && ($_tabsJsObject=$block->getJsObjectName())): ?>
    <?php echo $_tabsJsObject ?>.moveTabContentInDest();
    if (<?php echo $_tabsJsObject ?>.activeTab) {
        $('active_tab_id').value = <?php echo $_tabsJsObject ?>.activeTab.id;
    }
    $('active_tab_id').tabsJsObject = <?php echo $_tabsJsObject ?>;
<?php endif; ?>
//]]>
</script>