/* Product
 * Control variant selection and product effects
 ------------------------------*/
var Product = {
	groupSize				: null,
	groupGuarantee			: null,
	groupDisposal			: null,
	selectionSize			: null,
	selectionGuarantee		: null,
	selectionDisposal		: null,
	selectionTotal			: null,
	selectedSize			: null,
	selectedGuarantee		: null,
	selectedMattress		: null,
	selectedSizeText		: null,
	selectedBaseText		: null,
	selectedDrawText		: null,
	selectedTotal			: "<span class=\"details-title\">Total:</span><span class=\"details-total\">##TOTAL##</span>",
	productData				: null,
	variantData				: null,
	ajax					: null,
	baseVariant				: null,
	drawVariant				: null,
	quantityVariant			: null,
	selectedVariant			: null,
	init : function() {
		this.ajax = new Ajax();
		
		//Product.checkZoom();

		this.selectionSize		= document.getElementById("selection-size");
		this.selectionGuarantee = document.getElementById("selection-guarantee");
		this.selectionDisposal	= document.getElementById("selection-disposal");
		this.selectionTotal		= document.getElementById("product-total");
		
		var size		= FormUtils.getValue("rdCA", "product-variant");
		var guatantee	= FormUtils.getValue("rdAA", "product-variant");
		var mattress	= FormUtils.getValue("rdBA", "product-variant");
		
		var baseVariant = document.getElementById("base-variant");
		if (baseVariant) {
			this.baseVariant = baseVariant.getElementsByTagName("select")[0];
			
			// Update selection text on the last variant selection
			Event.add(this.baseVariant, "change", function() {
				Product.setVariant(this, "base") 
			});
		}
		
		
		var drawVariant = document.getElementById("draw-variant");
		if (drawVariant) {
			this.drawVariant = drawVariant.getElementsByTagName("select")[0];
			this.selectedVariant = this.drawVariant.value;
			
			// Update selection text on the last variant selection
			Event.add(this.drawVariant, "change", function() {
				Product.setVariant(this, "draw") 
			});
		}
		
		var quantityVariant = document.getElementById("quantity-variant");
		if (quantityVariant) {
			this.quantityVariant = quantityVariant.getElementsByTagName("select")[0];
			
			// Update selection text on the last variant selection
			Event.add(this.quantityVariant, "change", function() {
				Product.setQuantity()
			});
		}

		// Assign function to radio buttons
		this.groupSize = document.getElementById("size-variant");
		if (this.groupSize) {
			var groupSizeItems = this.groupSize.getElementsByTagName("input");
			for (var i = 0, c = groupSizeItems.length; i < c; i++) {
				if (groupSizeItems[i].getAttribute("type") == "radio") {
					Debug.w("Add set variant function, " + i);
					Event.add(groupSizeItems[i], "click", function() { 
							Product.setVariant(this, "size"); 
						}
					);
					if (groupSizeItems[i].checked) {
						Debug.w("Size radio is preselected, " + i);
						this.setVariant(groupSizeItems[i], "size");
					}
				}
			}
		}
		
		this.groupGuarantee = document.getElementById("guarantee-option");
		if (this.groupGuarantee) {
			var groupGuaranteeItems = this.groupGuarantee.getElementsByTagName("input");
			for (var i = 0, c = groupGuaranteeItems.length; i < c; i++) {
				if (groupGuaranteeItems[i].getAttribute("type") == "radio") {
					Debug.w("Add set variant function, " + i);
					Event.add(groupGuaranteeItems[i], "click", function() { 
							Product.setVariant(this, "guarantee") 
							
						}
					);
					if (groupGuaranteeItems[i].checked) {
						Debug.w("Guarantee radio is preselected, " + i);
						this.setVariant(groupGuaranteeItems[i], "guarantee");
					}
				}
			}
		}
		
		this.groupDisposal = document.getElementById("disposal-option");
		if (this.groupDisposal) {
			var groupDisposalItems = this.groupDisposal.getElementsByTagName("input");
			for (var i = 0, c = groupDisposalItems.length; i < c; i++) {
				if (groupDisposalItems[i].getAttribute("type") == "radio") {
					Debug.w("Add set variant function, " + i);
					Event.add(groupDisposalItems[i], "click", function() { 
							Product.setVariant(this, "disposaltype") 
						}
					);
					if (groupDisposalItems[i].checked) {
						Debug.w("Disposal radio is preselected, " + i);
						this.setVariant(groupDisposalItems[i], "disposaltype");
					}
				}
			}
		}	
		

	},
	setProductData : function(property) {
		if (property) {
			this.productData = eval("ProductData.p" + property.replace("-", ""));
		} else {
			this.productData = eval("ProductData.p");
		}
	},
	checkZoom : function() {
		var zpid = document.getElementById("pid").innerHTML + '';
		var property = 'zoom';
		
		Debug.w("Check Zoom");
		switch (property) {
			case "zoom":
				Debug.w("Zoom");					
					this.ajax.set(document.forms[0].action, {"ajax": "true", "action": "zoom", "proid": zpid});
					//alert(e);
					this.ajax.busy = function() {
					};

					this.ajax.complete = function() {
						Debug.w(this.response);
						//ajax_hide_loading(e);
						var container = document.getElementById('links');
												
						var json = this.toJson();	
						if(json.zoom) {
							var totFiles = json.zoom[0].value;
							var pname = json.zoom[1].value;
							var xmlBase = json.zoom[2].value.split('|');
							var imgBase = json.zoom[3].value.split('|');
							var lbl = json.zoom[4].value;							
							var i = 0;
							if(totFiles>0){
								//Update the Image Link
								var lnkProImg = document.getElementById('product-image-link');
								lnkProImg.href = "javascript:void(0);";
								Event.add(lnkProImg, "click", function() { javascript:showElement('zoom-container');});
								
								//Change Enlarge Text into zoom and its links also
								var lnkEnlarge = document.getElementById('pc-enlarge');
								var pickText = document.createTextNode(lbl);
								var picklink = document.createElement('A');
									picklink.href = "javascript:void(0);";
									picklink.title = lbl;
									picklink.className = "zoom";
									//picklink.rel = "lightbox";									
									Event.add(picklink, "click", function() { javascript:showElement('zoom-container');});
									//add text
									picklink.appendChild(pickText);
									lnkEnlarge.innerHTML = "";
									lnkEnlarge.appendChild(picklink);
								//lnkEnlarge.innerHTML = picklink.innerHTML;
								
								
								container.innerHTML = "";
								for(i=0;i<totFiles;i++){
									// Create a new <li> element for to insert inside <ul>
									var new_li_element = document.createElement('li');
									//create image
									var img = document.createElement('IMG')
									img.src = imgBase[i];
									img.align = 'middle';
									img.border = 0;									

									//create href
									var zlink = document.createElement('A');
									zlink.href = '#';
									zlink.title = pname;
									zlink.className = 'zoom';
									
									//Add Click Event
									Event.add(zlink, "click", function() { switchTo(event, "'" + xmlBase[i] + "'");});
									
									//Event.add(link, "click", function() { javascript:showElement('zoom-container');});
									
									//add iamge
									zlink.appendChild(img);
									
									//add href
									new_li_element.appendChild(zlink);									
									//add li
									container.appendChild(new_li_element);
								}
								alert(container.innerHTML);
							}
						}
						
						//Get the selected variant id and set the product data						
						
						//AjaxCache.set(cacheKey, json);
					};
					
					this.ajax.get();
					
					Debug.w(this.ajax.response);
				//}
			break;
		}
	},
	setVariant : function(e, property) {
		Debug.w("Set Variant");
		
		switch (property) {
			case "size":
				Debug.w("Set Size");
				
				//var cacheKey = "selectmattress" + e.value + this.selectedVariant;
				
				// Test the cache
				//var cache = AjaxCache.get(cacheKey);
				//if (cache) {
				//	if (cache.base) {
				//		FormUtils.populateDropDown(Product.baseVariant, cache.base, Product.selectedBaseText);
				//	}
				//	if (cache.draw) {
				//		FormUtils.populateDropDown(Product.drawVariant, cache.draw, Product.selectedVariant);
				//	}
				//
				//	this.selectionTotal.innerHTML = this.selectedTotal.replace("##TOTAL##",  this.selectedTotalText);
				//							
				//} else {
				
					
					this.ajax.set(document.forms[0].action, {"ajax": "true", "action": "selectmattress", "size": e.value});
					this.ajax.busy = function() {

						//size inputs
						var size_variant = document.getElementById('size-variant').getElementsByTagName('input');
						for (inputVal=0;inputVal<=size_variant.length-2;inputVal=inputVal+1) 
						{
							if(size_variant[inputVal].id!=e.id){
								size_variant[inputVal].onclick=null;
								ajax_hide_loading(size_variant[inputVal].id);
								ajax_hide_loading(e);
							}

						}
					};

					this.ajax.complete = function() {
						Debug.w(this.response);
						ajax_hide_loading(e);
												
						var json = this.toJson();	

						if (json.base) {
							FormUtils.populateDropDown(Product.baseVariant, json.base, Product.selectedBaseText);
						}
						if (json.draw) {
							FormUtils.populateDropDown(Product.drawVariant, json.draw, Product.selectedVariant);
						}
						
						//Get the selected variant id and set the product data
						this.selectedVariant = Product.getVariantId();
						Product.setProductData(this.selectedVariant);
						
						Product.selectionSize.innerHTML = Product.productData.message;
						Product.selectionTotal.innerHTML = Product.selectedTotal.replace("##TOTAL##", Product.getTotal());
						
						document.getElementById(e.id).checked = true;
						
						//AjaxCache.set(cacheKey, json);
					};
					
					this.ajax.get();
					
					Debug.w(this.ajax.response);
				//}
			break;
			case "base":
				Debug.w("Set Base");
				
				//var cacheKey = "selectbase" + e.value + this.selectedVariant;
				
				// Test the cache
				//var cache = AjaxCache.get(cacheKey);
				//if (cache) {
				//	if (cache.draw) {
				//		FormUtils.populateDropDown(Product.drawVariant, cache.draw, Product.selectedVariant);
				//		this.selectionTotal.innerHTML = this.selectedTotal.replace("##TOTAL##", this.selectedTotalText);
				//	}
				//	
				//} else {
					this.ajax.set(document.forms[0].action, {"ajax": "true", "action": "selectbase", "size": FormUtils.getOption("rdSize"), "base": e.value });
					this.ajax.complete = function() {
						AjaxUtils.freeze();
						var json = this.toJson();
						Debug.w(this.response);
						
						if (json.draw != null) {
							FormUtils.populateDropDown(Product.drawVariant, json.draw, Product.selectedVariant);
						}
						
						//Get the selected variant id and set the product data
						this.selectedVariant = Product.getVariantId();
						Product.setProductData(this.selectedVariant);
					
						Product.selectionSize.innerHTML = Product.productData.message;
						Product.selectionTotal.innerHTML = Product.selectedTotal.replace("##TOTAL##", Product.getTotal());
						
						//AjaxCache.set(cacheKey, json);
						ajax_hide_loading(e);
					};
					this.ajax.busy = function() {
						AjaxUtils.freeze();
					};
					this.ajax.get();
					Debug.w(this.ajax.response);
				//}
			break;
			case "draw":
				
				//Get the selected variant id and set the product data
				this.selectedVariant = this.getVariantId();
				this.setProductData(this.selectedVariant);
				
				//alert(this.selectedVariant);
				
				Product.selectionSize.innerHTML = Product.productData.message;
				Product.selectionTotal.innerHTML = Product.selectedTotal.replace("##TOTAL##", Product.getTotal());
			break;
			case "guarantee":
			
				//Get the selected variant id and set the product data
				this.selectedVariant = Product.getVariantId();
				Product.setProductData(this.selectedVariant);
				
				this.selectedGuarantee = convertToBoolean(e.value);
				
				if (this.selectedGuarantee) {
					this.selectionGuarantee.innerHTML = "With a 10 year Guarantee";
				} else {
					this.selectionGuarantee.innerHTML = "Without a 10 year Guarantee";
				}
				
				this.selectionTotal.innerHTML = this.selectedTotal.replace("##TOTAL##", this.getTotal());
			break;
			case "disposaltype":
				//Get the selected variant id and set the product data
				this.selectedVariant = Product.getVariantId();
				Product.setProductData(this.selectedVariant);
				
				this.selectedMattress = convertToBoolean(e.value);
				if(Product.productData.disposaltype=='disposalbed')
				{
					if (this.selectedMattress) {
						this.selectionDisposal.innerHTML = "You would like us to dispose of your existing bed";
					} else {
						this.selectionDisposal.innerHTML = "You would not like us to dispose of your existing bed";
					}
				}
				else
				{
					if (this.selectedMattress) {
						this.selectionDisposal.innerHTML = "You would like us to dispose of your existing mattress";
					} else {
						this.selectionDisposal.innerHTML = "You would not like us to dispose of your existing mattress";
					}
				}
				this.selectionTotal.innerHTML = this.selectedTotal.replace("##TOTAL##", this.getTotal());
			break;

		}	
		
	},
	setQuantity : function() {
		this.selectionTotal.innerHTML = this.selectedTotal.replace("##TOTAL##", this.getTotal());
	},
	getQuantity : function() {
	
		var quantityDDIndex  = this.quantityVariant.selectedIndex;
		return quantity = this.quantityVariant.options[quantityDDIndex].value;
		
	},
	getTotal : function() {
	
		if (!Product.productData) {
			Product.setProductData();
		}
	
		var guarantee = FormUtils.getOption("rdGuarantee");
		var disposal = FormUtils.getOption("rdDisposal");
		var quantity = this.getQuantity();
		var total = null;
		
		if (guarantee && disposal && convertToBoolean(guarantee) && convertToBoolean(disposal)) {
			total = Product.productData.priceguaranteedisposal;
		}
		else if (guarantee && convertToBoolean(guarantee)) {
			total = Product.productData.priceguarantee;
		}
		else if (disposal && convertToBoolean(disposal)) {
			total = Product.productData.pricedisposal;
		}
		else {
			total = Product.productData.price;
		}
		
		if (quantity > 1) {
		
			//Remove commas
			total = total.replace(",", "");
		
			var sign = total.substr(0,1);
			
			var amount = total.substr(1);
			amount = amount * quantity;
			
			amount = priceformat(amount);
			
			//Add commas for 
			if (parseFloat(amount) > 999) {
				
				amount = amount + "";
			
				var formattedAmount = "";
			
				var i=0;
				var j=1;
				for (i=amount.length-1; i>=0; i--) {
					if (j==3) {
						formattedAmount = "," + amount.charAt(i) + formattedAmount;
						j=0;
					} else {
						formattedAmount = amount.charAt(i) + formattedAmount;
					}
					
					j++;
				}
				
				amount = formattedAmount;
			}
			
			total = sign + amount;
		}
		
		return total;
	},
	getVariantId : function() {
		
		//Get the variant id, work backwards
		//1. check the draw option drop down, if its not visible...
		//2. check the base option drop down, if its not visible...
		//3. check the size radio button group
	
		var drawVariant = document.getElementById("draw-variant");
		if (drawVariant) {
			var select = drawVariant.getElementsByTagName("select")[0];
			return select.value;
		}
		else
		{
			var baseVariant = document.getElementById("base-variant");
			if (baseVariant) {
				var select = baseVariant.getElementsByTagName("select")[0];
				return select.value;
			}
			else
			{
				return FormUtils.getOption("rdSize");
			}
		}
	}
};

