/******************************************************************************
* odfForm.js
*******************************************************************************
Gestion de itl:form
*******************************************************************************
*                                                                             *
* Copyright 2006									                          *
*                                                                             *
******************************************************************************/

//
// ------------------------------------- Global functions
//
var odfFormManagers = new Object();

function odfRegisterFormManager(formManager)
{
	if(formManager != null)
		odfFormManagers[formManager.getId()] = formManager;
}
function odfGetFormManager(id)
{
	return odfFormManagers[id];
}

function initSelect(id)
{
	var select = document.getElementById(id);
	if(select == null) return;
	var value = select.getAttribute("V");
	if(value == null) return;
	var options = select.options;
	var defaultValue = -1;
	for(var i=0;i<options.length;i++) {
		var option = options.item(i);
		if(option.value == value) {
			select.selectedIndex = i;
			return;
		}
		if(option.getAttribute("DEFAULT") != null) {
			defaultValue = i;
		}
	}
	select.selectedIndex = defaultValue;
}

function odfDispatchEventOnChange(input)
{
	if (input != null) {
		if (document.all) 
			input.fireEvent("onchange"); 
		else { 
			var changeEvent = window.document.createEvent("HTMLEvents"); 
			changeEvent.initEvent("change", false, true); 
			input.dispatchEvent(changeEvent); 
		} 
	}
}

//
// ------------------------------------- class GenericControl
//
function GenericControl(id, formManager, name, map)
{
	if(id) {
		this._id = id;
		this._name = name;
		this._props = map;
		this._formId = formManager.getHtmlId();
		this._reason = "";
		
		// if (id == name) alert(["[odfForm.js] ATTENTION ! Le contrôle '",id,"' utilise la même valeur pour 'name' et 'id'\n=> risque de confusion (getElementById sous IE)"].join(""));
	}
}

GenericControl.prototype.getId = function()
{
	return this._id;
}
GenericControl.prototype.getName = function()
{
	return this._name;
}

GenericControl.prototype.getMainInput = function()
{
	return document.getElementById(this._id);
}

GenericControl.prototype.getStringValue = function()
{
	var input = this.getMainInput();
	if(input == null) {
		return;
	}
	return input.value;
}

GenericControl.prototype.isVisible = function(formManager)
{
	var input = this.getMainInput();
	if(input == null) {
		return false;
	}
	return formManager.elementIsVisible(input);
}

GenericControl.prototype.isChecked = function()
{
	var input = this.getMainInput();
	if(input == null) {
		return;
	}
	return input.checked;
}

GenericControl.prototype.isDisabled = function()
{
	var input = this.getMainInput();
	if(input == null) {
		return;
	}
	return input.disabled;
}

GenericControl.prototype.isReadOnly = function()
{
	var input = this.getMainInput();
	if(input == null) {
		return;
	}
	return input.readOnly;
}

GenericControl.prototype.disable = function(flag)
{
	var input = this.getMainInput();
	if(input != null)
		input.disabled = flag;
}

GenericControl.prototype.checkValue = function()
{
	var value = this.getStringValue();
	if(value == null || value == "") return false;
	return true;
}

GenericControl.prototype.getLength = function()
{
	var value = this.getStringValue();
	if(value == null || value == "") return 0;
	return value.length;
}

GenericControl.prototype.checkFormatValue = function(type)
{
	var value = this.getStringValue();
	if(value == null || value == "") return true;
	switch(type) {
	case "integer":
		if(!/^[-+]?[0-9]+\s*$/.test(value)) return false;
		break;
	case "double":
		value = value.replace(/,/, ".");
		if(!/^[-+]?(([0-9]+\.[0-9]*)|([0-9]*\.[0-9]+)|([0-9]+))([eE][-+]?[0-9]+)?\s*$/.test(value)) return false;
		break;
	case "date":
		if(!/^\d{1,2}\/\d{1,2}\/\d{4}\s*$/.test(value)) return false;
		break;
	case "dateTime":
		if(!/^\d{1,2}\/\d{1,2}\/\d{4}\s+\d{1,2}:\d{1,2}\s*?$/.test(value)) return false;
		break;
	}
	return true;
}

GenericControl.prototype.checkRegexpValue = function(check)
{
	var value = this.getStringValue();
	if(value == null || value == "") return true;
	var regexp = new RegExp("^(" + check + ")$");
	if(!regexp.test(value)) {
		return false;
	}
	return true;
}

