/**************************** CONFIGURABLE PRODUCT **************************/
define([
    'jquery',
    'mage/template',
    'mage/translate',
    'prototype'
], function (jQuery, mageTemplate) {

if (typeof Product == 'undefined') {
    window.Product = {};
}

Product.Config = Class.create();
Product.Config.prototype = {
    initialize: function (config) {
        // Magic preprocessing
        config.taxConfig = {
            showBothPrices: false,
            inclTaxTitle: jQuery.mage.__('Incl. Tax')
        };

        this.config     = config;
        this.taxConfig  = this.config.taxConfig;
        if (config.containerId) {
            this.settings   = $$('#' + config.containerId + ' ' + '.super-attribute-select');
        } else {
            this.settings   = $$('.super-attribute-select');
        }
        this.state      = new Hash();
        this.priceTemplate = mageTemplate(this.config.template);
        this.prices     = config.prices;
        this.values     = {};

        // Set default values from config
        if (config.defaultValues) {
            this.values = config.defaultValues;
        }

        // Overwrite defaults by url
        var separatorIndex = window.location.href.indexOf('#');
        if (separatorIndex != -1) {
            var paramsStr = window.location.href.substr(separatorIndex+1);
            var urlValues = paramsStr.toQueryParams();
            for (var i in urlValues) {
                this.values[i] = urlValues[i];
            }
        }

        // Overwrite defaults by inputs values if needed
        if (config.inputsInitialized) {
            this.values = {};
            this.settings.each(function (element) {
                if (element.value) {
                    var attributeId = element.id.replace(/[a-z]*/, '');
                    this.values[attributeId] = element.value;
                }
            }.bind(this));
        }

        // Put events to check select reloads
        this.settings.each(function (element) {
            Event.observe(element, 'change', this.configure.bind(this))
        }.bind(this));

        // fill state
        this.settings.each(function (element) {
            var attributeId = element.id.replace(/[a-z]*/, '');
            if (attributeId && this.config.attributes[attributeId]) {
                element.config = this.config.attributes[attributeId];
                element.attributeId = attributeId;
                this.state[attributeId] = false;
            }
        }.bind(this));

        // Init settings dropdown
        var childSettings = [];
        for (var i=this.settings.length-1; i>=0; i--) {
            var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
            var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
            if (i == 0) {
                this.fillSelect(this.settings[i])
            } else {
                this.settings[i].disabled = true;
            }
            $(this.settings[i]).childSettings = childSettings.clone();
            $(this.settings[i]).prevSetting   = prevSetting;
            $(this.settings[i]).nextSetting   = nextSetting;
            childSettings.push(this.settings[i]);
        }

        // Set values to inputs
        this.configureForValues();
        document.observe("dom:loaded", this.configureForValues.bind(this));
    },

    configureForValues: function () {
        if (this.values) {
            this.settings.each(function (element) {
                var attributeId = element.attributeId;
                element.value = (typeof(this.values[attributeId]) == 'undefined')? '' : this.values[attributeId];
                this.configureElement(element);
            }.bind(this));
        }
    },

    configure: function (event) {
        var element = Event.element(event);
        this.configureElement(element);
    },

    configureElement : function (element) {
        this.reloadOptionLabels(element);
        if (element.value) {
            this.state[element.config.id] = element.value;
            if (element.nextSetting) {
                element.nextSetting.disabled = false;
                this.fillSelect(element.nextSetting);
                this.resetChildren(element.nextSetting);
            }
        } else {
            this.resetChildren(element);
        }
        this.reloadPrice();
    },

    reloadOptionLabels: function (element) {
        var selectedPrice = 0;
        if (element.options[element.selectedIndex] && element.options[element.selectedIndex].config) {
            var option = element.options[element.selectedIndex].config;
            selectedPrice = parseFloat(this.config.optionPrices[option.allowedProducts[0]].finalPrice.amount);
        }
        element.setAttribute('price', selectedPrice);
        for (var i=0; i<element.options.length; i++) {
            if (element.options[i].config) {
                element.options[i].setAttribute('price', selectedPrice);
                element.options[i].setAttribute('summarizePrice', 0);
                element.options[i].text = this.getOptionLabel(element.options[i].config, selectedPrice);
            }
        }
    },

    resetChildren : function (element) {
        if (element.childSettings) {
            for (var i=0; i<element.childSettings.length; i++) {
                element.childSettings[i].selectedIndex = 0;
                element.childSettings[i].disabled = true;
                if (element.config) {
                    this.state[element.config.id] = false;
                }
            }
        }
    },

    fillSelect: function (element) {
        var attributeId = element.id.replace(/[a-z]*/, '');
        var options = this.getAttributeOptions(attributeId);
        this.clearSelect(element);
        element.options[0] = new Option('', '');
        element.options[0].innerHTML = this.config.chooseText;

        var prevConfig = false;
        if (element.prevSetting) {
            prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
        }

        if (options) {
            var index = 1;
            for (var i=0; i<options.length; i++) {
                var allowedProducts = [];
                if (prevConfig) {
                    for (var j=0; j<options[i].products.length; j++) {
                        if (prevConfig.config.allowedProducts
                            && prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1) {
                            allowedProducts.push(options[i].products[j]);
                        }
                    }
                } else {
                    allowedProducts = options[i].products.clone();
                }

                if (allowedProducts.size()>0) {
                    options[i].allowedProducts = allowedProducts;
                    element.options[index] = new Option(this.getOptionLabel(options[i]), options[i].id);
                    if (typeof options[i].price != 'undefined') {
                        element.options[index].setAttribute('price', options[i].price);
                    }
                    element.options[index].config = options[i];
                    index++;
                }
            }
        }
    },

    getOptionLabel: function (option) {
        return option.label;
    },

    formatPrice: function (price, showSign) {
        var str = '';
        price = parseFloat(price);
        if (showSign) {
            if (price<0) {
                str+= '-';
                price = -price;
            } else {
                str+= '+';
            }
        }

        var roundedPrice = (Math.round(price*100)/100).toString();

        if (this.prices && this.prices[roundedPrice]) {
            str+= this.prices[roundedPrice];
        } else {
            str+= this.priceTemplate({
                data: {
                    price:price.toFixed(2)
                }
            });
        }
        return str;
    },

    clearSelect: function (element) {
        for (var i=element.options.length-1; i>=0; i--) {
            element.remove(i);
        }
    },

    getAttributeOptions: function (attributeId) {
        if (this.config.attributes[attributeId]) {
            return this.config.attributes[attributeId].options;
        }
    },

    reloadPrice: function () {
        if (this.config.disablePriceReload) {
            return;
        }
        var price    = 0;
        var oldPrice = 0;
        var inclTaxPrice = 0;
        var exclTaxPrice = 0;
        for (var i=this.settings.length-1; i>=0; i--) {
            var selected = this.settings[i].options[this.settings[i].selectedIndex];
            if (selected.config) {
                price += parseFloat(selected.config.price);
                oldPrice += parseFloat(selected.config.oldPrice);
                inclTaxPrice += parseFloat(selected.config.inclTaxPrice);
                exclTaxPrice += parseFloat(selected.config.exclTaxPrice);
            }
        }

        optionsPrice.changePrice(
            'config',
            {
                'price': price,
                'oldPrice': oldPrice,
                'inclTaxPrice': inclTaxPrice,
                'exclTaxPrice': exclTaxPrice
            }
        );
        optionsPrice.reload();

        return price;

        if ($('product-price-'+this.config.productId)) {
            $('product-price-'+this.config.productId).innerHTML = price;
        }
        this.reloadOldPrice();
    },

    reloadOldPrice: function () {
        if (this.config.disablePriceReload) {
            return;
        }
        if ($('old-price-'+this.config.productId)) {
            var price = parseFloat(this.config.oldPrice);
            for (var i=this.settings.length-1; i>=0; i--) {
                var selected = this.settings[i].options[this.settings[i].selectedIndex];
                if (selected.config) {
                    price+= parseFloat(selected.config.price);
                }
            }
            if (price < 0) {
                price = 0;
            }
            price = this.formatPrice(price);

            if ($('old-price-'+this.config.productId)) {
                $('old-price-'+this.config.productId).innerHTML = price;
            }
        }
    }
};

});
