/**
 * OpenMage
 *
 * 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 at https://opensource.org/license/afl-3-0-php
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
 * @copyright   Copyright (c) 2022-2024 The OpenMage Contributors (https://www.openmage.org)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

var Product = {};

Product.Gallery = Class.create();
Product.Gallery.prototype = {
    images: [],
    file2id: {
        'no_selection': 0
    },
    idIncrement: 1,
    containerId: '',
    container: null,
    imageTypes: {},
    initialize: function (containerId, imageTypes) {
        this.containerId = containerId, this.container = $(this.containerId);
        this.imageTypes = imageTypes;

        document.on('uploader:fileSuccess', function (event) {
            var memo = event.memo;
            if (memo && this._checkCurrentContainer(memo.containerId)) {
                this.handleUploadComplete([{response: memo.response}]);
            }
        }.bind(this));

        this.images = this.getElement('save').value.evalJSON();
        this.imagesValues = this.getElement('save_image').value.evalJSON();
        this.template = new Template('<tr id="__id__" class="preview">' + this
            .getElement('template').innerHTML + '</tr>', new RegExp(
            '(^|.|\\r|\\n)(__([a-zA-Z0-9_]+)__)', ''));
        this.fixParentTable();
        this.updateImages();
        varienGlobalEvents.attachEventHandler('moveTab', this.onImageTabMove
            .bind(this));
    },
    _checkCurrentContainer: function (child) {
        return $(this.containerId).down('#' + child);
    },
    onImageTabMove: function (event) {
        var imagesTab = false;
        this.container.ancestors().each(function (parentItem) {
            if (parentItem.tabObject) {
                imagesTab = parentItem.tabObject;
                throw $break;
            }
        }.bind(this));

        if (imagesTab && event.tab && event.tab.name && imagesTab.name == event.tab.name) {
            this.container.select('input[type="radio"]').each(function (radio) {
                radio.observe('change', this.onChangeRadio);
            }.bind(this));
            this.updateImages();
        }

    },
    fixParentTable: function () {
        this.container.ancestors().each(function (parentItem) {
            if (parentItem.tagName.toLowerCase() == 'td') {
                parentItem.style.width = '100%';
            }
            if (parentItem.tagName.toLowerCase() == 'table') {
                parentItem.style.width = '100%';
                throw $break;
            }
        });
    },
    getElement: function (name) {
        return $(this.containerId + '_' + name);
    },
    showUploader: function () {
        this.getElement('add_images_button').hide();
        this.getElement('uploader').show();
    },
    handleUploadComplete: function (files) {
        files.each(function (item) {
            if (!item.response.isJSON()) {
                try {
                    console.log(item.response);
                } catch (e2) {
                    alert(item.response);
                }
                return;
            }
            var response = item.response.evalJSON();
            if (response.error) {
                return;
            }
            var newImage = {};
            newImage.url = response.url;
            newImage.file = response.file;
            newImage.label = '';
            newImage.position = this.getNextPosition();
            newImage.disabled = 0;
            newImage.removed = 0;
            this.images.push(newImage);
        }.bind(this));
        this.container.setHasChanges();
        this.updateImages();
    },
    updateImages: function () {
        this.getElement('save').value = Object.toJSON(this.images);
        $H(this.imageTypes).each(function (pair) {
            this.getFileElement('no_selection', 'cell-' + pair.key + ' input').checked = true;
        }.bind(this));
        this.images.each(function (row) {
            if (!$(this.prepareId(row.file))) {
                this.createImageRow(row);
            }
            this.updateVisualisation(row.file);
        }.bind(this));
        this.updateUseDefault(false);
    },
    onChangeRadio: function (evt) {
        var element = Event.element(evt);
        element.setHasChanges();
    },
    createImageRow: function (image) {
        var vars = Object.clone(image);
        vars.id = this.prepareId(image.file);
        var html = this.template.evaluate(vars);
        Element.insert(this.getElement('list'), {
            bottom: html
        });

        $(vars.id).select('input[type="radio"]').each(function (radio) {
            radio.observe('change', this.onChangeRadio);
        }.bind(this));
    },
    prepareId: function (file) {
        if (typeof this.file2id[file] == 'undefined') {
            this.file2id[file] = this.idIncrement++;
        }
        return this.containerId + '-image-' + this.file2id[file];
    },
    getNextPosition: function () {
        var maxPosition = 0;
        this.images.each(function (item) {
            if (parseInt(item.position) > maxPosition) {
                maxPosition = parseInt(item.position);
            }
        });
        return maxPosition + 1;
    },
    updateImage: function (file) {
        var index = this.getIndexByFile(file);

        var use_default_label = document.getElementById("use_default_label");
        if (use_default_label && use_default_label.checked) {
            this.images[index].label = null;
            this.images[index].label_use_default = true;
        } else {
            this.images[index].label = this.getFileElement(file, 'cell-label input').value;
            this.images[index].label_use_default = false;
        }

        var use_default_position = document.getElementById("use_default_position");
        if (use_default_position && use_default_position.checked) {
            this.images[index].position = null;
            this.images[index].position_use_default = true;
        } else {
            this.images[index].position = this.getFileElement(file, 'cell-position input').value;
            this.images[index].position_use_default = false;
        }

        this.images[index].removed = (this.getFileElement(file, 'cell-remove input').checked ? 1 : 0);
        this.images[index].disabled = (this.getFileElement(file, 'cell-disable input').checked ? 1 : 0);
        this.getElement('save').value = Object.toJSON(this.images);
        this.updateState(file);
        this.container.setHasChanges();
    },
    loadImage: function (file) {
        var image = this.getImageByFile(file);
        this.getFileElement(file, 'cell-image img').src = image.url;
        this.getFileElement(file, 'cell-image img').show();
        this.getFileElement(file, 'cell-image .place-holder').hide();
    },
    setProductImages: function (file) {
        $H(this.imageTypes)
            .each(
                function (pair) {
                    if (this.getFileElement(file,
                        'cell-' + pair.key + ' input').checked) {
                        this.imagesValues[pair.key] = (file == 'no_selection' ? null
                            : file);
                    }
                }.bind(this));

        this.getElement('save_image').value = Object.toJSON($H(this.imagesValues));
    },
    updateVisualisation: function (file) {
        var image = this.getImageByFile(file);

        var use_default_label = document.getElementById("use_default_label");
        if(use_default_label && use_default_label.checked) {
            this.getFileElement(file, 'cell-label input').value = image.label_default;
        } else {
            this.getFileElement(file, 'cell-label input').value = image.label;
        }

        var use_default_position = document.getElementById("use_default_position");
        if(use_default_position && use_default_position.checked) {
            this.getFileElement(file, 'cell-position input').value = image.position_default;
        } else {
            this.getFileElement(file, 'cell-position input').value = image.position;
        }

        this.getFileElement(file, 'cell-remove input').checked = (image.removed == 1);
        this.getFileElement(file, 'cell-disable input').checked = (image.disabled == 1);
        $H(this.imageTypes).each(function (pair) {
            if (this.imagesValues[pair.key] == file) {
                this.getFileElement(file, 'cell-' + pair.key + ' input').checked = true;
            }
        }.bind(this));
        this.updateState(file);
    },
    updateState: function (file) {
        // deprecated
    },
    getFileElement: function (file, element) {
        var selector = '#' + this.prepareId(file) + ' .' + element;
        var elems = document.querySelectorAll(selector);
        if (!elems[0]) {
            try {
                console.log(selector);
            } catch (e2) {
                alert(selector);
            }
        }

        return elems[0];
    },
    getImageByFile: function (file) {
        if (this.getIndexByFile(file) === null) {
            return false;
        }

        return this.images[this.getIndexByFile(file)];
    },
    getIndexByFile: function (file) {
        var index;
        this.images.each(function (item, i) {
            if (item.file == file) {
                index = i;
            }
        });
        return index;
    },
    updateUseDefault: function (el) {
        var inputs = document.querySelectorAll('#' + this.containerId + '_default td input');
        for (var i=0; i<inputs.length; i++) {
            var input = inputs[i];
            var radios = document.querySelectorAll('#' + this.containerId + '_list .preview .cell-' + input.value + ' input');
            for (var j=0; j<radios.length; j++) {
                var radio = radios[j];
                radio.disabled = input.checked;
            }
        }

        if (typeof el == "object" && el.id) {
            this.images.each(function (row) {
                this.updateImage(row.file);
            }.bind(this));
        }

        if (arguments.length == 0) {
            this.container.setHasChanges();
        }
    },
    handleUploadProgress: function (file) {
    },
    handleUploadError: function (fileId) {
    }
};

Product.AttributesBridge = {
    tabsObject: false,
    bindTabs2Attributes: {},
    bind: function (tabId, attributesObject) {
        this.bindTabs2Attributes[tabId] = attributesObject;
    },
    getAttributes: function (tabId) {
        return this.bindTabs2Attributes[tabId];
    },
    setTabsObject: function (tabs) {
        this.tabsObject = tabs;
    },
    getTabsObject: function () {
        return this.tabsObject;
    },
    addAttributeRow: function (data) {
        $H(data).each(function (item) {
            if (this.getTabsObject().activeTab.name != item.key) {
                this.getTabsObject().showTabContent($(item.key));
            }
            this.getAttributes(item.key).addRow(item.value);
        }.bind(this));
    }
};

Product.Attributes = Class.create();
Product.Attributes.prototype = {
    config: {},
    containerId: null,
    initialize: function (containerId) {
        this.containerId = containerId;
    },
    setConfig: function (config) {
        this.config = config;
        Product.AttributesBridge.bind(this.getConfig().tab_id, this);
    },
    getConfig: function () {
        return this.config;
    },
    create: function () {
        var win = window.open(this.getConfig().url, 'new_attribute',
            'width=900,height=600,resizable=1,scrollbars=1');
        win.focus();
    },
    addRow: function (html) {
        var attributesContainer = $$('#group_fields' + this.getConfig().group_id + ' .form-list tbody')[0];
        Element.insert(attributesContainer, {
            bottom: html
        });

        var childs = attributesContainer.childElements();
        var element = childs[childs.size() - 1].select('input', 'select',
            'textarea')[0];
        if (element) {
            window.scrollTo(0, Position.cumulativeOffset(element)[1]
                + element.offsetHeight);
        }
    }
};

Product.Configurable = Class.create();
Product.Configurable.prototype = {
    initialize: function (attributes, links, idPrefix, grid, readonly) {
        this.templatesSyntax = new RegExp('(^|.|\\r|\\n)(\'{{\\s*(\\w+)\\s*}}\')', "");
        this.attributes = attributes; // Attributes
        this.idPrefix = idPrefix; // Container id prefix
        this.links = $H(links); // Associated products
        this.newProducts = []; // For product that's created through Create
        // Empty and Copy from Configurable
        this.readonly = readonly;

        /* Generation templates */
        this.addAttributeTemplate = new Template(
            $(idPrefix + 'attribute_template').innerHTML.replace(/__id__/g,
            "'{{html_id}}'").replace(/ template no-display/g, ''),
            this.templatesSyntax);
        this.addValueTemplate = new Template(
            $(idPrefix + 'value_template').innerHTML.replace(/__id__/g,
            "'{{html_id}}'").replace(/ template no-display/g, ''),
            this.templatesSyntax);
        this.pricingValueTemplate = new Template($(idPrefix + 'simple_pricing').innerHTML, this.templatesSyntax);
        this.pricingValueViewTemplate = new Template($(idPrefix + 'simple_pricing_view').innerHTML, this.templatesSyntax);

        this.container = $(idPrefix + 'attributes');

        /* Listeners */
        this.onLabelUpdate = this.updateLabel.bindAsEventListener(this); // Update
        // attribute
        // label
        this.onValuePriceUpdate = this.updateValuePrice
            .bindAsEventListener(this); // Update pricing value
        this.onValueTypeUpdate = this.updateValueType.bindAsEventListener(this); // Update
        // pricing
        // type
        this.onValueDefaultUpdate = this.updateValueUseDefault
            .bindAsEventListener(this);

        /* Grid initialization and attributes initialization */
        this.createAttributes(); // Creation of default attributes

        this.grid = grid;
        this.grid.rowClickCallback = this.rowClick.bind(this);
        this.grid.initRowCallback = this.rowInit.bind(this);
        this.grid.checkboxCheckCallback = this.registerProduct.bind(this); // Associate/Unassociate
        // simple
        // product

        this.grid.rows.each(function (row) {
            this.rowInit(this.grid, row);
        }.bind(this));
    },
    createAttributes: function () {
        this.attributes.each(function (attribute, index) {
            var li = $(document.createElement('LI'));
            li.className = 'attribute';
            li.id = this.idPrefix + '_attribute_' + index;
            attribute.html_id = li.id;
            if (attribute && attribute.label && attribute.label.blank()) {
                attribute.label = '&nbsp;';
            }
            var label_readonly = '';
            var use_default_checked = '';
            if (attribute.use_default == '1' || attribute.id == null) {
                use_default_checked = ' checked="checked"';
                label_readonly = ' readonly="readonly"';
            }

            var template = this.addAttributeTemplate.evaluate(attribute);
            template = template.replace(new RegExp(' readonly="label"', 'ig'), label_readonly);
            template = template.replace(new RegExp(' checked="use_default"', 'ig'), use_default_checked);
            li.update(template);
            li.attributeObject = attribute;

            this.container.appendChild(li);
            li.attributeValues = li.down('.attribute-values');

            if (attribute.values) {
                attribute.values.each(function (value) {
                    this.createValueRow(li, value); // Add pricing values
                }.bind(this));
            }

            /* Observe label change */
            Event.observe(li.down('.attribute-label'), 'change', this.onLabelUpdate);
            Event.observe(li.down('.attribute-label'), 'keyup', this.onLabelUpdate);
            Event.observe(li.down('.attribute-use-default-label'), 'change', this.onLabelUpdate);
        }.bind(this));
        if (!this.readonly) {
            // Creation of sortable for attributes sorting
            Sortable.create(this.container, {
                handle: 'attribute-name-container',
                onUpdate: this.updatePositions.bind(this)
            });
        }
        this.updateSaveInput();
    },

    updateLabel: function (event) {
        var li = Event.findElement(event, 'LI');
        var labelEl = li.down('.attribute-label');
        var defEl = li.down('.attribute-use-default-label');

        li.attributeObject.label = labelEl.value;
        if (defEl.checked) {
            labelEl.readOnly = true;
            li.attributeObject.use_default = 1;
        } else {
            labelEl.readOnly = false;
            li.attributeObject.use_default = 0;
        }

        this.updateSaveInput();
    },
    updatePositions: function (param) {
        this.container.childElements().each(function (row, index) {
            row.attributeObject.position = index;
        });
        this.updateSaveInput();
    },
    addNewProduct: function (productId, attributes) {
        if (this.checkAttributes(attributes)) {
            this.links.set(productId, this.cloneAttributes(attributes));
        } else {
            this.newProducts.push(productId);
        }

        this.updateGrid();
        this.updateValues();
        this.grid.reload(null);
    },
    createEmptyProduct: function () {
        this.createPopup(this.createEmptyUrl);
    },
    createNewProduct: function () {
        this.createPopup(this.createNormalUrl);
    },
    createPopup: function (url) {
        if (this.win && !this.win.closed) {
            this.win.close();
        }

        this.win = window.open(url, '',
            'width=1000,height=700,resizable=1,scrollbars=1');
        this.win.focus();
    },
    registerProduct: function (grid, element, checked) {
        if (checked) {
            if (element.linkAttributes) {
                this.links.set(element.value, element.linkAttributes);
            }
        } else {
            this.links.unset(element.value);
        }
        this.updateGrid();
        this.grid.rows.each(function (row) {
            this.revalidateRow(this.grid, row);
        }.bind(this));
        this.updateValues();
    },
    updateProduct: function (productId, attributes) {
        var isAssociated = false;

        if (typeof this.links.get(productId) != 'undefined') {
            isAssociated = true;
            this.links.unset(productId);
        }

        if (isAssociated && this.checkAttributes(attributes)) {
            this.links.set(productId, this.cloneAttributes(attributes));
        } else if (isAssociated) {
            this.newProducts.push(productId);
        }

        this.updateGrid();
        this.updateValues();
        this.grid.reload(null);
    },
    cloneAttributes: function (attributes) {
        var newObj = [];
        for (var i = 0, length = attributes.length; i < length; i++) {
            newObj[i] = Object.clone(attributes[i]);
        }
        return newObj;
    },
    rowClick: function (grid, event) {
        var trElement = Event.findElement(event, 'tr');
        var isInput = Event.element(event).tagName.toUpperCase() == 'INPUT';

        if ($(Event.findElement(event, 'td')).down('a')) {
            return;
        }

        if (trElement) {
            var checkbox = $(trElement).down('input');
            if (checkbox && !checkbox.disabled) {
                var checked = isInput ? checkbox.checked : !checkbox.checked;
                grid.setCheckboxChecked(checkbox, checked);
            }
        }
    },
    rowInit: function (grid, row) {
        var checkbox = $(row).down('.checkbox');
        var input = $(row).down('.value-json');
        if (checkbox && input) {
            checkbox.linkAttributes = input.value.evalJSON();
            if (!checkbox.checked) {
                if (!this.checkAttributes(checkbox.linkAttributes)) {
                    $(row).addClassName('invalid');
                    checkbox.disable();
                } else {
                    $(row).removeClassName('invalid');
                    checkbox.enable();
                }
            }
        }
    },
    revalidateRow: function (grid, row) {
        var checkbox = $(row).down('.checkbox');
        if (checkbox) {
            if (!checkbox.checked) {
                if (!this.checkAttributes(checkbox.linkAttributes)) {
                    $(row).addClassName('invalid');
                    checkbox.disable();
                } else {
                    $(row).removeClassName('invalid');
                    checkbox.enable();
                }
            }
        }
    },
    checkAttributes: function (attributes) {
        var result = true;
        this.links
            .each(function (pair) {
                var fail = false;
                for (var i = 0; i < pair.value.length && !fail; i++) {
                    for (var j = 0; j < attributes.length && !fail; j++) {
                        if (pair.value[i].attribute_id == attributes[j].attribute_id
                            && pair.value[i].value_index != attributes[j].value_index) {
                            fail = true;
                        }
                    }
                }
                if (!fail) {
                    result = false;
                }
            });
        return result;
    },
    updateGrid: function () {
        this.grid.reloadParams = {
            'products[]': this.links.keys().size() ? this.links.keys() : [0],
            'new_products[]': this.newProducts
        };
    },
    updateValues: function () {
        var uniqueAttributeValues = $H({});
        /* Collect unique attributes */
        this.links.each(function (pair) {
            for (var i = 0, length = pair.value.length; i < length; i++) {
                var attribute = pair.value[i];
                if (uniqueAttributeValues.keys()
                    .indexOf(attribute.attribute_id) == -1) {
                    uniqueAttributeValues.set(attribute.attribute_id, $H({}));
                }
                uniqueAttributeValues.get(attribute.attribute_id).set(
                    attribute.value_index, attribute);
            }
        });
        /* Updating attributes value container */
        this.container
            .childElements()
            .each(
                function (row) {
                    var attribute = row.attributeObject;
                    for (var i = 0, length = attribute.values.length; i < length; i++) {
                        if (uniqueAttributeValues.keys().indexOf(
                                attribute.attribute_id) == -1
                            || uniqueAttributeValues
                                .get(attribute.attribute_id)
                                .keys()
                                .indexOf(
                                    attribute.values[i].value_index) == -1) {
                            row.attributeValues
                                .childElements()
                                .each(
                                    function (elem) {
                                        if (elem.valueObject.value_index == attribute.values[i].value_index) {
                                            elem.remove();
                                        }
                                    });
                            attribute.values[i] = undefined;

                        } else {
                            uniqueAttributeValues.get(
                                attribute.attribute_id).unset(
                                attribute.values[i].value_index);
                        }
                    }
                    attribute.values = attribute.values.compact();
                    if (uniqueAttributeValues
                        .get(attribute.attribute_id)) {
                        uniqueAttributeValues.get(
                            attribute.attribute_id).each(
                            function (pair) {
                                attribute.values.push(pair.value);
                                this
                                    .createValueRow(row,
                                        pair.value);
                            }.bind(this));
                    }
                }.bind(this));
        this.updateSaveInput();
        this.updateSimpleForm();
    },
    createValueRow: function (container, value) {
        var templateVariables = $H({});
        if (!this.valueAutoIndex) {
            this.valueAutoIndex = 1;
        }
        templateVariables.set('html_id', container.id + '_'
            + this.valueAutoIndex);
        templateVariables.update(value);
        var pricingValue = parseFloat(templateVariables.get('pricing_value'));
        if (!isNaN(pricingValue)) {
            templateVariables.set('pricing_value', pricingValue);
        } else {
            templateVariables.unset('pricing_value');
        }
        this.valueAutoIndex++;

        // var li = $(Builder.node('li', {className:'attribute-value'}));
        var li = $(document.createElement('LI'));
        li.className = 'attribute-value';
        li.id = templateVariables.get('html_id');
        li.update(this.addValueTemplate.evaluate(templateVariables));
        li.valueObject = value;
        if (typeof li.valueObject.is_percent == 'undefined') {
            li.valueObject.is_percent = 0;
        }

        if (typeof li.valueObject.pricing_value == 'undefined') {
            li.valueObject.pricing_value = '';
        }

        container.attributeValues.appendChild(li);

        var priceField = li.down('.attribute-price');
        var priceTypeField = li.down('.attribute-price-type');

        if (priceTypeField != undefined && priceTypeField.options != undefined) {
            if (parseInt(value.is_percent)) {
                priceTypeField.options[1].selected = !(priceTypeField.options[0].selected = false);
            } else {
                priceTypeField.options[1].selected = !(priceTypeField.options[0].selected = true);
            }
        }

        Event.observe(priceField, 'keyup', this.onValuePriceUpdate);
        Event.observe(priceField, 'change', this.onValuePriceUpdate);
        Event.observe(priceTypeField, 'change', this.onValueTypeUpdate);
        var useDefaultEl = li.down('.attribute-use-default-value');
        if (useDefaultEl) {
            if (li.valueObject.use_default_value) {
                useDefaultEl.checked = true;
                this.updateUseDefaultRow(useDefaultEl, li);
            }
            Event.observe(useDefaultEl, 'change', this.onValueDefaultUpdate);
        }
    },
    updateValuePrice: function (event) {
        var li = Event.findElement(event, 'LI');
        li.valueObject.pricing_value = (Event.element(event).value.blank() ? null
            : Event.element(event).value);
        this.updateSimpleForm();
        this.updateSaveInput();
    },
    updateValueType: function (event) {
        var li = Event.findElement(event, 'LI');
        li.valueObject.is_percent = (Event.element(event).value.blank() ? null
            : Event.element(event).value);
        this.updateSimpleForm();
        this.updateSaveInput();
    },
    updateValueUseDefault: function (event) {
        var li = Event.findElement(event, 'LI');
        var useDefaultEl = Event.element(event);
        li.valueObject.use_default_value = useDefaultEl.checked;
        this.updateUseDefaultRow(useDefaultEl, li);
    },
    updateUseDefaultRow: function (useDefaultEl, li) {
        var priceField = li.down('.attribute-price');
        var priceTypeField = li.down('.attribute-price-type');
        if (useDefaultEl.checked) {
            priceField.disabled = true;
            priceTypeField.disabled = true;
        } else {
            priceField.disabled = false;
            priceTypeField.disabled = false;
        }
        this.updateSimpleForm();
        this.updateSaveInput();
    },
    updateSaveInput: function () {
        var oldSaveAttributesValue = $(this.idPrefix + 'save_attributes').value;
        var oldSaveLinksValue = $(this.idPrefix + 'save_links').value;
        var newSaveAttributesValue = Object.toJSON(this.attributes);
        var newSaveLinksValue = Object.toJSON(this.links);
        $(this.idPrefix + 'save_attributes').value = newSaveAttributesValue;
        $(this.idPrefix + 'save_links').value = newSaveLinksValue;
        if (oldSaveAttributesValue != newSaveAttributesValue || oldSaveLinksValue != newSaveLinksValue) {
            try {
                document.getElementById('configurable_save_attributes').setHasChanges();
            } catch (e) {}
        }
    },
    initializeAdvicesForSimpleForm: function () {
        if ($(this.idPrefix + 'simple_form').advicesInited) {
            return;
        }

        $(this.idPrefix + 'simple_form').select('td.value').each(function (td) {
            var adviceContainer = $(Builder.node('div'));
            td.appendChild(adviceContainer);
            td.select('input', 'select').each(function (element) {
                element.advaiceContainer = adviceContainer;
            });
        });
        $(this.idPrefix + 'simple_form').advicesInited = true;
    },
    quickCreateNewProduct: function () {
        this.initializeAdvicesForSimpleForm();
        $(this.idPrefix + 'simple_form').removeClassName('ignore-validate');
        var validationResult = $(this.idPrefix + 'simple_form').select('input', 'select', 'textarea').collect(function (elm) {
            return Validation.validate(elm, {
                useTitle: false,
                onElementValidate: function () {
                }
            });
        }).all();
        $(this.idPrefix + 'simple_form').addClassName('ignore-validate');

        if (!validationResult) {
            return;
        }

        var params = Form.serializeElements($(this.idPrefix + 'simple_form').select('input', 'select', 'textarea'), true);
        params.form_key = FORM_KEY;
        $('messages').update();
        new Ajax.Request(this.createQuickUrl, {
            parameters: params,
            method: 'post',
            area: $(this.idPrefix + 'simple_form'),
            onComplete: this.quickCreateNewProductComplete.bind(this)
        });
    },
    quickCreateNewProductComplete: function (transport) {
        var result = transport.responseText.evalJSON();

        if (result.error) {
            if (result.error.fields) {
                $(this.idPrefix + 'simple_form').removeClassName(
                    'ignore-validate');
                $H(result.error.fields)
                    .each(function (pair) {
                        $('simple_product_' + pair.key).value = pair.value;
                        $('simple_product_' + pair.key + '_autogenerate').checked = false;
                        toggleValueElements(
                            $('simple_product_' + pair.key + '_autogenerate'),
                            $('simple_product_' + pair.key + '_autogenerate').parentNode);
                        Validation.ajaxError($('simple_product_' + pair.key), result.error.message);
                    });
                $(this.idPrefix + 'simple_form').addClassName('ignore-validate');
            } else {
                if (result.error.message) {
                    alert(result.error.message);
                } else {
                    alert(result.error);
                }
            }
            return;
        } else if (result.messages) {
            $('messages').update(result.messages);
        }

        result.attributes
            .each(function (attribute) {
                var attr = this.getAttributeById(attribute.attribute_id);
                if (!this.getValueByIndex(attr, attribute.value_index)
                    && result.pricing
                    && result.pricing[attr.attribute_code]) {

                    attribute.is_percent = result.pricing[attr.attribute_code].is_percent;
                    attribute.pricing_value = (result.pricing[attr.attribute_code].value == null ? ''
                        : result.pricing[attr.attribute_code].value);
                }
            }.bind(this));

        this.attributes.each(function (attribute) {
            if ($('simple_product_' + attribute.attribute_code)) {
                $('simple_product_' + attribute.attribute_code).value = '';
            }
        }.bind(this));

        this.links.set(result.product_id, result.attributes);
        this.updateGrid();
        this.updateValues();
        this.grid.reload();
    },
    checkCreationUniqueAttributes: function () {
        var attributes = [];
        this.attributes
            .each(function (attribute) {
                attributes.push({
                    attribute_id: attribute.attribute_id,
                    value_index: $('simple_product_' + attribute.attribute_code).value
                });
            }.bind(this));

        return this.checkAttributes(attributes);
    },
    getAttributeByCode: function (attributeCode) {
        var attribute = null;
        this.attributes.each(function (item) {
            if (item.attribute_code == attributeCode) {
                attribute = item;
                throw $break;
            }
        });
        return attribute;
    },
    getAttributeById: function (attributeId) {
        var attribute = null;
        this.attributes.each(function (item) {
            if (item.attribute_id == attributeId) {
                attribute = item;
                throw $break;
            }
        });
        return attribute;
    },
    getValueByIndex: function (attribute, valueIndex) {
        var result = null;
        attribute.values.each(function (value) {
            if (value.value_index == valueIndex) {
                result = value;
                throw $break;
            }
        });
        return result;
    },
    showPricing: function (select, attributeCode) {
        var attribute = this.getAttributeByCode(attributeCode);
        if (!attribute) {
            return;
        }

        select = $(select);
        if (select.value && !$('simple_product_' + attributeCode + '_pricing_container')) {
            Element.insert(select, {
                after: '<div class="left"></div> <div id="simple_product_' + attributeCode + '_pricing_container" class="left"></div>'
            });
            var newContainer = select.next('div');
            select.parentNode.removeChild(select);
            newContainer.appendChild(select);
            // Fix visualization bug
            $(this.idPrefix + 'simple_form').down('.form-list').style.width = '100%';
        }

        var container = $('simple_product_' + attributeCode + '_pricing_container');

        if (select.value) {
            var value = this.getValueByIndex(attribute, select.value);
            if (!value) {
                if (!container.down('.attribute-price')) {
                    if (value == null) {
                        value = {};
                    }
                    container.update(this.pricingValueTemplate.evaluate(value));
                    var priceValueField = container.down('.attribute-price');
                    var priceTypeField = container.down('.attribute-price-type');

                    priceValueField.attributeCode = attributeCode;
                    priceValueField.priceField = priceValueField;
                    priceValueField.typeField = priceTypeField;

                    priceTypeField.attributeCode = attributeCode;
                    priceTypeField.priceField = priceValueField;
                    priceTypeField.typeField = priceTypeField;

                    Event.observe(priceValueField, 'change', this.updateSimplePricing.bindAsEventListener(this));
                    Event.observe(priceValueField, 'keyup', this.updateSimplePricing.bindAsEventListener(this));
                    Event.observe(priceTypeField, 'change', this.updateSimplePricing.bindAsEventListener(this));

                    $('simple_product_' + attributeCode + '_pricing_value').value = null;
                    $('simple_product_' + attributeCode + '_pricing_type').value = null;
                }
            } else if (!isNaN(parseFloat(value.pricing_value))) {
                container.update(this.pricingValueViewTemplate.evaluate({
                    'value': (parseFloat(value.pricing_value) > 0 ? '+' : '')
                        + parseFloat(value.pricing_value)
                        + (parseInt(value.is_percent) > 0 ? '%' : '')
                }));
                $('simple_product_' + attributeCode + '_pricing_value').value = value.pricing_value;
                $('simple_product_' + attributeCode + '_pricing_type').value = value.is_percent;
            } else {
                container.update('');
                $('simple_product_' + attributeCode + '_pricing_value').value = null;
                $('simple_product_' + attributeCode + '_pricing_type').value = null;
            }
        } else if (container) {
            container.update('');
            $('simple_product_' + attributeCode + '_pricing_value').value = null;
            $('simple_product_' + attributeCode + '_pricing_type').value = null;
        }
    },
    updateSimplePricing: function (evt) {
        var element = Event.element(evt);
        if (!element.priceField.value.blank()) {
            $('simple_product_' + element.attributeCode + '_pricing_value').value = element.priceField.value;
            $('simple_product_' + element.attributeCode + '_pricing_type').value = element.typeField.value;
        } else {
            $('simple_product_' + element.attributeCode + '_pricing_value').value = null;
            $('simple_product_' + element.attributeCode + '_pricing_type').value = null;
        }
    },
    updateSimpleForm: function () {
        this.attributes.each(function (attribute) {
            if ($('simple_product_' + attribute.attribute_code)) {
                this.showPricing(
                    $('simple_product_' + attribute.attribute_code),
                    attribute.attribute_code);
            }
        }.bind(this));
    },
    showNoticeMessage: function () {
        $('assign_product_warrning').show();
    }
};