GenericControl.prototype.checkExtremaValue = function(check)
{
	var checkingMap = this._props;
	var value = this.getStringValue();
	if(value == null || value == "") return true;
	var min = checkingMap.minvalue;
	if(min == null) min = value;
	var max = checkingMap.maxvalue;
	if(max == null) min = value;
	switch(checkingMap.extrematype) {
	case "integer":
		value = parseInt(value, 10);
		min = parseInt(min, 10);
		max = parseInt(max, 10);
		break;
	case "double":
		value = parseFloat(value);
		min = parseFloat(min);
		max = parseFloat(max);
		break;
	case "date":
		min = parseFloat(min);
		max = parseFloat(max);
		var regexpDate = /^(\d{1,2})\/(\d{1,2})\/(\d{1,4})(\s+(\d{1,2}):(\d{1,2})(:(\d{1,2}))?)?\s*$/;
		var array = regexpDate.exec(value);
		if(!array) return true;
		var fullyear = parseInt(array[3]);
		var month = parseInt(array[2], 10);
		var day = parseInt(array[1], 10);
		var hours = 0;
		var minutes = 0;
		var seconds = 0;
		value = new Date(fullyear, month-1, day, hours, minutes, seconds).getTime();
		break;
	default:
		return true;
	}
	if(value < min || value > max) return false;
	return true;
}

GenericControl.prototype.fillPara = function(para, text)
{
	para.innerHTML = text.replace(/&/g, "&amp;").replace(/</g, "&lt;");
}

GenericControl.prototype.onSubmit = function(formManager)
{
	var failedPara = document.getElementById(this._id + "_failed");
	var checkingMap = this._props;
	if(failedPara == null || checkingMap == null) return true;

	// 1) checking the emptyness
	if(checkingMap.missingreason && this.checkValue && !this.checkValue()) {
		this._reason = checkingMap.missingreason;
		failedPara.style.display = "block";
		this.fillPara(failedPara, this._reason); 
		return false;
	}

	// 2) checking the size
	if(checkingMap.maxlengthreason) {
		var length = this.getLength();
		if(length > checkingMap.maxlength) {
			this._reason = checkingMap.maxlengthreason.replace(/%2/g, length + "");
			failedPara.style.display = "block";
			this.fillPara(failedPara, this._reason); 
			return false;
		}
	}

	// 3) checking the format
	if(checkingMap.formatreason && this.checkFormatValue && !this.checkFormatValue(checkingMap.formattype)) {
		this._reason = checkingMap.formatreason;
		failedPara.style.display = "block";
		this.fillPara(failedPara, this._reason); 
		return false;
	}

	// 4) checking the regexp
	if(checkingMap.checkreason && this.checkRegexpValue && !this.checkRegexpValue(checkingMap.checkregexp)) {
		this._reason = checkingMap.checkreason;
		failedPara.style.display = "block";
		this.fillPara(failedPara, this._reason); 
		return false;
	}
	// 5) checking the extrema
	if(checkingMap.extremareason && this.checkExtremaValue && !this.checkExtremaValue(checkingMap.checkregexp)) {
		this._reason = checkingMap.extremareason;
		failedPara.style.display = "block";
		this.fillPara(failedPara, this._reason); 
		return false;
	}
	// 6) checking the captcha
	// no check on the client for security reason

	failedPara.style.display = "none";
	this.fillPara(failedPara, "");
	this._reason = "";
	return true;
}

GenericControl.prototype.getReason = function()
{
	return this._reason;
}
//
// ------------------------------------- class KeywordControl
//
function KeywordControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
}

KeywordControl.prototype = new GenericControl();

KeywordControl.prototype.getMainInput = function()
{
	return document.getElementById(this._id + "_h");
}

//
// ------------------------------------- class HiddenControl
//
function HiddenControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
}

HiddenControl.prototype = new GenericControl();


HiddenControl.prototype.isVisible = function(formManager)
{
	return false;
}

HiddenControl.prototype.isChecked = function()
{
	return false;
}

HiddenControl.prototype.isDisabled = function()
{
	return true;
}

HiddenControl.prototype.isReadOnly = function()
{
	return true;
}

HiddenControl.prototype.disable = function(flag)
{
}

HiddenControl.prototype.checkValue = function()
{
	return true;
}

HiddenControl.prototype.onSubmit = function(formManager)
{
	return true;
}
//
// ------------------------------------- class ReferenceControl
//
function ReferenceControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
}

ReferenceControl.prototype = new GenericControl();

ReferenceControl.prototype.getInput = function()
{
	return document.getElementById(this._id + "_search");
}

