// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

/* 
PopupWindow.js
Author: Matt Kruse
Last modified: 02/16/04

DESCRIPTION: This object allows you to easily and quickly popup a window
in a certain place. The window can either be a DIV or a separate browser
window.

COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the 
Macintosh platform. Due to bugs in Netscape 4.x, populating the popup 
window with <STYLE> tags may cause errors.

USAGE:
// Create an object for a WINDOW popup
var win = new PopupWindow(); 

// Create an object for a DIV window using the DIV named 'mydiv'
var win = new PopupWindow('mydiv'); 

// Set the window to automatically hide itself when the user clicks 
// anywhere else on the page except the popup
win.autoHide(); 

// Show the window relative to the anchor name passed in
win.showPopup(anchorname);

// Hide the popup
win.hidePopup();

// Set the size of the popup window (only applies to WINDOW popups
win.setSize(width,height);

// Populate the contents of the popup window that will be shown. If you 
// change the contents while it is displayed, you will need to refresh()
win.populate(string);

// set the URL of the window, rather than populating its contents
// manually
win.setUrl("http://www.site.com/");

// Refresh the contents of the popup
win.refresh();

// Specify how many pixels to the right of the anchor the popup will appear
win.offsetX = 50;

// Specify how many pixels below the anchor the popup will appear
win.offsetY = 100;

NOTES:
1) Requires the functions in AnchorPosition.js

2) Your anchor tag MUST contain both NAME and ID attributes which are the 
   same. For example:
   <A NAME="test" ID="test"> </A>

3) There must be at least a space between <A> </A> for IE5.5 to see the 
   anchor tag correctly. Do not do <A></A> with no space.

4) When a PopupWindow object is created, a handler for 'onmouseup' is
   attached to any event handler you may have already defined. Do NOT define
   an event handler for 'onmouseup' after you define a PopupWindow object or
   the autoHide() will not work correctly.
*/ 

// Set the position of the popup window based on the anchor
function PopupWindow_getXYPosition(anchorname) {
	var coordinates;
	if (this.type == "WINDOW") {
		coordinates = getAnchorWindowPosition(anchorname);
		}
	else {
		coordinates = getAnchorPosition(anchorname);
		}
	this.x = coordinates.x;
	this.y = coordinates.y;
	}
// Set width/height of DIV/popup window
function PopupWindow_setSize(width,height) {
	this.width = width;
	this.height = height;
	}
// Fill the window with contents
function PopupWindow_populate(contents) {
	this.contents = contents;
	this.populated = false;
	}
// Set the URL to go to
function PopupWindow_setUrl(url) {
	this.url = url;
	}
// Set the window popup properties
function PopupWindow_setWindowProperties(props) {
	this.windowProperties = props;
	}
// Refresh the displayed contents of the popup
function PopupWindow_refresh() {
	if (this.divName != null) {
		// refresh the DIV object
		if (this.use_gebi) {
			document.getElementById(this.divName).innerHTML = this.contents;
			}
		else if (this.use_css) { 
			document.all[this.divName].innerHTML = this.contents;
			}
		else if (this.use_layers) { 
			var d = document.layers[this.divName]; 
			d.document.open();
			d.document.writeln(this.contents);
			d.document.close();
			}
		}
	else {
		if (this.popupWindow != null && !this.popupWindow.closed) {
			if (this.url!="") {
				this.popupWindow.location.href=this.url;
				}
			else {
				this.popupWindow.document.open();
				this.popupWindow.document.writeln(this.contents);
				this.popupWindow.document.close();
			}
			this.popupWindow.focus();
			}
		}
	}
// Position and show the popup, relative to an anchor object
function PopupWindow_showPopup(anchorname) {
	this.getXYPosition(anchorname);
	this.x += this.offsetX;
	this.y += this.offsetY;
	if (!this.populated && (this.contents != "")) {
		this.populated = true;
		this.refresh();
		}
	if (this.divName != null) {
		// Show the DIV object
		if (this.use_gebi) {
			document.getElementById(this.divName).style.left = this.x + "px";
			document.getElementById(this.divName).style.top = this.y + "px";
			document.getElementById(this.divName).style.visibility = "visible";
			}
		else if (this.use_css) {
			document.all[this.divName].style.left = this.x;
			document.all[this.divName].style.top = this.y;
			document.all[this.divName].style.visibility = "visible";
			}
		else if (this.use_layers) {
			document.layers[this.divName].left = this.x;
			document.layers[this.divName].top = this.y;
			document.layers[this.divName].visibility = "visible";
			}
		}
	else {
		if (this.popupWindow == null || this.popupWindow.closed) {
			// If the popup window will go off-screen, move it so it doesn't
			if (this.x<0) { this.x=0; }
			if (this.y<0) { this.y=0; }
			if (screen && screen.availHeight) {
				if ((this.y + this.height) > screen.availHeight) {
					this.y = screen.availHeight - this.height;
					}
				}
			if (screen && screen.availWidth) {
				if ((this.x + this.width) > screen.availWidth) {
					this.x = screen.availWidth - this.width;
					}
				}
			var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled );
			this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+"");
			}
		this.refresh();
		}
	}
// Hide the popup
function PopupWindow_hidePopup() {
	if (this.divName != null) {
		if (this.use_gebi) {
			document.getElementById(this.divName).style.visibility = "hidden";
			}
		else if (this.use_css) {
			document.all[this.divName].style.visibility = "hidden";
			}
		else if (this.use_layers) {
			document.layers[this.divName].visibility = "hidden";
			}
		}
	else {
		if (this.popupWindow && !this.popupWindow.closed) {
			this.popupWindow.close();
			this.popupWindow = null;
			}
		}
	}
// Pass an event and return whether or not it was the popup DIV that was clicked
function PopupWindow_isClicked(e) {
	if (this.divName != null) {
		if (this.use_layers) {
			var clickX = e.pageX;
			var clickY = e.pageY;
			var t = document.layers[this.divName];
			if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) {
				return true;
				}
			else { return false; }
			}
		else if (document.all) { // Need to hard-code this to trap IE for error-handling
			var t = window.event.srcElement;
			while (t.parentElement != null) {
				if (t.id==this.divName) {
					return true;
					}
				t = t.parentElement;
				}
			return false;
			}
		else if (this.use_gebi && e) {
			var t = e.originalTarget;
			while (t.parentNode != null) {
				if (t.id==this.divName) {
					return true;
					}
				t = t.parentNode;
				}
			return false;
			}
		return false;
		}
	return false;
	}

// Check an onMouseDown event to see if we should hide
function PopupWindow_hideIfNotClicked(e) {
	if (this.autoHideEnabled && !this.isClicked(e)) {
		this.hidePopup();
		}
	}
// Call this to make the DIV disable automatically when mouse is clicked outside it
function PopupWindow_autoHide() {
	this.autoHideEnabled = true;
	}
// This global function checks all PopupWindow objects onmouseup to see if they should be hidden
function PopupWindow_hidePopupWindows(e) {
	for (var i=0; i<popupWindowObjects.length; i++) {
		if (popupWindowObjects[i] != null) {
			var p = popupWindowObjects[i];
			p.hideIfNotClicked(e);
			}
		}
	}
// Run this immediately to attach the event listener
function PopupWindow_attachListener() {
	if (document.layers) {
		document.captureEvents(Event.MOUSEUP);
		}
	window.popupWindowOldEventListener = document.onmouseup;
	if (window.popupWindowOldEventListener != null) {
		document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();");
		}
	else {
		document.onmouseup = PopupWindow_hidePopupWindows;
		}
	}
// CONSTRUCTOR for the PopupWindow object
// Pass it a DIV name to use a DHTML popup, otherwise will default to window popup
function PopupWindow() {
	if (!window.popupWindowIndex) { window.popupWindowIndex = 0; }
	if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); }
	if (!window.listenerAttached) {
		window.listenerAttached = true;
		PopupWindow_attachListener();
		}
	this.index = popupWindowIndex++;
	popupWindowObjects[this.index] = this;
	this.divName = null;
	this.popupWindow = null;
	this.width=0;
	this.height=0;
	this.populated = false;
	this.visible = false;
	this.autoHideEnabled = false;
	
	this.contents = "";
	this.url="";
	this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no";
	if (arguments.length>0) {
		this.type="DIV";
		this.divName = arguments[0];
		}
	else {
		this.type="WINDOW";
		}
	this.use_gebi = false;
	this.use_css = false;
	this.use_layers = false;
	if (document.getElementById) { this.use_gebi = true; }
	else if (document.all) { this.use_css = true; }
	else if (document.layers) { this.use_layers = true; }
	else { this.type = "WINDOW"; }
	this.offsetX = 0;
	this.offsetY = 0;
	// Method mappings
	this.getXYPosition = PopupWindow_getXYPosition;
	this.populate = PopupWindow_populate;
	this.setUrl = PopupWindow_setUrl;
	this.setWindowProperties = PopupWindow_setWindowProperties;
	this.refresh = PopupWindow_refresh;
	this.showPopup = PopupWindow_showPopup;
	this.hidePopup = PopupWindow_hidePopup;
	this.setSize = PopupWindow_setSize;
	this.isClicked = PopupWindow_isClicked;
	this.autoHide = PopupWindow_autoHide;
	this.hideIfNotClicked = PopupWindow_hideIfNotClicked;
	}


// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// HISTORY
// ------------------------------------------------------------------
// March 14, 2003: Added ability to disable individual dates or date
//      ranges, display as light gray and strike-through
// March 14, 2003: Removed dependency on graypixel.gif and instead 
///     use table border coloring
// March 12, 2003: Modified showCalendar() function to allow optional
//      start-date parameter
// March 11, 2003: Modified select() function to allow optional
//      start-date parameter
// December 19, 2008 : add function addEnabledRangeDates, caugustin
// Feb 18 2008 : replace <= and >= by < and > for disable date range, caugustin.
/* 
DESCRIPTION: This object implements a popup calendar to allow the user to
select a date, month, quarter, or year.

COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the 
Macintosh platform.
The calendar can be modified to work for any location in the world by 
changing which weekday is displayed as the first column, changing the month
names, and changing the column headers for each day.

USAGE:
// Create a new CalendarPopup object of type WINDOW
var cal = new CalendarPopup(); 

// Create a new CalendarPopup object of type DIV using the DIV named 'mydiv'
var cal = new CalendarPopup('mydiv'); 

// Easy method to link the popup calendar with an input box. 
cal.select(inputObject, anchorname, dateFormat);
// Same method, but passing a default date other than the field's current value
cal.select(inputObject, anchorname, dateFormat, '01/02/2000');
// This is an example call to the popup calendar from a link to populate an 
// input box. Note that to use this, date.js must also be included!!
<A HREF="#" onClick="cal.select(document.forms[0].date,'anchorname','MM/dd/yyyy'); return false;">Select</A>

// Set the type of date select to be used. By default it is 'date'.
cal.setDisplayType(type);

// When a date, month, quarter, or year is clicked, a function is called and
// passed the details. You must write this function, and tell the calendar
// popup what the function name is.
// Function to be called for 'date' select receives y, m, d
cal.setReturnFunction(functionname);
// Function to be called for 'month' select receives y, m
cal.setReturnMonthFunction(functionname);
// Function to be called for 'quarter' select receives y, q
cal.setReturnQuarterFunction(functionname);
// Function to be called for 'year' select receives y
cal.setReturnYearFunction(functionname);

// Show the calendar relative to a given anchor
cal.showCalendar(anchorname);

// Hide the calendar. The calendar is set to autoHide automatically
cal.hideCalendar();

// Set the month names to be used. Default are English month names
cal.setMonthNames("January","February","March",...);

// Set the month abbreviations to be used. Default are English month abbreviations
cal.setMonthAbbreviations("Jan","Feb","Mar",...);

// Set the text to be used above each day column. The days start with 
// sunday regardless of the value of WeekStartDay
cal.setDayHeaders("S","M","T",...);

// Set the day for the first column in the calendar grid. By default this
// is Sunday (0) but it may be changed to fit the conventions of other
// countries.
cal.setWeekStartDay(1); // week is Monday - Saturday

// Set the weekdays which should be disabled in the 'date' select popup. You can
// then allow someone to only select week end dates, or Tuedays, for example
cal.setDisabledWeekDays(0,1); // To disable selecting the 1st or 2nd days of the week

// Selectively disable individual days or date ranges. Disabled days will not
// be clickable, and show as strike-through text on current browsers.
// Date format is any format recognized by parseDate() in date.js
// Pass a single date to disable:
cal.addDisabledDates("2003-01-01");
// Pass null as the first parameter to mean "anything up to and including" the
// passed date:
cal.addDisabledDates(null, "01/02/03");
// Pass null as the second parameter to mean "including the passed date and
// anything after it:
cal.addDisabledDates("Jan 01, 2003", null);
// Pass two dates to disable all dates inbetween and including the two
cal.addDisabledDates("January 01, 2003", "Dec 31, 2003");

// When the 'year' select is displayed, set the number of years back from the 
// current year to start listing years. Default is 2.
cal.setYearSelectStartOffset(2);

// Text for the word "Today" appearing on the calendar
cal.setTodayText("Today");

// Set the calendar offset to be different than the default. By default it
// will appear just below and to the right of the anchorname. So if you have
// a text box where the date will go and and anchor immediately after the
// text box, the calendar will display immediately under the text box.
cal.offsetX = 20;
cal.offsetY = 20;

NOTES:
1) Requires the functions in AnchorPosition.js and PopupWindow.js

2) Your anchor tag MUST contain both NAME and ID attributes which are the 
   same. For example:
   <A NAME="test" ID="test"> </A>

3) There must be at least a space between <A> </A> for IE5.5 to see the 
   anchor tag correctly. Do not do <A></A> with no space.

4) When a CalendarPopup object is created, a handler for 'onmouseup' is
   attached to any event handler you may have already defined. Do NOT define
   an event handler for 'onmouseup' after you define a CalendarPopup object 
   or the autoHide() will not work correctly.
   
5) The calendar popup display uses style sheets to make it look nice.

*/ 

// CONSTRUCTOR for the CalendarPopup Object
function CalendarPopup() {
	var c;
	if (arguments.length>0) {
		c = new PopupWindow(arguments[0]);
		}
	else {
		c = new PopupWindow();
		c.setSize(150,175);
		}
	c.offsetX = -152;
	c.offsetY = 25;
	c.autoHide();
	// Calendar-specific properties
	c.monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	c.monthAbbreviations = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	c.weekEndDays = new Array(0,0,0,0,0,1,1);
	c.dayHeaders = new Array("S","M","T","W","T","F","S");
	c.returnFunction = "CalendarPopup_tmpReturnFunction";
	c.returnMonthFunction = "CalendarPopup_tmpReturnMonthFunction";
	c.returnQuarterFunction = "CalendarPopup_tmpReturnQuarterFunction";
	c.returnYearFunction = "CalendarPopup_tmpReturnYearFunction";
	c.weekStartDay = 0;
	c.isShowYearNavigation = false;
	c.isSelectForYearAndMonths = false;
	c.displayType = "date";
	c.disabledWeekDays = new Object();
	c.disabledDatesExpression = "";
    c.startDateFromRange=null;
    c.endDateFromeRange = null;
	c.yearSelectStartOffset = 2;
	c.currentDate = null;
	c.todayText="Today";
	window.CalendarPopup_targetInput = null;
	window.CalendarPopup_targetInputMin = null;
	window.CalendarPopup_targetInputMax = null;
	window.CalendarPopup_dateFormat = "mm/dd/yyyy";
	// Method mappings
	c.setReturnFunction = CalendarPopup_setReturnFunction;
	c.setReturnMonthFunction = CalendarPopup_setReturnMonthFunction;
	c.setReturnQuarterFunction = CalendarPopup_setReturnQuarterFunction;
	c.setReturnYearFunction = CalendarPopup_setReturnYearFunction;
	c.setMonthNames = CalendarPopup_setMonthNames;
	c.setMonthAbbreviations = CalendarPopup_setMonthAbbreviations;
	c.setDayHeaders = CalendarPopup_setDayHeaders;
	c.setWeekStartDay = CalendarPopup_setWeekStartDay;
	c.setDisplayType = CalendarPopup_setDisplayType;
	c.setDisabledWeekDays = CalendarPopup_setDisabledWeekDays;
	c.addDisabledDates = CalendarPopup_addDisabledDates;
        c.addEnabledRangeDates = CalendarPopup_addEnabledRangeDates;
	c.setYearSelectStartOffset = CalendarPopup_setYearSelectStartOffset;
	c.setYearSelectEndOffset = CalendarPopup_setYearSelectEndOffset;
	c.setShowMoreText = CalendarPopup_setShowMoreText;
	c.setTodayText = CalendarPopup_setTodayText;
	c.setMoreText = CalendarPopup_setMoreText;
	c.showYearNavigation = CalendarPopup_showYearNavigation;
	c.showCalendar = CalendarPopup_showCalendar;
	c.hideCalendar = CalendarPopup_hideCalendar;
	c.getStyles = CalendarPopup_getStyles;
	c.refreshCalendar = CalendarPopup_refreshCalendar;
	c.getCalendar = CalendarPopup_getCalendar;
	c.select = CalendarPopup_select;
	// Return the object
	return c;
	}

