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

/**EXCUSTOM**/
function SetSelectValue(SelectObject, Value) {
  for(var index = 0; 
    index < SelectObject.length; 
    index++) {
   if(SelectObject[index].value == Value)
     SelectObject.selectedIndex = index;
   }
}
/**END EXCUSTOM**/

function updateSelectedVariation(parent, variation, id) {
	//alert(variation.thumb);
	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;
		}

		var stockMessageVisible = false;
		if($('.OutOfStockMessage', parent).css('display') != 'none') {
			stockMessageVisible = true;
		}

		//EXCUSTOM-RRP - added retailPrice row
		baseProduct = {
			saveAmount: $.trim($('.YouSaveAmount', parent).html()),
			price: $.trim($('.VariationProductPrice', parent).html()),
			retailPrice: $.trim($('.VariationProductRetailPrice', parent).html()),
			sku: $.trim($('.VariationProductSKU', parent).html()),
			weight: $.trim($('.VariationProductWeight', parent).html()),
			thumb: $.trim($('.ProductThumb img', parent).attr('src')),
			thumbLink: $.trim($('.ProductThumb .ViewLarger', parent).html()),							
			cartButton: cartVisible,
			stockMessage: stockMessageVisible,
			stockMessageText: $('.OutOfStockMessage', parent).html()
		};
	}

	//EXCUSTOM - bogo
	$('.SecondProductOptionList',parent).hide();
	//ENDEXCUSTOM		
	
	// Show the defaults again
	//alert(typeof(variation));	
	if(typeof(variation) == 'undefined') {
		if(baseProduct.saveAmount) {
			$('.YouSave', parent).show();
			$('.YouSaveAmount').html(baseProduct.saveAmount);
		} else {
			$('.YouSave', parent).hide();
		}
		$('.VariationProductPrice', parent).html(baseProduct.price);
		//EXCUSTOM-RRP - add this for RRP
		if (baseProduct.retailPrice) {
			$('.VariationProductRetailPrice',parent).show();
			$('.VariationProductRetailPrice',parent).html(baseProduct.retailPrice);
		} else {
			$('.VariationProductRetailPrice',parent).hide();
		}
		//END EXCUSTOM
		
		$('.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', '')
		//EXCUSTOM
		$('.VariationOutOfStockMessage', parent).remove();
		if(baseProduct.sku == '') {
			$('.ProductSKU', parent).hide();
		}
		if(baseProduct.cartButton) {
			$('.AddCartButton', parent).show();
			if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
				$('.QuantityInput', parent).show();
			}
		}

		if(baseProduct.stockMessage) {
			$('.OutOfStockMessage', parent)
				.show()
				.html(baseProduct.stockMessageText)
			;
		}
		else {
			$('.OutOfStockMessage').hide();
		}

		$('.InventoryLevel', parent).hide();
	}
	// Othersie, showing a specific variation
	else {	
		//EXCUSTOM
		$('.product-zoom',parent).attr('href',variation.zoomURL);
		$('.product-zoom',parent).attr('title',variation.sku);
		//END EXCUSTOM
		$('.VariationProductPrice', parent).html(variation.price);
		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();
			}
			$('.OutOfStockMessage', parent).hide();
			
			//EXCUSTOM - BOGOF
			$('.QuantityInput',parent).hide();
			//$('#AddToCartQty',parent).hide();			
			$('.SecondProductOptionList',parent).show();	
			//somewhere bits of this are disabled so just undisable them to counter it
			$('.SecondProductOptionList').removeAttr('disabled');
			$('.SecondProductOptionList select').change(function() {
				$('#wishlist_variation_id2').val($(this).val());
			});
			
			//END EXCUSTOM							
		}
		else {
			$('.AddCartButton, .QuantityInput', parent).hide();
			$('.OutOfStockMessage', parent).html(lang.VariationSoldOutMessage);
			$('.OutOfStockMessage', parent).show();
		}
		//alert(variation.thumb);
		//alert(baseProduct.thumbLink);
		if(variation.thumb != '') {
			$('.ProductThumb img', parent).attr('src', variation.thumb);
			/**EXCUSTOM**/
			if (variation.image==variation.zoom) {
				$('.ProductThumb .ViewLarger', parent).html('See larger picture');
			} else {
				$('.ProductThumb .ViewLarger', parent).html('See large close up');
			}
			/**END EXCUSTOM**/
			$(parent).attr('currentVariation', id);
			//$(parent).attr('currentVariationImage', variation.image)
			//EXCUSTOM - show zoom
			$(parent).attr('currentVariationImage', variation.zoom)
		}
		else {
			$('.ProductThumb img', parent).attr('src', baseProduct.thumb);
			$('.ProductThumb .ViewLarger', parent).html(baseProduct.thumbLink);
			$(parent).attr('currentVariation', '');
			$(parent).attr('currentVariationImage', '')
		}
		//EXCUSTOM: added (parseInt(variation.stock) != 0) to make stock not show
		if(variation.stock && (parseInt(variation.stock) != 0) ) {						
			$('.InventoryLevel', parent).show();
			//EXCUSTOM added sqty < 3 block to not show > 10 items in stock
			var sqty = parseInt(variation.stock);
			if(sqty < 3) {
				$('.VariationProductInventory', parent).html(variation.stock);
			} else {
				$('.VariationProductInventory', parent).html('In Stock'); 
			}
			//END EXCUSTOM
		}
		else {
			$('.InventoryLevel', parent).hide();
		}
		if(variation.saveAmount) {
			$('.YouSave', parent).show();
			$('.YouSaveAmount').html(variation.saveAmount);
		} else {
			$('.YouSave', parent).hide();
		}

		/**EXCUSTOM**/		
		if($('.ProductOptionList select', parent).length > 0) {
			var sel = $('.ProductOptionList select', parent).get(0);
			c_id=variation.combination //the list has the combination id in it		
			if (sel && c_id) SetSelectValue(sel,c_id);	
		}
		if($('#wishlist_variation_id', parent).length > 0) {
			if (variation.combination) 
				$('#wishlist_variation_id', parent).val(variation.combination);
		}
		/**END EXCUSTOM**/		
	}

	
}

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;
			}
		});
			
		
		/**EXCUSTOM**/
		$('.ProductThumb1 input[type=image]', parent).click(function() {
			for(x in VariationList) {
				variation = VariationList[x];
			
				if(variation.combination == $(this).val()) {						
					updateSelectedVariation('body', variation, x);
					return;
				}
			}
			// No match or incomplete selection
			updateSelectedVariation(parent);
		});		
		/**END EXCUSTOM **/
		
	}
	// 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');
		
		/**EXCUSTOM**/
		$('.ProductThumb1 input[type=image]', parent).click(function() {
			for(x in VariationList) {
				variation = VariationList[x];
			
				if(variation.combination == $(this).val()) {						
					updateSelectedVariation('body', variation, x);
					return;
				}
			}
			// No match or incomplete selection
			updateSelectedVariation(parent);
		});
		/**END EXCUSTOM**/		
	}
}