ReferenceControl.prototype.disable = function(flag)
{
	var input = document.getElementById(this._id + "_search");
	if(input != null)
		input.disabled = flag;
		
	var btn = document.getElementById(this._id + "_btn");
	if(btn != null)
		btn.style.display = (flag ? "none" : "inline");
}

ReferenceControl.prototype.getHiddenInput = function()
{
	var hidden = document.getElementById(this._id + "_h");
	if(hidden == null) hidden = document.getElementById(this._id);
	return hidden;
}

ReferenceControl.prototype.getDetailInput = function()
{
	return document.getElementById(this._id + "_searchdetail");
}

ReferenceControl.prototype.onkeyup = function()
{
	var id = this._id;
	var input = this.getInput();
	var hidden = this.getHiddenInput();
	var detail = this.getDetailInput();
	if(hidden == null || input == null) return;
	hidden.value = "";
	if (detail != null)
		detail.value = "";
	if(input.value == "") {
		input.title = "Aucune référence";
		input.className = input.className.replace("boundReference", "noReference").replace("openReference", "noReference");
	} else {
		input.title = "Le texte n'est plus associé à une référence : utilisez le dialogue pour saisir précisément la référence";
		input.className = input.className.replace("boundReference", "openReference").replace("noReference", "openReference");
	}
}
ReferenceControl.prototype.checkValue = function()
{
	if(!this.checkFormatValue()) return true;
	var hidden = this.getHiddenInput();
	return hidden.value != "";
}

ReferenceControl.prototype.checkFormatValue = function()
{
	var textArea = this.getInput();
	var hidden = this.getHiddenInput();
	if(hidden != null && textArea != null) {
		if(textArea.value != "" && hidden.value == "") {
			return false;
		}
	}
	return true;
}

ReferenceControl.prototype.browse = function(url, popupWidth, popupHeight)
{
	var id = this._id;
	var hidden = this.getHiddenInput();
	if(hidden == null) return;
	var width = !isNaN(popupWidth) ? popupWidth : "600";
	var height = !isNaN(popupHeight) ? popupHeight : "270";
	window.referenceSelectionProcessor = this;
	var params = this.buildParameters();
	if (params != "") {
		if (url.indexOf("?") > 0) url += "&";
		else url += "?";
		url += params;
	}
	showModalWindow(url, "referenceDialog", width, height, this);
}

ReferenceControl.prototype.select = function()
{
}

