<?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-2014 X.commerce, Inc. (http://www.magento.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>

<div class="content-header">
        <h3 class="icon-head head-categories"><?php echo $this->escapeHtml($this->getHeader()) . ($this->getCategoryId() ? ' (' . Mage::helper('catalog')->__('ID: %s', $this->getCategoryId()) . ')' : '') ?></h3>
        <p class="content-buttons form-buttons">
            <?php echo $this->getResetButtonHtml() ?>
            <?php if($this->getCategoryId()): ?>
                    <?php echo $this->getDeleteButtonHtml() ?>
            <?php endif; ?>
            <?php echo $this->getAdditionalButtonsHtml(); ?>
            <?php echo $this->getSaveButtonHtml() ?>
        </p>
</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">
    <div class="no-display">
        <input type="hidden" name="isIframe" value="1" />
        <input name="form_key" type="hidden" value="<?php echo $this->getFormKey() ?>" />
        <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{
                if (this.isSubmitted) {
                    return false;
                }
                this.isSubmitted = true;
                this._submit();
            }
            displayLoadingMask();
            return true;
        }
        return false;
    };

    categoryForm.refreshPath = function () {

        categoryId = this.getCategoryId();

        if (!categoryId) {
            return false;
        }

        var refreshPathSuccess = function(transport) {
            if (transport.responseText.isJSON()) {
                response = transport.responseText.evalJSON()
                if (response.error) {
                    alert(response.message);
                } else {
                    if (categoryForm.getCategoryId() == response['id']) {
                        categoryForm.setCategoryPath(response['path']);
                    }
                }
            }
        };

        new Ajax.Request(
                '<?php echo $this->getRefreshPathUrl() ?>',
                {
                    method:     'POST',
                    evalScripts: true,
                    onSuccess: refreshPathSuccess
                }
        );

    };

    categoryForm.getCategoryId = function () {
        collection = $(this.formId).getInputs('hidden','general[id]');
        if (collection.size() > 0) {
            return collection.first().value;
        }
        return false;
    };

    categoryForm.setCategoryPath = function (path) {
        collection = $(this.formId).getInputs('hidden','general[path]');
        if (collection.size() > 0) {
            return collection.first().value = path;
        }
    };

    /**
    * Create/edit some category
    */
    function categorySubmit(url, useAjax) {
        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();
        }

        // Get info about what we're submitting - to properly update tree nodes
        var categoryId = params['general[id]'] ? params['general[id]'] : 0;
        var isCreating = categoryId == 0; // Separate variable is needed because '0' in javascript converts to TRUE
        var path = params['general[path]'].split('/');
        var parentId = path.pop();
        if (parentId == categoryId) { // Maybe path includes category id itself
            parentId = path.pop();
        }

        // Make operations with category tree
        if (isCreating) {
            /* Some specific tasks for creating category */
            if (!tree.currentNodeId) {
                // First submit of form - select some node to be current
                tree.currentNodeId = parentId;
            }
            tree.addNodeTo = parentId;
        } else {
            /* Some specific tasks for editing category */
            // Maybe change category enabled/disabled style
            if (tree && tree.storeId==0) {
                var currentNode = tree.getNodeById(categoryId);

                if (currentNode) {
                    if (parseInt(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);
                }
            }
        }

        // Submit form
        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>
