
function isDefined(variable) {
    return (typeof(window[variable]) == "undefined") ?  false : true;
}

function showVariations() {
	if(productlist[selectedProduct]['variations']) {
		variationsHTML = '';
		for(i=1;i<productlist[selectedProduct]['variations'].length;i++) {
			variationsHTML += '<input type="radio" name="variations" class="radio variation" id="variation-' + i + '"';
			variationsHTML += ' value="' + productlist[selectedProduct]['variations'][i]['weight'] + '"';
			variationsHTML += ' onclick="showResult()"';
			if(i == 1)
				variationsHTML += ' checked="checked"';
			variationsHTML += ' />';
			variationsHTML += '<label for="variation-' + i + '" onclick="showResult()" class="radio">';
			variationsHTML += productlist[selectedProduct]['variations'][i]['name'];
			variationsHTML += '</label>';
		}
		variations.innerHTML = variationsHTML;
	}
	else {
		variations.innerHTML = '';
	}
}

function getSelectedVariationWeight() {
	if(productlist[selectedProduct]['variations']) {
		for(i=1;i<productlist[selectedProduct]['variations'].length;i++) {
			if(document.getElementById('variation-' + i).checked) {
				return document.getElementById('variation-' + i).value;
			}
		}
	}
	else {
		return false;
	}
}

function loadProductInfo() {
	selectedProduct = products.options[products.selectedIndex].value;
	productTitle.innerHTML = productlist[selectedProduct]['title'];
	productDescription.innerHTML = productlist[selectedProduct]['description'];
	showVariations();
}

function showResult() {
	resultToShow = 0;
	if(getSelectedVariationWeight()) {
		widthContainer.style.display = 'block';
		variationWeight = getSelectedVariationWeight();
		resultToShow = variationWeight * length.value * width.value;
	}
	else {
		if(productlist[selectedProduct]['nowidth']) {
			widthContainer.style.display = 'none';
			resultToShow = productlist[selectedProduct]['weight'] * length.value;
		}
		else {
			widthContainer.style.display = 'block';
			resultToShow = productlist[selectedProduct]['weight'] * length.value * width.value;
		}
	}
	resultToShow = Math.round(resultToShow*100)/100;
	result.value = addCommas(resultToShow) + ' ' + productlist[selectedProduct]['unit'];
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