ReferenceControl.prototype.buildParameters = function(descr)
{
	var id = this._id;
	var input = this.getInput();
	var hidden = this.getHiddenInput();
	if(hidden == null || input == null) return "";
	var oid = hidden.value;
	var fulltext = input.value;
	var search = "multi=false";
	if(oid != "") {
		search += "&oid=" + oid;
	}
	if(fulltext != "") {
		search += "&fulltext=" + escape(fulltext.replace(/"/g, ""));
	}
	return search;
}

ReferenceControl.prototype.commit = function(descr)
{
	var id = this._id;
	var input = this.getInput();
	var hidden = this.getHiddenInput();
	var detail = this.getDetailInput();
	if(hidden == null || input == null) return;
	var oldValue = hidden.value;
	if(descr != null) {
		hidden.value = "" + descr.oid;
		if (detail != null)
			detail.value = "" + descr.detail;
		input.value = descr.label;
		input.title = "Le texte est associé à une référence.\nLe formulaire peut être sousmis.";
		input.className = input.className.replace("noReference", "boundReference").replace("openReference", "boundReference");
	} else {
		hidden.value = "";
		if (detail != null)
			detail.value = "";
		input.value = "";
		input.title = "Aucune référence";
		input.className = input.className.replace("boundReference", "noReference").replace("openReference", "noReference");
	}

	// Dispatching of event onChange
	var newValue = hidden.value;
	if ((oldValue != newValue))
		odfDispatchEventOnChange(input);
}

//
// ------------------------------------- class ReferencesControl
//
function ReferencesControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
	var hidden = this.getHiddenInput();
	var textArea = this.getTextArea();
	this._lastValidatedValue = hidden.value;
	this._lastValidatedLabel = textArea.value;
}

ReferencesControl.prototype = new GenericControl();

ReferencesControl.prototype.getHiddenInput = function()
{
	var hidden = document.getElementById(this._id);
	return hidden;
}
ReferencesControl.prototype.getLabelInput = function()
{
	var input = document.getElementById(this._id + "_labels");
	return input;
}
ReferencesControl.prototype.getLabelSpan = function()
{
	var span = document.getElementById(this._id + "_labelSpan");
	return span;
}
ReferencesControl.prototype.getTextArea = function()
{
	var textArea = document.getElementById(this._id + "_search");
	return textArea;
}

ReferencesControl.prototype.browse = function(url, popupWidth, popupHeight)
{
	var hidden = this.getHiddenInput();
	if(hidden == null) return;
	var width = !isNaN(popupWidth) ? popupWidth : "600";
	var height = !isNaN(popupHeight) ? popupHeight : "300";
	window.referenceSelectionProcessor = this;
	var textArea = this.getTextArea();
	var fullText = textArea?textArea.value:"";
	var params = "multi=true&fulltext=" + escape(fullText) + "&oid=" + escape(hidden.value);
	if (params != "") {
		if (url.indexOf("?") > 0) url += "&";
		else url += "?";
		url += params;
	}
	showModalWindow(url, "referenceDialog", width, height, this);
}

ReferencesControl.prototype.select = function()
{
}

ReferencesControl.prototype.commit = function(descr)
{
	var span = this.getLabelSpan();
	if(span != null) this.updateLabelSpan(span, descr);
	var textAreaOnChange = false;
	var textArea = this.getTextArea();
	if(textArea != null) textAreaOnChange = this.updateTextArea(textArea, descr);

	// Dispatching of event onChange
	if (textAreaOnChange == true)
		odfDispatchEventOnChange(textArea);
}

ReferencesControl.prototype.checkValue = function()
{
	if(!this.checkFormatValue()) return true;
	var hidden = this.getHiddenInput();
	return hidden.value != "";
}

ReferencesControl.prototype.checkFormatValue = function()
{
	var textArea = this.getTextArea();
	var hidden = this.getHiddenInput();
	if(hidden != null && textArea != null) {
		if(textArea.value != "" && hidden.value == "") {
			return false;
		}
	}
	return true;
}

ReferencesControl.prototype.updateLabelSpan = function(listSpan, descr)
{
	var hidden = this.getHiddenInput();
	if(hidden == null) return;
	var children = listSpan.childNodes;
	var oids = "";
	var labelText = "";
	for(var i=0;i<descr.oids.length;i++) {
		var oid = descr.oids[i];
		if(oids != "") oids += " ";
		oids += oid;
		if(labelText != "") labelText += ", ";
		labelText += descr.labels[i];
	}
	hidden.value = oids;
	while(listSpan.firstChild) listSpan.removeChild(listSpan.firstChild);
	listSpan.appendChild(document.createTextNode(labelText));
}
ReferencesControl.prototype.getReferenceCount = function()
{
	var hidden = this.getHiddenInput();
	if(hidden == null) return;
	var oids = hidden.value.split(" ");
	var count = 0;
	for(var i=0;i<oids.length;i++) {
		if(oids[i] == "") continue;
		count++;
	}
	return count;
}
ReferencesControl.prototype.updateTextArea = function(textArea, descr)
{
	var hidden = this.getHiddenInput();
	if(hidden == null) return false;
	var children = textArea.childNodes;
	var oids = "";
	var labelText = "";
	for(var i=0;i<descr.oids.length;i++) {
		var oid = descr.oids[i];
		if(oids != "") oids += " ";
		oids += oid;
		if(labelText != "") labelText += ";\n";
		labelText += descr.labels[i];
	}
	var oldValue = hidden.value;
	hidden.value = oids;
	textArea.value = labelText;
	textArea.title = this.getReferenceCount() + " référence(s)";
	textArea.className = textArea.className.replace("noReference", "boundReference").replace("openReference", "boundReference");
	return (oldValue != oids);
}

ReferencesControl.prototype.onkeyup = function()
{
	var id = this._id;
	var input = this.getTextArea();
	var hidden = this.getHiddenInput();
	if(hidden == null || input == null) return;
	if(input.value == "") {
		hidden.value = "";
		input.title = "Aucune référence";
		input.className = input.className.replace("boundReference", "noReference").replace("openReference", "noReference");
	} else {
		if(this._lastValidatedLabel == input.value) {
			hidden.value = this._lastValidatedValue;
			this._lastValidatedLabel = input.value;
			input.title = this.getReferenceCount() + " référence(s)";
			input.className = input.className.replace("noReference", "boundReference").replace("openReference", "boundReference");
		} else {
			hidden.value = "";
			input.title = "Le texte n'est plus associé à des références : utilisez le dialogue pour saisir précisément chaque référence.";
			input.className = input.className.replace("boundReference", "openReference").replace("noReference", "openReference");
		}
	}
}
//
// ------------------------------------- class PasswordControl
//
function PasswordControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
	this._isConfirm = this._props.isConfirm;
}

