/* Product Variations */
var baseProduct = {};

function updateSelectedVariation(parent, variation, id) {
	if(parent == undefined) {
		parent = $('body');
	}
	else {
		parent = $(parent);
	}

	if(typeof(baseProduct.price) == 'undefined') {
		if($('.AddCartButton', parent).css('display') == "none") {
			var cartVisible = false;
		}
		else {
			var cartVisible = true;
		}
		baseProduct = {
			saveAmount: $('.YouSaveAmount', parent).html(),
			price: $('.VariationProductPrice', parent).html(),
			sku: $('.VariationProductSKU', parent).html(),
			weight: $('.VariationProductWeight', parent).html(),
			thumb: $('.ProductThumb img', parent).attr('src'),
			thumbLink: $('.ProductThumb .ViewLarger', parent).html(),
			cartButton: cartVisible
		};
	}
	var product_price = document.getElementById('prod_price').value;
	baseProduct.price = stripHTML(baseProduct.price);
	sAmount1=0.1;
	if (baseProduct.saveAmount!=null){
	baseProduct.saveAmount = stripHTML(baseProduct.saveAmount);
	sAmount=baseProduct.saveAmount.split(" ");
	sAmount1 =  sAmount[0].replace(",","");
	}
	bsprice = baseProduct.price.split(" ");
	bsprice1 =  bsprice[0].replace(",","");
	

	var kreditorprice;

	// Show the defaults again
	if(typeof(variation) == 'undefined') {
		if(baseProduct.saveAmount) {
			$('.YouSave', parent).show();
			$('.YouSaveAmount').html(baseProduct.saveAmount);
		} else {
			$('.YouSave', parent).hide();
		}

		baseProduct.price = stripHTML(baseProduct.price);
		krprice = baseProduct.price.split(" ");
		krprice1 =  krprice[0].replace(",","");
		kreditorprice = "Från "+ Math.round(eval(krprice1/24*1.015)) + ".00 SEK/mån";
		homepartyprice = eval(krprice1*(90/100));
		if(krprice1<homepartyprice)
		homepartyprice = krprice1;
		homepartyprice_display = homepartyprice.toFixed(2)+" "+bsprice[1];

		

		$('.VariationProductPrice', parent).html(baseProduct.price);
		$('.VariationProductKreditorPrice', parent).html(kreditorprice);
		$('.VariationProductHomepartyPrice', parent).html(homepartyprice_display);
		$('.VariationProductSKU', parent).html(baseProduct.sku);
		$('.VariationProductWeight', parent).html(baseProduct.weight);
		$('.CartVariationId', parent).val('');
		$('.ProductThumb img', parent).attr('src', baseProduct.thumb);
		$('.ProductThumb .ViewLarger', parent).html(baseProduct.thumbLink);
		$(parent).attr('currentVariation', '');
		$(parent).attr('currentVariationImage', '')
		$('.VariationOutOfStockMessage', parent).remove();
		if(baseProduct.sku == '') {
			$('.ProductSKU', parent).hide();
		}
		if(baseProduct.cartButton) {
			$('.AddCartButton', parent).show();
			if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
				$('.QuantityInput', parent).show();
			}
		}


		$('.InventoryLevel', parent).hide();
	}
	// Othersie, showing a specific variation
	else {
		
		krprice = variation.price.split(" ");
		krprice1 =  krprice[0].replace(",","");
		kreditorprice = "Från "+ Math.round(eval(krprice1/24*1.015)) + ".00 SEK/mån";
		var variation1 = eval(krprice1 - bsprice1);
		homepartyprice = parseFloat(krprice1)*(9/10);
		
		if (sAmount1>0.1){
		initial_price=$('.priceDetail strike', parent).html();
		initial_price_val=initial_price.split(" ");
		if (sAmount1/initial_price_val[0]>0.1)
		homepartyprice=parseFloat(krprice1);
		}
		
		if(parseFloat(krprice1)<homepartyprice)
		homepartyprice = parseFloat(krprice1);
		homepartyprice_display = homepartyprice.toFixed(0)+" "+bsprice[1];
		
		

		
		$('.VariationProductPrice', parent).html(variation.price);
		$('.VariationProductKreditorPrice', parent).html(kreditorprice);
		$('.VariationProductHomepartyPrice', parent).html(homepartyprice_display);
		if(variation.sku != '') {
			$('.VariationProductSKU', parent).html(variation.sku);
			$('.ProductSKU', parent).show();
		}
		else {
			$('.VariationProductSKU', parent).html(baseProduct.sku);
			if(baseProduct.sku) {
				$('.ProductSKU', parent).show();
			}
			else {
				$('.ProductSKU', parent).hide();
			}
		}
		$('.VariationProductWeight', parent).html(variation.weight);
		$('.CartVariationId', parent).val(id);
		if(variation.instock == true) {
			$('.AddCartButton', parent).show();
			if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
				$('.QuantityInput', parent).show();
			}
			$('.VariationOutOfStockMessage', parent).remove();
		}
		else {
			$('.AddCartButton, .QuantityInput', parent).hide();
			$('.VariationOutOfStockMessage', parent).remove();
			$('.AddCartButton', parent).before('<p class="VariationOutOfStockMessage">'+lang.VariationSoldOutMessage+'</p>');
		}
		if(variation.thumb != '') {
			$('.ProductThumb img', parent).attr('src', variation.thumb);
			$('.ProductThumb .ViewLarger', parent).html('See larger picture');
			$(parent).attr('currentVariation', id);
			$(parent).attr('currentVariationImage', variation.image)
		}
		else {
			$('.ProductThumb img', parent).attr('src', baseProduct.thumb);
			$('.ProductThumb .ViewLarger', parent).html(baseProduct.thumbLink);
			$(parent).attr('currentVariation', '');
			$(parent).attr('currentVariationImage', '')
		}
		if(variation.stock) {
			$('.InventoryLevel', parent).show();
			$('.VariationProductInventory', parent).html(variation.stock);
		}
		else {
			$('.InventoryLevel', parent).hide();
		}
		if(variation.saveAmount) {
			$('.YouSave', parent).show();
			$('.YouSaveAmount').html(variation.saveAmount);		
		} else {
			$('.YouSave', parent).hide();
		}
	}
}