/* Product Layout
 ------------------------------*/
 var Layout = {
	toggleProductList : function() {
		var list = document.getElementById("products-list");
		if (list) {
			if (/matrix-layout/.test(list.className)) {
				list.className = list.className.replace(" matrix-layout", "");
			} else {
				list.className += " matrix-layout";
			}
		}
	}
 };
 
// Added by Jeremy Thompson
// Format the price appropriately.
// Removes the decimal place if no decimal place (just displays pounds)
// e.g. 9.00 = 9 and 9.99 = 9.99
//
// Also adds an extra zero if pence is a multiple of ten 
// e.g. 99.90 is out as 99.9 so we need to add the extra 0 to the price as a string
function priceformat(num) {

pence = num % 1;
pounds = Math.round((num - pence));

priceString = pounds;

if (pence > 0)
{
	pence = Math.round((num % 1)*100); 
	priceString = priceString + "." + pence;
	
	//if (pence < 100) {
	//	priceString = priceString + "0";
	//}
	
	priceString;
}

// For anyone wondering % is the operator for modulus (returns the remainder of a division)
//if ((num % 1) == 0)
//{
//	priceString = num.toString();
//	parts = priceString.split(".");
//	num = parts[0];
//} else {
//	priceString = num.toString();
//    parts = priceString.split(".");
    
//    if(parts[1].Length == 1)
//    {
//		num = parts[1] + "0";
//    }
//}

//numString = num.toString();

//if (numString.Length ==)
//numString = numString + "0";

return priceString;
}