PasswordControl.prototype = new GenericControl();

PasswordControl.prototype.checkFormatValue = function()
{
	var input = document.getElementById(this._id);
	if(input == null) {
		return false;
	}
	var name = this._name;
	var value = input.value;
	var inputs = input.form[name];
	if(inputs == null) return true;
	if(typeof(inputs.length) == "number") {
		for(var i=0;i<inputs.length;i++) {
			var input = inputs[i];
			if(input.value != value) return false;
		}
	} else {
		var input = inputs;
		if(input.value != value) return false;
	}
	return true;
}

//
// ------------------------------------- class PropertySetControl
//
function PropertySetControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
	this._formId = formManager.getHtmlId()
	var div = document.getElementById(this._id);
	var value = div.getAttribute("V");
	var form = document.getElementById(this._formId);
	if(form == null) {
		return alert("no form " + this._formId);
	}
	var inputs = form[name];
	if(inputs == null) return;
	var values = new Object();
	var list = value.split(" ");
	for(var i=0;i<list.length;i++) values[list[i]] = 1;
	if(typeof(inputs.length) == "number") {
		for(var i=0;i<inputs.length;i++) {
			var input = inputs[i];
			if(values[input.value] == 1) {
				input.checked = true;
			}
		}
	} else {
		if(values[inputs.value] == 1) {
			inputs.checked = true;
		}
	}
}
PropertySetControl.prototype = new GenericControl();

PropertySetControl.prototype.getId = function()
{
	return this._id;
}
PropertySetControl.prototype.getName = function()
{
	return this._name;
}

PropertySetControl.prototype.getInputs = function()
{
	var form = document.getElementById(this._formId);
	if(form == null) {
		return;
	}
	return form[this._name];
}

PropertySetControl.prototype.getStringValue = function()
{
	var inputs = this.getInputs();
	if(inputs == null) {
		return;
	}
	if(typeof(inputs.length) == "number") {
		var res = "";
		for(var i=0;i<inputs.length;i++) {
			var input = inputs[i];
			if(input.checked) {
				if(res != "") res += " ";
				res += input.value;
			}
		}
		return res;
	}
	return inputs.value;
}

PropertySetControl.prototype.isVisible = function(formManager)
{
	var inputs = this.getInputs();
	if(inputs == null) {
		return false;
	}
	if(typeof(inputs.length) == "number") {
	    return formManager.elementIsVisible(inputs[0]);
	}
	return formManager.elementIsVisible(inputs);
}

PropertySetControl.prototype.isChecked = function()
{
	var inputs = this.getInputs();
	if (inputs == null) {
		return true;
	}
	if (typeof(inputs.length) == "number") {
		for (var i=0;i<inputs.length;i++) {
			var input = inputs[i];
			if (input.type != "checkbox") continue;	// skip hidden input
			if (input.checked) return true;
		}
		return false;
	}
	return false;	// the only one is the hidden input (there are no options)
}

PropertySetControl.prototype.isDisabled = function()
{
	var inputs = this.getInputs();
	if (inputs == null) {
		return;
	}
	if (typeof(inputs.length) == "number") {
		var nbInput = nbDisabledInput = 0;
		for (var i=0;i<inputs.length;i++) {
			var input = inputs[i];
			if (input.type != "checkbox") continue;	// skip hidden input
			nbInput++;
			if (input.disabled) 
				nbDisabledInput++;
		}
		return (nbDisabledInput == nbInput);
	}
	return false;	// the only one is the hidden input (there are no options)
}

PropertySetControl.prototype.isReadOnly = function()
{
	var input = document.getElementById(this._id);
	if(input == null) {
		return;
	}
	if(typeof(input.length) == "number") {
		return input[0].readOnly;
	}
	return input.readOnly;
}

PropertySetControl.prototype.disable = function(flag)
{
	var inputs = this.getInputs();
	if (inputs == null) {
		return;
	}	
	if (typeof(inputs.length) == "number") {
		for (var i=0;i<inputs.length;i++) {
			var input = inputs[i];
			if (input.type != "checkbox") continue;	// skip hidden input
			input.disabled = flag;
		}
	}
}

PropertySetControl.prototype.checkValue = function()
{
	return this.isChecked();
}