function stripHTML(oldString) {

   var newString = "";
   var inTag = false;
   for(var i = 0; i < oldString.length; i++) {
   
        if(oldString.charAt(i) == '<') inTag = true;
        if(oldString.charAt(i) == '>') {
              if(oldString.charAt(i+1)=="<")
              {
                              //dont do anything
        }
        else
        {
                inTag = false;
                i++;
        }
        }
   
        if(!inTag) newString += oldString.charAt(i);

   }

   return newString;
}

function initializeVariations(parent, VariationList)
{
	if(parent == undefined) {
		parent = $('body');
	}
	else {
		parent = $(parent);
	}

	// Select boxes are used if there is more than one variation type
	if($('.ProductOptionList select', parent).length > 0) {
		$('.ProductOptionList select', parent).each(function(index) {
			$(this).change(function() {
				if($(this).val()) {
					var next = $('.ProductOptionList select', parent).get(index+1);
					if(next) {
						$('.ProductOptionList select', parent).get(index+1).resetNext();
						$('.ProductOptionList select', parent).get(index+1).fill();
						$('.ProductOptionList select', parent).get(index+1).disabled = false;
					}
				}
				else {
					this.resetNext();
				}

				// Do we have a full match?
				ourCombination = this.getFullCombination();
				for(x in VariationList) {
					variation = VariationList[x];
					if(variation.combination == ourCombination) {
						updateSelectedVariation(parent, variation, x);
						return;
					}
				}
				// No match or incomplete selection
				updateSelectedVariation(parent);
			});

			this.getFullCombination = function() {
				var selected = new Array();
				$('.ProductOptionList select', parent).each(function() {
					selected[selected.length] = $(this).val();
				});
				return selected.join(',');
			}


			this.getCombination = function() {
				var selected = new Array();
				var thisSelect = this;
				$('.ProductOptionList select', parent).each(function() {
					if(thisSelect == this) {
						return false;
					}
					selected[selected.length] = $(this).val();
				});
				// Add the current item
				selected[selected.length] = $(this).val();
				return selected.join(',');
			}

			this.resetNext = function() {
				$(this).nextAll().each(function() {
					this.selectedIndex = 0;
					this.disabled = true;
				});
			};

			this.fill = function(selectedVal) {
				// Remove everything but the first option
				$(this).find('option:gt(0)').remove();

				var show = true;
				var previousSelection;

				// Get the values of the previous selects
				var previous = $('.ProductOptionList select', parent).get(index-1);
				if(previous) {
					previousSelection = previous.getCombination();
				}
				for(var i = 1; i < this.variationOptions.length; i++) {
					for(x in VariationList) {
						variation = VariationList[x];
						if(previousSelection) {
							var show = false;
							if((variation.combination+',').indexOf(previousSelection+','+this.variationOptions[i].value+',') == 0) {
								var show = true;
								break;
							}
							else {
							}
						}
					}
					if(show) {
						this.options[this.options.length] = new Option(this.variationOptions[i].text, this.variationOptions[i].value);
					}
				}
				
				if(selectedVal != undefined) {
					$(this).val(selectedVal);
				}
			};

			// Steal the options and store them away for later
			variationOptions = new Array();
			$(this).find('option').each(function() {
				if(typeof(this.text) == undefined) {
					this.text = this.innerHTML;
				}
				variationOptions[variationOptions.length] = {value: this.value, text: this.text };
			});
			selectedVal = $(this).val();
			this.variationOptions = variationOptions;
			if(index == 0) {
				this.fill(selectedVal);
			}
			else if(!selectedVal) {
				this.disabled = true;
			}
		});
	}
	// Otherwise, radio buttons which are very easy to deal with
	else {
		$('.ProductOptionList input[type=radio]', parent).click(function() {
			for(x in VariationList) {
				variation = VariationList[x];
				if(variation.combination == $(this).val()) {
					updateSelectedVariation(parent, variation, x);
					return;
				}
			}
			// No match or incomplete selection
			updateSelectedVariation(parent);
		});
		$('.ProductOptionList input[type=radio]:checked', parent).trigger('click');
	}
}

$(document).ready(function() {
	if(typeof VariationList == 'undefined') {
		return;
	}
	initializeVariations('body', VariationList);
});