if(typeof Product=='undefined') {
    var Product = {};
}

/**************************** CONFIGURABLE PRODUCT **************************/
Product.Config = Class.create();
Product.Config.prototype = {
    initialize: function(config){
        this.config     = config;
        this.taxConfig  = this.config.taxConfig;
        this.settings   = $$('.super-attribute-select');
        this.state      = new Hash();
        this.priceTemplate = new Template(this.config.template);
        this.prices     = config.prices;
		this.ulTemplate = new Template('<ul class="clearfix attr-#{attributeId}">#{listItems}</ul>');
		this.liTemplate = new Template('<li id="option-#{attributeId}-#{optionId}" class="#{selected} #{stock}">#{optionTitle}</li>');
		

        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;
            }
			element.addClassName('display-hidden'); // Hide 'em
        }.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]);
        }

		// Get options for first setting
		var firstSettingOptions = [];
		this.settings[0].childElements().each(function(el){
			if (el.readAttribute('value')) {
				firstSettingOptions.push(el.readAttribute('value'));
			}
		});

        // try retireve options from url
        var separatorIndex = window.location.href.indexOf('#');
		var firstId = this.settings[0].id.replace(/[a-z]*/, '');
        if (separatorIndex!=-1) {
            var paramsStr = window.location.href.substr(separatorIndex+1);
            this.values = paramsStr.toQueryParams();
            this.settings.each(function(element){
                var attributeId = element.attributeId;
                element.value = this.values[attributeId];
                this.configureElement(element);
				this.doLists(element);
            }.bind(this));
		} else if (this.config.attributes[firstId]['default'] && firstSettingOptions.indexOf(this.config.attributes[firstId]['default']) !== -1) {
			this.settings[0].setValue(this.config.attributes[firstId]['default']);
			this.configureElement(this.settings[0]);
			this.doLists(this.settings[0]);
		} else {
			if (this.settings.length > 1) {
				var initValue = 0;
				// Search for Men's Med or the first option of the first attribute and select that option
				this.settings[0].childElements().each(function(el){
					if (el.innerHTML.match(/^MEN(\'S)? [DRM]/i)) {
						initValue = el.readAttribute('value');
					}
				});
				
				if (initValue === 0) initValue = this.settings[0].childElements()[1].readAttribute('value');
				this.settings[0].setValue(initValue);
			}
			
			this.configureElement(this.settings[0]);
			this.doLists(this.settings[0]);
		}
		
		if (this.settings.length > 1) {
			var elV = this.settings[0].getValue();
			if (elV) {
				var title = this.settings[0].select('[value="'+elV+'"]')[0].innerHTML;
				this.settings[0].up().previous().select('span')[0].update(title);
			}
		}
		
		
    },

    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);

				// Clear any selected label
				element.nextSetting.up().previous().select('span')[0].update();


				this.doLists(element.nextSetting);
			}
        }
        else {
            this.resetChildren(element);
        }
        this.reloadPrice();