PropertySetControl.prototype.onSubmit1 = function(formManager)
{
	var failurePara = document.getElementById(this._id + "_failure");
	var failureContent = document.getElementById(this._id + "_failure_content");
	if(failurePara == null) return true;
	var message = failureContent.innerHTML;
	if(this.checkValue()) {
		failurePara.style.display = "none";
		return true;
	}
	this._reason = message;
	failurePara.style.display = "block";
	return false;
}

PropertySetControl.prototype.getReason = function()
{
	return this._reason;
}

//
// ------------------------------------- class RadioControl
//
function RadioControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
}

RadioControl.prototype = new GenericControl();

RadioControl.prototype.getInputs = function()
{
	var form = document.getElementById(this._formId);
	if(form == null) {
		return;
	}
	return form.elements[this._name];
}

RadioControl.prototype.getStringValue = function()
{
	var input = this.getInputs();
	if(input == null) return;
	if(typeof(input.length) == "number") {
		for(var i=0;i<input.length;i++) {
			if(input[i].checked) return input[i].value;
		}
	} else {
		return input.value;
	}
}

RadioControl.prototype.isVisible = function(formManager)
{
	var input = this.getInputs();
	if(input == null) {
		return false;
	}
	if(typeof(input.length) == "number") {
	    return formManager.elementIsVisible(input[0]);
	}
	return formManager.elementIsVisible(input);
}

RadioControl.prototype.isChecked = function()
{
	var input = this.getInputs();
	for(var i=0;i<input.length;i++) {
		if(input[i].checked && input[i].value != "") return true;
	}
	return false;
	return input.checked;
}

RadioControl.prototype.isDisabled = function()
{
	var input = this.getInputs();
	if(input == null) {
		return;
	}
	if(typeof(input.length) == "number") {
		return input[0].disabled;
	}
	return input.disabled;
}

RadioControl.prototype.isReadOnly = function()
{
	var input = this.getInputs();
	if(input == null) {
		return;
	}
	if(typeof(input.length) == "number") {
		return input[0].readOnly;
	}
	return input.readOnly;
}

RadioControl.prototype.disable = function(flag)
{
	var input = document.getElementById(this._id);
	if(input != null) {
		if(typeof(input.length) == "number")
			input[0].disabled = flag;
		else
			input.disabled = flag;
	}
}

RadioControl.prototype.checkValue = function()
{
	return this.isChecked();
}

RadioControl.prototype.getReason = function()
{
	return this._reason;
}

//
// ------------------------------------- class CheckboxControl
//
function CheckboxControl(id, formManager, name, map)
{
	GenericControl.call(this, id, formManager, name, map);
	this.onchange(true);
}

CheckboxControl.prototype = new GenericControl();

CheckboxControl.prototype.onchange = function(init)
{
	var id = this._id;
	var hidden = document.getElementById(id + "_h");
	var checkbox = document.getElementById(id);
	if(hidden == null) { // compatibilité last runtime
		hidden = checkbox;
		checkbox = document.getElementById(id + "_c");
	}
	if(hidden == null || checkbox == null) {
		return;
	}
	if(init) {
		checkbox.checked = hidden.value == "true";
	} else {
		hidden.value = "" + checkbox.checked;
	}
}

CheckboxControl.prototype.getId = function()
{
	return this._id;
}
CheckboxControl.prototype.getName = function()
{
	return this._name;
}

CheckboxControl.prototype.getInputs = function()
{
	var form = document.getElementById(this._formId);
	if(form == null) {
		return;
	}
	return form[this._name];
}

CheckboxControl.prototype.getStringValue = function()
{
	var input = this.getInputs();
	if(input == null) return;
	if(typeof(input.length) == "number") {
		var value = "";
		for(var i=0;i<input.length;i++) {
			if(input[i].checked) {
				if(value != "") value += " ";
				value += input[i].value;
			}
		}
		return value;
	} else {
		return input.value;
	}
}
CheckboxControl.prototype.isVisible = function(formManager)
{
	var input = this.getInputs();
	if(input == null) {
		return false;
	}
	if(typeof(input.length) == "number") {
	    return formManager.elementIsVisible(input[0]);
	}
	return formManager.elementIsVisible(input);
}
CheckboxControl.prototype.getHiddenInput = function()
{
	var input = document.getElementById(this._id+"_c");
	if(input != null) return null;
	return document.getElementById(this._id);
}