// Temporary default functions to be called when items clicked, so no error is thrown
function CalendarPopup_tmpReturnFunction(y,m,d) { 
	// if a target input has been set
	if (window.CalendarPopup_targetInput!=null)
	{
		var dt = new Date(y,m-1,d,0,0,0);
		// if minimum date setted
		if(window.CalendarPopup_minimumDate != undefined && window.CalendarPopup_minimumDate != null)
		{
			// test the selected date
			if(dt.getTime() < window.CalendarPopup_minimumDate)
			{
				alert("Vous ne pouvez pas sélectionner une date inférieure au "+formatDate(new Date(window.CalendarPopup_minimumDate),"dd/MM/yyyy")+".");
				return;
			}
		}
		window.CalendarPopup_targetInput.value = formatDate(dt,window.CalendarPopup_dateFormat);
		if(window.CalendarPopup_targetInputMax != null && window.CalendarPopup_targetInput == window.CalendarPopup_targetInputMin)
			ensureMaxIsNotInf(window.CalendarPopup_targetInputMin,window.CalendarPopup_targetInputMax)
		if(window.CalendarPopup_targetInputMin != null && window.CalendarPopup_targetInput == window.CalendarPopup_targetInputMax)
			ensureMinIsNotSup(window.CalendarPopup_targetInputMin,window.CalendarPopup_targetInputMax);

               // added by fabien
               window.CalendarPopup_targetInput.select();
               // IE
               if( window.CalendarPopup_targetInput.onchange != null )
                  window.CalendarPopup_targetInput.onchange();
               // Mozilla
               if( window.CalendarPopup_targetInput.onChange != null )
                  window.CalendarPopup_targetInput.onChange();

		if(window.CalendarPopup_onchange != undefined && window.CalendarPopup_onchange != null)
		{
			var test = eval(window.CalendarPopup_onchange);
			if(test != undefined && !test)
				return;
		}

			}
	else {
		alert('Use setReturnFunction() to define which function will get the clicked results!'); 
		}
	}
	
function CalendarPopup_tmpReturnMonthFunction(y,m) { 
	alert('Use setReturnMonthFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , month='+m); 
	}
function CalendarPopup_tmpReturnQuarterFunction(y,q) { 
	alert('Use setReturnQuarterFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , quarter='+q); 
	}
function CalendarPopup_tmpReturnYearFunction(y) { 
	alert('Use setReturnYearFunction() to define which function will get the clicked results!\nYou clicked: year='+y); 
	}

// Set the name of the functions to call to get the clicked item
function CalendarPopup_setReturnFunction(name) { this.returnFunction = name; }
function CalendarPopup_setReturnMonthFunction(name) { this.returnMonthFunction = name; }
function CalendarPopup_setReturnQuarterFunction(name) { this.returnQuarterFunction = name; }
function CalendarPopup_setReturnYearFunction(name) { this.returnYearFunction = name; }

// Over-ride the built-in month names
function CalendarPopup_setMonthNames() {
	for (var i=0; i<arguments.length; i++) { this.monthNames[i] = arguments[i]; }
	}

// Over-ride the built-in month abbreviations
function CalendarPopup_setMonthAbbreviations() {
	for (var i=0; i<arguments.length; i++) { this.monthAbbreviations[i] = arguments[i]; }
	}

// Over-ride the built-in column headers for each day
function CalendarPopup_setDayHeaders() {
	for (var i=0; i<arguments.length; i++) { this.dayHeaders[i] = arguments[i]; }
	}

// Set the day of the week (0-7) that the calendar display starts on
// This is for countries other than the US whose calendar displays start on Monday(1), for example
function CalendarPopup_setWeekStartDay(day) { this.weekStartDay = day; }

// Show next/last year navigation links
function CalendarPopup_showYearNavigation() { this.isShowYearNavigation = true; }

// Which type of calendar to display
function CalendarPopup_setDisplayType(type) {
	if (type!="date"&&type!="week-end"&&type!="month"&&type!="quarter"&&type!="year") { alert("Invalid display type! Must be one of: date,week-end,month,quarter,year"); return false; }
	this.displayType=type;
	}

// How many years back to start by default for year display
function CalendarPopup_setYearSelectStartOffset(num) { this.yearSelectStartOffset=num; }

function CalendarPopup_setYearSelectEndOffset(num) { this.yearSelectEndOffset=num; }

function CalendarPopup_setShowMoreText( bShow ) { this.bShowMoreText = bShow; }

// Set which weekdays should not be clickable
function CalendarPopup_setDisabledWeekDays() {
	this.disabledWeekDays = new Object();
	for (var i=0; i<arguments.length; i++) { this.disabledWeekDays[arguments[i]] = true; }
	}
	
// Disable individual dates or ranges
// Builds an internal logical test which is run via eval() for efficiency
function CalendarPopup_addDisabledDates(start, end) {
	if (arguments.length==1) { end=start; }
	if (start==null && end==null) { return; }
	if (this.disabledDatesExpression!="") { this.disabledDatesExpression+= "||"; }
	if (start!=null) { start = parseDate(start); start=""+start.getFullYear()+LZ(start.getMonth()+1)+LZ(start.getDate());}
	if (end!=null) { end=parseDate(end); end=""+end.getFullYear()+LZ(end.getMonth()+1)+LZ(end.getDate());}
	if (start==null) { this.disabledDatesExpression+="(ds<"+end+")"; }
	else if (end  ==null) { this.disabledDatesExpression+="(ds>"+start+")"; }
	else { this.disabledDatesExpression+="(ds>"+start+"&&ds<"+end+")"; }
}
// Enable all date inside the range
function CalendarPopup_addEnabledRangeDates(start, end) {
	if (start==null || end==null || start=='' || end=='') { return; }
        this.addDisabledDates( null, start );
        this.addDisabledDates( end, null );
        this.startDateFromRange = start;
        this.endDateFromRange =  end ;
}
	
// Set the text to use for the "Today" link
function CalendarPopup_setTodayText(text) {
	this.todayText = text;
	}
	
function CalendarPopup_setMoreText(text)
{
   this.moreText = text;
}

// Hide a calendar object
function CalendarPopup_hideCalendar() {
	if (arguments.length > 0) { window.popupWindowObjects[arguments[0]].hidePopup(); }
	else { this.hidePopup(); }
	}

// Refresh the contents of the calendar display
function CalendarPopup_refreshCalendar(index) {
	var calObject = window.popupWindowObjects[index];
	if (arguments.length>1) { 
		calObject.populate(calObject.getCalendar(arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]));
		}
	else {
		calObject.populate(calObject.getCalendar());
		}
	calObject.refresh();
	}

// Populate the calendar and display it
function CalendarPopup_showCalendar(anchorname) {
	if (arguments.length>1) {
		if (arguments[1]==null||arguments[1]=="") {
			this.currentDate= getCurrentDate();
			}
		else {
			this.currentDate=new Date(parseDate(arguments[1]));
			}
		}
	this.populate(this.getCalendar());
	this.showPopup(anchorname);
	}

// Simple method to interface popup calendar with a text-entry box
function CalendarPopup_select(inputobj, linkname, format)
{
	var selectedDate=(arguments.length>3)?arguments[3]:null;
	if (!window.getDateFromFormat) {
		alert("calendar.select: To use this method you must also include 'date.js' for date formatting");
		return;
		}
	if (this.displayType!="date"&&this.displayType!="week-end") {
		alert("calendar.select: This function can only be used with displayType 'date' or 'week-end'");
		return;
		}
	if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") { 
		alert("calendar.select: Input object passed is not a valid form input object"); 
		window.CalendarPopup_targetInput=null;
		return;
		}
	if(arguments.length > 4)
		window.CalendarPopup_targetInputMin = arguments[4];
	if(arguments.length > 5)
		window.CalendarPopup_targetInputMax = arguments[5];
	if(arguments.length > 6)
	{
		var minimum_date = arguments[6];
		minimum_date = getDateFromFormat(minimum_date,format);
		if(minimum_date != 0)
			window.CalendarPopup_minimumDate = minimum_date;
	}
	if(arguments.length > 7)
	{
		window.CalendarPopup_onchange = arguments[7];
	}
	window.CalendarPopup_targetInput = inputobj;
	this.currentDate=null;
	var time=0;
	if (selectedDate!=null) {
		time = getDateFromFormat(selectedDate,format)
		}
        else if (inputobj.value!="") {
		time = getDateFromFormat(inputobj.value,format);
		}

    if (selectedDate!=null || inputobj.value!="")
    {
		if (time==0) { this.currentDate=null; }
		else
        { 
            this.currentDate=new Date(time);
        }
	}
    else if(this.startDateFromRange)
    {
        time = getDateFromFormat(this.startDateFromRange,format);
        this.currentDate=new Date(time);
    }

    window.CalendarPopup_dateFormat = format;
    this.showCalendar( linkname );  
}

function ensureMaxIsNotInf(oMin,oMax)
{
	if(oMax.value != "" && oMin.value != "")
	{
		datemin = parseDate(oMin.value,true);
		datemax = parseDate(oMax.value,true);
		if(datemin!= null && datemax != null && datemin > datemax)
			oMax.value = formatDate(datemin,"dd/MM/yyyy");
	}
}
function ensureMinIsNotSup(oMin,oMax)
{
	if(oMax.value != "" && oMin.value != "")
	{
		datemin = parseDate(oMin.value,true);
		datemax = parseDate(oMax.value,true);
		if(datemin!= null && datemax != null && datemin > datemax)
			oMin.value = formatDate(datemax,"dd/MM/yyyy");
	}
}

	
// Get style block needed to display the calendar correctly
function CalendarPopup_getStyles() {
	var result = "";
	result += "<STYLE>\n";
	result += "TD.cal,TD.calday,TD.calmonth,TD.caltoday,A.textlink,.disabledtextlink { font-family:arial; font-size: 8pt; }\n";
	result += "TD.calday{border:solid thin #C0C0C0;border-width:0 0 1 0;}\n";
	result += "TD.calmonth{text-align:right;}\n";
	result += "TD.caltoday{text-align:right;color:white;background-color:#C0C0C0;border-width:1;border:solid thing #800000;}\n";
	result += "TD.textlink{border:solid thin #C0C0C0; border-width:1 0 0 0;}\n";
	result += "A.textlink{height:20px;color:black;}\n";
	result += ".disabledtextlink{height:20px;color:#808080;}\n";
	result += "A.cal{text-decoration:none;color:#000000;}\n";
	result += "A.calthismonth{text-decoration:none;color:#000000;}\n";
	result += "A.calothermonth{text-decoration:none; color:#808080;}\n";
	result += ".calnotclickable{color:#808080;}\n";
	result += ".disabled{color:#D0D0D0;text-decoration:line-through;}\n";
	result += "</STYLE>\n";
	return result;
	}