/*

Zoom functionality Help Functions
*/

//Zoom Viewer
var viewer = null;
function makeControlUp() {
				var controlUp = document.createElement("a");
				var controlUpText = document.createTextNode("Up"); 
				//var controlUpImg = document.createImageNode("top.png");
				controlUp.href = "#"; 
				controlUp.title = "Move image up (You can also click and drag with your mouse to move the image)"; 				            
				controlUp.className = "up";
				controlUp.id = "up-button";
				controlUp.appendChild(controlUpText);
				Seadragon.Utils.addEvent(controlUp, "click", onControlClickUp);
				return controlUp;
			}
			function makeControlDn() {
				var controlDn = document.createElement("a");
				var controlDnText = document.createTextNode("Down");
				controlDn.href = "#"; 
				controlDn.title = "Move image down (You can also click and drag with your mouse to move the image)"; 
				controlDn.className = "down";
				controlDn.id = "down-button";				
				controlDn.appendChild(controlDnText);
				Seadragon.Utils.addEvent(controlDn, "click", onControlClickDn);
				return controlDn;
			}
			function makeControlLt() {
				var controlLt = document.createElement("a");
				var controlLtText = document.createTextNode("Left");
				controlLt.href = "#"; 
				controlLt.title = "Move image left (You can also click and drag with your mouse to move the image)"; 
				controlLt.className = "left";
				controlLt.id = "left-button";				
				controlLt.appendChild(controlLtText);
				Seadragon.Utils.addEvent(controlLt, "click", onControlClickLt);
				return controlLt;
			}
				function makeControlRt() {
				var controlRt = document.createElement("a");
				var controlRtText = document.createTextNode("Right");
				controlRt.href = "#"; 
				controlRt.title = "Move image right (You can also click and drag with your mouse to move the image)"; 
				controlRt.className = "right";
				controlRt.id = "right-button";				
				controlRt.appendChild(controlRtText);
				Seadragon.Utils.addEvent(controlRt, "click", onControlClickRt);
				return controlRt;
			}
			
            function onControlClickUp(event) {
				Seadragon.Utils.cancelEvent(event);    // so link isn't processed 
				if (!viewer.isOpen()) {return;}    
				
				var currentPoint=viewer.viewport.getCenter().toString();

				var currentPointArray=currentPoint.split(",");
				var x=currentPointArray[0];
				var y=currentPointArray[1];
				
				x=x.replace("(","");
				y=y.replace(")","");
	
				x=x/1;	
				y=y/1;
				
				y=y-0.05;
				
				viewer.viewport.panTo(new Seadragon.Point(x,y));
				viewer.viewport.ensureVisible(); 
				canvasDSFix();
		
				}                        
			
			function onControlClickDn(event) {
				Seadragon.Utils.cancelEvent(event);    // so link isn't processed 
				if (!viewer.isOpen()) {return;}    
				
				var currentPoint=viewer.viewport.getCenter().toString();

				var currentPointArray=currentPoint.split(",");
				var x=currentPointArray[0];
				var y=currentPointArray[1];
				
				x=x.replace("(","");
				y=y.replace(")","");
	
				x=x/1;	
				y=y/1;
				
				y=y+0.05;
				
				viewer.viewport.panTo(new Seadragon.Point(x,y));	
			    canvasDSFix();       
				viewer.viewport.ensureVisible();            
			}       
			function onControlClickLt(event) {
			
			}
			
			function onControlClickLt(event) {
				Seadragon.Utils.cancelEvent(event);    // so link isn't processed 
				if (!viewer.isOpen()) {return;}    
				
				var currentPoint=viewer.viewport.getCenter().toString();

				var currentPointArray=currentPoint.split(",");
				var x=currentPointArray[0];
				var y=currentPointArray[1];
				
				x=x.replace("(","");
				y=y.replace(")","");
	
				x=x/1;	
				y=y/1;
				
				x=x-0.05;
				
				viewer.viewport.panTo(new Seadragon.Point(x,y));	
			    canvasDSFix();       
				viewer.viewport.ensureVisible();           
			}      
			
			function onControlClickRt(event) {
				Seadragon.Utils.cancelEvent(event);    // so link isn't processed 
				if (!viewer.isOpen()) {return;}    
				
				var currentPoint=viewer.viewport.getCenter().toString();

				var currentPointArray=currentPoint.split(",");
				var x=currentPointArray[0];
				var y=currentPointArray[1];
				
				x=x.replace("(","");
				y=y.replace(")","");
	
				x=x/1;	
				y=y/1;
				
				x=x+0.05;
				
				viewer.viewport.panTo(new Seadragon.Point(x,y));	
			    canvasDSFix();       
				viewer.viewport.ensureVisible();          
			}
			
			function switchTo(event, dzi) {
                if (dzi) {
                    viewer.openDzi(dzi);
                } else {
                    viewer.close();
                }
                
                Seadragon.Utils.cancelEvent(event);    // so links aren't processed
            }