CheckboxControl.prototype.isChecked = function()
{
	var inputs = this.getInputs();
	if(inputs == null) {
		return false;
	}
	if(typeof(inputs.length) == "number") {
		for(var i=0;i<inputs.length;i++) {
			var input = inputs[i];
			if(input.value == "true") return true;
		}
		return false;
	}
	return inputs.value == "true";
}

CheckboxControl.prototype.isDisabled = function()
{
	var input = this.getInputs();
	if(input == null) {
		return;
	}
	if(typeof(input.length) == "number") {
		return input[0].disabled;
	}
	return input.disabled;
}

CheckboxControl.prototype.isReadOnly = function()
{
	var input = this.getInputs();
	if(input == null) {
		return;
	}
	if(typeof(input.length) == "number") {
		return input[0].readOnly;
	}
	return input.readOnly;
}

CheckboxControl.prototype.disable = function(flag)
{
	var input = this.getInputs();
	if(input != null) {
		if(typeof(input.length) == "number")
			input[0].disabled = flag;
		else
			input.disabled = flag;
	}
}

CheckboxControl.prototype.checkValue = function()
{
	return this.isChecked();
}

CheckboxControl.prototype.onSubmit1 = function(formManager)
{
	var failurePara = document.getElementById(this._id + "_failure");
	var failureContent = document.getElementById(this._id + "_failure_content");
	if(failurePara == null) return true;
	var message = failureContent.innerHTML;
	if(this.checkValue()) {
		failurePara.style.display = "none";
		return true;
	}
	this._reason = message;
	failurePara.style.display = "block";
	return false;
}

CheckboxControl.prototype.getReason = function()
{
	return this._reason;
}

//
// ------------------------------------- class ColorClient
//
function ColorClient(input)
{ 
	this.input = input;
}

ColorClient.prototype.getColor = function()
{
	return this.input.value;
}

ColorClient.prototype.setColor = function(str)
{
	this.input.value = str;
	updateColor(this.input.id, false);
}

function showColorDialog(id)
{
	var input = document.getElementById(id);
	window.colorClient = new ColorClient(input);
	showModalWindow("iso_scripts/colorDialog.html", "_blank", 233, 301, null);
}

function updateColor(id, init)
{
	var input = document.getElementById(id);
	var image = document.getElementById(id + "_image");
	var color = input.value;
	if(/^#[0-9A-F]{6}$/i.test(color)) {
		image.style.backgroundColor = color;
		input.style.backgroundColor = "white";
	} else {
		image.style.backgroundColor = "transparent";
		if(color == "") {
			input.style.backgroundColor = "white";
		} else {
			input.style.backgroundColor = "#FFC0C0";
		}
	}
}

//
// ------------------------------------- class FormManager
//
function FormManager(id, htmlId, windowOptions, target, globalId)
{
	this._id = id;
	this._globalId = globalId;
	this._htmlId = htmlId;
	this._windowOptions = windowOptions;
	this._target = target;
	this._controls = new Array();
	this._bByPassStdChecking = false;
	this._visibilityFormulas = new Object();
	this._hasVisibilityFormulas = false;
	this._modified = false;
	
	odfRegisterFormManager( this );
}
FormManager.prototype.getId = function()
{
	return this._id;
}

FormManager.prototype.getHtmlId = function()
{
	return this._htmlId;
}

FormManager.prototype.registerControl = function(control)
{
	this._controls[this._controls.length] = control;
}

FormManager.prototype.getControls = function(name)
{
	var list = new Array();
	for(var i=0;i<this._controls.length;i++) {
		control = this._controls[i];
		if(control.getName() == name) list[list.length] = control;
	}
	return list;
}

FormManager.prototype.byPassStandardChecking = function( bByPass )
{
	if ( bByPass == null ) 	var bByPass = true;
	this._bByPassStdChecking = bByPass;
}