// Return a string containing all the calendar code to be displayed
function CalendarPopup_getCalendar() {
	var now = getCurrentDate();
	// Reference to window
	if (this.type == "WINDOW") { var windowref = "window.opener."; }
	else { var windowref = ""; }
	var result = "";
	// If POPUP, write entire HTML document
	if (this.type == "WINDOW") {
		result += "<HTML><HEAD><TITLE>Calendrier</TITLE>"+this.getStyles()+"</HEAD><BODY MARGINWIDTH=0 MARGINHEIGHT=0 TOPMARGIN=0 RIGHTMARGIN=0 LEFTMARGIN=0>\n";
		result += '<CENTER><TABLE WIDTH=100% BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>\n';
		}
	else {
		result += '<TABLE WIDTH=144 BORDER=1 BORDERWIDTH=1 BORDERCOLOR="#808080" CELLSPACING=0 CELLPADDING=1>\n';
		result += '<TR><TD ALIGN=CENTER>\n';
		result += '<CENTER>\n';
		}
	var t144="<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
	// Code for DATE display (default)
	// -------------------------------
	if (this.displayType=="date" || this.displayType=="week-end") {
		if (this.currentDate==null) { this.currentDate = now; }
		if (arguments.length > 0) { var month = arguments[0]; }
			else { var month = this.currentDate.getMonth()+1; }
		if (arguments.length > 1) { var year = arguments[1]; }
			else { var year = this.currentDate.getFullYear(); }
		var daysinmonth= new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
		if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) {
			daysinmonth[2] = 29;
			}
		var current_month = new Date(year,month-1,1);
		var display_year = year;
		var display_month = month;
		var display_date = 1;
		var weekday= current_month.getDay();
		var offset = 0;
		if (weekday >= this.weekStartDay) {
			offset = weekday - this.weekStartDay;
			}
		else {
			offset = 7-this.weekStartDay+weekday;
			}
		if (offset > 0) {
			display_month--;
			if (display_month < 1) { display_month = 12; display_year--; }
			display_date = daysinmonth[display_month]-offset+1;
			}
		var next_month = month+1;
		var next_month_year = year;
		if (next_month > 12) { next_month=1; next_month_year++; }
		var last_month = month-1;
		var last_month_year = year;
		if (last_month < 1) { last_month=12; last_month_year--; }
		var date_class;
		if (this.type!="WINDOW") {
			result += t144;
			}
		result += '<TR>\n';
		var refresh = 'javascript:'+windowref+'CalendarPopup_refreshCalendar';
		var td = '<TD CLASS="cal"';
		if (this.isSelectForYearAndMonths)
		{
			var shown_month = "<select id='month_select' onchange='"+refresh+"("+this.index+",1*(getElementById(\"month_select\").options[getElementById(\"month_select\").selectedIndex].value),1*(getElementById(\"year_select\").options[getElementById(\"year_select\").selectedIndex].value))'>";
			for(i=0;i<12;i++)
				shown_month+="<option value='"+(i+1)+"' "+(i == month-1 ? "selected":"")+">"+this.monthNames[i]+"</option>\n";
			shown_month += "</select>";
			var shown_year = "<select id='year_select' onchange='"+refresh+"("+this.index+",1*(getElementById(\"month_select\").options[getElementById(\"month_select\").selectedIndex].value),1*(getElementById(\"year_select\").options[getElementById(\"year_select\").selectedIndex].value))'>";
			
			var nStartOffset = this.yearSelectStartOffset;
			var nEndOffset = this.yearSelectEndOffset > 0 ? this.yearSelectEndOffset : nStartOffset;
			for(i=-nStartOffset;i<nEndOffset;i++)
			{
				var sValue = year + i;
				var sLabel = this.bShowMoreText && ( i == -nStartOffset || i == nEndOffset - 1 ) ? this.moreText : sValue;
				shown_year+="<option value='"+sValue+"' "+(sValue == year ? "selected":"")+">"+sLabel+"</option>\n";
			}
			shown_year += "</select>";
		}
		else
		{
			var shown_month = this.monthNames[month-1];
			var shown_year = year;
		}
		if (this.isShowYearNavigation) {
			result += td+'10><B><A CLASS="cal" HREF="'+refresh+'('+this.index+','+last_month+','+last_month_year+');">&lt;</A></B></TD>';
			result += td+'58>'+shown_month+'</TD>';
			result += td+'10><B><A CLASS="cal" HREF="'+refresh+'('+this.index+','+next_month+','+next_month_year+');">&gt;</A></B></TD>';
			result += td+'10>&nbsp;</TD>';
			result += td+'10><B><A CLASS="cal" HREF="'+refresh+'('+this.index+','+month+','+(year-1)+');">&lt;</A></B></TD>';
			result += td+'36>'+shown_year+'</TD>';
			result += td+'10><B><A CLASS="cal" HREF="'+refresh+'('+this.index+','+month+','+(year+1)+');">&gt;</A></B></TD>';
			}
		else {
			result += td+'22><B><A CLASS="cal" HREF="'+refresh+'('+this.index+','+last_month+','+last_month_year+');">&lt;&lt;</A></B></TD>\n';
			result += td+'100>'+shown_month+' '+shown_year+'</TD>\n';
			result += td+'22><B><A CLASS="cal" HREF="'+refresh+'('+this.index+','+next_month+','+next_month_year+');">&gt;&gt;</A></B></TD>\n';
			}
		result += '</TR></TABLE>\n';
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=0 CELLPADDING=1 ALIGN=CENTER>\n';
		result += '<TR>\n';
		for (var j=0; j<7; j++) {
			var td = "	<TD CLASS='"+(this.weekEndDays[j] > 0 ? "calday_weekend":"calday")+"' ALIGN=RIGHT WIDTH=14%>";
			result += td+this.dayHeaders[(this.weekStartDay+j)%7]+'</TD>\n';
			}
		result += '</TR>\n';
		for (var row=1; row<=6; row++) {
			result += '<TR>\n';
			for (var col=1; col<=7; col++) {
				if (display_month == month) {
					date_class = "calthismonth";
					}
				else {
					date_class = "calothermonth";
					}
				if ((display_month == this.currentDate.getMonth()+1 && display_month == now.getMonth()+1) && (display_date==this.currentDate.getDate() && display_date==now.getDate()) && (display_year==this.currentDate.getFullYear() && display_year==now.getFullYear())) {
					td_class="calselectedtoday"+(this.weekEndDays[col-1]>0 ? "_weekend":"");
					}
				else if ((display_month == this.currentDate.getMonth()+1) && (display_date==this.currentDate.getDate()) && (display_year==this.currentDate.getFullYear())) {
					td_class="calselectedday"+(this.weekEndDays[col-1]>0 ? "_weekend":"");
					}
				else if ((display_month == now.getMonth()+1) && (display_date==now.getDate()) && (display_year==now.getFullYear())) {
					td_class="caltoday"+(this.weekEndDays[col-1]>0 ? "_weekend":"");
					}
				else {
					td_class="calmonth"+(this.weekEndDays[col-1]>0 ? "_weekend":"");
					}
				var disabled=false;
				if (this.disabledDatesExpression!="") {
					var ds=""+display_year+LZ(display_month)+LZ(display_date);
					eval("disabled=("+this.disabledDatesExpression+")");
					}
				if (disabled || this.disabledWeekDays[col-1]) {
					date_class=(disabled)?"disabled":"calnotclickable";
					result += '	<TD CLASS="'+td_class+'"><SPAN CLASS="'+date_class+'">'+display_date+'</SPAN></TD>\n';
					}
				else {
					var selected_date = display_date;
					var selected_month = display_month;
					var selected_year = display_year;
					if (this.displayType=="week-end") {
						var d = new Date(selected_year,selected_month-1,selected_date,0,0,0,0);
						d.setDate(d.getDate() + (7-col));
						selected_year = d.getYear();
						if (selected_year < 1000) { selected_year += 1900; }
						selected_month = d.getMonth()+1;
						selected_date = d.getDate();
						}
					result += '	<TD CLASS="'+td_class+'"><A HREF="javascript:'+windowref+this.returnFunction+'('+selected_year+','+selected_month+','+selected_date+');'+windowref+'CalendarPopup_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+display_date+'</A></TD>\n';
					}
				display_date++;
				if (display_date > daysinmonth[display_month]) {
					display_date=1;
					display_month++;
					}
				if (display_month > 12) {
					display_month=1;
					display_year++;
					}
				}
			result += '</TR>';
			}
		var current_weekday = now.getDay();
		result += '<TR>\n';
		result += '	<TD COLSPAN=7 ALIGN=CENTER CLASS="textlink">\n';
		if (this.disabledWeekDays[current_weekday+1]) {
			result += '		<SPAN CLASS="disabledtextlink">'+this.todayText+'</SPAN>\n';
			}
		else {
			result += '		<A CLASS="textlink" HREF="javascript:'+windowref+this.returnFunction+'(\''+now.getFullYear()+'\',\''+(now.getMonth()+1)+'\',\''+now.getDate()+'\');'+windowref+'CalendarPopup_hideCalendar(\''+this.index+'\');">'+this.todayText+'</A>\n';
			}
		result += '		<BR>\n';
		result += '	</TD></TR></TABLE></CENTER></TD></TR></TABLE>\n';
	}

	// Code common for MONTH, QUARTER, YEAR
	// ------------------------------------
	if (this.displayType=="month" || this.displayType=="quarter" || this.displayType=="year") {
		if (arguments.length > 0) { var year = arguments[0]; }
		else { 
			if (this.displayType=="year") {	var year = now.getFullYear()-this.yearSelectStartOffset; }
			else { var year = now.getFullYear(); }
			}
		if (this.displayType!="year" && this.isShowYearNavigation) {
			result += t144;
			result += '<TR BGCOLOR="#C0C0C0">\n';
			result += '	<TD BGCOLOR="#C0C0C0" CLASS="cal" WIDTH=22 ALIGN=CENTER VALIGN=MIDDLE><B><A CLASS="cal" HREF="javascript:'+windowref+'CalendarPopup_refreshCalendar('+this.index+','+(year-1)+');">&lt;&lt;</A></B></TD>\n';
			result += '	<TD BGCOLOR="#C0C0C0" CLASS="cal" WIDTH=100 ALIGN=CENTER>'+year+'</TD>\n';
			result += '	<TD BGCOLOR="#C0C0C0" CLASS="cal" WIDTH=22 ALIGN=CENTER VALIGN=MIDDLE><B><A CLASS="cal" HREF="javascript:'+windowref+'CalendarPopup_refreshCalendar('+this.index+','+(year+1)+');">&gt;&gt;</A></B></TD>\n';
			result += '</TR></TABLE>\n';
			}
		}
		
	// Code for MONTH display 
	// ----------------------
	if (this.displayType=="month") {
		// If POPUP, write entire HTML document
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<4; i++) {
			result += '<TR>';
			for (var j=0; j<3; j++) {
				var monthindex = ((i*3)+j);
				result += '<TD WIDTH=33% ALIGN=CENTER><A CLASS="textlink" HREF="javascript:'+windowref+this.returnMonthFunction+'('+year+','+(monthindex+1)+');'+windowref+'CalendarPopup_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+this.monthAbbreviations[monthindex]+'</A></TD>';
				}
			result += '</TR>';
			}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
		}
	
	// Code for QUARTER display
	// ------------------------
	if (this.displayType=="quarter") {
		result += '<BR><TABLE WIDTH=120 BORDER=1 CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<2; i++) {
			result += '<TR>';
			for (var j=0; j<2; j++) {
				var quarter = ((i*2)+j+1);
				result += '<TD WIDTH=50% ALIGN=CENTER><BR><A CLASS="textlink" HREF="javascript:'+windowref+this.returnQuarterFunction+'('+year+','+quarter+');'+windowref+'CalendarPopup_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">Q'+quarter+'</A><BR><BR></TD>';
				}
			result += '</TR>';
			}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
		}

	// Code for YEAR display
	// ---------------------
	if (this.displayType=="year") {
		var yearColumnSize = 4;
		result += t144;
		result += '<TR BGCOLOR="#C0C0C0">\n';
		result += '	<TD BGCOLOR="#C0C0C0" CLASS="cal" WIDTH=50% ALIGN=CENTER VALIGN=MIDDLE><B><A CLASS="cal" HREF="javascript:'+windowref+'CalendarPopup_refreshCalendar('+this.index+','+(year-(yearColumnSize*2))+');">&lt;&lt;</A></B></TD>\n';
		result += '	<TD BGCOLOR="#C0C0C0" CLASS="cal" WIDTH=50% ALIGN=CENTER VALIGN=MIDDLE><B><A CLASS="cal" HREF="javascript:'+windowref+'CalendarPopup_refreshCalendar('+this.index+','+(year+(yearColumnSize*2))+');">&gt;&gt;</A></B></TD>\n';
		result += '</TR></TABLE>\n';
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<yearColumnSize; i++) {
			for (var j=0; j<2; j++) {
				var currentyear = year+(j*yearColumnSize)+i;
				result += '<TD WIDTH=50% ALIGN=CENTER><A CLASS="textlink" HREF="javascript:'+windowref+this.returnYearFunction+'('+currentyear+');'+windowref+'CalendarPopup_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+currentyear+'</A></TD>';
				}
			result += '</TR>';
			}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
		}
	// Common
	if (this.type == "WINDOW") {
		result += "</BODY></HTML>\n";
		}
	return result;
	}

function checkDateInput(sTFDate,sMinimumDate)
{
	var sValue = document.all[sTFDate].value;
	var tValue = getDateFromFormat(sValue,"d/M/y");
	var tMin = getDateFromFormat(sMinimumDate,"d/M/y");
	if(tValue == 0)
	{
		alert("La date n'est pas valide.");
		document.all[sTFDate].value = window[sTFDate+"_old_value"];
		return false;
	}
	if(tValue == 0 || tValue < tMin)
	{
		alert("La date ne peut pas être inférieure au \""+sMinimumDate+"\".");
		document.all[sTFDate].value = window[sTFDate+"_old_value"];
		return false;
	}
	else
	{
		window[sTFDate+"_old_value"] = sValue;
		return true;
	}
}




/**************************** Calendar functions ******************************************************/
function createFrenchCalendar()
{
	var calendar = new CalendarPopup();
	calendar.setDayHeaders("&nbsp;Dim&nbsp;","&nbsp;Lun&nbsp;","&nbsp;Mar&nbsp;","&nbsp;Mer&nbsp;","&nbsp;Jeu&nbsp;","&nbsp;Ven&nbsp;","&nbsp;Sam&nbsp;");
	calendar.setWeekStartDay(1);
	calendar.setTodayText("Aujourd'hui");
	calendar.setMoreText("Plus...");
	calendar.setMonthAbbreviations("Jan","Fev","Mar","Avr","Mai","Juin","Juil","Aout","Sep","Oct","Nov","Dec");
	calendar.setMonthNames("Janvier","Fevrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Décembre");
	calendar.isShowYearNavigation = true;
	calendar.isSelectForYearAndMonths = true;
	calendar.offsetX = 10;
	calendar.offsetY = 10;
	calendar.getStyles = calendarStyles;
	calendar.setSize(185,175);
	calendar.yearSelectStartOffset = 4;
	return calendar;
}
function calendarStyles()
{
	return g_sStyleElements;
}

pCalendar = createFrenchCalendar();



/**
 * JavaScript librairy
 * To enable cross-browser functionality on HostFlow
 * 
 * Should be compatible with : Internet Explorer (5+), Opera (7.1+), Netscape (7+), Mozilla (1.3+) and Konqueror 3.0+
 * Compatibility with previous versions has not been tested but might work with : Opera 7, Netscape 6 and Mozilla 1.0
 * 
 * Author : Cyril MICHAUD
 * Date : 08/05/2003
 */
var CURRENT_DATE;
var CURRENT_DATE_TIME;
var browser = 0;
//var browserVersion = 0;

var g_sHTMLTemplate = null;

var NETSCAPE = 1;
var IE = 2;
//notice: Konqueror is also Webkit, i.e. Safari
var KONQUEROR = 3;
var OPERA = 4;

var HELP_LAYER_NAME = "hf_help_layer";
var HELP_BGCOLOR = "#fffedd";

var TEXT_TO_UPPER = 1;
var TEXT_TO_LOWER = 2;
var TEXT_TO_CAPITALIZE = 3;
var TEXT_NO_FORMAT = 4;
var TEXT_TO_UPPER_ONLY_WORD = 5;

//from here
DOM = (document.getElementById) ? 1 : 0;
NS4 = (document.layers) ? 1 : 0;
IE4 = (document.all) ? 1 : 0;
IE7 = navigator.userAgent.indexOf("MSIE 7") > -1 ? 1 : 0;
Opera5 = (navigator.userAgent.indexOf("Opera 5") > -1 || navigator.userAgent.indexOf("Opera/5") > -1) ? 1 : 0;
//to here : to be deleted
//only here for compatibility with old templates

/**
 * Identify the browser
 * Return :
 *    - NETSCAPE : for Netscape Navigator and compatibles (ex: Mozilla)
 *    - IE : for Internet Explorer and compatibles (ex: Opera)
 *    - KONQUEROR : for Konqueror browser
 */
function getBrowser() {
    if(browser == 0) {
        var bwr = navigator.appName;
        if(bwr == "Netscape") {
            browser = NETSCAPE;
        }
        else if (bwr == "Microsoft Internet Explorer") {
            browser = IE;
        }
        else if (bwr == "Konqueror") {
            browser = KONQUEROR;
        }
        else if (bwr == "Opera") {
            browser = OPERA;
        }
        else {
            //unknown browser... we suppose it is a JavaScript compliant (not JScript) like Netscape or Mozilla
            browser = NETSCAPE;
        }
    }
    return browser;
}

// Figure out what browser is being used - taken from JQuery
/*function getBrowser() {
	if (browser == 0) {
		var userAgent = navigator.userAgent.toLowerCase();
		if (/webkit/.test( userAgent ))
			browser = KONQUEROR;
		else if (/opera/.test( userAgent ))
			browser = OPERA;
		else if (/msie/.test( userAgent ) && !/opera/.test( userAgent ))
			browser = IE;
		else if (/mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ))
			browser = NETSCAPE;
		else
			browser = NETSCAPE;
	}
	return browser;
};

function getBrowserVersion() {
	if (browserVersion == 0) {
		var userAgent = navigator.userAgent.toLowerCase();
		browserVersion = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1]; 
	}
	return browserVersion;
}

FF3 = (getBrowser()==NETSCAPE && getBrowserVersion()>3) ? 1 : 0;
if (FF3)
	alert('Running under firefox 3');*/

/**
 * Get the specified layer
 * Parameters :
 *   - layerName : the short name of the layer to show (example : <DIV id="toto">  => layerName="Toto")
 *                 note : a layer must be a <DIV> object to be compatible with both Netscape and IE
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 *   the layer object
 */
function getLayer(layerName, myDocument) {
    if(myDocument == null) myDocument = window.document;
    return myDocument.getElementById(layerName);

    var browser = getBrowser();

    var object;
    var style;
    switch (browser) {
    case NETSCAPE :
        object = myDocument.getElementById(layerName);
        break;
    case KONQUEROR :
    case IE :
    case OPERA :
        object = eval("myDocument.all."+layerName);
        break;
    }
    return object;
}


/**
 * Show the specified layer
 * Parameters :
 *   - layerName : the short name of the layer to show (example : <DIV id="toto">  => layerName="Toto")
 *                 note : a layer must be a <DIV> object to be compatible with both Netscape and IE
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 *   void
 */
function showLayer(layerName, myDocument, bBugFix, sNewValue, bSetVisibilityAttribute )
{
  var layers = getLayer(layerName, myDocument);

  var sNewDisplay = sNewValue ? sNewValue : '';

  if( bBugFix && layerName != 'globalcontent'  ) hideGlobalLayer();

  if(layers)
  {
    if( layers.length != null && layers.length > 0 )
    {
      for( var i = 0 ; i < layers.length ; i++ )
      {
        if (bSetVisibilityAttribute)
          layers[ i ].style.visibility = 'visible';
        else
          layers[ i ].style.display = sNewDisplay;
      }
    }
    else
    {
      if (bSetVisibilityAttribute)
        layers.style.visibility = 'visible';
      else
        layers.style.display = sNewDisplay;
    }
  }

  if( bBugFix && layerName != 'globalcontent'  ) showGlobalLayer();
}

/**
 * Hide the specified layer on the current html document
 * Parameters :
 *   - layerName : the short name of the layer to show (example : <DIV id="toto">  => layerName="Toto")
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 *   void
 */
function hideLayer( layerName, myDocument, bBugFix, unused, bSetVisibilityAttribute )
{
  var layers = getLayer(layerName, myDocument);
  if( layers == null )
  {
    return;
  }

  if( bBugFix && layerName != 'globalcontent' ) hideGlobalLayer();

  if( layers.length != null && layers.length > 0 )
  {
    for( var i = 0 ; i < layers.length ; i++ )
    {
      if (bSetVisibilityAttribute)
        layers[ i ].style.visibility = 'hidden';
      else
        layers[ i ].style.display = 'none';
    }
  }
  else
  {
    if (bSetVisibilityAttribute)
      layers.style.visibility = 'hidden';
    else
      layers.style.display = 'none';
  }

  if( bBugFix && layerName != 'globalcontent' ) showGlobalLayer();
}

