/* Chooserific Coffee Finder */

coffeeAttributes = {
	acidity: 0,
	body: 0,
	flavor: 0,
	aroma: 0
}

setCoffeeAttributesFromHTML = function() {
	// HTML form based input
	var form = document.getElementById("chooser");
	// get acidity
	for (var i=0; i<form.acidity.length; i++) {
		if (form.acidity[i].checked) {
			coffeeAttributes.acidity = form.acidity[i].value;
			break;
		}
	}
	// get body
	for (var i=0; i<form.body.length; i++) {
		if (form.body[i].checked) {
			coffeeAttributes.body = form.body[i].value;
			break;
		}
	}
	// get flavor
	for (var i=0; i<form.flavor.length; i++) {
		if (form.flavor[i].checked) {
			coffeeAttributes.flavor = form.flavor[i].value;
			break;
		}
	}
	// get aroma
	for (var i=0; i<form.aroma.length; i++) {
		if (form.aroma[i].checked) {
			coffeeAttributes.aroma = form.aroma[i].value;
			break;
		}
	}
	getCoffeeRecommendation();
};

setCoffeeAttributesFromFlash = function(attribute,value) {
	coffeeAttributes[attribute] = value;
	getCoffeeRecommendation();
};

getCoffeeRecommendation = function() {
	// don't do the server side lookup unless we have to
	var checkAgainstCurrentChoice = coffeeAttributes.acidity + "." + coffeeAttributes.body + "." + coffeeAttributes.flavor + "." + coffeeAttributes.aroma;
	if (checkAgainstCurrentChoice == currentChoice) return;
	else currentChoice = checkAgainstCurrentChoice;
	
	var url = "get-recommendations.php?dummyvar=1";
	if (coffeeAttributes.acidity) url += "&acidity=" + coffeeAttributes.acidity;
	if (coffeeAttributes.body) url += "&body=" + coffeeAttributes.body;
	if (coffeeAttributes.flavor) url += "&flavor=" + coffeeAttributes.flavor;
	if (coffeeAttributes.aroma) url += "&aroma=" + coffeeAttributes.aroma;
	
	var xmlhttp = setupAJAX();
	loadFragmentInToElement(xmlhttp,url,"results")
};

chooserificInit = function() {
	if (!document.getElementById || !xmlhttp) return;
	// variable to record the current choice
	currentChoice = 0;
	// add calculation functions to each input box
	var chooser = document.getElementById("chooser");
	var inputs = chooser.getElementsByTagName("INPUT");
	for (var i=0; i<inputs.length; i++) {
		inputs[i].onclick = function() {		
			setCoffeeAttributesFromHTML();
		};
	}	
};

xmlhttp = setupAJAX();
// if this browser can do ajax then show the chooserific
if (xmlhttp) {	
	document.write("<style type=\"text/css\">");
	// if there have javascript hide the wholesale login
	document.write("body#chooserific #chooser { display: block; }");
	document.write("body#chooserific #recommendedcoffee { display: block; }");
	document.write("body#chooserific #incompatible { display: none; }");
	document.write("</style>");
}

addLoadEvent(chooserificInit);
