/*
	getIndexByValue(elem, val)
	setExclusive(obj, name, method)
	setExclusiveFast(obj, obj_name, default_value)
	setExclusiveSlow(obj, obj_name, default_value)
	SelectBox2List(select_box, value_delim, pair_delim)
	List2SelectBox(select_box, list, value_delim, pair_delim)
	addOption(select_box, val, txt, position)
	getFirstSelectBox(obj_name)
	initExclusive(obj, obj_name, default_value)
	addOptionToAllSelectBox(cur_obj, obj_name, val, txt, position)
	deleteOptionFromAllSelectBox(cur_obj, obj_name)
	deleteOption(select_box, val)
 */

/* ---------------------------------------------------------------------
This function return the index of a specified value of a select box
----------------------------------------------------------------------*/
function getIndexByValue(elem, val){
	for(var i = 0; i<elem.length; i++) {
		if(elem.options[i].value == val) {return i;}
	}
	return -1;
}
function setExclusive(obj, name, default_value, method){
	if(method.toUpperCase()=='FAST') {setExclusiveFast(obj, name, default_value);}
	else setExclusiveSlow(obj, name, default_value);
}

/* --------------------------------------------------------------------------
This function is used to prevent that the user select 2 times the same value
of a select bon in a subform or a grid
---------------------------------------------------------------------------*/
function setExclusiveFast(obj, obj_name, default_value){
	var old_value = null;
	var default_index = getIndexByValue(obj, default_value);
	if(obj.old_value) {old_value = obj.old_value;} 
	else {old_value = 0;}
	finish = 0;
	for(var j=0; j<=1; j++) {
		if(j == 0)
			field_type = "Modify";
		if(j == 1)
			field_type = "Add";
		finish = 0;
		i = 1;
		while(!finish) {
			each_obj = eval("document.dsp_form." + field_type + "__" + i + "__" + obj_name);
			if(each_obj) {
				if(each_obj.options[each_obj.options.selectedIndex].value != default_value && obj.options[obj.options.selectedIndex].value != default_value) {
					if(each_obj && each_obj.name != obj.name && each_obj.options[each_obj.options.selectedIndex].value == obj.options[obj.options.selectedIndex].value) {
						alert("You cannot select the same value more than 1 time");
						obj.options[getIndexByValue(obj, old_value)].selected = true;
	//					finish = 1;j=3;
						return 0;
					}
				}
			} 
			else {finish = 1;}
			i++;
		}
	}
	obj.old_value = obj.options[obj.options.selectedIndex].value;
	return 1;
}
function setExclusiveSlow(obj, obj_name, default_value){
	var finish = 0;
	var field_type = "Add";
	// --- get the original list (the complete one) ---
	// first, search the first select box ...
	var first_obj = getFirstSelectBox(obj_name);
/*	if(!first_obj) { // if it is not a modify select box, try the Add one
		first_obj = eval("document.dsp_form.Add__" + 1 + "__" + obj_name);
		if(!first_obj)
			return false; // if not, return false because we don't found the first select box ...
	}
*/
	var orig_value = first_obj.orig_value;

	// there was an old value = default_value => add it in other select box ...
	if(obj.old_value != null) {
		addOptionToAllSelectBox(obj, obj_name, obj.old_value, obj.old_text, listFind(orig_value, obj.old_value + "," + obj.old_text, "~"));
	}
		
	// delete the new selected option from the other select boxes
	if(obj.options[obj.options.selectedIndex].value != default_value)
		deleteOptionFromAllSelectBox(obj, obj_name);
	return true;
}
/* convert select box options to a list */
function SelectBox2List(select_box, value_delim, pair_delim){
	var value_list = "";
	for(var i=0; i<select_box.length; i++) {
			value_list = listAppend(value_list, select_box.options[i].value + value_delim + select_box.options[i].text, pair_delim);
	}
	return value_list;
}

/* convert a list to a select box options */
function List2SelectBox(select_box, list, value_delim, pair_delim){
	for(var i=1; i<=listLen(list, pair_delim); i++) {
		select_box.options[select_box.options.length] = new Option();
		select_box.options[select_box.options.length-1].text = listGetAt(listGetAt(list, i, pair_delim), 2, value_delim);
		select_box.options[select_box.options.length-1].value =  listGetAt(listGetAt(list, i, pair_delim), 1, value_delim);
	}
	return true;
}

