

var elementgroups = null;
var element = null;
var noChoices = false;
var elementData = null;

function initGuiFromCalculationDataId(lineid) {
	if (lineid != null) {
		AjaxService.getCalculationData(lineid, initGuiFromCalculationData);
	}
}

function initGuiFromCalculationData(cd) { 
	if (cd.selectedElementTypeID != null) {
		elementData = cd
		DWRUtil.setValue("productline", elementData.selectedProductLineID);
		DWRUtil.setValue("elementtype", elementData.selectedElementTypeID);
		
		DWRUtil.setValues({
			dimensionwidth: elementData.selectedWidth,
			dimensionheight: elementData.selectedHeight,
			noofelements: elementData.numberOfElements,
			comment: elementData.comment
		});
		
		if (elementData.selectedElementTypeID > 0) {
			Calculator.getElementgroups($("elementtype").value, morePreparation);
		}
	}		
}

function morePreparation(groups) {
	afterChangeElementType(groups);
	DWRUtil.setValue("elementgroup", elementData.selectedElementGroupID);

	AjaxService.buildChoiceTables(elementData, preparationStep3);

}

function preparationStep3(choices) {
	populateChoiceTables(choices);
	
	changeElementGroup(); // This also recalculates
}

function initGuiFromTypeAndGroup(typeID, groupID) {
	DWRUtil.setValue("elementtype", typeID);
	Calculator.getElementgroups($("elementtype").value, 
		function(groups) { 
			afterChangeElementType(groups);
			DWRUtil.setValue("elementgroup", groupID);
			changeElementGroup();
		}
	);
}

function changeProductLine() {
	var id = DWRUtil.getValue("productline");
	if (id > 0) {
		Calculator.getElementtypes(id, afterChangeProductLine);
	}
}

function afterChangeProductLine(elementTypes) {
	var egid = DWRUtil.getValue("elementgroup");
	
	DWRUtil.removeAllOptions("elementtype");
	DWRUtil.removeAllOptions("elementgroup");
	DWRUtil.addOptions("elementtype", ["Vælg type..."] );
	DWRUtil.addOptions("elementtype", elementTypes, "elementTypeId", "name");
	
	if (egid > 0) {
		Calculator.getSiblingInProductLine(DWRUtil.getValue("productline"), egid, afterFindSiblings);
	}
}

var currentSibling = null;
function afterFindSiblings(siblingMap) {
	// There is only one, but this way we will get the right index
	for (var i in siblingMap) {
		currentSibling = siblingMap[i];
		currentSibling.elementtype = { elementTypeId: i };
	}
	DWRUtil.setValue("elementtype", currentSibling.elementtype.elementTypeId);
	changeElementType();
}


function changeElementType() {
	var id = DWRUtil.getValue("elementtype");
	if (id > 0) {
		Calculator.getElementgroups(id, afterChangeElementType);
		$("productimage").src = "";
	}
}

function afterChangeElementType(a_elementgroups) {
	elementgroups = a_elementgroups;
	DWRUtil.removeAllOptions("elementgroup");
	DWRUtil.addOptions("elementgroup", ["Vælg element..."] );
	DWRUtil.addOptions("elementgroup", a_elementgroups, "elementgroupId", "name");
	if (currentSibling != null) {
		DWRUtil.setValue("elementgroup", currentSibling.elementgroupId);
		currentSibling = null;
		changeElementGroup();
	}
}

function changeElementGroup() {
	var group = getSelectedElementgroup();
	if (group != null) {
		minDim = group.minimumDimension;
		maxDim = group.maximumDimension;
		DWRUtil.setValues( {
			widthDimensions: 	minDim.width.toFixed(1) + "-" + maxDim.width.toFixed(1),
			heightDimensions: 	minDim.height.toFixed(1) + "-" + maxDim.height.toFixed(1)
		} );
		loadGroupImage(group);
	}
	recalculate();
}

function loadGroupImage(group) {
	img = new Image();
	img.onerror = function() {
		$("productimage").width = "150";
		$("productimage").height = "";
		$("productimage").src = "/export/sites/dk.net2vinduer.web/billeder/produkter/nopicture.gif";
	}
	img.onload = function() {
/*		if (this.height > this.width) {
			$("productimage").width = "";
			$("productimage").height = "150";
		} else {
			$("productimage").width = "150";
			$("productimage").height = "";
		} */
		$("productimage").width = this.width;
		$("productimage").height = this.height;
		$("productimage").src = this.src;
	}
	img.src = "/billeder/produkter/" + group.productNumber + ".gif";
}

function recalculate(data) {
	if (canRecalculate()) {
		if (data == null) {
			data = createCalculationData();
		}
		Calculator.calculate(data, afterRecalculate);
	}
}

function afterRecalculate(data, reload) {
	reload = reload != null ? reload : true;
	element = data.source;
	elementData = null;
	setTotalPrice(data.result, false);
	if (reload) {
	 	getChoiceTables(createCalculationData());
 	}
}

