<?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
 * @package     default_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.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 style="width:50%;"><h3 class="icon-head head-product-attribute-sets"><?php echo $this->htmlEscape($this->_getHeader()) ?></h3></td>
            <td class="form-buttons">
                <?php echo $this->getBackButtonHtml() ?>
                <?php echo $this->getResetButtonHtml() ?>
                <?php echo $this->getDeleteButtonHtml() ?>
                <?php echo $this->getSaveButtonHtml() ?>
            </td>
        </tr>
    </table>
</div>
<table cellspacing="0" width="100%">
    <tr>
        <td width="360" style="border-right:1px solid #ddd; padding:0 23px 23px 0;" class="edit-attribute-set">
            <?php echo $this->getSetFormHtml() ?>
        </td>
        <td width="320" style="border-right:1px solid #ddd; padding:0 23px 23px 23px;">
            <div class="content-header skip-header">
            <table cellspacing="0">
                    <tbody>
                        <tr>
                            <td><h3><?php echo Mage::helper('catalog')->__('Groups') ?></h3></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <?php if (!$this->getIsReadOnly()): ?>
                <p><?php echo $this->getAddGroupButton() ?>&nbsp;<?php echo $this->getDeleteGroupButton() ?></p>
                <p class="note-block"><?php echo Mage::helper('catalog')->__('Double click on a group to rename it') ?></p>
            <?php endif; ?>

            <?php echo $this->getSetsFilterHtml() ?>
            <?php echo $this->getGroupTreeHtml() ?>
        </td>
        <td style="padding:0 0 23px 23px;">
            <div class="content-header skip-header">
                <table cellspacing="0">
                    <tbody>
                        <tr>
                            <td><h3><?php echo Mage::helper('catalog')->__('Unassigned Attributes') ?></h3></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div id="tree-div2" style="height:400px; margin-top:5px;overflow:auto"></div>
            <script type="text/javascript">
            //<![CDATA[
            var allowDragAndDrop = <?php echo ($this->getIsReadOnly() ? 'false' : 'true'); ?>;
            var canEditGroups = <?php echo ($this->getIsReadOnly() ? 'false' : 'true'); ?>;

            var TreePanels = function() {
                // shorthand
                var Tree = Ext.tree;

                return {
                    init : function(){
                        // yui-ext tree

                        var tree = new Ext.tree.TreePanel('tree-div1', {
                            animate:false,
                            loader: false,
                            enableDD:allowDragAndDrop,
                            containerScroll: true,
                            rootVisible: false
                        });

                        // set the root node
                        this.root = new Ext.tree.TreeNode({
                            text: 'ROOT',
                            allowDrug:false,
                            allowDrop:true,
                            id:'1'
                        });

                        tree.setRootNode(this.root);
                        buildCategoryTree(this.root, <?php echo $this->getGroupTreeJson() ?>);
                        // render the tree
                        tree.render();
                        this.root.expand(false, false);
                        tree.expandAll();

                        this.ge = new Ext.tree.TreeEditor(tree, {
                            allowBlank:false,
                            blankText:'<?php echo Mage::helper('catalog')->__('A name is required') ?>',
                            selectOnFocus:true,
                            cls:'folder'
                        });

                        this.root.addListener('beforeinsert', editSet.leftBeforeInsert);
                        this.root.addListener('beforeappend', editSet.leftBeforeInsert);

                        //this.ge.addListener('beforerender', editSet.editGroup);
                        this.ge.addListener('beforeshow', editSet.editGroup);
                        this.ge.addListener('beforecomplete', editSet.beforeRenameGroup);
                        //this.ge.addListener('startedit', editSet.editGroup);

                        //-------------------------------------------------------------

                        var tree2 = new Ext.tree.TreePanel('tree-div2', {
                            animate:false,
                            loader: false,
                            enableDD:allowDragAndDrop,
                            containerScroll: true,
                            rootVisible: false,
                            lines:false
                        });

                        // set the root node
                        this.root2 = new Ext.tree.TreeNode({
                            text: 'ROOT',
                            draggable:false,
                            id:'free'
                        });
                        tree2.setRootNode(this.root2);
                        buildCategoryTree(this.root2, <?php echo $this->getAttributeTreeJson() ?>);

                        this.root2.addListener('beforeinsert', editSet.rightBeforeInsert);
                        this.root2.addListener('beforeappend', editSet.rightBeforeAppend);

                        this.root2.addListener('append', editSet.rightAppend);
                        this.root2.addListener('remove', editSet.rightRemove);
                        // render the tree
                        tree2.render();
                        this.root2.expand(false, false);
                        tree2.expandAll();
                    },

                    rebuildTrees : function(){
                        editSet.req.attributes = new Array();
                        rootNode = TreePanels.root;
                        var gIterator = 0;
                        for( i in rootNode.childNodes ) {
                            if(rootNode.childNodes[i].id) {
                                var group = rootNode.childNodes[i];
                                editSet.req.groups[gIterator] = new Array(group.id, group.attributes.text.strip(), (gIterator+1));
                                var iterator = 0
                                for( j in group.childNodes ) {
                                    iterator ++;
                                    if( group.childNodes[j].id > 0 ) {
                                        editSet.req.attributes[group.childNodes[j].id] = new Array(group.childNodes[j].id, group.id, iterator, group.childNodes[j].attributes.entity_id);
                                    }
                                }
                                iterator = 0;
                            }
                            gIterator ++;
                        }

                        editSet.req.not_attributes = new Array();
                        rootNode = TreePanels.root2;

                        var iterator = 0;
                        for( i in rootNode.childNodes ) {
                            if(rootNode.childNodes[i].id) {
                                if( rootNode.childNodes[i].id > 0 ) {
                                    editSet.req.not_attributes[iterator] = rootNode.childNodes[i].attributes.entity_id;
                                }
                                iterator ++;
                            }
                        }
                    }
                };
            }();

            function buildCategoryTree(parent, config){
                if (!config) return null;
                if (parent && config && config.length){
                    for (var i = 0; i < config.length; i++) {
                        var node = new Ext.tree.TreeNode(config[i]);
                        parent.appendChild(node);
                        node.addListener('click', editSet.register);
                        node.addListener('beforemove', editSet.groupBeforeMove);
                        node.addListener('beforeinsert', editSet.groupBeforeInsert);
                        node.addListener('beforeappend', editSet.groupBeforeInsert);
                        if( config[i].children ) {
                            for( j in config[i].children ) {
                                if(config[i].children[j].id) {
                                    newNode = new Ext.tree.TreeNode(config[i].children[j]);
                                    node.appendChild(newNode);
                                    newNode.addListener('click', editSet.unregister);
                                }
                            }
                        }
                    }
                }
            }

            var editSet = function() {
                return {
                    register : function(node) {
                        editSet.currentNode = node;
                    },

                    unregister : function() {
                        editSet.currentNode = false;
                    },

                    submit : function() {
                        if( TreePanels.root.firstChild == TreePanels.root.lastChild ) {
                            return;
                        }

                        if( editSet.SystemNodesExists(editSet.currentNode) ) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This group contains system attributes. Please move system attributes to another group and try again.')) ?>');
                            return;
                        }

                        if (editSet.ConfigurableNodeExists(editSet.currentNode)) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This group contains attributes, used in configurable products. Please move these attributes to another group and try again.')) ?>');
                            return;
                        }

                        if( editSet.currentNode && editSet.currentNode.attributes.cls == 'folder' ) {
                            TreePanels.root.removeChild(editSet.currentNode);
                            for( i in editSet.currentNode.childNodes ) {
                                if( editSet.currentNode.childNodes[i].id ) {
                                    child = editSet.currentNode.childNodes[i];
                                    newNode = new Ext.tree.TreeNode(child.attributes);

                                    if( child.attributes.is_user_defined == 1 ) {
                                        TreePanels.root2.appendChild(newNode);
                                    }
                                }
                            }
                            editSet.req.removeGroups[editSet.currentNode.id] = editSet.currentNode.id;
                            editSet.currentNode = false;
                        }
                    },

                    SystemNodesExists : function(currentNode) {
                        for( i in currentNode.childNodes ) {
                            if( currentNode.childNodes[i].id ) {
                                child = editSet.currentNode.childNodes[i];
                                if( child.attributes.is_user_defined != 1 ) {
                                    return true;
                                }
                            }
                        }
                    },

                    ConfigurableNodeExists : function(currentNode) {
                        for (var i in currentNode.childNodes ) {
                            if (currentNode.childNodes[i].id) {
                                child = editSet.currentNode.childNodes[i];
                                if (child.attributes.is_configurable) {
                                    return true;
                                }
                            }
                        }
                        return false;
                    },

                    rightAppend : function(node) {
                        return;
                    },

                    addGroup : function() {
                        var group_name = prompt("<?php echo Mage::helper('catalog')->__('Please enter a new group name') ?>","");
                        group_name = group_name.strip();
                        if( group_name == '' ) {
                            this.addGroup();
                        } else if( group_name != false && group_name != null && group_name != '' ) {

                            if (!editSet.validateGroupName(group_name, 0)) {
                                return;
                            }

                            var newNode = new Ext.tree.TreeNode({
                                    text : group_name.escapeHTML(),
                                    cls : 'folder',
                                    allowDrop : true,
                                    allowDrag : true
                                });
                            TreePanels.root.appendChild(newNode);
                            newNode.addListener('beforemove', editSet.groupBeforeMove);
                            newNode.addListener('beforeinsert', editSet.groupBeforeInsert);
                            newNode.addListener('beforeappend', editSet.groupBeforeInsert);
                            newNode.addListener('click', editSet.register);
                        }
                    },

                    editGroup : function(obj) {
                        if( obj.editNode.attributes.cls != 'folder' || !canEditGroups) {
                             TreePanels.ge.cancelEdit();
                             return false;
                        }
                    },

                    beforeRenameGroup : function(obj, after, before) {
                        return editSet.validateGroupName(after, obj.editNode.id);
                    },

                    validateGroupName : function(name, exceptNodeId) {
                        name = name.strip();
                        if (name === '') {
                            return false;
                        }
                        for (var i=0; i < TreePanels.root.childNodes.length; i++) {
                            if (TreePanels.root.childNodes[i].text.toLowerCase() == name.toLowerCase() && TreePanels.root.childNodes[i].id != exceptNodeId) {
                                errorText = "<?php echo Mage::helper('catalog')->__('Attribute group with the \"/name/\" name already exists') ?>";
                                alert(errorText.replace("/name/",name));
                                return false;
                            }
                        }
                        return true;
                    },

                    save : function() {
                        $('messages').update();
                        TreePanels.rebuildTrees();
                        var _validator = new Validation('set_prop_form', {onSubmit:false});
                        if( !_validator.validate() ) {
                            return;
                        }
                        editSet.req.attribute_set_name = $('attribute_set_name').value;
                        if (!editSet.req.form_key) {
                            editSet.req.form_key = FORM_KEY;
                        }
                        var req = {data : Ext.util.JSON.encode(editSet.req)};
                        var con = new Ext.lib.Ajax.request('POST', '<?php echo $this->getMoveUrl() ?>', {success:editSet.success,failure:editSet.failure}, req);
                    },

                    success : function(o) {
                        var response = Ext.util.JSON.decode(o.responseText);
                        if( response.error ) {
                            $('messages').update(response.message);
                        } else if( response.ajaxExpired && response.ajaxRedirect ){
                            setLocation(response.ajaxRedirect);
                        } else if( response.url ){
                            setLocation(response.url);
                        } else if( response.message ) {
                            $('messages').update(response.message);
                        }
                    },

                    failure : function(o) {
                        alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('Unable to complete this request.')) ?>');
                    },

                    groupBeforeMove : function(tree, nodeThis, oldParent, newParent) {
                        if( newParent.attributes.cls == 'folder' && nodeThis.attributes.cls == 'folder' ) {
                            return false;
                        }

                        if( newParent == TreePanels.root && nodeThis.attributes.cls != 'folder' ) {
                            return false;
                        }
                    },

                    rightBeforeAppend : function(tree, nodeThis, node, newParent) {
                        if (node.attributes.is_user_defined == 0) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('You cannot remove system attribute from this set.')) ?>');
                            return false;
                        }
                        else if (node.attributes.is_configurable == 1) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This attribute is used in configurable products. You cannot remove it from the attribute set.')) ?>');
                            return false;
                        }
                        else {
                            return true;
                        }
                    },

                    rightBeforeInsert : function(tree, nodeThis, node, newParent) {
                        var empty = TreePanels.root2.findChild('id', 'empty');
                        if( empty ) {
                            return false;
                        }

                        if (node.attributes.is_user_defined == 0) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('You cannot remove system attribute from this set.')) ?>');
                            return false;
                        }
                        else if (node.attributes.is_configurable == 1) {
                            alert('<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This attribute is used in configurable products. You cannot remove it from the attribute set.')) ?>');
                            return false;
                        }
                        else {
                            return true;
                        }
                    },

                    groupBeforeInsert : function(tree, nodeThis, node, newParent) {
                        if( node.allowChildren ) {
                            return false;
                        }
                    },

                    rightAppend : function(tree, nodeThis, node) {
                        var empty = TreePanels.root2.findChild('id', 'empty');
                        if( empty && node.id != 'empty' ) {
                            TreePanels.root2.removeChild(empty);
                        }
                    },

                    rightRemove : function(tree, nodeThis, node) {
                        if( nodeThis.firstChild == null && node.id != 'empty' ) {
                            var newNode = new Ext.tree.TreeNode({
                                    text : '<?php echo Mage::helper('catalog')->__('Empty') ?>',
                                    id : 'empty',
                                    cls : 'folder',
                                    is_user_defined : 1,
                                    allowDrop : false,
                                    allowDrag : false
                                });
                            TreePanels.root2.appendChild(newNode);
                        }
                    },

                    leftBeforeInsert : function(tree, nodeThis, node, newParent) {
                        if( node.allowChildren == false ) {
                            return false;
                        }
                    }
                }
            }();

            function initVars() {
                editSet.req = {};
                editSet.req.attributes = false;
                editSet.req.groups = new Array();
                editSet.req.not_attributes = false;
                editSet.req.attribute_set_name = false;
                editSet.req.removeGroups = new Array();
            }

            initVars();
            Ext.EventManager.onDocumentReady(TreePanels.init, TreePanels, true);
            //]]>
            </script>
        </td>
    </tr>
</table>
