/*	Product
------------------------------ */
var Product = {
	product				: null, // The product that has the variants
	variantCount		: null, // Current index of variant
	variants			: null, // The list item that holds the radio button
	variantData			: null, // Json data for the current variant
	variantDesc			: "##name##, in ##colour##", // Brief description
	addToBasket			: null, // Add to basket button
	productPrice		: null, // Large price to add to basket button
	nowPrice			: null, // If a product is on sale it's current price
	wasPrice			: null,	// If a product is on sale it's old price
	specPrice			: null,
	specCode			: null,
	specVariantDesc		: null,
	heroImage			: null,
	heroImageLink		: null,
	heroImageOriginal	: null,
	alternativeImages	: null,
	rangeSelector		: null, // Drop-down for range selector
	currentRange		: null, // Select range
	currentVariant		: null, // Selected variant
	imagePath			: "images/default/en/catalogue/",
	groupName			: "variant-id",
	setLengthSelector : function() {
		var lengthSelector	= document.getElementById("product-length");
		if (lengthSelector) {
			var input = lengthSelector.getElementsByTagName("input");
			for (var i = 0, c = input.length; i < c; i++) {
				if (input[i].type == "radio") {
					input[i].onclick = function() {
						var submitLength = document.getElementById("select-length");
						submitLength.focus();
					}
				}
			}
		}
	},
	init : function() {
		if (!document.getElementById) { return; }
		
		// Set up length selector
		this.setLengthSelector();
		// Get matrix and the variant item containers
		this.product		= document.getElementById("variant-matrix");
		this.variants		= this.product.getElementsByTagName('li');

		// Get alternative images
		this.heroImage			= document.getElementById("main-product-image");
		this.alternativeImages	= document.getElementById("alternative-images");
		this.heroImageLink		= document.getElementById("heroImageLink");

   		// Adds popup to main image (requires core.js)
		Product.setImageEnlarge();

		if (this.heroImage && this.alternativeImages) { this.setAltImages(); }

		// Exit if there are no variants
		if (this.variants.length < 1) { return; }

		Debug.p('Product count', this.variants.length);

		// 1st - Get spec elements
		
		if (Config.isPlanet())
		{
			this.specCode			= document.getElementById("spec-code");
			this.specPrice			= document.getElementById("spec-price");
			this.productPrice		= document.getElementById("product-price");
			this.nowPrice			= document.getElementById("now-price");
			this.wasPrice			= document.getElementById("was-price");
			this.addToBasket		= document.getElementById("add-to-basket");
			this.rangeSelector		= document.getElementById("dd-size");
		}
		else if (Config.isWindsmoor())
		{
			this.specCode			= document.getElementById("product-code");
			//this.specPrice		= document.getElementById("spec-price");
			this.productPrice		= document.getElementById("price");
			this.addToBasket		= document.getElementById("add-to-basket");
			this.rangeSelector		= document.getElementById("dd-size");
			this.nowPrice			= document.getElementById("now-price");
			this.wasPrice			= document.getElementById("was-price");
		}
		else if (Config.isJacquesVert())
		{
			this.specCode			= document.getElementById("spec-code");
			this.specPrice			= document.getElementById("spec-price");
			this.productPrice		= document.getElementById("product-price");
			this.addToBasket		= document.getElementById("add-to-basket");
			this.rangeSelector		= document.getElementById("dd-size");
		}
		else if (Config.isPrecis())
		{
			this.specCode			= document.getElementById("spec-code");
			this.specPrice			= document.getElementById("spec-price");
			this.productPrice		= document.getElementById("spec-price");
			this.addToBasket		= document.getElementById("add-to-basket");
			this.rangeSelector		= document.getElementById("dd-size");
		}
		// 2nd - Replace the radio buttons
		for (var i = 0, c = this.variants.length; i < c; i++) {
			this.variantCount = i;
			if (this.variants[i].firstChild.nodeName.toLowerCase() == "input") {
				this.setItem(this.variants[i]);
			}
		}
		
		// 3rd - Add event for the drop-down 
		if (this.rangeSelector) {
			this.currentRange = this.rangeSelector.options[this.rangeSelector.selectedIndex].value;
			this.rangeSelector.onchange = function() {
				Product.setRange(this);
			}		
		}	

		// 4th - Clear the unnecessary ranges
		this.clearRange();
		this.setRange(this.rangeSelector, this.currentVariant);
	},
	setImageEnlarge : function() {
		var productImageBlock = document.getElementById("product-image");
		if (productImageBlock) {
			var productImageBlockLinks = productImageBlock.getElementsByTagName('a');
			for (var i = 0, c = productImageBlockLinks.length; i < c; i++) {
				if (productImageBlockLinks[i].className == "enlarge-image") {
					productImageBlockLinks[i].onclick = function () {
						PopUp.newPopUp(this, {width: 472, height: 680 });
						return false;
					}
				}
			}
		}
		
		productImageBlock = document.getElementById("different-views");
		if (productImageBlock) {
			var productImageBlockLinks = productImageBlock.getElementsByTagName('a');
			for (var i = 0, c = productImageBlockLinks.length; i < c; i++) {
				if (productImageBlockLinks[i].className == "enlarge-image") {
					productImageBlockLinks[i].onclick = function () {
						PopUp.newPopUp(this, {width: 470, height: 690 });
						return false;
					}
				}
			}
		}
	},
	setAltImages : function() {
		var altImage = this.alternativeImages.getElementsByTagName('a');

        this.heroImageOriginal = this.heroImage.src;
		
		if (!altImage) { return; }
		
		for (var i = 0, c = altImage.length; i < c; i++) {
			altImage[i].onclick = function () {
				Product.heroImage.src = this.firstChild.src.replace("thumb_", "medium_");
				Product.heroImage.parentNode.href = this.firstChild.src.replace('alt/thumb','large/large');
				Product.heroImageLink.href = Product.heroImage.parentNode.href;
				return false;
			}
		}
	},
	cleanVariantValue : function(value) {
		return 'p' + value.replace('-', '');
	},
	setItem : function(variant) {
		Debug.w("Item is a variant");

		var radio = variant.getElementsByTagName("input");

		if (!radio) { return; }

		Debug.w("Label and radio exist", 1);

		radio = radio[0];

		// Json array of variant data
		this.variantData = eval("ProductData." + this.cleanVariantValue(radio.value));
		
		// default select size option has no swatch data there skip
		if (radio.value != "SelectSize") 
		{		
			// Create link for the swatch
			var link		= document.createElement('a');
			link.id			= radio.id + "-form-replaced";
			link.className	= "form-replaced";
			link.href		= '#';
			link.title	= this.variantDesc.replace("##name##", this.variantData.name).replace("##size##", this.variantData.size).replace("##colour##", this.variantData.colour);
		}
		
		if (radio.value != "SelectSize") 
		{	
			this.setVariantFunction(link, radio.value, radio.id, this.variantData.swatch);	
			//this.updateHeroImage(this, this.variantData.swatch);
		}
		else
		{
			// Set the radio button
			document.getElementById(radio.id).checked = true;
		}
		
		// default select size option has no swatch data therefore skip
		if (radio.value != "SelectSize") 
		{
			// Create image for the swatch
			var img			= document.createElement("img");
			img.className	= "form-replaced";
			img.className	= (radio.checked) ?  "form-replaced selected" : "form-replaced";
			img.alt			= this.variantDesc.replace("##name##", this.variantData.name).replace("##colour##", this.variantData.colour);
			img.src			=  UrlUtils.absoluteWebPath() + "/" + this.imagePath + "swatches/" + this.variantData.swatch + ".gif";
			if (radio.checked) {
				this.currentVariant = radio;

			} 
		
				
			// For showing swatch description for variants under their respective style
			if (this.variantBriefStart != this.variantData.style) {
				this.variantBrief = document.getElementById("variant-brief-" + this.variantData.style.toLowerCase());
				this.variantBriefStart = this.variantData.style;
			}
			
			// Add hidden class and add the swatch to the item
			variant.className = "form-replacement";
			link.appendChild(img);
			variant.appendChild(link);

		}
		// Set the information for the pre-selected variant
		if (radio.checked) {
			Debug.w("This item is checked", 2);
			this.setInfo();
		}
	},
	updateHeroImage : function(e, variantColour) {
		var re = new RegExp("medium[^_]*/", "gi");
		if (this.heroImageOriginal)
			this.heroImage.src = this.heroImageOriginal.replace(re, "medium/" + variantColour + "/");
	},
	resetHeroImage : function(e, variantColour) {
		this.heroImage.src = this.heroImage.src.replace("medium/" + variantColour, "medium");
	},
	setVariantFunction : function(e, variantValue, variantId, variantColour) { 
		// Apply lexical variables correctly
		e.onclick = function() {
			Product.updateHeroImage(this, variantColour);
			return Product.setVariant(this, variantValue, variantId);
		};
	},
	setVariant : function(e, variantValue, variantId) {
		Debug.w('Set variant');

		// Clean the selection
		this.clearProduct();

		// Set the radio button
		document.getElementById(variantId).checked = true;

		// Change the image state
		if (e.firstChild.nodeName.toLowerCase() == "img") {
			var img = e.firstChild;
			img.className = "form-replaced selected";
		}

		// Set new Json array to correct variant
		this.variantData = eval('ProductData.' + this.cleanVariantValue(variantValue));

		// Refresh the details
		this.setInfo();

		return false;
	},
	setInfo : function() {
		// Update information
	if (this.variantData != null)
		{
				// bring back the add to bag/coming soon button
				if (document.getElementById("add-to-basket"))
				{
					// enable the quantity drop down
					document.getElementById("DefaultMode_newContentRegion_ucProductVariantItem_ddlQuantity").disabled = false;
					document.getElementById("add-to-basket").style.display = "block";
				}else{
					document.getElementById("coming-soon").style.display = "block";
				}
				
				
				if (this.specCode)
					this.specCode.innerHTML		= this.variantData.code;
				if (this.specPrice)
					this.specPrice.innerHTML	= this.variantData.price;
				
				if (this.variantData.saleprice)
				{
					if (this.nowPrice)
					{
						this.wasPrice.innerHTML = this.variantData.saleprice;
					}
					
					if (this.wasPrice)
					{
						this.nowPrice.innerHTML = this.variantData.price;
					}
				}
				else
				{
					this.productPrice.innerHTML	= this.variantData.price;
				}

				// Disable the add-to-basket button
				if (this.addToBasket) {
					if (!this.getStock(this.variantData.stock)) {
						if (this.addToBasket.src.search("-d.gif") == -1) {
        						this.addToBasket.src = this.addToBasket.src.replace(".gif", "-d.gif");
        						this.addToBasket.disabled = true;
						}
					} else {
						this.addToBasket.src = this.addToBasket.src.replace("-d.gif", ".gif");
						this.addToBasket.disabled = false;
					}		
				}
		}else {
		
				// size defaults to select size or is changed to select size
				this.addToBasket = document.getElementById("add-to-basket");
				if (this.addToBasket != null)
				{
					// disable the quantity drop down
					document.getElementById("DefaultMode_newContentRegion_ucProductVariantItem_ddlQuantity").disabled = true;
					// disable the hide add to back button
					this.addToBasket.disabled = true;
					document.getElementById("add-to-basket").style.display = "none";
					this.specCode.innerHTML		= document.getElementById("hdnProdCode").value;
				
				}else{
					//picked a non selllable product therefore is coming soon
					this.addToBasket = document.getElementById("coming-soon");
					// disable the quantity drop down
					document.getElementById("DefaultMode_newContentRegion_ucProductVariantItem_ddlQuantity").disabled = true;
					// disable the hide add to back button
					this.addToBasket.disabled = true;
					document.getElementById("coming-soon").style.display = "none";
					this.specCode.innerHTML		= document.getElementById("hdnProdCode").value;
				
				}
	}	
	},
	setOpacity : function(el, opacity) {
		el.style.opacity		= (opacity / 50);
		el.style.MozOpacity	= (opacity / 50);
		el.style.KhtmlOpacity	= (opacity / 50);
		el.style.filter		= 'alpha(opacity=' + opacity + ')';
	},
	// Display the required variant range
	setRange : function(e, currentVariant) {
		if (currentVariant) {
			this.variantData = eval("ProductData." + this.cleanVariantValue(currentVariant.value));
			this.currentRange = this.variantData.size;
			FormUtils.preselectDropDown(e, this.variantData.size);
		} else {
			if (e.options[e.selectedIndex].value != "Select Size")
			{		
				this.currentRange = e.options[e.selectedIndex].value;

			}
			else
			{		
				// Refresh the details
				this.variantData = null;
				this.setInfo();

			}
		}
		var variantRange = document.getElementById("variant-range-" + this.currentRange);
		if (variantRange) {
			this.clearRange();
		}
		variantRange.style.display = "block";
		


		// Preselect the first item of a range to ensure correctness
		var selectedVariant = variantRange.getElementsByTagName("input");
		var hasSelected = false;
		for (var i = 0, c = selectedVariant.length; i < c; i++) {
			if (selectedVariant[i].checked) {
				hasSelected = true;
				break;
			}
		}
		if (!hasSelected) {
			var select = selectedVariant[0].parentNode.getElementsByTagName('a')[0];
			if(select)
				select.onclick();
		}
	},
	// Hide the variant range
	clearRange : function() {
		for (var i = 0, c = this.variants.length; i < c; i++) {
			if (this.variants[i].id && this.variants[i].id != "variant-range-" + this.currentRange) {
				this.variants[i].style.display = "none";
			}
		}
	},
	clearProduct : function() {
		// Remove checked radio buttons
		var radio = this.product.getElementsByTagName("input");
		for (var i = 0, c = radio.length; i < c; i++) {
			var item = radio[i];
			if (item.name == this.groupName && item.type == "radio") {
				radio[i].checked = false;

			}
		}

		// Remove selected graphics
		var img = this.product.getElementsByTagName("img");
		for (var i = 0, c = img.length; i < c; i++) {
			var item = img[i];
			if (item.className.search("form-replaced") != -1) {
				item.className = "form-replaced";
			}
		}
	},
	getStock : function(stock) {
		switch(stock.toLowerCase()) {
			case "in stock":
				return true;
			break;
			case "out of stock":
				return false;
			break;
			default:
				return false;
			break;
		}
	}
};