// plus propre pour firefox
function showRow( sRowID, pDocument, bBugFix )
{
  var sNewDisplay = '';
  if ( getBrowser() == NETSCAPE )
    sNewDisplay = 'table-row';

  showLayer( sRowID, pDocument, bBugFix, sNewDisplay );
}

function showRowIf( sRowID, bTest, pDocument, bBugFix )
{
  if( bTest )
    showRow( sRowID, pDocument, bBugFix );
  else
    hideRow( sRowID, pDocument, bBugFix );
}

// juste un alias
function hideRow( sRowID, pDocument, bBugFix )
{
  hideLayer( sRowID, pDocument, bBugFix );
}

/**
 * Get if the layer is currently displayed or not
 * Parameters :
 *   - layerName : the short name of the layer (example : <LAYER id="toto">  => layerName="Toto")
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 *   - true : the layer is displayed
 *   - false : the layer is not displayed
 */
function getLayerDisplayed(layerName, myDocument)
{
  var layers = getLayer(layerName, myDocument);

  var style = (layers.length != null) ? layers[0].style : layers.style;

  return style.display == '' || style.display == 'block';
}



/**
 * Resize a layer
 * Parameters :
 *   - layerName : the short name of the layer (example : <LAYER id="toto">  => layerName="Toto")
 *   - width : the new width for the layer
 *   - height : the new height for the layer
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 *   - true : the layer is displayed
 *   - false : the layer is not displayed
 */
function resizeLayer(layerName, width, height, myDocument) {
  var objLayer = getLayer(layerName,myDocument);
  objLayer.style.width = width;
  objLayer.style.height = height;
}


/**
 * Get a layer size
 * Parameters :
 *   - layerName : the short name of the layer (example : <LAYER id="toto">  => layerName="Toto")
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 *   an array containing the size :
 *      ['height']
 *      ['width']
 */
function getLayerSize(layerName, myDocument) {
  var objLayer = getLayer(layerName, myDocument);
  var res = new Array();
  res['width'] = objLayer.style.width;
  res['height'] = objLayer.style.height;

  return res;
}


/**
 * Move a layer
 * Parameters :
 *   - layerName : the short name of the layer (example : <LAYER id="toto">  => layerName="Toto")
 *   - x : the new horizontal position
 *   - y : the new vertical position
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 */
function moveLayer(layerName, x, y, myDocument) {
  var browser = getBrowser();
  if(myDocument == null) myDocument = window.document;

  var objLayer = getLayer(layerName, myDocument);
  switch (browser) {
  case NETSCAPE :
      objLayer.style.top = y;
      objLayer.style.left = x;
      break;
  case KONQUEROR :
  case OPERA :
  case IE :
      objLayer.style.pixelTop = y;
      objLayer.style.pixelLeft = x;
      break;
  }
}

/**
 * Permet de déplacer une layer (div avec position: absolute)
 * A la même place qu'un autre élément de la page.
 * bUnderElement permet de positioner la layer en dessous de l'élement en question
 */
function moveLayerToElement(pLayer, pElement, bUnderElement)
{
    // sous internet explorer
    //  la proporiété element.style.top est une chaine de caratère qui peut
    //  être sous la forme 1cm ou 1px, c'est pourquoi on passe par la propriété
    //  offsetLeft et offsetHeight, qui est une propriété récursive de parent en parent
    if(getBrowser() == IE)
    {
        var iTop = pElement.offsetTop;
        var iLeft = pElement.offsetLeft;
        pParent = pElement.offsetParent;
        while( pLayer.offsetParent != pParent )
        {
            iTop += pParent.offsetTop;
            iLeft += pParent.offsetLeft;
            pParent = pParent.offsetParent;
        }
        pLayer.style.pixelTop = iTop + (bUnderElement ? pElement.offsetHeight : 0);
        pLayer.style.pixelLeft = iLeft;
    }
    // sous firefox, cela marche de faire cela... je ne sais pas ce qui se passe
    //  si une valeur est spécifiée en "cm"
    else
    {
        pLayer.style.top = pElement.style.top + (bUnderElement ? pElement.style.height : 0);
        pLayer.style.left = pElement.style.left;
    }
}


/**
 * Get a layer position
 * Parameters :
 *   - layerName : the short name of the layer (example : <LAYER id="toto">  => layerName="Toto")
 *   - myDocument (optional) : default value = window.document
 *           Allows to specify a document object on another window
 * Returns :
 *   an array containing the positions :
 *      ['top'] : the vertical postion
 *      ['left'] : the horizontal position
 */
function getLayerPosition(layerName, myDocument) {
  var browser = getBrowser();
  var objLayer = getLayer(layerName, myDocument);
  var res = new Array();
  switch (browser) {
  case NETSCAPE :
    res['top'] = objLayer.style.top;
    res['left'] = objLayer.style.left;
    break;
  case KONQUEROR :
  case OPERA :
  case IE :
    res['top'] = objLayer.style.pixelTop;
    res['left'] = objLayer.style.pixelLeft;
    break;
  }
  return res;
}

/*
 * Hides the global layer (on mozilla only) so that operations on layers are done smoothly and without error
 * hideGlobalLayer and showGlobalLayer should be used when showing or hiding large layers.
 */
function hideGlobalLayer( pDocument )
{
  if ( getBrowser() == NETSCAPE )
    setDOMObjectProperty( 'globalcontent', 'style.display', 'none' );
}

/*
 * See hideGlobalLayer()
 */
function showGlobalLayer( pDocument )
{
  if ( getBrowser() == NETSCAPE )
    setDOMObjectProperty( 'globalcontent', 'style.display', '' );
}

var paRegExp = new Array();

function getRegExp( sExp, sParams )
{
    if( !paRegExp[ sExp ] )
    {
        paRegExp[ sExp ] = new RegExp( sExp, sParams );
    }
    paRegExp[ sExp ].lastIndex = 0;
    return paRegExp[ sExp ];
}

function clearRegExpCache()
{
  paRegExp = new Array();
}

/**
 * Get a form object.
 * Parameters :
 *   - inputName : the short name of the object to get (example : <INPUT NAME="toto">  => Name="Toto")
 *   - formName (optional) : the name of the form which contains the input object
 *                 If the input object is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 * Returns :
 *   . the object if found
 */
function getFormObject(inputName, formName, myDocument, enforce)
{
    var browser = getBrowser();
    if(myDocument == null || myDocument == '') myDocument = window.document;
    var object;
    switch(browser)
    {
      case NETSCAPE :
        if(formName == null || formName == '' || formName == "all")
          object = myDocument.getElementById(inputName);
        else if( myDocument[formName] )
          object = myDocument[formName][inputName];
        if(!object)
          return null;
        break;
      case KONQUEROR :
      case OPERA :
      case IE :
        if(formName == null || formName == '')
          formName = "all";
        object = myDocument[formName] ? myDocument[formName][inputName] : null;
        if(!object)
          return null;
        
        if((object.id == null || object.id == "") && formName == 'all' && !enforce)
          window.alert("Warning : your Javascript will only work on Internet Explorer browsers.\nYou have to provide a value for the 'formName' argument.");
        break;
    }
    return object;
}

/**
 * Get objects with specified name.
 */
function getObjectsByName( sName )
{
    return document.getElementsByName( sName );
}

function setObjectProperty(pObject,sProperty,sValue)
{
  if(pObject == null)
    return null;
  var aProperties = new String(sProperty).split(".");
  var sOldValue = null;
  if(pObject)
  {
    if(aProperties.length == 1)
    {
      sOldValue = pObject[aProperties[0]];
      pObject[aProperties[0]] = sValue;
    }
    else if(aProperties.length == 2)
    {
      sOldValue = pObject[aProperties[0]][aProperties[1]];
      pObject[aProperties[0]][aProperties[1]] = sValue;
    }
  }
  return sOldValue;
}

function setNamedObjectProperty(inputName, sProperty, sValue)
{
    var aObjects = document.getElementsByName(inputName);
    for(var i=0;i<aObjects.length;i++)
    {
        aObjects[i][sProperty] = sValue;
    }
}

function setDOMObjectProperty( inputName, sProperty, sValue, pDocument )
{
  var sOldValue;
  if(g_sHTMLTemplate && g_sHTMLTemplate != "")
  {
    var a;
    // if it's a style
    if(a = getRegExp('^style\.(.*)$').exec(sProperty))
      sOldValue = updateInputObjectStyleTag(inputName, a[1], sValue);
    // if its a tag without value (e.g. disabled)
    else if(sValue === true || sValue === false)
      sOldValue = updateInputObjectNoValueTag(inputName, sProperty, sValue);
    else
      sOldValue = updateInputObjectTag(inputName, sProperty, sValue);
  }
  else
  {
    var pObject = getDOMObject( inputName, pDocument );
    sOldValue = setObjectProperty(pObject, sProperty, sValue);
  }
  return sOldValue;
}

function setFormObjectProperty(inputName, formName, sProperty, sValue, pDocument)
{
  var sOldValue;
  if(g_sHTMLTemplate && g_sHTMLTemplate != "")
  {
    var a;
    // if it's a style
    if(a = getRegExp('^style\.(.*)$').exec(sProperty))
    {
      var sStyle = a[1];
      sOldValue = updateInputObjectStyleTag(inputName, sStyle, sValue);
      //updateInputObjectStyleTag(inputName+'_select', sStyle, sValue);
      //updateInputObjectStyleTag(inputName+'_text', sStyle, sValue);
    }
    // if its a tag without value (e.g. disabled)
    else if(sValue === true || sValue === false)
    {
      sOldValue = updateInputObjectNoValueTag(inputName, sProperty, sValue);
      //updateInputObjectNoValueTag(inputName+'_select', sProperty, sValue);
      //updateInputObjectNoValueTag(inputName+'_text', sProperty, sValue);
    }
    else
    {
      sOldValue = updateInputObjectTag(inputName, sProperty, sValue);
      //updateInputObjectTag(inputName+'_select', sProperty, sValue);
      //updateInputObjectTag(inputName+'_text', sProperty, sValue);
    }
    // special, when we disable a field that have an associated link, hide this link
//    if(sProperty == 'disabled')
//      updateInputObjectStyleTag(inputName+'_link', 'visibility', sValue ? 'hidden' : 'visible');
  }
  else
  {
    var pObject = getFormObject(inputName, formName, pDocument);
    sOldValue = setObjectProperty(pObject, sProperty, sValue);
/*    pObject = getFormObject(inputName+'_select', formName);
    setObjectProperty(pObject, sProperty, sValue);
    pObject = getFormObject(inputName+'_text', formName);
    setObjectProperty(pObject, sProperty, sValue);*/
    // special, when we disable a field that have an associated link, hide this link
/*    if(sProperty == 'disabled')
    {
      pObject = getDOMObject(inputName+'_link');
      setObjectProperty(pObject, 'style.visibility', sValue ? 'hidden' : 'visible');
    }*/
  }
  return sOldValue;
}

function getDOMObject(inputName, myDocument)
{
    var browser = getBrowser();
    if(myDocument == null || myDocument == '') myDocument = window.document;
    if (myDocument.getElementById)
    {
            return myDocument.getElementById(inputName);
    }
    else if (myDocument.all)
    {
            return myDocument.all[inputName];
    }
    else if (myDocument.layers)
    {
            return myDocument.layers[inputName];
    }
}

function getDOMObjects(inputName, myDocument)
{
    if(myDocument == null || myDocument == '') myDocument = window.document;
    //if (myDocument.getElementsById)
    //{
        // après vérification dans la documentation MSDN, getElementByName retourne les éléments
        //  référencés par ID ou NAME
    	// LMA: Apres verification dans la doc Mozilla on a pas le meme comportement sous Moz
    	// seuls les objets avec attribut name sont cherches 
    	// (voir http://developer.mozilla.org/fr/docs/DOM:document.getElementsByName)
    	// donc: mefiance si vous utilisez cette fonction pour retrouver 
    	//des elements par ID sous Moz ca fonctionnera pas pareil que IE
        return myDocument.getElementsByName(inputName);
    //}
}

function getDOMInputValue( sObjectID, pDocument )
{
  return getObjectValue( getDOMObject( sObjectID, pDocument ) );
}

/**
 * Get the value of a form object.
 * Parameters :
 *   - inputName : the short name of the layer (example : <INPUT NAME="toto">  => Name="Toto")
 *   - formName (optional) : the name of the form which contains the input object
 *                 If the input object is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 * Returns :
 *   . object is unique textfield/textarea : the value of the textfield
 *   . object is unique checkbox or radio : TRUE is checked, FALSE otherwise
 *   . object is multiple radio : the value of the radio checked
 *   . object is unique select-one : the value of the selected option
 *   . object is unique select-multiple : array of the values representing the selected options
 *   . other : unsupported
 */
function getInputValue( inputName, formName, myDocument, enforce )
{
  return getObjectValue( getFormObject( inputName, formName, myDocument, enforce ) );
}

function getObjectValue( object )
{
  if( object == null )
  {
    return null;
  }
    
  if(object.length != null)
  {
      var nb = object.length;
      if(object.type == "select-one")
      {
        var i;
        for(i=0; i<nb; i++)
        {
          if(object.options[i].selected)
            return object.options[i].value;
        }
        return null;
      }
      else if(object.type == "select-multiple")
      {
        var res = new Array();
        for(var i=0; i<object.options.length; i++)
        {
          if(object.options[i].selected)
              res.push(object.options[i].value);
        }
        return res;
      }
      else if(object[0].type == "radio")
      {
        var i;
        for(i=0; i<nb; i++)
        {
          if(object[i].checked)
            return object[i].value;
        }
        return null;
      }
  }
  else if(object.type == "checkbox")
  {
    return object.checked;
  }
  else if(object.type == "radio")
  {
    if(object.checked)
      return object.value;
    else
      return null;
  }
  else
    return object.value;
}





/**
 * Set the value of a form object.
 * Parameters :
 *   - inputName : the short name of the layer (example : <INPUT NAME="toto">  => Name="Toto")
 *   - value : the new value
 *      . object is unique textfield/textarea : the new value of the textfield
 *      . object is unique checkbox or radio : TRUE to check, FALSE to uncheck
 *      . object is multiple radio : the value of the radio to check
 *      . object is unique select-one : the value of the option to select
 *      . object is unique select-multiple : array of values representing the options to select
 *      . other : not supported
 *   - formName (optional) : the name of the form which contains the input object
 *                 If the input object is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 * Returns :
 */

function setObjectValue( object, value )
{
  if( object == null )
    return;
  
  // text field    
  if(object.type == "text")
  {
    if(value == undefined)
      object.value = '';
    else
      object.value = value;
  }
  // select
  else if(object.length != null)
  {
    var nb = object.length;
    if(object.type == "select-one")
    {
      var i;
      for(i=0; i<nb; i++)
      {
        if(object[i].value == value)
          object.options[i].selected = true;
      }
    }
    else if(object.type == "select-multiple")
    {
      var i, j;
      if(!(value instanceof Array))
      {
        var aValue = new Array();
        aValue.push(value);
        value = aValue;
      }
      for(i=0; i<nb; i++)
      {
        object[i].selected = false;
        for (j=0; j<value.length; j++)
        {
          if(object[i].value == value[j])
            object[i].selected = true;
        }
      }
    }
    else if(object[0].type == "radio")
    {
      var i;
      for(i=0; i<nb; i++)
      {
        object[i].checked = false;
        if(object[i].value == value)
          object[i].checked = true;
      }
    }
  }
  else if(object.type == "checkbox")
  {
    if (!value || value == 'false')
      object.checked = false;
    else
      object.checked = true;
  }
  else if(object.type == "radio") 
  {
    object.checked = value;
  }
  else
  {
    if(value == undefined)
      object.value = '';
    else
      object.value = value;
  }
}

function setInputValue(inputName, value, formName, myDocument, enforce)
{
  // if set value in html template
  if(g_sHTMLTemplate && g_sHTMLTemplate != "")
  {  
    // update value tag
    updateInputObjectTag(inputName, 'value', value);
  }
  else
  {
    var pObject = getFormObject(inputName, formName, myDocument, enforce);
    setObjectValue( pObject, value );
  }
}