function canRecalculate() {
	height = NET2Util.parseNumber($("dimensionheight").value);
	width = NET2Util.parseNumber($("dimensionwidth").value);
	cnt = parseInt($("noofelements").value);
	var group = getSelectedElementgroup();
	if (group != null) {
		minDim = group.minimumDimension;
		maxDim = group.maximumDimension;
		if ( 
			height >= minDim.height && height <= maxDim.height &&
			width  >= minDim.width  && width  <= maxDim.width &&
			cnt > 0
		) {
			return true;
		} else {
			setTotalPrice("Indtast venligst en korrekt størrelse og antal", true);
		}
	}
	return false;
}

function createCalculationData() {
	if (elementData != null) {
		return elementData;
	}
	return { // Should resolve to ElementCalculationDataBean
			selectedElementTypeID: 	parseInt($("elementtype").value),
			selectedElementGroupID: parseInt($("elementgroup").value),
			numberOfElements: 		parseInt($("noofelements").value),
			selectedWidth: 			NET2Util.parseNumber($("dimensionwidth").value), 
			selectedHeight: 		NET2Util.parseNumber($("dimensionheight").value),
			selectedChoices:		getSelectedChoices(),
			selectedElementID:		getCalculatedElement().elementId
	}
}

function getSelectedChoices() {
	choices = Array();
	
	if (!noChoices) {
		selects = document.getElementsByTagName("SELECT");
		for (var i = 0; i < selects.length; i++) {
			/* if (typeof(selects[i]) == "object") {
				var sb = "selects[" + i + "] {\n"
				for (var p in selects[i]) {
					sb += "\t" + p + ": " + selects[i][p] + ",\n";
				}
				sb += "}\n";
				alert(sb);
			} */
			
			if (selects[i].name == "choices") {
				v = selects[i].value;
				v = parseInt(v);
				if (!isNaN(v)) {
					choices[choices.length] = v;
				}
			}
		}
	}
	return choices;
}

function getCalculatedElement() {
	if (element != null) {
		return element;
	} else {
		return { elementId: null };
	}
}

function getSelectedElementgroup() {
	return getElementgroup($("elementgroup").value);
}

function getElementgroup(id) {
	if (elementgroups != null) {
		for (var e in elementgroups) {
			if (elementgroups[e].elementgroupId == id) {
				return elementgroups[e];
			}
		}
	}
	return null;
}

function setTotalPrice(price, error) {
	error = error != null ? error : false;
	$("priceBlock").style.display = "block";
	price = error ? price : NET2Util.formatCurrency(price);
	if (error) {
		$("totalPrice").style.color = "red";
		$("totalPrice").style.fontWeight = "normal";
	} else {
		$("totalPrice").style.color = "black";
		$("totalPrice").style.fontWeight = "bold";
		price += " DKK";
	} 
	DWRUtil.setValue("totalPrice", price);
}


function getChoiceTables(data) {
 	AjaxService.buildChoiceTables(data, populateChoiceTables);
}

function populateChoiceTables(tables) {
	DWRUtil.setValue("choicetables", tables);
	
	if (decoGreyboxLinks) {
		if(GB_SETS["info"]) { GB_SETS["info"] = []; }
		decoGreyboxLinks();
	}
}

function changeChoicetype(choiceTypeId) {
	AjaxService.changeChoice(choiceTypeId, createCalculationData(), afterChangeChoicetype);
}

function afterChangeChoicetype(data) {
	afterRecalculate(data[0], false);
	
	var id = "choicetype" + data[1].choiceTypeId;

	DWRUtil.removeAllOptions(id);
	DWRUtil.addOptions(id, data[2], 0, 1);

	for (var i in data[2]) {
		var c = data[2][i];
		if (c[2]) {
			$(id).options[i].selected = true;
		}
		if (!c[3]) {
			$(id).options[i].className = "unselectable";
		}
	}
}

// Not used any longer. To reactivate, change the AjaxService to include the button again.
function clearChoices() {
	noChoices = true;
	recalculate();
	noChoices = false;
}


function validateChoices() {
	for (var i = 0; i < selects.length; i++) {
		if (selects[i].name == "choices") {
			sel = selects[i];
			opt = sel.options[sel.selectedIndex];
			if (opt.className == "unselectable") {
				alert("Valget '" + opt.text + "' er ikke et gyldigt tilvalg. Vælg venligst et andet.");
				return false;
			}
		}
	}
	return true;
}

function beforeSubmit() {
	if (!canRecalculate()) { 
		alert("De kan ikke tilføje et element før De har angivet en korrekt størrelse");
		return false;
	} else if (!validateChoices()) {
		// alert("Mindst et af de valgte tilvalg er ikke gyldigt. De bedes vælge et gyldigt tilvalg og prøve igen.");
		return false;
	} else {
		return true;
	}
}