//      Calculator.updatePrice();
    },

	doLists: function(element){
		element.siblings().invoke('remove');
		
		var aId = element.readAttribute('id').replace('attribute', '');
		var items = new Hash();
		var options, index;
		
		var allowedProducts = {};
		
		if (this.settings.length > 1) {
			if (element.prevSetting) {
		        options = this.getAttributeOptions(aId);
	            prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];

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

		                if(allowedProducts.length>0){
		                    index++;
		                }
		            }
		        }
			
			}
		} else {
			options = this.getAttributeOptions(aId);

	        if(options) {
	            index = 1;
	            for(var i=0;i<options.length;i++){
                    for(var j=0;j<options[i].products.length;j++){
                        allowedProducts[options[i].id] = options[i].products[j];
                    }

	                if(allowedProducts.length>0){
	                    index++;
	                }
	            }
	        }
		}
		
		element.childElements().each(function(option){
			var v = option.readAttribute('value');
			if (v.empty()) return;
			
			var sel = $F('attribute'+aId);
			var stk = true;
			var date;
			var t;
			
			if (allowedProducts) {
				if (allowedProducts[v]) {
					stk = prodInventory[allowedProducts[v]].inStock;
					date = prodInventory[allowedProducts[v]].available;
				}
			}
			
			this.config.attributes[aId].options.each(function(option){
				if (option.id == v) t = option.label.replace(/ - .*$/, '');
			}.bind(this));
			items.set('_'+v, this.liTemplate.evaluate({
				attributeId: aId,
				optionId: v,
				optionTitle: t,
				selected: sel && sel == v? 'selected': '',
				stock: !stk? date? 'backorder': 'stock-out': ''
			}));
		}.bind(this));
		
		element.insert({
			after: this.ulTemplate.evaluate({
				attributeId: aId,
				listItems: items.values().join("\n")
			})
		});
		
		// Set up observers
		$$('.product-options li').each(function(liEl){
			// clear existing observers
			liEl
				.stopObserving('click')
				.stopObserving('mouseover')
				.stopObserving('mouseout');
			
			var a = liEl.readAttribute('id').split('-');
			var stk, date;
			
			if (allowedProducts) {
				if (allowedProducts[a[2]]) {
					stk = prodInventory[allowedProducts[a[2]]].inStock;
					date = prodInventory[allowedProducts[a[2]]].available;
				}
			}
			
			liEl
				.observe('mouseover', function(ev){
					// get attribute title
					var date = ev.element().readAttribute('data-availability') || 'In Stock';
					var title = $('attribute'+a[1]).select('[value="'+a[2]+'"]')[0].innerHTML;
					if ($$('.product-options select').last().identify().replace('attribute', '') == a[1]) title += ' – ' + date;
					$('attribute'+a[1]).up().previous().select('span')[0].removeClassName('error').update(title);
				}.bind(this))
				.observe('mouseout', function(){
					var elV = $F('attribute'+a[1]);
					if (elV) {
						var date = $$('.attr-'+a[1]+' .selected')[0].readAttribute('data-availability') || 'In Stock';
						var title = $('attribute'+a[1]).select('[value="'+elV+'"]')[0].innerHTML;
						if ($$('.product-options select').last().identify().replace('attribute', '') == a[1]) title += ' – ' + date;
						$('attribute'+a[1]).up().previous().select('span')[0].removeClassName('error').update(title);
					} else {
						$('attribute'+a[1]).up().previous().select('span')[0].removeClassName('error').update();
					}
				}.bind(this));
			
			if ($$('html.ie7').length) {
				var x = (33 * $$('.product-options .sizes li').length) + 200;
				prototipOffset = {x: x*-1, y: 0};
			}
			
			if (!liEl.hasClassName('stock-out')) {
				liEl
					.observe('mouseover', Util.onHover)
					.observe('mouseout', Util.offHover);
					
				if (liEl.hasClassName('backorder') && date) {
					liEl.writeAttribute('data-availability', date);
				}
					
				liEl.observe('click', this.doClick.bind(this));
			} else {
				liEl.writeAttribute('data-availability', 'Out of Stock');
			}
		}.bind(this));
	},
	
	doClick: function(e){
		var liEl = Event.element(e);
		if (liEl.hasClassName('selecetd')) return;
		liEl.removeClassName('over');
		liEl.siblings().each(function(el){
			el.removeClassName('selected');
		});
		
		var a = liEl.identify().split('-');
		Form.Element.setValue('attribute'+a[1], a[2]);
		this.configureElement($('attribute'+a[1]));
		
		liEl.addClassName('selected');
	},

    reloadOptionLabels: function(element){
        var selectedPrice;
        if(element.options[element.selectedIndex].config){
            selectedPrice = parseFloat(element.options[element.selectedIndex].config.price);
        }
        else{
            selectedPrice = 0;
        }
        for(var i=0;i<element.options.length;i++){
            if(element.options[i].config){
                element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-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(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].price), options[i].id);
                    element.options[index].config = options[i];
                    index++;
                }
            }
        }
    },

    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;
    },

    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.evaluate({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(){
        var price = 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);
            }
        }

        optionsPrice.changePrice('config', price);
        optionsPrice.reload();

        return price;

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

    reloadOldPrice: function(){
        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;
            }

        }
    }
};