function setDOMInputValue( sObjectID, sValue, pDocument )
{
  setObjectValue( getDOMObject( sObjectID, pDocument ), sValue );
}
//All words first lettre toUpper 
function capitalizeObject(obj) {
    var sVal = obj.value;
    var sNewVal = '';
    sVal = sVal.split(' ');
    for(var c=0; c < sVal.length; c++) {
        sNewVal += sVal[c].substring(0,1).toUpperCase() +
                   sVal[c].substring(1, sVal[c].length );
        if( c < sVal.length - 1 )
            sNewVal += ' ';
    }
    obj.value = sNewVal;
}

function formatText(inputName, pObject, formName, nFormat, myDocument )
{
    if( !pObject && inputName )
        pObject = getFormObject( inputName, formName, myDocument )
        
    if( pObject )
    {
        var sVal = pObject.value;
        if(nFormat == TEXT_TO_UPPER)
        {
           pObject.value =  sVal.toUpperCase();
        }
        else if(nFormat == TEXT_TO_LOWER)
        {
            pObject.value =  sVal.toLowerCase();
        }
        else if(nFormat == TEXT_TO_CAPITALIZE)
        {
            capitalizeObject( pObject );
        }
        else if( nFormat == TEXT_TO_UPPER_ONLY_WORD )
        {
            pObject.value = new String( sVal.toUpperCase() ).replace( /\W/ig, ' ' );
        }
    }
}

function updateInputObjectNoValueTag(sName, sTag, sValue)
{
    // Ancienne fonction

  // remove it
  var re = getRegExp('<!--OBJ_' + sName + '--><(.*?)' + sTag + '(.*?)>(.*)<!--END_OBJ_' + sName + '-->', 'm');
  g_sHTMLTemplate = g_sHTMLTemplate.replace(re, '<!--OBJ_' + sName + '--><$1 $2>$3<!--END_OBJ_' + sName + '-->');
  if(sValue)
  {
    re = getRegExp('<!--OBJ_' + sName + '--><(.*?)>(.*)<!--END_OBJ_' + sName + '-->', 'm');
    g_sHTMLTemplate = g_sHTMLTemplate.replace(re, '<!--OBJ_' + sName + '--><$1 ' + sTag + '>$2<!--END_OBJ_' + sName + '-->');
  }

/*
     // Nouvelle
  var re = getRegExp('<!--OBJ_' + sName + '--><(.*?)(?:' + sTag + ')?(.*?)>(.*)<!--END_OBJ_' + sName + '-->', 'm');
  g_sHTMLTemplate = g_sHTMLTemplate.replace(re, '<!--OBJ_' + sName + '--><$1 ' + ( sValue ? sTag : '' ) + ' $2>$3<!--END_OBJ_' + sName + '-->');
*/
}

function updateInputObjectTag(sName, sTag, sValue)
{
  sValue = htmlAttributeQuote(sValue);
  // replace $ by $$
  sValue = sValue.replace( /\$/g, '$$$$' );
  var re = getRegExp('<!--OBJ_' + sName + '-->(.*?)' + sTag + '="(.*?)"(.*?)<!--END_OBJ_' + sName + '-->', 'm');
  if(re.test(g_sHTMLTemplate))
  {
    var sNewTag = '<!--OBJ_' + sName + '-->$1'+sTag+'='+sValue+'$3<!--END_OBJ_' + sName + '-->';
    g_sHTMLTemplate = g_sHTMLTemplate.replace(re, sNewTag);
  }
  else
  {
    re = getRegExp('<!--OBJ_' + sName + '--><(.*?)>(.*?)<!--END_OBJ_' + sName + '-->', 'm');
    g_sHTMLTemplate = g_sHTMLTemplate.replace(re, '<!--OBJ_' + sName + '--><$1 '+sTag+'='+sValue+'>$2<!--END_OBJ_' + sName + '-->');
  }
}

function updateInputObjectStyleTag(sName, sTag, sValue)
{
  var re = getRegExp('<!--OBJ_' + sName + '-->([^>]*?)style="([^>]*?)"(.*?)<!--END_OBJ_' + sName + '-->', 'm');
  if(re.test(g_sHTMLTemplate))
  {
    var reExists = getRegExp('<!--OBJ_' + sName + '-->([^>]*?)style="([^>]*?)'+sTag+':(.*?);(.*?)"(.*?)<!--END_OBJ_' + sName + '-->', 'm');
    if(reExists.test(g_sHTMLTemplate))
      g_sHTMLTemplate = g_sHTMLTemplate.replace(reExists, '<!--OBJ_' + sName + '-->$1style="$2'+sTag+':'+sValue+';$4"$5<!--END_OBJ_' + sName + '-->');
    else
      g_sHTMLTemplate = g_sHTMLTemplate.replace(re, '<!--OBJ_' + sName + '-->$1style="$2'+sTag+':'+sValue+';"$3<!--END_OBJ_' + sName + '-->');
  }
  else
  {
    //re = new RegExp('<!--OBJ_' + sName + '--><(.*?)>(.*?)<!--END_OBJ_' + sName + '-->', 'm');
    re = getRegExp('<!--OBJ_' + sName + '-->(?:\r\n|\n|\s)*<(.*?)>((?:\r\n|\n|.)*?)<!--END_OBJ_' + sName + '-->', 'm');
    g_sHTMLTemplate = g_sHTMLTemplate.replace(re, '<!--OBJ_' + sName + '--><$1 style="'+sTag+':'+sValue+';">$2<!--END_OBJ_' + sName + '-->');
  }
}

//
// met a jour le contenu HTML d'un champ input (textarea)
//
function updateInputObjectContent( sName, sContent )
{
  var pRegExp = getRegExp( '<!--OBJ_' + sName + '--><(.*?)>(.*)</(.*?)><!--END_OBJ_' + sName + '-->', 'm' );
  g_sHTMLTemplate = g_sHTMLTemplate.replace( pRegExp, '<!--OBJ_' + sName + '--><$1>' + sContent + '</$3><!--END_OBJ_' + sName + '-->' );
}

/**
 * Append the value of a form object.
 * Parameters :
 *   - sSeparator : The used separator between old value and new one.
 *   - inputName : the short name of the layer (example : <INPUT NAME="toto">  => Name="Toto")
 *   - value : the new value
 *      . object is unique textfield/textarea : the new value of the textfield
 *      . object is unique checkbox or radio : TRUE to check, FALSE to uncheck
 *      . object is multiple radio : the value of the radio to check
 *      . object is unique select-one : the value of the option to select
 *      . object is unique select-multiple : array of values representing the options to select
 *      . other : not supported
 *   - formName (optional) : the name of the form which contains the input object
 *                 If the input object is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 *   - bHTMLTagsReplace : Replace / destroy all HTML tags
 * Returns :
 */
function appendInputValue(sSeparator,inputName, value, formName, myDocument, enforce, bHTMLTagsReplace)
{
	var sOldValue = getInputValue(inputName,formName,myDocument,enforce);
	sOldValue = sOldValue + ( sOldValue != '' ? sSeparator : '' ) + value;
        
        // Faut il supprimer les tags HTML de la chaine
        if( bHTMLTagsReplace )
        {
            sOldValue = replaceHTMLTags( sOldValue );
        }
        
	setInputValue(inputName, sOldValue, formName, myDocument, enforce); 
}


/*
 *  On demande le remplacement des tags HTML
 *     (Ne plus les afficher)
 *  Parameters :
 *    - sText : Chaine de caractère avec tags HTML
 *  Return :
 *    - sText : Chaine de caractère sans tags HTML
 */
function replaceHTMLTags( sText )
{
    //    \n
    sText = sText.replace(/\n/gi,'');
    //    <br>
    sText = sText.replace(/\<br\>/gi,"\n");    
    //    Tous les tags <>
    sText = sText.replace(/<.*?\>/gi,' ');
    //    &nbsp;
    sText = sText.replace(/&nbsp;/gi,' ');

    return sText;
}



/**
 * Set an input object disabled.
 * Parameters :
 *   - inputName : the short name of the layer (example : <INPUT NAME="toto">  => Name="Toto")
 *   - formName (optional) : the name of the form which contains the input object
 *                 If the input object is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 * Returns :
 */
function disableInput(inputName, formName, myDocument, enforce) {
  var object = getFormObject(inputName, formName, myDocument, enforce);
  if( object.disabled != null )
  {
    object.disabled = true;
  }
  if( object.length != null )
  {
    for( var i = 0 ; i < object.length ; i++ )
    {
      if( object[i].disabled != null )
      {
        object[i].disabled = true;
      }
    }
  }
}

/**
 * Enable an input object.
 * Parameters :
 *   - inputName : the short name of the layer (example : <INPUT NAME="toto">  => Name="Toto")
 *   - formName (optional) : the name of the form which contains the input object
 *                 If the input object is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 * Returns :
 */
function enableInput(inputName, formName, myDocument, enforce) {
  var object = getFormObject(inputName, formName, myDocument, enforce);
  if( object.disabled != null )
  {
    object.disabled = false;
  }
  if( object.length != null )
  {
    for( var i = 0 ; i < object.length ; i++ )
    {
      if( object[i].disabled != null )
      {
        object[i].disabled = false;
      }
    }
  }
}

/**
 * Get if an input object is disabled or enabled
 * Parameters :
 *   - inputName : the short name of the layer (example : <INPUT NAME="toto">  => Name="Toto")
 *   - formName (optional) : the name of the form which contains the input object
 *                 If the input object is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 * Returns :
 *    - true : object is enabled
 *    - false : object is disabled
 */
function getInputEnabled(inputName, formName, myDocument, enforce) {
    var object = getFormObject(inputName, formName, myDocument, enforce);
    return !object.disable;
}


/**
 * Submit a form
 * Parameters :
 *   - formName : the name of the form to submit
 *   - action (optional) : to submit the form to a specific URL
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 * Returns : false
 */
function submitForm(formName, action, myDocument, sAnchor )
{
  var browser = getBrowser();
  if(myDocument == null || myDocument == '') myDocument = window.document;

  var object = document.getElementById(formName);
  if( object == null )
    throw new Error("Cannot found form '"+formName+"' in document");

  if (action != null && action != '')
  {
    object.action = action;
  }
  if( sAnchor && sAnchor != '' )
  {
    object.action += "#" + sAnchor;
  }
  
  if (document.getElementById(formName).from_page)
  {
    document.getElementById(formName).from_page.value = formName;
  }                
  
  object.submit();  
  
}

function submitDisplayFormIn( sLink, sNewFormAction, sNewTarget )
{
    if( sLink.match( /submitDisplayForm\((.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*)\)/ ) )
    {
        var sFormName      = RegExp.$1;
        var sDisplay       = RegExp.$2;
        var sActions       = RegExp.$3;
        var sTokens        = RegExp.$4;
        var sCheckFunction = RegExp.$5;
        var pDocument      = RegExp.$6;
        var sAnchor        = RegExp.$7;
        var sFormAction    = RegExp.$8;
        var sLinkID        = RegExp.$9;
        var sTarget        = RegExp.$10;
        
        sNewFormAction = sNewFormAction ? "'"+sNewFormAction+"'" : sFormAction;
        sNewTarget     = sNewTarget     ? "'"+sNewTarget+"'"     : sTarget;

        var sNewCall = "submitDisplayForm( "+sFormName+", "+sDisplay+", "+sActions+", "+sTokens+", "+sCheckFunction+", "+pDocument+", "+sAnchor+", "+sNewFormAction+", "+sLinkID+", "+sNewTarget+")";
        eval( sNewCall );
    }
}

function submitDisplayForm( sFormName, sDisplay, sActions, sTokens, sCheckFunction, pDocument, sAnchor, sFormAction, sLinkID, sTarget )
{
		
  var bRet = true;
  if(sDisplay != undefined && sDisplay !== null)
    setInputValue('display', sDisplay, sFormName, pDocument);
  if(sActions != undefined && sActions !== null)
    setInputValue('actions', sActions, sFormName, pDocument);
  if(sTokens != undefined && sTokens !== null)
    setInputValue('tokens', sTokens, sFormName, pDocument);
  if(sTarget != undefined && sTarget !== null ) // Change le target du formulaire
  {
    var pForm = getForm(sFormName, pDocument);
    if(pForm && pForm != undefined && sTarget !== null)
    {
        pForm.target = sTarget;
    }
  }
   
  if( !pDocument && sCheckFunction != null && sCheckFunction != '' )
  {
    // on ne plante pas si la fonction n'existe pas
    var bDefined = false;
    try
    {
      //alert(sCheckFunction);
      bDefined = eval( sCheckFunction ) != '';
    }
    catch (ex) {}
    if( bDefined )
    {
      try
      {
        bRet = eval( sCheckFunction+"( '"+sFormName+"' );" )
      }
      catch (ex)
      {
        bRet = false;
      }
    }
  }
  
  if( bRet )
  {
    // faudrait peut-etre un try catch pour rétablir l'affichage si le submitForm echoue
    // mais on risque de perdre l'exception
    try
    {
      if( getDOMObject( 'please_wait_layer', pDocument ) )
      {
        hideLayer( 'content_layer', pDocument );
        showLayer( 'please_wait_layer', pDocument );
      }
      // vérification que l'utilisateur ne clique pas deux fois sur le bouton
      if( sLinkID )
      {
        var pLink = getDOMObject( sLinkID );
        if( pLink && pLink instanceof Array )
        {
          for(var i=0;i<pLink.length;i++)
            pLink.style.visibility = 'hidden';
        }
        else if(pLink)
        {
          pLink.style.visibility = 'hidden';
        }
      }
      // valide le formulaire
      
      submitForm( sFormName, sFormAction, pDocument, sAnchor );
    }
    catch( ex )
    {
    	
      if( getDOMObject( 'please_wait_layer' ) )
      {
        showLayer( 'content_layer' );
        hideLayer( 'please_wait_layer' );
      }
      throw ex;
    }
  }
}



/**
 * Reset a form
 * Parameters :
 *   - formName : the name of the form to reset
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 * Returns :
 */
function resetForm(formName, action, myDocument) {
    var browser = getBrowser();
    if(myDocument == null || myDocument == '') myDocument = window.document;

    var object;
    switch(browser) {
    case KONQUEROR :
    case OPERA :
    case NETSCAPE :
    case IE :
        object = eval("myDocument." + formName);
        break;
    }

    object.reset();
    //return object;
}

/**
 * Submit a form
 * Parameters :
 *   - inputValue : the value of the input to be posted ( 'go', 'update', ... )
 *   - formName : the name of the form to reset
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 * Returns :
 */
function submitActionForm( actionName, formName, myDocument)
{
  var browser = getBrowser();
  if(myDocument == null || myDocument == '') myDocument = window.document;

  var object = eval("myDocument." + formName);
  if( object == null )
    throw new Error("Cannot found form '"+formName+"' in document");

  setInputValue( 'formAction', actionName, formName, myDocument );

  if( !validateForm( formName, actionName ) )
  {
    return;
  }

  if(object)
  {
    for( var i=0 ; i<object.elements.length ; i++ )
    {
      object.elements[ i ].disabled = false;
    }
  }

  showPleaseWait();

  if(object.onsubmit)
    object.onsubmit();
  object.submit();
}

function submitSortbarName( sortbarName, formName, myDocument)
{
  var browser = getBrowser();
  if(myDocument == null || myDocument == '') myDocument = window.document;

  var object = eval("myDocument." + formName);
  if( object == null )
    throw new Error("Cannot found form '"+formName+"' in document");

  setInputValue( 'selected_sortbar_name', sortbarName, formName, myDocument );
  setInputValue( 'formAction', 'GO_ITEMS', formName, myDocument );

  if( !validateForm( formName, sortbarName ) )
  {
    return;
  }

  if(object)
  {
    for( var i=0 ; i<object.elements.length ; i++ )
    {
      object.elements[ i ].disabled = false;
    }
  }

  showPleaseWait();

  if(object.onsubmit)
    object.onsubmit();
  object.submit();
}