var onInitDisableFieldsList = [];

function toogleFieldEditMode(toogleIdentifier, fieldContainer) {
    if ($(toogleIdentifier).checked) {
        enableFieldEditMode(fieldContainer);
    } else {
        disableFieldEditMode(fieldContainer);
    }
}

function disableFieldEditMode(fieldContainer) {
    if ($(fieldContainer)) {
        $(fieldContainer).disabled = true;
    }
    if ($(fieldContainer + '_hidden')) {
        $(fieldContainer + '_hidden').disabled = true;
    }
}

function enableFieldEditMode(fieldContainer) {
    if ($(fieldContainer)) {
        $(fieldContainer).disabled = false;
    }
    if ($(fieldContainer + '_hidden')) {
        $(fieldContainer + '_hidden').disabled = false;
    }
}

function initDisableFields(fieldContainer) {
    onInitDisableFieldsList.push(fieldContainer);
}

function onCompleteDisableInited() {
    onInitDisableFieldsList.each(function (item) {
        disableFieldEditMode(item);
    });
}

function onUrlkeyChanged(urlKey) {
    urlKey = $(urlKey);
    var hidden = urlKey.next('input[type=hidden]');
    var chbx = urlKey.next('input[type=checkbox]');
    var oldValue = chbx.value;
    chbx.disabled = (oldValue == urlKey.value);
    hidden.disabled = chbx.disabled;
}

function onCustomUseParentChanged(element) {
    var useParent = (element.value == 1) ? true : false;
    element.up(2).select('input', 'select', 'textarea').each(function (el) {
        if (element.id != el.id) {
            el.disabled = useParent;
        }
    });
    element.up(2).select('img').each(function (el) {
        if (useParent) {
            el.hide();
        } else {
            el.show();
        }
    });
}

Event.observe(window, 'load', onCompleteDisableInited);