/* this function add an option to a select box at the specified position 
	if position = -1 => add to the end of the select box options
*/
function addOption(select_box, val, txt, position){
	// create the new option ...
	select_box.options[select_box.length] = new Option();

	// copy all option on the next value
	for(var i=select_box.length-1; i>=position; i--) {
		select_box.options[i].value = select_box.options[i-1].value;
		select_box.options[i].text = select_box.options[i-1].text;
		select_box.options[i].selected = select_box.options[i-1].selected;
	}
	// copy the value at the right place
	if(position >= select_box.length)
		position = select_box.length;
	select_box.options[position-1].text = txt;
	select_box.options[position-1].value = val;
}
function getFirstSelectBox(obj_name){
	for(var j=0; j<=1; j++) {
		if(j == 0)
			field_type = "Modify";
		if(j == 1)
			field_type = "Add";
		var finish = 0;
		var i = 1;
		while(!finish) {
			var each_obj = eval("document.dsp_form." + field_type + "__" + i + "__" + obj_name);
			if(each_obj) {
				if(each_obj.options) {return each_obj;}
			} 
			else finish = 1;
			i++;
		}
	}
}
function initExclusive(obj, obj_name, default_value){
	var presel_value = "";
	if(!obj.initiated) { // this bool specify that the select boxeS have already been initiated ...
		var first_obj = getFirstSelectBox(obj_name);
		if(first_obj) { // there are some Modify__ select boxes => delte these value from the Add__ select boxes
			first_obj.orig_value = SelectBox2List(first_obj, ",", "~"); // set the orig_value properties ...
			// the select box has been initiated !
			for(var j=0; j<=1; j++) {
				if(j == 0)
					field_type = "Modify";
				if(j == 1)
					field_type = "Add";
				var finish = 0;
				var i = 1;
				while(!finish) {
					var each_obj = eval("document.dsp_form." + field_type + "__" + i + "__" + obj_name);
					if(each_obj) {
						each_obj.initiated = 1; 
						if(field_type == "Modify") {
							deleteOptionFromAllSelectBox(each_obj, obj_name);
							if(!each_obj.options) {
								first_obj.orig_value = listDeleteAt(first_obj.orig_value, listContains(first_obj.orig_value, each_obj.value + ",", "~"), "~");
							}
						}
					} 
					else finish = 1;
					i++;
				}
			}
		} else { // if it is not a modify select box, try the Add one
			first_obj = eval("document.dsp_form.Add__" + 1 + "__" + obj_name);
			first_obj.orig_value = SelectBox2List(first_obj, ",", "~"); // set the orig_value properties ...
		}
	}
	
	if(obj.options[obj.options.selectedIndex].value != default_value) {
		obj.old_value = obj.options[obj.options.selectedIndex].value;
		obj.old_text = obj.options[obj.options.selectedIndex].text;
	} 
	else {obj.old_value = null;}
}

/* this function add a value to all select box of the specified name but not in the specified select box */
function addOptionToAllSelectBox(cur_obj, obj_name, val, txt, position){
	for(var j=0; j<=1; j++) {
		if(j == 0)
			var field_type = "Modify";
		if(j == 1)
			var field_type = "Add";
		var finish = 0;
		var i = 1;
		while(!finish) {
			var each_obj = eval("document.dsp_form." + field_type + "__" + i + "__" + obj_name);
			if(each_obj) {
				if(each_obj.name != cur_obj.name)
					if(each_obj.options) addOption(each_obj, val, txt, position);
			} 
			else finish = 1;
			i++;
		}
	}
}

/* this function delete the selected index of the current object from all select boxes of the specified name 
	if cur_obj == -1 => delete from all select boxes !
*/
function deleteOptionFromAllSelectBox(cur_obj, obj_name){
	for(var j=0; j<=1; j++) {
		if(j == 0)
			var field_type = "Modify";
		if(j == 1)
			var field_type = "Add";
		var finish = 0;
		var i = 1;
		while(!finish) {
			var each_obj = eval("document.dsp_form." + field_type + "__" + i + "__" + obj_name);
			if(each_obj) {
				if(each_obj.name != cur_obj.name)
					if(cur_obj.options) deleteOption(each_obj, cur_obj.options[cur_obj.options.selectedIndex].value);
					else deleteOption(each_obj, cur_obj.value);
			} 
			else finish = 1;
			i++;
		}
	}
}

/* delete an option from a select box */
function deleteOption(select_box, val){
	var lg = select_box.length;
	if(val == -1) {select_box.length = 0;} 
	else {
		for(var i=0; i<select_box.length; i++) {
			if(select_box.options[i].value == val) {select_box.options[i] = null;}
		}
	}
	return true;
}

