var ProductOptions = {
	optionsSrc: null,
	
	// fonction de gestion du xml universel browser
	selectNodes: function (node, xpath) {
		if (node.xml) {
			return node.selectNodes(xpath);
		}
		var result = [];
		var xpathResult = node.ownerDocument.evaluate(xpath, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		for (var i=0; i<xpathResult.snapshotLength; i++) {
			result[i] = xpathResult.snapshotItem(i);
		}
		return result;
	},
	selectSingleNode: function (node, xpath) {
		if (node.xml) {
			return node.selectSingleNode(xpath);
		}
		return node.ownerDocument.evaluate(xpath, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	},
	
	toXML: function(node) {
		var output ="";
		if (!node ) 
			throw new Error("Undefined node to serialize");
		if (node.xml) return node.xml;
		if (node.nodeType==1) { // serialisation de l'element
			output = "<"+ node.nodeName
			if (node.attributes.length) {
				for (var i=0, l=node.attributes.length; i<l; i++) {
					output +=  this.toXML(node.attributes[i]);
				}
			}
			if (node.childNodes.length) {
				output += ">"
				for (var i=0, l=node.childNodes.length; i<l; i++) {
					output += this.toXML(node.childNodes[i]);
				} 
				output += "</"+ node.nodeName +">\n";
			} else {
				output += "/>\n";
			}
		} else if (node.nodeType==2) { // serialisation de l'attribut
			var value = node.nodeValue.replace(/&/gi, "&amp;");
			value = value.replace(/&/gi, "&amp;");
			value = value.replace(/"/gi, "&quot;");
			value = value.replace(/</gi, "&lt;");
			value = value.replace(/>/gi, "&gt;");
			output += " "+ node.nodeName +"=\""+ value +"\"";
		} else { // serialisation des autres types de noeud (text, cdata...)
			if (node.textContent)
				output += "<![CDATA["+ node.textContent +"]]>";
		}
		return output;
	},

	// gestion des options
	serialize: function(params) {
		$('idml_options_source').value = this.toXML(this.optionsSrc);
	},
	
	setInteractive: function () {
		// gère la selection par defaut de la première options des groupes select|radio qui n'ont pas de selection courante
		var defaultSelection = this.selectNodes(this.optionsSrc, "//options-group[(@type='radio' or @type='select') and not(option/@selected)]")
		for (var i=0, l=defaultSelection.length; i<l; i++) {
			var firstOption = this.selectSingleNode(defaultSelection[i], "option")
			if (firstOption) {
				firstOption.setAttribute("selected", "selected");
			}
		}
		// active la selection pour chaque option
		var options = this.selectNodes(this.optionsSrc, "//option[@selected]")
		for (var i=0, l=options.length; i<l; i++) {
			var option = options[i];
			var id = option.getAttribute("id");
			var input = $('#'+ id);
			if (input) {
				// met la valeur à jour
				input.value = option.getAttribute('type')=='custom' ? option.getAttribute("value") || "" : 1;
				this.setOption(input)
			}
			this.toggleBlock(id, option.getAttribute("selected") ? true : false);
		} 
	},
	
	clean: function() {
	},
	
	display: function (params) {
		var hasOptions = (this.optionsSrc && this.selectNodes(this.optionsSrc, "//option").length >0)
		if (!hasOptions) {
			if($('idml_options_obj')) {
				$('idml_options_obj').style.display = 'none';
			}
			if($('idml_options_div')) {
				$('idml_options_div').style.display = 'none';
			}
			return;
		}
		if($('idml_options_obj')) {
			$('idml_options_obj').style.display = '';
		}
		if($('idml_options_div')) {
			$('idml_options_div').style.display = '';
		}
		ProductOptions.optionsSrc.setAttribute("base-price", this.basePrice);
		new Ajax.Updater($('idml_options_content'), this.url, {method: 'post', encoding: 'iso-8859-1', parameters: {action: "display", options: ProductOptions.toXML(ProductOptions.optionsSrc)}, onComplete:function(){
			try {
				ProductOptions.setInteractive();
				if (params && params.onComplete) {
					params.onComplete();
				}
			} catch(any) {
				alert(any);
			}
			}});
		
	},
	
	load: function(id, url) {
		url = url || this.url;
		this.url = url;
		this.id = id;
		// TODO gérer le chargement de l'option en xml
		new Ajax.Request(url, {method: 'post', encoding: 'iso-8859-1', parameters: "action=load&idp="+ (id || '') +"&base-price="+ this.basePrice,
			onSuccess: function(result) {
				try {
					ProductOptions.optionsSrc = result.responseXML.documentElement;
					ProductOptions.clean();
					ProductOptions.__src = ProductOptions.toXML(ProductOptions.optionsSrc);
					ProductOptions.display();
				} catch (any) {
					alert("Erreur inattendue :  "+ (any.description || any));
				}
			}
		});
	}
}

ProductOptions.update = function(id, value) {
	var id = id.replace(/CHOICE_|#/gi, '');
	var itemXml  = this.selectSingleNode(this.optionsSrc, "//*[@id='"+ id +"']");
	if (!itemXml) {
		alert("Impossible de mettre la valeur "+ input.getAttribute("name") +" à jour pour l'option "+ id);
		return;
	}
	var formField = $('OPT_#'+ id +'_VAL');
	if (!formField) return;
	if (value) {
		itemXml.setAttribute("selected", "true")
		itemXml.setAttribute("value", value);
		formField.value = value
		this.toggleBlock(id, true);
		//inhibe les sous-options éventuellement indésirables
		var unwanted = this.selectNodes(itemXml, "*[@type='if-not-selected']/option");
		for (var i=0, l=unwanted.length; i<l; i++) {
			this.update(unwanted[i].getAttribute("id"), null);
		}
	} else {
		itemXml.removeAttribute("selected")
		itemXml.removeAttribute("value");
		if (itemXml.getAttribute("type")=='custom') {
			formField.value = "";
		} else {
			formField.value = 0;
		}
		this.toggleBlock(id, false);
		//inhibe les sous-options éventuellement indésirables
		var unwanted = this.selectNodes(itemXml, "*[@type='if-selected']/option");
		for (var i=0, l=unwanted.length; i<l; i++) {
			this.update(unwanted[i].getAttribute("id"), null);
		}
	}
	if (typeof this.onUpdate == 'function') {
		this.onUpdate();
	}
}

ProductOptions.onUpdateStoreDetail = function() {
	if (!$('idml_options_content')) return;
	if (!this.optionsSrc) {
		this.load(js_mainReference, '/_include/store/liveoptions.asp', true);
	} else {
		this.display();
	}
}

ProductOptions.setBasePrice = function(value) {
	this.basePrice = parseFloat(value.replace(/[^0-9.]/gi, ''));
}

	
ProductOptions.toggleBlock = function(id, state) {
	if (state) {
		var block = $('#'+ id +'-selected');
		if (block) block.style.display = '';
		block = $('#'+ id +'-unselected');
		if (block) block.style.display = 'none';
	} else {
		var block = $('#'+ id +'-selected');
		if (block) block.style.display = 'none';
		block = $('#'+ id +'-unselected');
		if (block) block.style.display = '';
	}
}

ProductOptions.setChoice = function(ctrl, source) {
	source = source || ctrl;
	var selectionTest = "";
	var options = []
	// dans le cas d'une option, on choisit le controle select parent
	if (ctrl.nodeName.toLowerCase()=='option') {
		ctrl = ctrl.parentNode;
	}
	if (ctrl.getAttribute("type")=='radio') {
		selectionTest = "checked"
		options = Form.getInputs(ctrl.form, 'radio', ctrl.name);
	} else if (ctrl.nodeName.toLowerCase()=='select') {
		selectionTest = "selected"
		options = ctrl.options;
		ctrl = ctrl.options[ctrl.selectedIndex];
	}
	for (var i=0, l=options.length; i<l; i++) {
		//alert(options[i].id.replace(/#/gi, '') +"\n"+ options[i][selectionTest] +"\n"+ options[i].value)
		if (options[i].id) {
			this.update(options[i].id.replace(/#/gi, ''), options[i][selectionTest] ? options[i].value : '');
		}
	}
}

ProductOptions.setOption = function(ctrl, source) {
	var id = ctrl.id;
	if (ctrl.nodeName.toLowerCase()=='option' || ctrl.type=='radio') {
		ctrl.selected = true;
		ctrl.checked = true;
		this.setChoice(ctrl, source);
	} else if (ctrl.type=='checkbox') {
		if (ctrl.checked) {
			this.update(id.replace(/#/gi, ''), ctrl.value);
		} else {
			this.update(id.replace(/#/gi, ''), 0);
		}
	} else {
		this.update(id.replace(/#/gi, ''), ctrl.value);
	}
	// duplique la valeur de l'option si le mm code est présent
	if (ctrl.name && ctrl.type!='radio') {
		var duplicates = document.getElementsByName(ctrl.name);
		var l = duplicates.length
		if (l>1 && ctrl.type!='radio') {
			for (var i=0; i<l; i++) {
				var duplicate = duplicates[i]
				if (duplicate!=ctrl && duplicate!=source) {
					duplicate.checked = ctrl.checked;
					duplicate.value = ctrl.value;
				}
			}
		}
	}
}