FormManager.prototype.paramRegexp = /\$([a-zA-Z_][-.#a-zA-Z0-9_:]*);?/i;
FormManager.prototype.expandVariables = function(variables, text)
{
	if(variables == null) return text;
	var array = this.paramRegexp.exec(text);
	var res = "";
	var lastPos = 0;
	while(array != null && array.index >= 0) {
		if(array.index > 0) res += text.substr(0, array.index);
		text = text.substr(array.index + array[0].length);
		var name = array[1];
		var root = name;
		var chunks = name.split("#");
		if(chunks.length > 0) {
			name = chunks[0];
			var i;
			for(i=1; i< chunks.length; i++) {
				var v;
				if(variables.nodeType == 1) {
					v = variables.getAttribute(chunks[i]);
				} else {
					v = variables[chunks[i]];
				}
				if(v == null) v = "";
				name += v;
			}
		}
		var value;
		if(variables.nodeType == 1) {
			value = variables.getAttribute(name);
		} else {
			value = variables[name];
		}
		if(value == null) {
			value = variables[root];
			if(variables.nodeType == 1) {
				value = variables.getAttribute(root);
			} else {
				value = variables[root];
			}
			if(value == null) {
				value = "";
			}
		}
		if(typeof(value) == "string") {
		} else if(typeof(value) == "number") {
				value = "" + value;
		} else value = "";
		res += '"' + value.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
		array = this.paramRegexp.exec(text);
		//break;
	}
	res += text;
	return res;
}

FormManager.prototype.controlChanged = function(control)
{
	this._modified = true;
	if(control != null && typeof(control.onchange) == "function") {
		control.onchange();
	}
	if(this._hasVisibilityFormulas) {
		var values = this.getAllValues();
		for(var id in this._visibilityFormulas) {
			var element = document.getElementById(id);
			if(element == null) continue;
			var formula = this._visibilityFormulas[id];
			formula = this.expandVariables(values, formula);
			var visible = true;
			try {
				visible = eval(formula);
			} catch(e) {
			}
			if(visible) {
				switch(element.tagName.toLowerCase()) {
				case "span":
					element.style.display = "inline";
					break;
				case "div":
				case "p":
					element.style.display = "block";
					break;
				}
			} else {
				element.style.display = "none";
			}
		}
	}
}
FormManager.prototype.getAllValues = function()
{
	var map = new Object();
	for(var i=0;i<this._controls.length;i++) {
		var control = this._controls[i];
		var name = control.getName();
		var value = control.getStringValue();
		map[name] = value;
	}
	return map;
}

FormManager.prototype.elementIsVisible = function(element)
{
    while(element != null && element.nodeType == 1) {
        if(element.style.display == "none") return false;
        element = element.parentNode;
    }
    return true;
}
FormManager.prototype.addVisibilityFormula = function(id, formula)
{
	this._hasVisibilityFormulas = true;
	this._visibilityFormulas[id] = formula;
}

FormManager.prototype.onSubmit = function()
{
	var reasons = new Array();
	var firstFalseControl = null;
	var customStatus = true;
	if(this.onCustomCheck) {
		var status = this.onCustomCheck();
		switch(typeof(status)) {
		case "string":
			reasons[reasons.length] = status;
			customStatus = false;
			break;
		case "object":
			if (typeof(status.length) == "number") {
				for (var ind=0; ind<status.length; ind++)
					reasons[reasons.length] = "" + status[ind];
				customStatus = false;
			}
			break;
		case "boolean":
			customStatus = status;
			if ( this._bByPassStdChecking == true )
				return customStatus;
			break;
		}
	}
	if (this._bByPassStdChecking == false) {
		for(var i=0;i<this._controls.length;i++) {
			var control = this._controls[i];
			if(control.isVisible != null && !control.isVisible(this)) continue;
			if(control.onSubmit == null) continue;
			var status = control.onSubmit(this);
			if(status == false) {
				if(firstFalseControl == null && control.focus != null) firstFalseControl = control;
				var reason = control.getReason(this);
				reasons[reasons.length] =  reason;
			}
		}
	}
	switch(reasons.length) {
	case 0:
		var target = this._target;
		if(this._windowOptions != null) {
			window.open("about:blank", target, this._windowOptions);
		}
		return customStatus;	// Custom status can be false
	case 1:
		alert(reasons[0]);
		if(firstFalseControl != null) firstFalseControl.focus();
		return false;
	default:
		var msg = objThesaurus.translate("odf20");
		for(var i=0;i<reasons.length;i++) {
			msg += "\n-\240" + reasons[i];
		}
		alert(msg);
		if(firstFalseControl != null) firstFalseControl.focus();
		return false;
	}
}



FormManager.prototype.changeLanguage = function(lang)
{
	var status = null;
	if(this.onLanguageChange != null) {
		status = this.onLanguageChange();
	}
	if(status == false) return false;
	var form = document.getElementById(this._htmlId);
	if(status == true) {
		var input = form.elements("_formLanguage" + this._globalId);
		input.value = lang;
		form.submit();
		return false;
	}
	if(this._modified) {
		if(!confirm("Les modifications saisies seront perdues si vous continuez.\nVoulez-vous continuer?")) return false;
	}
	repostPage(this._globalId, "lang:" + lang, "A" + this._id , null, null, null);
	return false;
}