function GenerateProductTabs()
{
	var ActiveTab = 'Active';
	var ProductTab = '';
	var TabNames = new Array();

	TabNames['ProductDescription'] = lang.Description;
	TabNames['ProductWarranty'] = lang.Warranty;
	TabNames['ProductOtherDetails'] = lang.OtherDetails;
	TabNames['SimilarProductsByTag'] = lang.ProductTags;
	TabNames['ProductByCategory'] = lang.SimilarProducts;
	TabNames['ProductReviews'] = lang.Reviews;
	TabNames['ProductVendorsOtherProducts'] = lang.OtherProducts;
	$('#LayoutColumn2 .Moveable').each (

		function() {
			if(this.id != 'ProductBreadcrumb' &&  this.id != 'ProductDetails') {

				if (TabNames[this.id]) {

					TabName = TabNames[this.id];
					ProductTab += '<li id="'+this.id+'_Tab" class="'+ActiveTab+'"><a onclick="ActiveProductTab(\''+this.id+'_Tab\'); return false;" href="#">'+TabName+'</a></li>';

					if (ActiveTab == '')
					{
						$('#'+this.id).hide();
					}
					$('#'+this.id).removeClass('Moveable');
					ActiveTab = "";
				}
			}
		}
	);

	if (ProductTab != '')
	{
		$('#ProductTabsList').html(ProductTab);
	}
}

function ActiveProductTab(TabId)
{
	var CurTabId = $('#ProductTabs .Active').attr('id');
	var CurTabContentId = CurTabId.replace('_Tab','');

	$('#ProductTabs .Active').removeClass('Active');

	$('#'+CurTabContentId).hide();

	$('#'+TabId).addClass('Active');

	var NewTabContentId = TabId.replace('_Tab','');
	$('#'+NewTabContentId).show();

}

function CheckEventDate() {

	var result = true;

	if(typeof(eventDateData) == 'undefined')
		return true;

	if ($('#EventDateDay').val() == -1 || $('#EventDateMonth').val() == -1 || $('#EventDateYear').val() == -1) {
		alert(eventDateData['invalidMessage']);
		return false;
	}

	if (eventDateData['type'] == 1) {

		if (new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) > new Date(eventDateData['compDateEnd'])
		 || new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) < new Date(eventDateData['compDate'])
		) {
			result = false;
		}

	} else if (eventDateData['type'] == 2) {
		if (new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) < new Date(eventDateData['compDate'])) {
			result = false;
		}

	} else if (eventDateData['type'] == 3) {
		if (new Date($('#EventDateYear').val()+'/'+$('#EventDateMonth').val()+'/'+$('#EventDateDay').val()) > new Date(eventDateData['compDate'])) {
			result = false;
		}
	} else {
		result = true;
	}

	if (!result) {
		alert(eventDateData['errorMessage']);
	}
	return result;
}

$(document).ready(function() {
	
	if(typeof(HideProductTabs) != 'undefined' && HideProductTabs == 0) {
		GenerateProductTabs();
		if (CurrentProdTab && CurrentProdTab != "") {
			ActiveProductTab(CurrentProdTab);
			document.location.href = '#ProductTabs';
		}
	}

	if(typeof VariationList == 'undefined') {
		return;
	}
	initializeVariations('body', VariationList);

});