/**************************** SUPER PRODUCTS ********************************/

Product.Super = {};
Product.Super.Configurable = Class.create();

Product.Super.Configurable.prototype = {
    initialize: function(container, observeCss, updateUrl, updatePriceUrl, priceContainerId) {
        this.container = $(container);
        this.observeCss = observeCss;
        this.updateUrl = updateUrl;
        this.updatePriceUrl = updatePriceUrl;
        this.priceContainerId = priceContainerId;
        this.registerObservers();
    },
    registerObservers: function() {
        var elements = this.container.getElementsByClassName(this.observeCss);
        elements.each(function(element){
            Event.observe(element, 'change', this.update.bindAsEventListener(this));
        }.bind(this));
        return this;
    },
    update: function(event) {
        var elements = this.container.getElementsByClassName(this.observeCss);
        var parameters = Form.serializeElements(elements, true);

        new Ajax.Updater(this.container, this.updateUrl + '?ajax=1', {
                parameters:parameters,
                onComplete:this.registerObservers.bind(this)
        });
        var priceContainer = $(this.priceContainerId);
        if(priceContainer) {
            new Ajax.Updater(priceContainer, this.updatePriceUrl + '?ajax=1', {
                parameters:parameters
            });
        }
    }
};

/**************************** PRICE RELOADER ********************************/
Product.OptionsPrice = Class.create();
Product.OptionsPrice.prototype = {
    initialize: function(config) {
        this.productId          = config.productId;
        this.priceFormat        = config.priceFormat;
        this.includeTax         = config.includeTax;
        this.defaultTax         = config.defaultTax;
        this.currentTax         = config.currentTax;
        this.productPrice       = config.productPrice;
        this.showIncludeTax     = config.showIncludeTax;
        this.showBothPrices     = config.showBothPrices;
        this.productPrice       = config.productPrice;
        this.productOldPrice    = config.productOldPrice;
        this.skipCalculate      = config.skipCalculate;
        this.duplicateIdSuffix  = config.idSuffix;

        this.oldPlusDisposition = config.oldPlusDisposition;
        this.plusDisposition    = config.plusDisposition;

        this.oldMinusDisposition = config.oldMinusDisposition;
        this.minusDisposition    = config.minusDisposition;

        this.optionPrices = {};
        this.containers = {};

        this.displayZeroPrice   = true;

        this.initPrices();
    },

    setDuplicateIdSuffix: function(idSuffix) {
        this.duplicateIdSuffix = idSuffix;
    },

    initPrices: function() {
        this.containers[0] = 'product-price-' + this.productId;
        this.containers[1] = 'bundle-price-' + this.productId;
        this.containers[2] = 'price-including-tax-' + this.productId;
        this.containers[3] = 'price-excluding-tax-' + this.productId;
        this.containers[4] = 'old-price-' + this.productId;
    },

    changePrice: function(key, price) {
        this.optionPrices[key] = parseFloat(price);
    },

    getOptionPrices: function() {
        var result = 0;
        var nonTaxable = 0;
        $H(this.optionPrices).each(function(pair) {
            if (pair.key == 'nontaxable') {
                nonTaxable = pair.value;
            } else {
                result += pair.value;
            }
        });
        var r = new Array(result, nonTaxable);
        return r;
    },

    reload: function() {
        var price;
        var formattedPrice;
        var optionPrices = this.getOptionPrices();
        var nonTaxable = optionPrices[1];
        optionPrices = optionPrices[0];
        $H(this.containers).each(function(pair) {
            var _productPrice;
            var _plusDisposition;
            var _minusDisposition;
            if ($(pair.value)) {
                if (pair.value == 'old-price-'+this.productId && this.productOldPrice != this.productPrice) {
                    _productPrice = this.productOldPrice;
                    _plusDisposition = this.oldPlusDisposition;
                    _minusDisposition = this.oldMinusDisposition;
                } else {
                    _productPrice = this.productPrice;
                    _plusDisposition = this.plusDisposition;
                    _minusDisposition = this.minusDisposition;
                }

                var price = optionPrices+parseFloat(_productPrice);
                if (this.includeTax == 'true') {
                    // tax = tax included into product price by admin
                    var tax = price / (100 + this.defaultTax) * this.defaultTax;
                    var excl = price - tax;
                    var incl = excl*(1+(this.currentTax/100));
                } else {
                    var tax = price * (this.currentTax / 100);
                    var excl = price;
                    var incl = excl + tax;
                }

                excl += parseFloat(_plusDisposition);
                incl += parseFloat(_plusDisposition);
                excl -= parseFloat(_minusDisposition);
                incl -= parseFloat(_minusDisposition);

                //adding nontaxlable part of options
                excl += parseFloat(nonTaxable);
                incl += parseFloat(nonTaxable);

                if (pair.value == 'price-including-tax-'+this.productId) {
                    price = incl;
                } else if (pair.value == 'old-price-'+this.productId) {
                    if (this.showIncludeTax || this.showBothPrices) {
                        price = incl;
                    } else {
                        price = excl;
                    }
                } else {
                    if (this.showIncludeTax) {
                        price = incl;
                    } else {
                        if (!this.skipCalculate || _productPrice == 0) {
                            price = excl;
                        } else {
                            price = optionPrices+parseFloat(_productPrice);
                        }
                    }
                }

                if (price < 0) price = 0;

                if (price > 0 || this.displayZeroPrice) {
                    formattedPrice = this.formatPrice(price);
                } else {
                    formattedPrice = '';
                }

                if ($(pair.value).select('.price')[0]) {
                    $(pair.value).select('.price')[0].innerHTML = formattedPrice;
                    if ($(pair.value+this.duplicateIdSuffix) && $(pair.value+this.duplicateIdSuffix).select('.price')[0]) {
                        $(pair.value+this.duplicateIdSuffix).select('.price')[0].innerHTML = formattedPrice;
                    }
                } else {
                    $(pair.value).innerHTML = formattedPrice;
                    if ($(pair.value+this.duplicateIdSuffix)) {
                        $(pair.value+this.duplicateIdSuffix).innerHTML = formattedPrice;
                    }
                }
            };
        }.bind(this));
    },
    formatPrice: function(price) {
        return formatCurrency(price, this.priceFormat);
    }
};

	
document.observe('dom:loaded', function(){
	
	if ($$('body.catalog-product-view').length) {
		var Tabs = new LFI.Tabs('#product-details .tabs');

		// Read Review link functionality
		var reviewChecker = new PeriodicalExecuter(function(e){
			if (!$$('.pr-snippet-read-reviews a').length) return;

			$$('.pr-snippet-read-reviews a')[0].observe('click', function(event){
				Effect.ScrollTo('product-details', {
					duration: 1.5,
					offset: -20,
					transition: Effect.Transitions.EaseFromTo,
					afterFinish: function(){
						Tabs.showContent($$('a[href="#product_tabs_reviews"]')[0], event);
					}
				});
				event.stop();
			});
			reviewChecker.stop();
		}, 0.1); // End Read Review

	}
	
	var socialShare = $$('.social .share');
	if (socialShare.length) {
		socialShare[0].observe('click', function(e){
			newWin(this.href, 495, 666, 'addThis');
			e.preventDefault();
		});
	}
});