/**
 * Simulate a click on the specified button
 * WARNING : the click() function can only be called on a BUTTON or on a LINK
 *           DO NOT TRY to call it on a <input type="image" ...>, it does NOT work on Netscape/Mozilla/Konqueror
 * Parameters :
 *   - buttonName : the short name of the button (example : <BUTTON ID="toto">  => Name="Toto")
 *   - formName (optional) : the name of the form which contains the object
 *                 If the button is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 *   - enforce (optional) : SHOULD NOT BE USED.
 *                 When an input object is not inside a form object, the input object must be named with the ID tag
 *                 instead of the NAME tag. If not, the object will not be accessible by Netscape browsers.
 *                 Setting enforce value to TRUE removes the Internet Explorer warning message.
 * Returns :
 *    the value returned by [button].click()
 */
function clickButton(buttonName, myDocument) {
    var object = getFormObject(buttonName, formName, myDocument, enforce);
    return object.click();
}



/**
 * Get a form
 * Parameters :
 *   - formName : the name of the form which contains the object
 *                If the button is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 * Returns :
 *    the form object
 */
function getForm(formName, myDocument) {
    var browser = getBrowser();
    if(myDocument == null || myDocument == '') myDocument = window.document;

    var object;
    switch(browser) {
    case KONQUEROR :
    case NETSCAPE :
    case OPERA :
    case IE :
        object = eval( "myDocument." + formName);
        break;
    }

    return object;
}

/**
 * Get the action of a form
 * Parameters :
 *   - formName : the name of the form which contains the object
 *                If the button is not in a form, put formName = ''
 *   - myDocument (optional) : default value = window.document
 *                 Allows to specify a document object on another window
 * Returns :
 *    the form object
 */
function getFormAction(formName, myDocument) {
    var object = getForm(formName, myDocument);
    return object.action;
}




function printCurrentWindow() {
    if(window.print) {
        window.print();
    }
    else {
        window.alert("Your browser does not support this functionnality. To print this document, try to click with the right button on the page and select \"Print\".");
    }
}



var helpLayer;

function mouse_move(e)
{
   if (!loaded)
   {
      return;
   }

   if (!helpLayer)
   {
       helpLayer = getLayer(HELP_LAYER_NAME);
   }

   var x;
   var y;
   var maxX;
   var width = helpLayer.style.width;
   if (!width)
   {
      width = 250;
   }

   switch(browser) {
      case IE :
      case OPERA :
         x = event.x + document.body.scrollLeft - 45;
         y = event.y + document.body.scrollTop + 20;
         maxX = document.body.clientWidth;
         break;
      case KONQUEROR :
         x = event.x - 45;
         y = event.y + 20;
         maxX = document.body.clientWidth;
         break;
      case NETSCAPE :
         x = e.pageX - 45;
         y = e.pageY + 20;
         maxX = window.innerWidth;
   }

   if (x + width > maxX) { x = maxX - width; }
   if (x < 0) { x = 0; }

   helpLayer.style.left = x;
   helpLayer.style.top = y;

   return true;
}

function setQuickHelpBGColor(bgcolor)
{
   HELP_BGCOLOR = bgcolor;
}

function displayQuickHelp(msg, width) 
{
   if (!loaded)
   {
      return;
   }

   if (!width)
   {
      width = 200;
   }

   var content="<TABLE BORDER=\"0\" WIDTH=\"" + width + "\" CELLPADDING=\"1\" CELLSPACING=\"0\" BGCOLOR=\"#000000\">" +
               "  <tr><td><TABLE WIDTH=\"100%\" BORDER=\"0\" CELLPADDING=\"3\" CELLSPACING=\"0\"> "+
               "  <tr><TD BGCOLOR=\"" + HELP_BGCOLOR + "\" style=\"font-size:10px\">" + msg + "</TD></TR></TABLE></TD></TR></TABLE>";
   
   var zeLayer = getLayer(HELP_LAYER_NAME);
   zeLayer.innerHTML = content;
   showLayer(HELP_LAYER_NAME);
}

function hideQuickHelp()
{
   if (!loaded)
   {
      return;
   }
   hideLayer(HELP_LAYER_NAME);
   var zeLayer = getLayer(HELP_LAYER_NAME);
   zeLayer.innerHTML = "";
}

var openedWindows = new Array();

/**
 * Open a popup window.
 */
function popup(path,name,props)
{
  openedWindows[ openedWindows.length ] = window.open(path,name,props);

  //return openedWindows[ openedWindows.length - 1 ];
}

function modal(path,name,props)
{
  if(window.showModalDialog)
  {
    var aArgs = new Array();
    aArgs['name'] = name;
    aArgs['opener'] = window;
    return window.showModalDialog('dblframe.cgi?url='+encodeURIComponent(path),aArgs,getModalAttributes(props));
  }
  else
  {
    popup(path,name, props);
    return null;
  }
}

function getModalAttributes(props)
{
    props = props.replace(/width=(\d+)/,'dialogWidth:$1px');
    props = props.replace(/height=(\d+)/,'dialogHeight:$1px');
    props = props.replace(/\,/g,';');
    props = props.replace(/\=/g,':');
    return props;
}

function closeAllOpenedWindows()
{
  for( var i = 0 ; i < openedWindows.length ; i++ )
  {
    if( !openedWindows[i].closed )
    {
      if( openedWindows[i].closeAllOpenedWindows )
      {
        openedWindows[i].closeAllOpenedWindows();
      }

      eval( 'openedWindows[i].close()' );
    }
  }
}

//*******************************************************************
//*                    MENU FUNCTIONS                               *
//* Some browser specific functions or variable to display the menu *
//*******************************************************************
var thresholdY = 15;		// in pixels; threshold for vertical repositioning of a layer
var ordinata_margin = -10;	// to start the layer a bit above the mouse vertical coordinate
var currentY = -1;

if(document.all) {
   window.onresize = hf_resizeWindow;
}
function hf_resizeWindow() {
   if( document.all && document.body && document.body.clientHeight && document.all('hf_template_data') ) {
      document.all('hf_template_data').style.height = parseInt(document.body.clientHeight) - 138;
   }
   return true;
}

/**
 * Capture the mouse movements
 */
function captureMouseEvents() {
    var browser = getBrowser();
    switch(browser) {
    case NETSCAPE :
       //if (!document.getElementsByClassName)
    	   document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE);
       /*else
       {
    	   document.addEventListener("MouseDown", function() {}, true);
    	   document.addEventListener("MouseMove", function() {}, true);
       }*/
       break;
    }
}

/**
 * Used to get menu vertical position
 */
function grabMouse(e) {
   var browser = getBrowser();
   switch(browser) {
   case NETSCAPE :
      currentY = e.pageY;
      break;
   case OPERA :
   case IE :
   case KONQUEROR :
      currentY = event.y + document.body.scrollTop;
      break;
   }
}


/**
 * Move a menu layer to its location
 */
function moveLayerY(menuName, level, obj) 
{
  var browser = getBrowser();
  if(loaded)
  { // to avoid stupid errors of Microsoft browsers
    if( obj )
    {
      if( browser == NETSCAPE) 
      {
        if (level == 3) 
        {
          document.getElementById(menuName).style.left = getx(obj+'_right_position', level);
          document.getElementById(menuName).style.top = gety(obj);
        }
        else
        {
          document.getElementById(menuName).style.left = getx(obj, level);
        }
      }
      else
      {
        if (level == 3) 
		    {
  				document.all[menuName].style.pixelTop = gety(obj)+2;
  				document.all[menuName].style.pixelLeft = getx(obj+'_right_position', level);
  			}
  			else
  			{
  				document.all[menuName].style.pixelLeft = getx(obj, level);
  			}
      }
    }
  }
}


function setOnClickFunction(fonction) {
    var browser = getBrowser();
    switch(browser) {
    case NETSCAPE:
    case OPERA :
    case KONQUEROR:
    case IE:
        document.onclick = fonction;
        break;
    }
}



function getElementsToHide() {
    var browser = getBrowser();
    if(browser == NETSCAPE || browser == OPERA || IE7)
        return new Array();

    if(browser == IE) {
        return document.all.tags("SELECT");
    }

    if(browser == KONQUEROR) {
        var res = new Array();
        var cpt = 0;
        var formsArray = document.forms;
        for (var i = 0; i < formsArray.length; i++) {
            var elementsArray = formsArray[i].elements;
            for(var j = 0; j < elementsArray.length; j++) {
                var elem = elementsArray[j];
                if(elem.type != 'hidden')
                    res[cpt++] = elem;
            }
        }
        return res;
    }

    return new Array();
}

function getElementsToShow() {
    return getElementsToHide();
}


function getx( obj, level )
{
  var x = 0;
  var elt = getLayer(obj);
 
  if (!elt)
	  return 0;
  if (level == 2)
  {
	  while (elt.tagName != "BODY")
	  {
		  x += elt.offsetLeft;
		  elt = elt.parentNode;
	  }
	  return x;
  }
  else
  {
	  switch (browser)
    {
      case NETSCAPE:
     //     return elt.pageX;
      case IE:
      case OPERA :
      case KONQUEROR:
        x =  elt.offsetLeft + 4;
      do
      {
        x += parseInt( elt.offsetLeft );
        elt = elt.offsetParent;
      } while ( elt );
		  return x;
	  }
  }
}

function gety(obj, level)
{
	var elt = getLayer(obj);
	var y = -7;
	if (!elt) {
		return 0;
	}
	switch (browser) {
	case NETSCAPE:
 //   	return elt.y;
    case OPERA :
    case KONQUEROR:
	case IE:
		do { y += parseInt( elt.offsetTop );
		elt = elt.offsetParent;
		} while ( elt );
		return y;
	}
}


function sprintf()
{
  if (!arguments || arguments.length < 1 || !RegExp)
    {
      return;
    }
  var str = arguments[0];
  var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
  var a = b = [], numSubstitutions = 0, numMatches = 0;
  while (a = re.exec(str))
    {
      var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
      var pPrecision = a[5], pType = a[6], rightPart = a[7];
      
      //alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);
      
      numMatches++;
      if (pType == '%')
        {
          subst = '%';
        }
      else
        {
          numSubstitutions++;
          if (numSubstitutions >= arguments.length)
            {
              alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
            }
          var param = arguments[numSubstitutions];
          var pad = '';
          if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
          else if (pPad) pad = pPad;
          var justifyRight = true;
          if (pJustify && pJustify === "-") justifyRight = false;
          var minLength = -1;
          if (pMinLength) minLength = parseInt(pMinLength);
          var precision = -1;
          if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
          var subst = param;
          if (pType == 'b') subst = parseInt(param).toString(2);
          else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
          else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
          else if (pType == 'u') subst = Math.abs(param);
          else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
          else if (pType == 'o') subst = parseInt(param).toString(8);
          else if (pType == 's') subst = param;
          else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
          else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
        }
      str = leftpart + subst + rightPart;
    }
  return str;
}

