﻿var items = new Array();

function Item(id, productId, name, code, outOfStock, categoryMapping) {
	var item = new Object();
	item.ProductId = productId;
	item.Id = id;
	item.ItemName = name;
	item.ItemCode = code;
	item.OutOfStock = outOfStock;
	item.CategoryMapping = categoryMapping;
	
	return item;
}

function AddItem(id, productId, name, code, outOfStock, categoryMapping) {
	items.push(new Item(id, productId, name, code, outOfStock, categoryMapping));
}

function StockAvailable(id) {
	var item = FindItem(id);

	if (item == null) {
		return false;
	}
		
	return !item.OutOfStock;
}

function FindItem(id) {	
	for(var i = 0; i < items.length; i++) {
		if (items[i].Id == id) {
			return items[i];
		}
	}
	
	return null;
}


function FindItemByCategory(categoryMapping) {	
	for(var i = 0; i < items.length; i++) {
		if (items[i].CategoryMapping == categoryMapping) {
			return items[i];
		}
	}
	
	return null;
}

function AddToCart(itemId, quantity, autoship) {
	//Check to make sure we have a valid itemId
	if (itemId != false) {
		// Check stock
		if (StockAvailable(itemId)) {
			window.location.href = 'addItem.aspx?itemId=' + itemId + '&qty=' + quantity + '&autoship=' + (autoship || 0) + "&previous=" + encodeURIComponent(window.location.href);
		} else {
			AlertOutOfStock();
			return false;
		}
	} 
}

function AddToWishList(itemId) {
	window.location.href = 'additem.aspx?wlItemId=' + itemId;
}

function AlertOutOfStock() {
	alert('Sorry, this item is currently out of stock');
}

function ResolveSelectedItem() {
	var argLength = arguments.length;	
	var categoryMapping = [];
	var el;
	
	
	for(var i = 0; i < argLength; i++) {
		el = document.getElementById(arguments[i]);
		switch(el.tagName.toLowerCase()) {
			case 'span': // radiobuttonlist wrapper
				categoryMapping.push(FindSelectedRadioButton(arguments[i] + '_*'));
				break;
			case 'select':
				categoryMapping.push(el.options[el.selectedIndex].value);
				break;
		}
	}
	
	//Check to make sure any of the selections were not default selections - Please Select ...
	for (var i in categoryMapping) {
		if (categoryMapping[i] == 0) {
			alert('Please make a valid selection before adding this to your cart');
			return false;
		}
	}

	// Sort it ascending so that the category string will match the item
	categoryMapping.sort(function(a, b) { return a - b })
		
	var item = FindItemByCategory(categoryMapping.join(','));
	
	if(item == null) {
		alert('Sorry, we don\'t carry this item combination');
		return false;
	}
	
	return item.Id;
}

function FindSelectedRadioButton(nameRegEx) {
	var re = new RegExp(nameRegEx)	
	var el;	
	
	for(var i = 0; i < document.forms[0].elements.length; i++) {
		el = document.forms[0].elements[i];
		
		if(el.type.toLowerCase() == 'radio') {
			if (re.test(el.id) && el.checked) {
				return el.value;
			}
		}
	}
	
	return -1;
}