var imgFormat		= 'http://images.americas.creative.com/images/products/large/[id].png';
var buyButtonImg	= '/images/shop/cartaddusa_1_1_70.gif';
var buyButtonLink	= 'http://us.store.creative.com/addToCart.htm?asin=[ref]&amazonProduct=false&hasVariations=false';
var chkButtonImg	= '/images/shop/buynowusa_1_1_70.gif';
var chkButtonLink	= 'http://us.store.creative.com/[ref]/M/[ref].htm';
//var chkStockLink	= 'http://us.store.creative.com/api/products/[ref]-M?products.properties=offersSummary';
var chkStockLink	= '/products/stockQuery.asp';

var buyButtonObj	= { img: buyButtonImg, link: buyButtonLink, height: 30, width: 149 };
var chkButtonObj	= { img: chkButtonImg, link: chkButtonLink, height: 30, width: 84 };

var tmpXmlObj		= null;

function createXmlHttpObj() {
	var xmlhttp = null;
	if (window.XMLHttpRequest) { // code for all new browsers
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {// code for IE5 and IE6
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	tmpXmlObj	= xmlhttp;
	return xmlhttp;
}


function createProductObject( prodID, prodParentID, prodName, prodDesc, prodSku, prodPrice, prodCapacity, prodColor, prodShopStatus, prodRef, prodListPrice ) {
	return {
		id:			prodID,
		parentID:	prodParentID,
		name:		prodName,
		desc:		prodDesc,
		sku:		prodSku,
		price:		prodPrice,
		listPrice:	prodListPrice,
		capacity:	prodCapacity,
		color:		prodColor,
		shopStatus:	prodShopStatus,
		ref:		prodRef
	};
}

// Adds new option to select list
function addNewOption( optionText, optionValue, selectList, isSelected ) {
	if (optionText != null && optionValue != null && selectList != null) {
		selectList.options[selectList.length] = new Option(optionText, optionValue);
		if (isSelected) { selectList.options[selectList.length - 1].selected = true; }
	}
}

// Removes all options
function removeOptions( selectList ) {
	var selMax		= selectList.length - 1;
	for (var i=selMax; i >= 0; i--) {
		selectList.options[i]		= null;
	}
}


function formatCurrency(input) {
	if (input != null || !isNaN(input)) {
		input			= Math.round(input * 100);
		input			= String(input);
		input			= '$' + input.substring(0,input.length-2) + '.' + input.substring(input.length-2);
		return input;
	}
	return null;
}


Prototype.attrSelect = Class.create();
Prototype.attrSelect.prototype = {
	
	/* *********************** FireFox "Select" hack to be like IE ***********************
		This script is used to bind the "keyUp" event for any product selectors to make
		them fire similar to that of IE
	*/
	Firefox_select_scroll_hack: function(Ev) {
		// prevent tab, alt, ctrl keys from fireing the event
		if (Ev.keyCode && (Ev.keyCode == 1 || Ev.keyCode == 9 || 
		    Ev.keyCode == 16 || Ev.altKey || Ev.ctrlKey))
			return true;
		Ev.target.onchange();
		return true;
	},
	
	initialize: function(productList, select1, select2, name, desc, price, sku, image, btnWrapper, saveMessage, overlayImg) {
		this.instance			= this;
		this.products			= productList;
		this.select1			= $$('#' + select1)[0];
		this.select2			= $$('#' + select2)[0];
		
		// Optionals
		if (sku != null && sku.length > 0)
			this.displaySku		= $$('#' + sku)[0];
		
		if (image != null && image.length > 0)
			this.image			= $$('#' + image)[0];
		
		if (overlayImg != null && overlayImg.length > 0)
			this.overlayImg		= $$('#' + overlayImg)[0];
		
		if (btnWrapper != null && btnWrapper.length > 0)
			this.btnWrapper		= $$('#' + btnWrapper)[0];
		
		if (name != null && name.length > 0)
			this.name			= $$('#' + name)[0];
		
		if (desc != null && desc.length > 0)
			this.desc			= $$('#' + desc)[0];
		
		if (price != null && price.length > 0)
			this.price			= $$('#' + price)[0];
		
		if (saveMessage != null && saveMessage.length > 0)
			this.saveMessage	= $$('#' + saveMessage)[0];
		
		//this.xmlObj				= createXmlHttpObj();
		this.ajaxObj			= window.AjaxWrapper;
		
		this.capList			= null;
		this.colorList			= null;
		this.select1Idx			= -1;
		this.select2Idx			= -1;
		
		this.selectedProduct	= null;
		this.selectType 		= 'none';
				
		this.select1.hide();
		this.select2.hide();
		this.btnWrapper.hide();

		
		this.initialSetup();
		this.setupSelectors();
		this.setProduct();
		this.setDisplays();
		
		this.registerCallbacks();
	},
	
	
	registerCallbacks: function() {
		if (this.selectType == 'double' || (this.selectType == 'single' && this.colorList.length > 0)) {
			this.select2Handler = this.colorChange.bindAsEventListener(this);
			Event.observe(this.select2, 'change', this.select2Handler, false);
		}
		
		if (this.selectType == 'single' || this.selectType == 'double') {
			this.select1Handler = this.capacityChange.bindAsEventListener(this);
			Event.observe(this.select1, 'change', this.select1Handler, false);
		}
	},
	
	
	dispose: function() {
		if (this.select2Handler != null) {
			Event.stopObserving(this.select2, 'change', this.select2Handler, false);
			this.select2Handler = null;
		}
		
		if (this.select1Handler != null) {
			Event.stopObserving(this.select1, 'change', this.select1Handler, false);
			this.select1Handler = null;
		}
	},
	
	// Util function
	getReplaceString: function( replaceString ) {
		var tmpVar		= replaceString.replace( '[id]', this.selectedProduct.id ).replace( '[mpid]', this.selectedProduct.parentID );
		return tmpVar.replace( '[ref]', this.selectedProduct.ref ).replace( '[ref]', this.selectedProduct.ref );
	},
	
	getStatusImg: function() {
		if (this.selectedProduct != null && ovrlayImgFormat != null && ovrlayImgFormat.length > 0) {
			var status		= this.selectedProduct.shopStatus;
			if (status != null && status.length > 0 && status != 'null') {
				var statusReplace	= '';
				if (status == 'C' || status == 'S' || status == 'SC') {
					statusReplace	= 'save';
				} else if (status == 'R' || status == 'RP') {
					statusReplace	= 'refurb';
				} else if (status == 'M') {
					statusReplace	= 'rebate';
				} else if (status == 'N') {
					statusReplace	= 'now-available';
				} else if (status == 'P') {
					statusReplace	= 'promo';
				} else if (status == 'E') {
					statusReplace	= 'email';
				}
				
				if (statusReplace.length > 0) {
					return this.getReplaceString( ovrlayImgFormat.replace( '[status]', statusReplace ) );
				}
				return null;
			}
		}
		return null;
	},
	
	xmlRequest: function() {
		if (this.ajaxObj != null) {
			urlParams		= new Array();
			urlParams.push( this.ajaxObj.getParamObject( 'ref', this.selectedProduct.ref ) );
			urlParams.push( this.ajaxObj.getParamObject( 'id', this.selectedProduct.id ) );
			this.ajaxObj.setAjaxPage( this.getReplaceString( chkStockLink ) );
			this.ajaxObj.callAjax('stockQuery', urlParams, this.selectedProduct.ref, this, this.instance )
		}
	},
	
	refreshFromJSON: function(results) {
		var	stock	= 0;
		try {
			stock	= results.totalNew;
		} catch (ex) {
		}
		this.setButton( stock > 0 );
	},
	
/*	xmlRequest: function() {
		if (this.xmlObj != null) {
			this.xmlObj.onreadystatechange = this.xmlResponse;
//alert('url: ' + this.getReplaceString( chkStockLink ));
			this.xmlObj.open("GET", this.getReplaceString( chkStockLink ), true);
			this.xmlObj.send(null);
		}
	},
	
	xmlResponse: function(xmlObj) {
		if (tmpXmlObj.readyState == 4) { // 4 = "loaded"
			var status = 200;
			if (tmpXmlObj.status == 200) { // 200 = OK
				//this.setButton(false);
				alert('retrieved\n' + tmpXmlObj.responseText);
			} else {
				alert("Problem retrieving XML data");
			}
		}
	},
*/
	
	initialSetup: function() {
		if (this.displaySku != null) {
			this.displaySku.hide();
		}
		
		if (this.name != null) {
			this.name.hide();
		}
		
		if (this.desc != null) {
			this.desc.hide();
		}
		
		if (this.price != null) {
			this.price.hide();
		}
		
		// if more than one product determine type of selector setup
		if (this.products.length > 0) {
			
			// Retrieve capacity list
			this.capList = this.products.findAll(
				function(node) {
					return (node.capacity != null && node.capacity != 'null' && node.capacity.length > 0);
				}
			).pluck('capacity').uniq();
			
			// If no capacities then check for colors
			if (this.capList == null || this.capList.length == 0) {
				// try pulling colors
				this.colorList = this.products.findAll(
					function(node) {
						return (node.color != null && node.color != 'null' && node.color.length > 0);
					}
				).pluck('color').uniq();
				
				// Either color selector or generic product selector
				if (this.products.length == 1) {
					this.selectType = 'none';
				} else {
					this.selectType = 'single';
				}
				
				// If no colors populate it with products
				if (this.colorList == null || this.colorList.length == 0) {
					this.capList = this.products.findAll(
						function(node) {
							return (node.name != 'null' && node.name.length > 0);
						}
					).pluck('name').uniq();
				}
				
			// Setup colors for initial capacity (idx = 0)
			} else {
				
				// Sort numerically
				this.capList = this.capList.sortBy(
					function(node) {
						var numeric = parseInt(node);
						if (node.toUpperCase().indexOf("KB") > 0) { numeric = numeric * 1000; }
						if (node.toUpperCase().indexOf("MB") > 0) { numeric = numeric * 1000000; }
						if (node.toUpperCase().indexOf("GB") > 0) { numeric = numeric * 1000000000; }
						if (node.toUpperCase().indexOf("TB") > 0) { numeric = numeric * 1000000000000; }
						return (numeric);
					}
				);
				
				this.select1Idx		= 0;
				
				// try pulling colors
				this.colorList = this.products.findAll(
					function(node) {
						return ( node.color != null && node.color != 'null' && node.color.length > 0);
					}
				).pluck('color').uniq();
				
				if (this.colorList == null || this.colorList.length == 0) {
					this.selectType 	= 'single';
				} else {
					this.select2Idx		= 0;
					this.selectType 	= 'double';
				}
			}
		
		// No products
		} else {
			this.selectType = 'none';
		}
	},
	
	
	setupSelectors: function() {
		//addNewOption( capacities[i], capacities[i], this.capacitySelect, false );
		
		if (this.selectType != 'none') {
		
			removeOptions( this.select1 );
			
			if (this.capList.length > 0) {
				var selCap			= this.capList[this.select1Idx];
				
				for (var i=0; i < this.capList.length; i++) {
					addNewOption( this.capList[i], this.capList[i], this.select1, false );
				}
				
				this.select1.show();
			}
			
			
			if (this.selectType == 'double' || (this.selectType == 'single' && this.colorList.length > 0)) {
				this.setColorSelector();
				this.select2.show();
			}
		
		}	// End of check to make sure it's a selector type
	},
	
	
	setColorSelector: function() {
		removeOptions(this.select2);
		
		var selCap			= '';
		if (this.capList.length > 0) {
			selCap		= this.capList[this.select1Idx];
			
			// try pulling colors
			this.colorList = this.products.findAll(
				function(node) {
					return ( node.color != null && node.color != 'null' && node.color.length > 0 && node.capacity == selCap);
				}
			).pluck('color').uniq();
		} else {
			// try pulling colors
			this.colorList = this.products.findAll(
				function(node) {
					return ( node.color != null && node.color != 'null' && node.color.length > 0);
				}
			).pluck('color').uniq();
		}
		
		this.select2Idx	= 0;
		var selColor	= this.colorList[this.select2Idx];
		
		for (var i=0; i < this.colorList.length; i++) {
			addNewOption( this.colorList[i], this.colorList[i], this.select2, false );
		}
	},

	
	capacityChange: function() {
		this.select1Idx = this.select1.selectedIndex;
		this.setColorSelector();
		this.setProduct();
		this.setDisplays();
	},


	colorChange: function() {
		this.select2Idx = this.select2.selectedIndex;
		this.setProduct();
		this.setDisplays();
	},
	
	
	setProduct: function() {
		var selCap		= '';
		var selColor	= '';
		
		// If no selectors select first product if available
		if (this.selectType == null || this.selectType == 'none') {
			if (this.products.length > 0) {
				this.selectedProduct	= this.products[0];
			}
				
		
		// Find the product for single list type
		} else if (this.selectType == 'single') {
			
			// If only capacity
			if (this.capList != null && this.capList.length > 0) {
			
				selCap					= this.capList[this.select1Idx];
				this.selectedProduct	= this.products.findAll(
						function(node) {
							return ( node.capacity != null && node.capacity != 'null' && node.capacity.length > 0 && node.capacity == selCap);
						}
					).first();

			} else if (this.colorList != null && this.colorList.length > 0) {
				selColor				= this.colorList[this.select2Idx];
				this.selectedProduct	= this.products.findAll(
						function(node) {
							return ( node.color != null && node.color != 'null' && node.color.length > 0 && node.color == selColor);
						}
					).first();
				
			}
		
		
		// Find the product for double list type
		} else if (this.selectType == 'double') {
			
			selCap					= this.capList[this.select1Idx];
			selColor				= this.colorList[this.select2Idx];
			
			this.selectedProduct	= this.products.findAll(
					function(node) {
						return ( node.capacity != null && node.capacity != 'null' && node.capacity.length > 0 && node.capacity == selCap &&
							node.color != null && node.color != 'null' && node.color.length > 0 && node.color == selColor);
					}
				).first();
		
		// Otherwise empty
		} else {
			this.selectedProduct		= null;
		}
		
	},
	
	checkStock: function() {
		this.xmlRequest();
		//this.setButton(false);
	},
	
	setButton: function(hasStock) {
		//var hasStock = this.xmlRequest;
		//alert('hasStock: ' + hasStock);
		
		if (this.btnWrapper != null) {
			if (hasStock) {
				try {
					this.btnWrapper.innerHTML		= '<a href="' + this.getReplaceString(buyButtonObj.link) + '"><img src="' + this.getReplaceString(buyButtonObj.img) + '" height="' + buyButtonObj.height + '" width="' + buyButtonObj.width + '" alt="Add to Cart" title="Add to Cart" border="0"></a>';
				} catch (ex) {
					this.btnWrapper.innerHTML		= '<a href="' + this.getReplaceString(buyButtonLink) + '"><img src="' + this.getReplaceString(buyButtonImg) + '" alt="Add to Cart" title="Add to Cart" border="0"></a>';
				}
				this.btnWrapper.show();
			} else {
				try {
					this.btnWrapper.innerHTML		= '<a href="' + this.getReplaceString(chkButtonObj.link) + '"><img src="' + this.getReplaceString(chkButtonObj.img) + '" width="' + chkButtonObj.width + '" height="' + chkButtonObj.height + '" alt="Check Stock" title="Check Stock" border="0"></a>';
					//alert('<a href="' + this.getReplaceString(chkButtonObj.link) + '"><img src="' + this.getReplaceString(chkButtonObj.img) + '" width="' + chkButtonObj.width + '" height="' + chkButtonObj.height + '" alt="Check Stock" title="Check Stock" border="0"></a>');
				} catch (ex) {
					this.btnWrapper.innerHTML		= '<a href="' + this.getReplaceString(chkButtonLink) + '"><img src="' + this.getReplaceString(chkButtonImg) + '" alt="Check Stock" title="Check Stock" border="0"></a>';
				}
				this.btnWrapper.show();
			}
		}
	},
	
	setDisplays: function() {
		// Only work if selected product is set
		if (this.selectedProduct != null) {
			if (this.selectType == 'none') {
				this.select1.hide();
				this.select2.hide();
			} else if (this.selectType == 'single' && this.capList.length > 0) {
				this.select1.show();
				this.select2.hide();
			} else if (this.selectType == 'single' && this.colorList.length > 0) {
				this.select2.show();
				this.select1.hide();
			} else if (this.selectType == 'double') {
				this.select1.show();
				this.select2.show();
			}
			
			// Handles button linking
			this.checkStock();
			
			// Sku display
			if (this.displaySku != null) {
				this.displaySku.show();
				try {
					this.displaySku.innerHTML	= this.selectedProduct.sku;
				} catch (ex) {
					this.displaySku.value		= this.selectedProduct.sku;
				}
			}
						
			// Product Name
			if (this.name != null) {
				this.name.show();
				try {
					this.name.innerHTML			= this.selectedProduct.name;
				} catch (ex) {
					this.name.value				= this.selectedProduct.name;
				}
			}
			
			// Product Description
			if (this.desc != null) {
				this.desc.show();
				try {
					this.desc.innerHTML			= this.selectedProduct.desc;
				} catch (ex) {
					this.desc.value				= this.selectedProduct.desc;
				}
			}
			
			// Price
			if (this.price != null) {
				this.price.show();
				try {
					this.price.innerHTML		= formatCurrency( this.selectedProduct.price );
				} catch (ex) {
					this.price.value			= formatCurrency( this.selectedProduct.price );
				}
			}
			
			// Image swap
			if (this.image != null) {
				try {
					this.image.src				= this.getReplaceString(imgFormat);
				} catch (ex) {
				}
			}
			
			// Overlay img
			if (this.overlayImg != null) {
				if (this.selectedProduct.shopStatus != null && this.selectedProduct.shopStatus.length > 0) {
					try {
						this.overlayImg.src			= this.getStatusImg();
						this.overlayImg.show();
					} catch (ex) {
					} 
				} else {
					this.overlayImg.hide();
				}
			}
			
			if (this.saveMessage != null) {
				if (this.selectedProduct.listPrice != null && this.selectedProduct.listPrice > 0 && this.selectedProduct.listPrice > this.selectedProduct.price ) {
					var saveMsg						= this.getSaveMessage(this.selectedProduct.listPrice, this.selectedProduct.price);
					try {
						this.saveMessage.innerHTML	= saveMsg;
					} catch (ex) {
						this.saveMessage.value		= saveMsg;
					}
					this.saveMessage.show();
				} else {
					this.saveMessage.hide();
				}
			}
			
		}	// End of selected product check
	},
	
	formatSaveMsg: function(number) {
		if (number <= 0 || isNaN(number)) {
			return "";
		}
		return 'Save ' + Math.round(number) + '%';
	},
	
	formatCurrency: function(input) {
		if (input != null || !isNaN(input)) {
			input			= Math.round(input * 100);
			input			= String(input);
			input			= '$' + input.substring(0,input.length-2) + '.' + input.substring(input.length-2);
			return input;
		}
		return null;
	},
	
	getSaveMessage: function(listPrice, price) {
		var priceDiff		= 0.0;
		if (listPrice != null && price != null) {
			try {
				priceDiff		= listPrice - price;
			} catch (ex) {
			}
		}
		
		var saveMsg				= '';
		
		if (priceDiff > 5.0) {
			saveMsg				= 'Save ' + this.formatCurrency(priceDiff);
		} else if (priceDiff > 0.01) {
			var savePercent		= Math.round(priceDiff / listPrice * 100);
			saveMsg				= this.formatSaveMsg(savePercent);
		}
		return saveMsg;
	}
	
}