function jsQuote( sVar )
{
  if(sVar != null )
  {
	  sVar = new String(sVar);
	  sVar = sVar.replace( /\"/g, '\\"' );
	  sVar = sVar.replace( /\n/g, '\\n' );
    return ('"' + sVar + '"');
  }
  else
  {
    return '\'\'';
  }
}
/**
 * Supprime les espaces inutiles en début et fin de la chaîne passée en paramètre.
 */
function trim(aString) {
    return aString.replace(/^\s+/, "").replace(/\s+$/, "");
}
 
/**
 * Supprime les espaces inutiles en début de la chaîne passée en paramètre.
 */
function ltrim(aString) {
    return aString.replace(/^\s+/, "");
}
 
/**
 * Supprime les espaces inutiles en fin de la chaîne passée en paramètre.
 */
function rtrim(aString) {
    return aString.replace(/\s+$/, "");
} 

function htmlAttributeQuote(sValue)
{
  if(sValue != null )
  {
    sValue = new String(sValue);
    sValue = sValue.replace( /\"/g, '&#34;' );
    sValue = sValue.replace( /&/g, '&#38;' );
    return "\""+sValue+"\"";
  }
  else
  {
    return "\"\"";
  }
}


function evalFunc()
{
  var args = evalFunc.arguments;
  if(evalFunc.arguments < 1)
    return null;
  // function name
  var sFuncName = args[0];
  // arguments
  var aTmp = new Array();
  for( var i=1 ; i<args.length ; i++ )
    aTmp[aTmp.length] = 'args['+i+']';
  var sArgs = aTmp.join(',');
  var sRet = eval( sFuncName + '(' + sArgs + ')' );
  return sRet;
}

function switchLayer( sLayerName, bBugFix )
{
  if( getLayerDisplayed( sLayerName ) )
  {
    hideLayer( sLayerName, null, bBugFix );
  }
  else
  {
    showLayer( sLayerName, null, bBugFix );
  }
}

function startPleaseWait()
{
  hideLayer( 'global_layer' );
  showLayer( 'please_wait_layer' );
}

function  stopPleaseWait()
{
  hideLayer( 'please_wait_layer' );
  showLayer( 'global_layer' );
}

function cancelRequest()
{
    stopPleaseWait();
    window.stop();
}

function copyArray( src, dest )
{
  for( i in src )
  {
    dest[i] = src[i];
  }

  return dest;
}

function getRecParentDocument( frameName, parentWindow )
{
  if( parentWindow == null )
  {
    parentWindow = window;
  }
  if( frameName == null )
  {
    return parentWindow;
  }
  if( parentWindow.parent[frameName] != null )
  {
    return parentWindow.parent[frameName];
  }
  else
  {
    if( parentWindow.opener != null )
    {
      return getParentDocument( frameName, parentWindow.opener );
    }
    else if(parentWindow.parent != null)
    {
      return getParentDocument( frameName, parentWindow.parent );
    }
    else
    {
      return parentWindow;
    }
  }
}

function getParentDocument( frameName, parentWindow )
{
  if( parentWindow == null )
  {
    parentWindow = window;
  }
  if( frameName == null )
  {
    return parentWindow;
  }
  if( parentWindow.parent[frameName] != null )
  {
    return parentWindow.parent[frameName];
  }
  else
  {
    return parentWindow;
  }
}

function findParentDocument(sName, pWindow)
{
    var pWin = findParentWindow(sName, pWindow);
    return pWin ? pWin.document : null;
}

function findParentWindow(sName, pWindow)
{
    if(pWindow.name == sName)
        return pWindow;
    if(pWindow.opener && pWindow.opener.name != pWindow.name)
        return findParentWindow(sName, pWindow.opener);
    if(pWindow.parent && pWindow.parent.name != pWindow.name)
        return findParentWindow(sName, pWindow.parent);

    //Try to find the window.opener from dialogArguments if it is a modal window
    if(
        pWindow.dialogArguments
        && pWindow.dialogArguments[ 'opener' ]
        && pWindow.dialogArguments[ 'opener' ].name != pWindow.name
      ) return findParentWindow( sName, pWindow.dialogArguments[ 'opener' ] );

    return null;
}

function createSelectOption(sID, sText, pDocument)
{
  pDocument = pDocument ? pDocument : window.document;
  if( pDocument.parentWindow )
    return pDocument.parentWindow.Option( sText, sID );
  else
    return new Option( sText, sID );
}

function cancelBackAndRefresh( event )
{
  if( event == null )
  {
    return;
  }

  if( event.keyCode == 116 )
  {
    // F5
    //alert( 'The F5 key has been disabled' );
    cancelKeyEvent( event );
  }

  if( event.ctrlKey && (event.keyCode == 78 || event.keyCode == 82) )
  {
    // When ctrl is pressed with R or N
    cancelKeyEvent( event );
  }
//   if( event.keyCode > 17 )
//     {
//       alert( 'event.ctrlKey='+event.ctrlKey+' event.keyCode=' + event.keyCode );
//     }

  if (event.keyCode == 8 && (event.srcElement && event.srcElement.type != "text" && event.srcElement.type != "textarea" && event.srcElement.type != "password" && !event.srcElement.isContentEditable))
  {
    // When backspace is pressed but not in form element
    cancelKeyEvent(event);
  }
}

function cancelKeyEvent( event )
{
  //alert( event.preventDefault );
  if( event.preventDefault )
  {
    event.preventDefault();
    return false;
  }
  else
  {
    event.keyCode = 0;
    event.returnValue = false;
  }
}

if(navigator.appName == "Netscape" )
{
  /*if (!document.getElementsByClassName)
  {*/
	  document.captureEvents( "KeyPress" );
	  document.captureEvents( "KeyDown" );
  //}
  document.addEventListener( "KeyPress", cancelBackAndRefresh, true );
  document.addEventListener( "KeyDown", cancelBackAndRefresh, true );
}

document.onkeydown = cancelBackAndRefresh;

//history.forward();

//alert( 'OK' );

function showPleaseWait()
{
  hideLayer( 'global_layer' );

  showLayer( 'please_wait_layer' );
}

function move( inputName, formName, offset )
{
  var obj = getFormObject( inputName, formName );

  if( obj.options == null )
  {
    return;
  }

  var minPos = 0;
  var maxPos = obj.options.length - 1;
  var oldPos = obj.options.selectedIndex;
  var newPos = oldPos + offset;
  if( newPos < minPos )
  {
    newPos = minPos;
  }
  if( newPos > maxPos )
  {
    newPos = maxPos;
  }
  if( newPos == oldPos )
  {
    return;
  }

  //  alert( 'oldPos='+oldPos +' newPos='+newPos );
  var option = new Option( obj.options[ oldPos ].text, obj.options[ oldPos ].value );
  if( newPos < oldPos )
  {
    for( var i = oldPos ; i > newPos ; i-- )
    {
      //      alert( obj.options[ i ].text + ' ' + obj.options[ i - 1 ].text );
      obj.options[ i ] = new Option( obj.options[ i - 1 ].text, obj.options[ i - 1 ].value );
      //      alert( obj.options[ i ].text + ' ' + obj.options[ i - 1 ].text );
    }
  }
  else
  {
    for( var i = oldPos ; i < newPos ; i++ )
    {
      //      alert( obj.options[ i ].text + ' ' + obj.options[ i + 1 ].text );
      obj.options[ i ] = new Option( obj.options[ i + 1 ].text, obj.options[ i + 1 ].value );
      //      alert( obj.options[ i ].text + ' ' + obj.options[ i + 1 ].text );
    }
  }
  obj.options[ newPos ] = option;
  obj.options.selectedIndex = newPos;
}

function selectAllOptions( inputName, formName )
{
  var obj = getFormObject( inputName, formName );

  if( obj.options == null )
  {
    return;
  }

  for( var i = 0 ; i < obj.options.length ; i++ )
  {
    obj.options[i].selected = true;
  }
}

function emptyAllOptions( inputName, formName )
{
  var obj = getFormObject( inputName, formName );

  if( obj.options == null )
  {
    return;
  }

  for( var i = (obj.options.length - 1) ; i >= 0 ; i-- )
  {
    obj.options[i] = null;
  }
}

function removeArrayElement(aArray, pElement)
{
	var index;
	for(index=0;index<aArray.length && aArray[index] != pElement;index++);
	if(index != aArray.length)
	{
		for(;index<aArray.length-1;index++)
			aArray[index]=aArray[index+1];
		delete aArray[aArray.length - 1];
		aArray.length = aArray.length - 1;
		return pElement;
	}
	return false;
}

function arrayContains(aArray, pElement)
{
  for(var index=0;index<aArray.length;index++)
    if(aArray[index] == pElement)
      return true;
}

function arrayPush(aDest, aSrc)
{
    for(var i=0;i<aSrc.length;i++)
        aDest.push(aSrc[i]);
    return aDest;
}

function cloneArray(aArray)
{
  if(aArray == null)
    return null;
  var aNewArray = new Array();
  for(var index=0;index<aArray.length;index++)
    aNewArray.push(aArray[index]);
  return aNewArray;
}

function goAction( sAction, sFormName, bGlobal, sDocument, bUseActionAsFormAction )
{
  if ( bGlobal )
  {
    enableAll( 'select', sFormName, 1 );
  }
  setInputValue( sAction, '1', sFormName, sDocument );
  submitActionsForm( bUseActionAsFormAction ? sAction : 'update', sFormName, sDocument );
}

function toggleActionLayer( sAction, sLayerOn, sLayerOff, pObjectToFocus )
{
  if( sLayerOn )
  {
    switchLayer( sLayerOn, true );
    switchLayer( sAction + '_button_layer' );
    if ( pObjectToFocus )
        pObjectToFocus.focus();
  }
  if( sLayerOff )
  {
    switchLayer( sLayerOff, true );
  }
}

function switchPortlet( nContainerID )
{
  switchLayer( nContainerID );
  switchLayer( nContainerID + '_close_button' );
  switchLayer( nContainerID + '_open_button' );

  if ( getBrowser() != IE ) //&& getLayer('portalview') )
  {
      setDOMObjectProperty('portalview', 'style.display', 'none');
      setDOMObjectProperty('portalview', 'style.display', '');
  }
}

// bAppend to append the result to the existing value
// bMultiple to return multiple results (if the function is called more than once)
function setReturnValue( sJSSetter, sFieldName, sFormName, sValue, bAppend, bFocus, bMultiple )
{
  if( window.dialogArguments != undefined )
  {
    if( bMultiple && window.returnValue != undefined )
      window.returnValue += ',' + sValue;
    else
      window.returnValue = sValue;
  }
  else
  {
    var pDocument = findParentDocument( 'app', window.opener );

    if( !getFormObject( sFieldName, sFormName, pDocument ) )
      pDocument = window.opener.document;
    
    var sExistingValue = getInputValue( sFieldName, sFormName, pDocument );
    var sReturnValue = bAppend
      ? sExistingValue + ( sExistingValue != '' ? ',' : '' ) + sValue
      : sValue;

    evalFunc( sJSSetter, sFieldName, sReturnValue, sFormName, pDocument );

    var pInputObject = getFormObject( sFieldName, sFormName, pDocument );
    
    if( bFocus )
       focusObject( pInputObject );
       
    try { pInputObject.onchange(); } catch( ex ) {}
    try { pInputObject.onblur(); } catch( ex ) {}
  }
}


// Works well BUT because of the fixed-layout table, the content of the former scrollview
// spills over the other cells :/
// Update: Fixed??

function hideScrollPanels( pDocument )
{
  if ( getBrowser() == NETSCAPE || g_bDisableScrolPanels )
  {
    hideGlobalLayer();
    
    var aPanels = getScrollPanes( pDocument );
    for (var nI=0; nI<aPanels.length; nI++)
    {
      var pPanel = aPanels[nI];
      var nH = pPanel.style.height;

      if ( !nH || nH.substring( nH.length-1, nH.length ) == '%' )
      {
        pPanel.style.overflow = 'visible';
        // ca m'arrange dans certains cas, mais ca pourrait causer des problèmes
        pPanel.style.height = '';          
      }
    }
    
    var aTables = getFixedTables( pDocument );
    for( var nJ = 0; nJ < aTables.length; nJ++ )
    {
      aTables[ nJ ].style.tableLayout = "";
    }

    showGlobalLayer();
  }
}

function getScrollPanes( pDocument )
{
  if( pDocument == null ) pDocument = window.document;

  var panels = new Array();

  var divs = pDocument.getElementsByTagName('DIV');
  for (var d=0; d<divs.length; d++)
  {
    if ( divs[d].className == 'scrollpane' )
    {
      panels.push( divs[d] );
    }
  }
  
  var pPlanningDiv = getDOMObject("master_div");
  if( pPlanningDiv )
  {
    panels.push( pPlanningDiv );
  }

  return panels;
}

function getFixedTables( pDocument )
{
  if( pDocument == null ) pDocument = window.document;

  var aFixed  = new Array();

  // pas la peine de boucler sur toutes les tables, il n'y en a que très peu à modifier:

  var p1 = getDOMObject( 'planning_fixed_layer', pDocument );
  if( p1 != null )
    aFixed.push(p1);

  var p2 = getDOMObject( 'sub_global_fixed_layer', pDocument );
  if( p2 != null )
    aFixed.push(p2);

  var p3 = getDOMObject( 'global_popup_fixed_layer', pDocument );
  if( p3 != null )
    aFixed.push(p3);

/*
  var p4 = getDOMObject( 'global_iframe_fixed_layer', pDocument );
  if( p4 != null )
    aFixed.push(p4);
*/
  
/*
  var aTables = pDocument.getElementsByTagName('TABLE');
  for( var nI = 0; nI < aTables.length; nI++ )
  {
    if( aTables[nI].style.tableLayout == 'fixed' && aTables[nI].id != 'menu_layer' )
    {
      aFixed.push( aTables[ nI ] );
    }
  }
*/

  return aFixed;
}

function getParentNode( pObject, sTagName )
{
  var pParent = pObject.parentNode;
  if( sTagName )
  {
    while( pParent != null && pParent.tagName.toUpperCase() != sTagName )
      pParent = pParent.parentNode;
  }
  return pParent;
}

// Simple encryption function

var g_sCryptKey = "fs'v#{~^@]$1s\"d5x.4(*_=s9";

function _xorString( sString, sKey )
{
  var sResult = "";
  for(var nI=0; nI<sString.length; ++nI)
  {
    sResult += String.fromCharCode( sKey.charCodeAt(nI % sKey.length) ^ sString.charCodeAt(nI) );
  }
  return sResult;
}

function encryptString( sString, sKey )
{
  return "C"+encodeURIComponent(_xorString(sString,sKey));
}

function decryptString( sString, sKey )
{
  if( sString.charAt(0) == 'C' )
  {
    sString = sString.substring(1);
    sString = decodeURIComponent(sString);
    sString = _xorString( sString, sKey );
  }
  
  return sString;
}

function findPosX(obj, pParent)
{
  var curleft = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent && (!pParent || obj.offsetParent != pParent) )
    {
      curleft += obj.offsetLeft;
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY( obj, pParent )
{
  var curtop = 0;
  if( obj.offsetParent )
  {
    while( obj.offsetParent  && (!pParent || obj.offsetParent != pParent) )
    {
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

function findBrowserPosX( obj, pParent )
{
  return findPosX(obj, pParent);
  if( getBrowser() == IE )
    return obj.offsetLeft;
  else
    return findPosX(obj, pParent);
}

function findBrowserPosY( obj, pParent )
{
  
  if( getBrowser() == IE )
    return obj.offsetTop;
  else
    return findPosY(obj, pParent);
}

function fireOnChangeEvent( pObject )
{
  // IE
  if( pObject.onchange != null )
    pObject.onchange();
  // Mozilla
  if( pObject.onChange != null )
    pObject.onChange();
}

function printfire()
{
    if (document.createEvent)
    {
        printfire.args = arguments;
        var ev = document.createEvent("Events");
        ev.initEvent("printfire", false, true);
        dispatchEvent(ev);
    }
}

// fonction pour gérer les positions

function parsePosition( sString )
{
  var pRegExp = getRegExp( '([^p]*)\s*(?:px)?', 'm');
  var aMatches = pRegExp.exec(sString);
  if( aMatches )
    return aMatches[1] * 1;
  return 0;
}

function positionToString( nPosition )
{
  return nPosition + 'px';
}

function getScrollX( pElement ) 
{
  var sx = 0;

  if( pElement != null && pElement.scrollLeft )
    return pElement.scrollLeft;
    
  if ( document.documentElement && document.documentElement.scrollLeft )
    sx = document.documentElement.scrollLeft;
  else if ( document.body && document.body.scrollLeft ) 
    sx = document.body.scrollLeft; 
  else if ( window.pageXOffset )
    sx = window.pageXOffset;
  else if ( window.scrollX )
    sx = window.scrollX;
  return sx;
}

function getScrollY( pElement ) 
{
  var sy = 0;
  
  if( pElement != null && pElement.scrollTop )
    return pElement.scrollTop;
  
  if ( document.documentElement && document.documentElement.scrollTop )
    sy = document.documentElement.scrollTop;
  else if ( document.body && document.body.scrollTop ) 
    sy = document.body.scrollTop; 
  else if ( window.pageYOffset )
    sy = window.pageYOffset;
  else if ( window.scrollY )
    sy = window.scrollY;
  return sy;
}



function showWaitLayer( sLayerName, sWaitMessage)
{ 
  var pWaitLayer = getLayer( sLayerName );
  if( pWaitLayer )
  {
    // place le layer
    //try
    //{
    //    var nScreenWidth  = document.body.offsetWidth;
    //    var nScreenHeight = document.body.offsetHeight;
    //    var nLayerWidth  = parsePosition( pWaitLayer.style.width );
    //    var nLayerHeight = parsePosition( pWaitLayer.style.height );
    //
    //    if( getBrowser() == NETSCAPE )
    //    {
    //      //pWaitLayer.style.left = getScrollX() + nScreenWidth / 2 - nLayerWidth / 2;
    //      //pWaitLayer.style.top  = getScrollY() + nScreenHeight / 2 - nLayerHeight / 2;
    //    }
    //    else
    //    {
    //      //pWaitLayer.style.left = 0;
    //      //pWaitLayer.style.top  = 0;
    //      //pWaitLayer.style.width = document.body.clientWidth;
    //      //pWaitLayer.style.height  = document.body.clientHeight;
    //    }
    //}
    //catch( ex ) { }

    // sous IE 6 cache les select car sinon, ils apparaissent toujours en avant plan
    if( getBrowser() == IE )
      hideSelect( null );
      
    // spécification du message d'attente
    var pWaitMessageLabel = getDOMObject('wait_message_label');
    if( pWaitMessageLabel )
        pWaitMessageLabel.innerHTML = sWaitMessage;
    
    // on affiche la layer
    showLayer( sLayerName, null, true );
    showLayer( sLayerName+"_content", null, true );
  }
}

function hideWaitLayer( sLayerName )
{ 
    var pWaitLayer = getLayer( sLayerName );
    if( pWaitLayer )
    {
      if( getBrowser() == IE )
        showSelect( null );
        
      hideLayer( sLayerName, null, true );
      hideLayer( sLayerName+"_content", null, true );
    }
}

// Fonctions permettant l'affichage d'un élément avant l'appel à une fonction (remote)

function showLayerAndCall( sLayerName, fFunction )
{ 
  var aArguments = showLayerAndCall.arguments;
  if( aArguments < 2 )
    return;
  
  var aRealArgs = new Array();
  // ignore les 2 premiers arguments
  for( var i=2; i < aArguments.length; i++ )
    aRealArgs.push( aArguments[ i ] );

  var pWaitLayer = getLayer( sLayerName );
  if( pWaitLayer )
  {
    // place le layer
    try
    {
        var nScreenWidth  = document.body.offsetWidth;
        var nScreenHeight = document.body.offsetHeight;
        var nLayerWidth  = parsePosition( pWaitLayer.style.width );
        var nLayerHeight = parsePosition( pWaitLayer.style.height );
  
        if( getBrowser() == NETSCAPE )
        {
          pWaitLayer.style.left = getScrollX() + nScreenWidth / 2 - nLayerWidth / 2;
          pWaitLayer.style.top  = getScrollY() + nScreenHeight / 2 - nLayerHeight / 2;
        }
        else
        {
          pWaitLayer.style.left = nScreenWidth / 2 - nLayerWidth / 2;
          pWaitLayer.style.scrollTop  = nScreenHeight / 2 - nLayerHeight / 2;
        }
    }
    catch( ex ) { }

    if( getBrowser() == IE )
      hideSelect( null ); // pWaitLayer
    showLayer( sLayerName, null, true );
  }

  // utilise un timer pour appeler la vraie fonction
  var hCallBack = getCallbackHandler( sLayerName, fFunction, aRealArgs );
  window.setTimeout( hCallBack, 50 );
}

// retourne une fonction anonyme pour gérer l'appel
function getCallbackHandler( sLayerName, fFunction, aRealArgs )
{
  return function ()
  {
    var pException = null;
    try
    {
      fFunction.call( aRealArgs[0], aRealArgs[1], aRealArgs[2], aRealArgs[3], aRealArgs[4], aRealArgs[5], aRealArgs[6], aRealArgs[7], aRealArgs[8], aRealArgs[9], aRealArgs[10] );
    }
    catch( ex )
    {
      pException = ex;
    }

    var pWaitLayer = getLayer( sLayerName );
    if( pWaitLayer )
    {
      if( getBrowser() == IE )
        showSelect( null ); // pWaitLayer
      hideLayer( sLayerName, null, true );
    }

    if( pException != null )
      throw pException;
  }
}

function DumpObjectToFile(sName, xObject, sFile)
{
   WriteToFile( sFile, DumpObject( sName, xObject ) );
   //alert(DumpObject( sName, xObject ));
}

function DumpObject(sName, xObject, aAlreadyDumped, nLevel)
{
   aAlreadyDumped = aAlreadyDumped ? aAlreadyDumped : new Array();
   nLevel = nLevel ? nLevel : 0;
   var sDump = new String();
   if( ! (xObject instanceof Function) )
   {
      for(i=0;i<nLevel;i++)
         sDump += ' ';
      try
      {
         if( xObject instanceof DBObject ||
             xObject instanceof Array)
         {
            if( arrayContains(aAlreadyDumped, xObject) )
            {
               sDump += sName+': ...\n';
            }
            else
            {
               aAlreadyDumped.push(xObject);
               sDump += sName+':\n';
               for (var xProperty in xObject)
                 sDump += DumpObject( xProperty, xObject[xProperty], aAlreadyDumped, nLevel+1);
            }
         }
         else
            sDump += sName+": "+xObject+'\n';
      }
      catch(ex)
      {
         sDump += sName+': ERROR';
      }
   }
   return sDump;
}

function WriteToFile(sFile, sContent) {
 try {
   var fso, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s = fso.OpenTextFile(sFile , 2, 1, -2);
   s.writeline(sContent);
   s.Close();
 }
catch(err){
  var strErr = 'Error:';
  strErr += '\nNumber:' + err.number;
  strErr += '\nDescription:' + err.description;
  alert(strErr);
 }
}

function getRowCount( sButtonID, sLabelID, sListName, sParameters )
{
  var nCount = "-";
  
  // Remote pour avoir le nombre d'éléments
  try
  {
    var pLabel = getDOMObject( sLabelID );
    if( pLabel )
    {
      pLabel.innerHTML = '&nbsp;&nbsp;...&nbsp;&nbsp;';
      hideLayer( sButtonID );
      showLayer( sLabelID );

      nCount = remoteCall( 'engine::remote::listparam',
                                'getRowCount',
                                sListName,
                                sParameters );
      
      var pLabel = getDOMObject( sLabelID );
      if( pLabel )
        pLabel.innerHTML = nCount;
    }
  }
  catch( ex )
  {
  }
}



/* **************************************************************
                            Console
 ************************************************************* */

function DBConsole()
{
}

DBConsole.prototype.setFrame = function DBConsole_setFrame( sFrameName, pFrameWindow, pEvalWindow )
{
  this.pEvalWindow   = pEvalWindow;
  this.sFrameName    = sFrameName;
  this.pFrameWindow  = pFrameWindow;
  this.bInit         = false;
  this.bEnabled      = true;
  this.pTable        = null;
  this.pInputCell    = null;
  this.pInput        = null;
  
  this.aCommandHistory      = new Array();
  this.nHistoryCurrentIndex = 0;
  this.nHistoryInsertIndex  = -1;
  this.nHistoryMax          = 50;
  
  this.aTimers = new Array();
  
  // handler pour scroller
  var pSelf = this;
  this.hScrollFunc = function( event ) { pSelf._scrollToLast(); }
}

// Initialisation de l'objet et du tableau
DBConsole.prototype.init = function DBConsole_init()
{
  if( !this.bInit )
  {
    try
    {
      this.pFrameDocument = this.pFrameWindow.document;
      
      var pFrame = getDOMObject( this.sFrameName, this.pFrameDocument );
      
      var pTable = getDOMObject( 'db_list', this.pFrameDocument );
      var pInput = getDOMObject( 'db_command_input', this.pFrameDocument );
      var pClear = getDOMObject( 'db_clear_button', this.pFrameDocument );

      if( !pTable )
      {
        // Liste
        pTable = this.pFrameDocument.createElement("table");
        pTable.id = 'db_list';
        pTable.cellPadding = 0; // saleté d'IE qui comprend rien
        pTable.cellSpacing = 0;
        pTable.className = 'dbconsole_table';
  
        var pBody = this.pFrameDocument.createElement("tbody");
        pTable.appendChild( pBody );

        pFrame.appendChild( pTable );
      }

      if( !pInput )
      {
        // Editeur
        var pInputTable = this.pFrameDocument.createElement("table");
        pInputTable.cellPadding = 0; // saleté d'IE qui comprend rien
        pInputTable.cellSpacing = 0;
        pInputTable.className = 'dbconsole_table';
        
        var pInputBody = this.pFrameDocument.createElement("tbody");
        pInputTable.appendChild( pInputBody );
        
        var pInputRow = pInputBody.insertRow(-1);
        
        this.pInputCell = pInputRow.insertCell(-1);
        this.pInputCell.className = "dbconsole_log_row dbconsole_log_row_command_input";
        var pButtonsCell = pInputRow.insertCell(-1);
        pButtonsCell.className = "dbconsole_log_row dbconsole_log_row_command_buttons";
  
        pInput = this.pFrameDocument.createElement("input");
        pInput.id = 'db_command_input';
        pInput.type = 'text';
        pInput.className = 'dbconsole_log_row dbconsole_input';

        this.pInputCell.appendChild( pInput );
        
        pClear = this.pFrameDocument.createElement("input");
        pClear.id = 'db_clear_button';
        pClear.type = 'button';
        pClear.value = 'Clear';
        pClear.className = 'dbconsole_log_row dbconsole_button';
        
        pButtonsCell.appendChild( pClear );

        pFrame.appendChild( pInputTable );
      }

      // on fait ça en dehors de if au cas où les tables soient déjà
      // initialisées mais qu'on aie changé d'objet et dans ce cas il
      // faut relier les evenements!

      // Evenements
      var pSelf = this;
      this.onKeyPress = function( event ) { pSelf.onInputKeyPress(event); }
      if( pInput.addEventListener )
        pInput.addEventListener( "keypress", this.onKeyPress, true );
      else if( pInput.attachEvent )
        pInput.attachEvent( "onkeydown", this.onKeyPress );

      this.onClearPress = function( event ) { pSelf.clear(); }
      if( pClear.addEventListener )
        pClear.addEventListener( "click", this.onClearPress, true );
      else if( pClear.attachEvent )
        pClear.attachEvent( "onclick", this.onClearPress );

      this.pTable = pTable;
      this.pInput = pInput;

      // HACK : ultime bidouille...
      // le problème lorsqu'on stock l'objet dans la frame server
      // c'est que les autres objets sont initialisés avec leur
      // propre objet (mais qui ne fait rien).
      // Si on change de page dans "app" on va bien utiliser le
      // bon pDBObject, mais les autres frames (menu et top) ne
      // sont jamais rechargées. Pour que tout le monde aie le
      // même objet, je les remplace moi même dans le init!
      
      // sinon on utilise une console vide qui n'affiche rien
      if( this.pEvalWindow )
      {
        this.pEvalWindow.pDBConsole = this;
        for( var nI=0; nI < this.pEvalWindow.frames.length; nI++ )
          this.pEvalWindow.frames[nI].pDBConsole = this;
      }
      
      this.bInit = true;
    }
    catch( ex )
    {
      alert(ex);
      return false;
    }
  }
  
  return true;
}

DBConsole.prototype._log = function DBConsole_log( sMessage, sRowClass )
{
  // si pas bien initialisé on ne fait rien...
  if( !this.bInit || !this.bEnabled ) return;

  var pTable = this.pTable;
  var pBody  = pTable.tBodies[0];

  var pRow = pBody.insertRow(-1);
  
  var pCell = pRow.insertCell(-1);

  if( sMessage && typeof(sMessage) == "string" && sRowClass == "result" )
    sMessage = '"'+sMessage+'"';
  
  // pas la peine de surcharger ça avec Firefox
  if( getBrowser() == IE && sMessage )
  {
    if( typeof(sMessage) == "object" && this.pEvalWindow.eval(sMessage instanceof Error) )
      sMessage = sMessage.name + ": " + sMessage.message;
    else if( typeof(sMessage) == "object" && sMessage.toString )
      sMessage = sMessage.toString();
      
    if( sMessage && typeof(sMessage) == "string" )
    {
      sMessage = sMessage.replace( / /g, '&nbsp;' );
      sMessage = sMessage.replace( /\n/g, '<br>' );
    }
  }

  pCell.innerHTML = sMessage != null && sMessage != "" ? sMessage : "&nbsp;";
  pCell.className = "dbconsole_log_row dbconsole_log_row_"+sRowClass;
  
  this._startScroll();
}

// Le défilement n'est pas synchrone, on le fait après 100ms
// Donc si d'autres appels sont fait, on ne scroll qu'une fois

DBConsole.prototype._startScroll = function DBConsole__startScroll()
{
  if( this.nScrollTimer != null ) return;
  this.nScrollTimer = this.pFrameWindow.setTimeout( this.hScrollFunc, 150 );
}

DBConsole.prototype._scrollToLast = function DBConsole__scrollToLast()
{
  this.nScrollTimer = null;
  this.pFrameWindow.scrollTo( 0, this.pInputCell.y ? this.pInputCell.y : this.pInputCell.offsetTop );
}

DBConsole.prototype._evaluateInput = function DBConsole__evaluateInput()
{
  var sExpression = this.pInput.value
  
  if( sExpression == "" )
    return;
  
  this.pInput.value = '';

  this._appendToHistory( sExpression );

  this._log( ">>> " + sExpression, "command" );
  
  var sResult = null;
  var sError = null;
  try
  {
    var pEvalWindow = this.pEvalWindow ? this.pEvalWindow : window;

    //with(this.pEvalWindow)
    //{
    //    pDBConsoleEvalFunction = new Function("return "+sExpression);
    //    sResult = pDBConsoleEvalFunction();
    //}

    sResult = pEvalWindow.eval( sExpression );
  }
  catch( ex )
  {
    // window.eval perd le type du résultat sur l'IE o_O
    if( getBrowser() == IE && ex && ex.message )
    {
      var pNew = new Error();
      pNew.name = ex.name;
      pNew.message = ex.message;
      ex = pNew;
    }
    this.error( ex );
  }
  
  if( sResult != null && sResult != undefined )
    this._log( sResult, "result" );
}

DBConsole.prototype._appendToHistory = function DBConsole__appendToHistory( sExpression )
{
  if( ++this.nHistoryInsertIndex >= this.nHistoryMax )
    this.nHistoryInsertIndex = 0;
    
  this.nHistoryCurrentIndex = this.nHistoryInsertIndex + 1;
  this.aCommandHistory[ this.nHistoryInsertIndex ] = sExpression;
}

DBConsole.prototype._cycleInputHistory = function DBConsole__cycleInputHistory( nOffset )
{
  this.aCommandHistory[ this.nHistoryCurrentIndex ] = this.pInput.value;
  
  if( nOffset < 0 )
  {
    this.nHistoryCurrentIndex += nOffset;
    if( this.nHistoryCurrentIndex < 0 )
      this.nHistoryCurrentIndex = 0;
  }
  else
  {
    this.nHistoryCurrentIndex += nOffset;
    if( this.nHistoryCurrentIndex > this.nHistoryInsertIndex + 1 )
      this.nHistoryCurrentIndex = this.nHistoryInsertIndex + 1;
  }

  var sExpression = this.aCommandHistory[ this.nHistoryCurrentIndex ];

  this.pInput.value = sExpression;
  
  if( this.pInput.setSelectionRange )
  {
    this.pInput.setSelectionRange( sExpression.length, sExpression.length );
  }
  else if( this.pInput.setSelectionRange )
  {
    var pRange = this.pInput.createTextRange();
    pRange.collapse( true );
    pRange.moveEnd( 'character', sExpression.length );
    pRange.moveStart( 'character', sExpression.length );
    pRange.select();
  }
}

DBConsole.prototype.onInputKeyPress = function DBConsole_onInputKeyPress( event )
{
  if( event.keyCode == 13 )
    this._evaluateInput();
  else if( event.keyCode == 27 )
    this.pInput.value = '';
  else if( event.keyCode == 38 )
    this._cycleInputHistory(-1);
  else if( event.keyCode == 40 )
    this._cycleInputHistory(1);
}


  /* Fonction publiques */

// TODO : pourquoi 'arguments' ne marche pas???

DBConsole.prototype.log = function DBConsole_log( sMessage )
{
  this._log( sMessage, "log" );
}

DBConsole.prototype.debug = function DBConsole_debug( sMessage )
{
  this._log( sMessage, "debug" );
}

DBConsole.prototype.info = function DBConsole_info( sMessage )
{
  this._log( sMessage, "info" );
}

DBConsole.prototype.warn = function DBConsole_warn( sMessage )
{
  this._log( sMessage, "warn" );
}

DBConsole.prototype.error = function DBConsole_error( sMessage )
{
  this._log( sMessage, "error" );
}

DBConsole.prototype.clear = function DBConsole_clear()
{
  if( !this.bInit || !this.bEnabled ) return;

  var pTable = this.pTable;
  var pBody  = pTable.tBodies[0];
  while( pBody.rows.length != 0 )
    pBody.deleteRow(0);
}

DBConsole.prototype.time = function DBConsole_time( sName )
{
  if( !this.bInit || !this.bEnabled || !sName ) return;

  var pTime = new Date().getTime();
  this.aTimers[ sName ] = pTime;
}

DBConsole.prototype.timeEnd = function DBConsole_timeEnd( sName )
{
  if( !this.bInit || !this.bEnabled || !sName ) return;

  var pTime = new Date().getTime();

  var pStartTime = this.aTimers[ sName ];
  if( pStartTime )
  {
    this._log( sName + ": " + ( pTime - pStartTime ) + "ms", "log" );
    delete this.aTimers[ sName ];
  }
}

DBConsole.prototype.trace = function DBConsole_trace()
{
  this._log( getStackTrace(1), "stack" );
}

DBConsole.prototype.focus = function DBConsole_focus()
{
  if( !this.bInit ) return;
  
  this.pInput.focus();
}

/* Fonction utiles */

function getStackTrace( nIgnoreLevel )
{
  var sOut = '';
  try
  {
    nIgnoreLevel = nIgnoreLevel ? nIgnoreLevel : 0;
    
    var fCaller = getStackTrace.caller;
    var nLevel = 0;
    
    for( var a = fCaller; a != null; a = a.caller )
    {
      var sFuncName = "anonymous";
      try
      {
        var aMatches = a.toString().match(/function (\w*)/);
        if( aMatches && aMatches[1] )
          sFuncName = aMatches[1];
      }
      catch( ex ) {}
  
      if( a.caller == a )
        sFuncName += "*";
  
      if( nLevel >= nIgnoreLevel )
        sOut += sFuncName + "\n";
  
      if( a.caller == a )
        break;
      
      nLevel++;
    }
  }
  catch(ex)
  {
    sOut += 'Cannot get stacktrace: '+ex.message;
  }
  
  return sOut;
}

function getTopFrameSet()
{
  var pFrameSet = null;
  
  if( getDOMObject( "homeframes", window.document ) )
    pFrameSet = getDOMObject( "homeframes", window.document );
  else if( window.top && getDOMObject( "homeframes", window.top.document ) )
    pFrameSet = getDOMObject( "homeframes", window.top.document );

  return pFrameSet;  
}

function showDBConsole()
{
  var pFrameSet = getTopFrameSet();
  if( pFrameSet )
    pFrameSet.rows = "80%,20%,0%";
  pDBConsole.focus();
}

function hideDBConsole()
{
  var pFrameSet = getTopFrameSet();
  if( pFrameSet )
    pFrameSet.rows = "100%,0%,0%";
}

// si la console dans la frame 'server' est initialisée on l'utilise
// sinon on utilise une console vide qui n'affiche rien
var pDBConsole = window.top && window.top.server && window.top.server.pDBConsole
                    ? window.top.server.pDBConsole
                    : new DBConsole();
// TODO : tester window.console (Firebug) aussi

// Renvoie la date du jour en fonction de la configuration
// /!\ Il faut utiliser cette fonction au lieu de new Date() 
function getCurrentDate()
{
  if( CURRENT_DATE == undefined )
    return new Date();
  return parseFixedDate( CURRENT_DATE );
}

function getCurrentDateTime()
{
  if( CURRENT_DATE_TIME == undefined )
    return new Date();
  return parseFixedDateTime( CURRENT_DATE_TIME );
}

function goHref(newHref, windowObj)
{
  if(windowObj == null)
    windowObj = window;
  if(windowObj.destroyPage)
  {
    try
    {
      if(windowObj.destroyPage(newHref) !== false)
        windowObj.location.href = newHref;
    }
    catch(ex)
    {
      //if(ex instanceof CheckerException && ex.getErrorNumber() == WARNING_PLEASE_SAVE_BEFORE_QUITTING )
        ex.showUser();
    }
  }
  else
    windowObj.location.href = newHref;
}

function hideTab(name) {
	jQuery('#tab_center_'+name,top.app.document).parents('table:first').hide();
}