/* ========================================
		INTUITIVE SELECT
   ======================================== 
  Keyboard handling for SELECT controls
  Add onkeypress='keypress()' to your HTML SELECT control to use this functionality:
  Multiple keys pressed with a small interval time will be used as a substring
  to locate an entry, like in many other non-browser applications.
  NB: should only be used on sorted lists
*/
function stripAccents(s) {
	// return the given string in uppercase without accent letters
	s = s.toUpperCase();
	while ((i=s.search(/[\xc0-\xdd]/))!=-1) {
		s = s.replace(s.charAt(i), 'AAAAAAACEEEEIIIIDNOOOOOXOUUUUY'.charAt(s.charCodeAt(i)-192));
	}
	return s;
}
function selectKeydown() {
	if(event.keyCode < 41 && event.keyCode > 32) {
	    // clear the charbuffer when user uses arrow keys:
		event.srcElement.charbuffer = '';
		event.srcElement.mvalue = null;
	}
}
function keypress() {
	obj = event.srcElement;
	// This routine is only designed to process
	// keypresses on a SELECT list which has
	// at least two elements
	if (obj.tagName != 'SELECT') return;
	if (obj.children.length < 2) return;
	if (String.fromCharCode(event.keyCode).length==0) return;
	
	if (obj.charbuffer==null) {
		// First time this event is called on this object!
		// Define extra attributes and attach other event handlers
		obj.charbuffer=''; // used to find an OPTION that alphabetically follows right after this value (or is equal to it)
		obj.charbufferdate=0; // time when the last key was added to the buffer -- used as timeout
		obj.recursing=null; // used to prevent recursive onchange events
		obj.attachEvent("onkeydown", selectKeydown);
		obj.attachEvent("onclick", selectClick);
		if  (parseInt(obj.size) < 2) {
			obj.attachEvent("onchange", selectChange);
		}
	}
	// Treat ESC key: 
	if (event.keyCode==27) {
		obj.fireEvent('onchange'); // this call makes sure our mvalue is maintained as value.
		return;
	}
	// Clear the charbuffer if more than one second passed since the
	// last keystroke:
	if ((new Date).valueOf() - parseInt(obj.charbufferdate) > 1000) obj.charbuffer='';
	obj.charbufferdate = (new Date).valueOf();
	// Add the key to a charbuffer 
    obj.charbuffer += String.fromCharCode(event.keyCode).toUpperCase();


	// If we only have one key, then the default 
	// behaviour is fine. If not, we will do our own
	// processing...
	if (obj.charbuffer.length!=1) {
		// Find the closest matching option. It is assumed the labels
		// of the options are sorted alphabetically (case-insensitive). 
		var i = 0;
		var j = obj.children.length-1;
		while (j-i > 1) {
			var k = Math.floor((i+j) / 2);
			if (stripAccents(obj.children[k].innerText) >= obj.charbuffer) j = k;
			if (stripAccents(obj.children[k].innerText) <= obj.charbuffer) i = k;
		}
		if (stripAccents(obj.children[i].innerText) < obj.charbuffer) i = j;
		// Now select that option.
		obj.mvalue = i; // this is a custom property we define on the spot
		// this call will assure mvalue is used as value, even if IE had changed it.
		setTimeout("selectCorrect('" + event.srcElement.uniqueID + "');", 1);
	}
	else {
		obj.mvalue = null;
	}
}
function selectChange() {
	// After the change event has completed,
	// we need to re-correct the selected value to mvalue.
	if(event.srcElement.recursing == null ) {
		setTimeout("selectCorrect('" + event.srcElement.uniqueID + "');", 1);
		//event.srcElement.mvalue = null; -- removed by TK: source of bug. selectClick() takes over this function
	}
}

function selectCorrect(sID) {
	// IE has its own mechanism we need to override: mvalue should 
	// be the value to display, not the value of which the first
	// letter corresponds with the last key pressed.
	obj = document.getElementById(sID);
	if(obj.mvalue != null ) {
		if (obj.selectedIndex == obj.mvalue) {
			obj.selectedIndex = -1; // force next assignement to be really performed
		};
		obj.selectedIndex = obj.mvalue;
		if  (parseInt(obj.size) < 2) {
			obj.recursing=1; // prevent recursive call of this function in event handler
				obj.fireEvent('onchange');
			obj.recursing=null;
		}
	}
}

function selectClick() {
	// abort multichar functionality when mouse is used to select 
	obj.mvalue=null;
}

/*
used by the cascading select ...
*/
function setCascSelectValue(elem, val, init)
{
	var finish = 0;
	var cur_elem = casc_field[elem]["sub_select"];
	if(cur_elem == 0) // there is no more sub_select ...
		return ;
	while(!finish) {
		deleteOption(eval("document.all." + cur_elem), -1);
		if(casc_array[casc_field[elem]["selectCascNumber"]][casc_field[cur_elem]["nb_select"]][val]) {
			List2SelectBox(eval("document.all." + cur_elem), casc_array[casc_field[elem]["selectCascNumber"]][casc_field[cur_elem]["nb_select"]][val], "~", ",");
		}
		if(init) {
			eval("document.all." + cur_elem).options.selectedIndex = getIndexByValue(eval("document.all." + cur_elem), casc_field[cur_elem]["field_value"]);
			if(eval("document.all." + cur_elem).options.selectedIndex < 0)
				eval("document.all." + cur_elem).options.selectedIndex = 0;
		}
		if(casc_field[cur_elem]["sub_select"] != 0) {
			if(eval("document.all." + cur_elem).options.length > 0)
				val = eval("document.all." + cur_elem).options[eval("document.all." + cur_elem).options.selectedIndex].value;
			else 
				val = -1;
			elem = cur_elem;
			cur_elem = casc_field[cur_elem]["sub_select"];
		} else {
			finish = 1;
		}
	}
}



