if (!Array.prototype.indexOf){  
	Array.prototype.indexOf = function(elt /*, from*/){  
     var len = this.length >>> 0;  
   
     var from = Number(arguments[1]) || 0;  
     from = (from < 0)  
          ? Math.ceil(from)  
          : Math.floor(from);  
     if (from < 0)  
       from += len;  
   
     for (; from < len; from++)  
     {  
       if (from in this &&  
           this[from] === elt)  
         return from;  
     }  
     return -1;  
   };  
}

function Configurable(config) {

    this.config     = config;
    this.taxConfig  = this.config.taxConfig;
    this.settings   = $('.super-attribute-select');
    this.state      = {};
    //this.priceTemplate = new Template(this.config.template);
    this.prices     = config.prices;

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

    this.clearSelect = function(element) {
        /*
        for (var i=element.options.length-1; i>=0; i--){
            element.remove(i);
        }
        */
       $(element).empty();
    };

    this.getOptionLabel = function(option, price) {
        var price = parseFloat(price);
        if (this.taxConfig.includeTax) {
            var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
            var excl = price - tax;
            var incl = excl*(1+(this.taxConfig.currentTax/100));
        } else {
            var tax = price * (this.taxConfig.currentTax / 100);
            var excl = price;
            var incl = excl + tax;
        }

        if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
            price = incl;
        } else {
            price = excl;
        }

        var str = option.label;
        if(price){
            if (this.taxConfig.showBothPrices) {
                str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
            } else {
                str+= ' ' + this.formatPrice(price, true);
            }
        }
        return str;
    };

    this.reloadOptionLabels = function(element) {

        var selectedPrice;

        var config = $('#' + $(element).attr('id') + ' > option:selected').get(0).config;

        if (config) {
            selectedPrice = parseFloat(config.price)
        } else {
            selectedPrice = 0;
        }

        root = this;

        $('#' + $(element).attr('id') + ' > option').each(function() {
            if (this.config) {
                $(this).text(root.getOptionLabel(root.config, root.config.price - selectedPrice));
            }
        })
    };

    this.fillSelect = function(element) {
        var attributeId = $(element).attr('id').replace(/[a-z]*/, '');
        var options = this.getAttributeOptions(attributeId);
        this.clearSelect(element);

		  choice = new Option(this.config.chooseText, '');
		  $(choice).text(this.config.chooseText);
        $(choice).appendTo(element);

        var prevConfig = false;

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

        if (options) {
            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 = $.extend([], options[i].products);
                }

                if (allowedProducts.length > 0) {
                    options[i].allowedProducts = allowedProducts;
                    option = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
                    option.config = options[i];
						  $(option).text(this.getOptionLabel(options[i], options[i].price));
                    $(option).appendTo(element);

                }
            }
        }
    };

    this.configure = function(event) {
        this.configureElement(event.target);
    };

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

    this.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;
                }
            }
        }
    };

    root = this;
	
	 // iterate through select tags, and bind change event to root.configue
    this.settings.each(function() {
        $(this).change(function(event) {
            root.configure(event);
        })
    });


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

    // 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]).attr('disabled', 'disabled');
        }
        this.settings[i].childSettings = $.extend([], childSettings);
        this.settings[i].prevSetting   = prevSetting;
        this.settings[i].nextSetting   = nextSetting;
        childSettings.push(this.settings[i]);
    }
}