 /*
Spot Image SYRIUS Online - Main JS file
Copyright (c) 2005-2006 WS Interactive
Author: Sebastien Pauchet <sebastien.pauchet@ws-interactive.fr>
Created : 21/12/2005
$Id: common.api.js,v 1.5.1a 2008/11/04 08:30:31 sebastien Exp $
version 1.5.1.a "troncature" auto des nombres avec plus de 2 chiffres apres la virgule
*/

/** 
  * main debug var
  * 0 : no errors 
  * 1 : display errors
  * 2 : display errors and exceptions
  * 3 : display all Ajax call to server as an exception
  * 4 : display all call from Flash as an exception (including Flash logs)
  */
var Debug = 0;

/**
  * Declare Files call here
  */
///Tab pages
var searchTabpage = 	'FrameSearch.aspx';
var resultsTabpage = 	'FrameResults.aspx';
var orderTabpage = 		'FrameOrder.aspx';
//Other pages
var mapPopUp = 			'PageMap.aspx';
var datasheetPopUp = 	'PageResultDetail.aspx';
var preferencePage = 	'PagePreference.aspx';
var loginPage = 		'PageLogin.aspx';
var alertsPage = 		'PageAlert.aspx';
var contextPage =		'PageSave.aspx';
var indexPage = 		'PageIndex.aspx';
var savePage = 			'PageSave.aspx';
var addressesPage = 	'PageAddresses.aspx';
// DM21455 ALE
//download page
var downloadPage = 		'PageDownload.aspx';
// FIN DM 21455

//For print & export
var printPage = 		'PagePrint.aspx';
//Programming estimate
var petPage = 			'PageProgrammingEstimate.aspx';
//search page
var searchPage = 		'PageSearch.aspx';


/**
  * Declare all AJAX call here
 */
var xmlPreference = "Interface/Ajax/XMLPreference.ashx?preference={preference}&value={value}";
var xmlEmailPage = "Interface/Ajax/XMLPageEmailResult.ashx";


//SOL VERSION
var solVersion = '1.5.1a';
//document name definition
// DM 22392 Changment de nom 
document.name="SPOTCatalog";
//document language code
var languageCode;
//user preference vars
var userPreference = new Array();
//screen size
var screensize;
//flash vars
var flashWidth = 520;
var flashHeight = 570;
var flashFile = 'swf/carte_1024.swf';
//flash load status
var flashLoaded;
//flash context
var defaultFlashContext = 'layers=||extent=';
//Current popup mode
var popupMode = false;
var popupReference;
if (typeof windowType == 'undefined') {
	var windowType = 'window';
	window.name= 'SOL';
}
/**********************************************
* Browser definition                          *
**********************************************/
if (typeof skipBrowserCheck == 'undefined') {
	var browserOK = false;
	if (navigator.userAgent.toLowerCase().indexOf('msie') != -1 && navigator.userAgent.toLowerCase().indexOf('opera') == -1) {
		var isIE = true;
		var menutimer;
		//get IE version
//		if (navigator.userAgent.toLowerCase().indexOf("msie 5.5") != -1) {
//			var isIE55 = true;
//			pr('[I am the '+windowType+' and I am running on IE5.5 -- v'+solVersion+']');
//		} else if (navigator.userAgent.toLowerCase().indexOf("msie 6") != -1)  {
//			var isIE6 = true;
//			pr('[I am the '+windowType+' and I am running on IE6.0 -- v'+solVersion+']');
//			browserOK = true;
//		} else if (navigator.userAgent.toLowerCase().indexOf("msie 7") != -1)  {
//			var isIE7 = true;
//			pr('[I am the '+windowType+' and I am running on IE7.0 -- v'+solVersion+']');
//			browserOK = true;
//		}
        //DM 22586 changement de version des browsers
        var numVersionIE = navigator.userAgent.substr(navigator.userAgent.toLowerCase().indexOf('msie')+ 5 ,3);
        if (numVersionIE > '5.5')
        {
           pr('[I am the '+windowType+' and I am running on IE'+ numVersionIE + '-- v'+solVersion+']');
           browserOK = true;
        }
		var timerdiv;
		var timerli;
		var elementdiv;
		var elementli;
	} else if (navigator.userAgent.toLowerCase().indexOf('opera') != -1) {
		//not compatible for now (tried with opera 8 & 9)
		var isOp = true;
		pr('[I am the '+windowType+' and I am running on Opera -- v'+solVersion+']');
	} else if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1 || 
			  (navigator.userAgent.toLowerCase().indexOf('mozilla') != -1 && (navigator.userAgent.toLowerCase().indexOf('rv:1.7') != -1 || navigator.userAgent.toLowerCase().indexOf('rv:1.8') != -1))) {
		browserOK = true;
		var isMoz = true;
		pr('[I am the '+windowType+' and I am running on Gecko :-D -- v'+solVersion+']');
	}
	if (!browserOK) {
		location.replace(indexPage);
	}
}
/* RESOLUTION SWITCHER - Add needed CSS */
function chooseResolution() {
	var small = 1024;
	var middle = 1280;
	var large = 1600;
	// Constantes vars
	if (windowType == 'frame') {
		screensize = getVar('screensize');
	} else {
		screensize = 1024; // Default
		var currentMode = 'both'; // "width", "height", "both"
		var width,height;
		// Get current window screensize
		width = (isMoz) ? window.innerWidth : document.documentElement.clientWidth;
		height = (isMoz) ? window.innerHeight : document.documentElement.clientHeight;
		pr('=> set screen resolution (Detected : '+width+' x '+height+')');
		// Width level
		widthDefault = (width < 1250) ? small : (width >= 1579) ? large : middle ;
		
		// Height level
		heightDefault = (height < 823) ? small : (height >= 999) ? large : middle ;
		
		// Set current resolution
		switch (currentMode){
			case 'width':
				screensize = widthDefault;
			break;
			case 'height':
				screensize = heightDefault;
			break;
			case 'both':
				screensize = (widthDefault < heightDefault) ? widthDefault : heightDefault;
			break;
		}
	}
	//set flash vars
	if (screensize == large) {
		flashWidth = 820;
		flashHeight = 851;
	} else if (screensize == middle) {
		flashWidth = 630;
		flashHeight = 665;
	}
	flashFile = 'swf/carte_'+screensize+'.swf';
	// Display
	if (windowType == 'frame') {
		addStyle('css/' + screensize + '/frame.css');
		if (currentTab == 'search') {
			addStyle('css/' + screensize + '/search.css');
		} else if (currentTab == 'result') {
			addStyle('css/' + screensize + '/results.css');
		} else if (currentTab == 'order') {
			addStyle('css/' + screensize + '/order.css');
		}
	} else if (windowType == 'window') {
		addStyle('css/' + screensize + '/index.css');
		if (typeof accountPage != 'undefined' && accountPage) {
			addStyle('css/' + screensize + '/account.css');
		}
	}
	return true;
}
/*add stylesheet to existent ones*/
function addStyle(styleHref) {
	var style = document.createElement("LINK");
	style.rel = 'stylesheet';
	style.type = 'text/css';
	style.media = 'screen';
	style.href = styleHref;
	document.body.appendChild(style);
	return true;
}
/**********************************************
* MISC. FUNCTIONS                             *
**********************************************/

/* Add usefull Method getElementsByClassName*/
document.getElementsByClassName = function (needle)
{
	var my_array = document.getElementsByTagName("*");
	var retvalue = new Array();
	var i;
	var j;
	
	for (i = 0, j = 0; i < my_array.length; i++) {
		var c = " " + my_array[i].className + " ";
		if (c.indexOf(" " + needle + " ") != -1) {
			retvalue[j++] = my_array[i];
		}
	}
	return retvalue;
}

/* show/hide given element*/
function showHide(eid)
{
	var f;
	if (typeof(eid) == 'string') {
		f = getE(eid);
		if (f == false) {
			return false;
		}
	} else {
		f = eid;
	}
	if (f.style.display != 'block' && f.style.display != 'table-row' && f.style.display != 'table-cell') {
		if (f.tagName=='TR' && !isIE) {
			f.style.display = 'table-row';
		} else if (f.tagName=='TD' && !isIE) {
			f.style.display = 'table-cell';
		} else if (f.tagName=='SPAN') {
			f.style.display = 'inline';
		} else {
			f.style.display = 'block';
		}
		return 'visible';
	} else {
		f.style.display = 'none';
		return 'hidden';
	}
	return false;
}
/* show given element*/
function show(eid)
{
	var f;
	if (typeof(eid) == 'string') {
		f = getE(eid);
		if (f == false) {
			return false;
		}
	} else {
		f = eid;
	}
	if (f.tagName=='TR' && !isIE) {
		f.style.display = 'table-row';
	} else if (f.tagName=='TD' && !isIE) {
		f.style.display = 'table-cell';
	} else if (f.tagName=='SPAN' || f.tagName=='SELECT') {
		f.style.display = 'inline';
	} else {
		f.style.display = 'block';
	}
	return true;
}
/* hide given element*/
function hide(eid)
{
	var f;
	if (typeof(eid) == 'string') {
		f = getE(eid);
		if (f == false) {
			return false;
		}
	} else {
		f = eid;
	}
	f.style.display = 'none';
	return true;
}
/*format a date*/
//input format must be yyyy.mm.dd
//output is set by user preference calendarformat
function formatDate(date) {
	var userFormat = userPreference['calendarformat'];
	var returnDate = '';
	var day = date.substr(8,2);
	var month = date.substr(5,2);
	var year = date.substr(0,4);
	userFormat = userFormat.replace('dd',day);
	userFormat = userFormat.replace('mm',month);
	userFormat = userFormat.replace('yyyy',year);
	returnDate = userFormat;
	return returnDate;
}

//ALE
/*Truncate Coordinate if number of decimal > 2
 * DM 21811 tronque la valeur de la lat/long lorsque l utilisateur
 * sort de la case
 * param value : valeur saisie, id : identifiant du label
 */
 
function truncateCoordinate(value, id){
    
   if ( userPreference['coordinatesformat'] == 'decimal')
   {
     document.getElementById(id).value = Math.round(value * 100) /100 ;
   }
}

/* Truncate decimal value coordinate */
// DM21811 ALE ajout d'une fonction tronquant les coordonnees
// cette fonction est appelé au chargment de la page ainsi  lorsque les coordonnees
// proviennent de l'exterieur c'est tronque
function truncateCoordinates(value){

   if ( userPreference['coordinatesformat'] == 'decimal')
   {
      value = Math.round(value * 100) /100 ;
   }
    return value;
}



/**
  * function to open Navigator Windows
  * parameters available: width (w), height (h), resizable (r), scrollbars (s), menubar (m), left position (left), top position (top)
  */
function openWindow(url, name) {
	var w = arguments[2];
	var h = arguments[3];
	var r = arguments[4];
	var s = arguments[5];
	var m = arguments[6];
	var left = arguments[7];
	var top = arguments[8];
	var popupWin;
	if (arguments.length > 2) {
		//open popup
		popupWin = window.open(url, '_blank', 'width=' + w + ',height=' + h + ',resizable=' + r + ',scrollbars=' + s + ',menubar=' + m + ',left=' + left + ',top=' + top);
	} else {
		//open new window
		popupWin = window.open(url);
	}
	return popupWin;
}
/*get element by id (cross frames method)*/
function getE(id) {
	var el;
	//same document
	if (el = document.getElementById(id)) { 
		return el;
	} else 
	//in parent
	if (el = parent.document.getElementById(id)) { 
		return el;
	} else 
	//in frame
	if (document.getElementById('innerframe') && (el = document.getElementById('innerframe').contentWindow.document.getElementById(id))) {
		return el;
	} else
	//in popup 
	if (parent.popupReference && !parent.popupReference.closed) {
		return parent.popupReference.document.getElementById(id);
	} else
	//in opener 
	if (windowType == 'popup' && (typeof accountPage == 'undefined' || !accountPage) && window.opener && (el = window.opener.document.getElementById(id))) {
		return el;
	} else {
		return false;
	}
}
/*get var value (cross frames method)*/
function getVar(varName) {
	if (typeof arguments[1] == 'undefined') {
		//auto detect var location between same document, frame and popup
		//same document
		if (eval('typeof ' + varName + ' != \'undefined\'')) {
			return eval(varName);
		} else 
		//in frame (from window)
		if (document.getElementById('innerframe') && eval('typeof document.getElementById(\'innerframe\').contentWindow.' + varName + ' != \'undefined\'')) {
			return eval('document.getElementById(\'innerframe\').contentWindow.' + varName);
		} else
		//in window (from frame)
		if (window.parent && eval('typeof window.parent.' + varName + ' != \'undefined\'')) {
			return eval('window.parent.' + varName);
		} else
		//in window (from popup)
		if (window.opener) {
			return window.opener.getVar(varName);
		}
	} else {
		//var location is given by arguments[1]
		if (arguments[1] == 'same') {
			return eval(varName);
		} else if (arguments[1] == 'frame') {
			//from window
			if (windowType == 'window') {
				return eval('document.getElementById(\'innerframe\').contentWindow.' + varName);
			} else 
			//from popup
			if ((windowType == 'popup')) {
				return eval('window.opener.document.getElementById(\'innerframe\').contentWindow.' + varName);
			} else {
				//from frame
				return eval(varName);
			}
		} else if (arguments[1] == 'popup') {
			return window.opener.getVar(varName);
		} else {
			pr('getVar : unknown position to get : ' + arguments[1] + ' for var '+varName);
		}
	}
}
/*set var value (cross frames method)*/
function setVar(varName, varValue, targetName) {
	//var location is given by targetName
	if (targetName == 'same') {
		eval(varName+'=varValue;');
		return true;
	} else if (targetName == 'frame') {
		//from window
		if (windowType == 'window') {
			eval('document.getElementById(\'innerframe\').contentWindow.' + varName + '=varValue;');
			return true;
		} else 
		//from popup
		if ((windowType == 'popup')) {
			eval('window.opener.document.getElementById(\'innerframe\').contentWindow.' + varName+'=varValue;');
			return true;
		} else {
			//from frame
			eval(varName + '=varValue;');
			return true;
		}
	} else if (targetName == 'popup') {
		return window.opener.setVar(varName,varValue);
	} else {
		pr('setVar : unknown position to get : ' + targetName + ' for var '+varName);
		return false;
	}
}
/*create an URL with parameters*/
function createURL(url,parameters) {
	var urlReg = new RegExp('\{([a-zA-Z]+)\}','');
	var loop = true;
	while (loop) {
		var param = urlReg.exec(url);
		if (param == null || typeof param[1] == 'undefined') {
			loop = false;
		} else if (typeof parameters[param[1]] == 'undefined') {
			pr('createURL : Unknown parameter ' + param[1] + '. Function called by '+createURL.caller.name);
			return false;
		} else {
			var replaceReg = new RegExp('(\{' + param[1] + '\})');
			url = url.replace(replaceReg,escape(parameters[param[1]]));
		}
	}
	return url;
}
/*send user to login page (disconnected)*/
function goToLogin() {
	if (windowType == 'window') {
		return location.replace(loginPage)
	} else {
		return window.parent.location.replace(loginPage);
	}
}
/**********************************************
* Sensitive IO FUNCTIONS                      *
**********************************************/
/* check if given value is a correct coordinate format*/
function isCoordinate(value, isLat) {
	switch (userPreference['coordinatesformat']) {
		case "sexa":
			var format = "^[NEWS]{1}[0-9]{1,3}[" + applicationMessages['degree'] + "]{1}[0-9]{0,2}$";
		break;
		case "decimal":
		default:
			var format = "^[+-]{0,1}[0-9]{1,3}[.]?[0-9]{0,2}$";
		break;
	}
	//test format
	if (!isFormat(value,format)) {
		return false;
	}
	//clean value
	var reg = new RegExp('[^0-9.' + applicationMessages['degree'] + ']','g');
	var reg2 = new RegExp('[' + applicationMessages['degree'] + ']','g');
	value = value.replace(reg, '').replace(reg2, '.');
	//then test value (absolute value between 0->90 for Lat and 0->180 for Long)
	if (isLat && parseFloat(value) > 90) {
		return false;
	} else if (parseFloat(value) > 180) {
		return false;
	}
	return true;
}
/*check if coordinate is a sexagesimal coordinate format*/
function isSexaCoordinate(value) {
	var format = "^[NEWS]{1}[0-9]{1,3}[" + applicationMessages['degree'] + "]{1}[0-9]{0,2}$";
	return isFormat(value,format);
}
/* check if given value is a positive integer (max : 999)*/
function isInteger(value) {
	var format = "^[+]{0,1}[0-9]{1,3}$";
	return isFormat(value,format);
}
function isPhone(value) {
	var format = "^[0-9]{1,}$";
	return isFormat(value,format);
}
/* check if given value is a float (range : -999.99 to 999.99)*/
function isFloat(value) {
	var format = "^[+-]{0,1}[0-9]{1,3}[.]?[0-9]{0,2}$";
	return isFormat(value,format);
}
/* check if given value is a valid email*/
function isEmail(value) {
	var format = '^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,3}$';
	var reg = new RegExp(format);
	return reg.test(value);
}
/* check if given value is a correct date format*/
function isDate(value) {
	switch (userPreference['calendarformat']) {
		case "yyyy/mm/dd":
		case "yyyy-mm-dd":
			var format = "^[0-9]{4}[/-]{1}[0-9]{2}[/-]{1}[0-9]{2}$";
		break;
		case "dd/mm/yyyy":
		case "mm/dd/yyyy":
		case "dd-mm-yyyy":
		case "mm-dd-yyyy":
			var format = "^[0-9]{2}[/-]{1}[0-9]{2}[/-]{1}[0-9]{4}$";
		break;
		default:
			pr('isDate : unknown date format '+userPreference['calendarformat']);
			return false;
		break;
	}
	return isFormat(value,format);
}
/* check if given value match given regexp format*/
function isFormat(value,format) {
	var reg = new RegExp(format,"g");
	return reg.test(value);
}
/*simple trim function*/
function trim(string){
	return string.replace(/(^\s*)|(\s*$)/g,'');
}
/*fill start value with zero until given length*/
function fillWithZero(value,length) {
	if (value.toString().length < length) {
		while (value.toString().length < length) {
			value = "0" + value;
		}
	}
	return value;
}
/*function to convert coordinate value in decimal or sexagesimal*/
function convertCoordinateFormat(value,newFormat,isLat) {
	if (newFormat != 'decimal' && newFormat != 'sexa') {
		pr("convertCoordinateFormat : Unknown format of conversion : " + newFormat);
		return false;
	}
	if (!value || typeof value == 'undefined') {
		return '';
	}
	var newValue = '';
	if (newFormat == 'decimal') {
		//explode format N12°21 or S12°21 or W... S...
		var regSplit = new RegExp("[" + applicationMessages['degree'] + "]+");
		var values = value.toString().split(regSplit);
		if (values[0].toUpperCase().indexOf("S") != -1 || values[0].toUpperCase().indexOf("W") != -1) {
			//negative value
			newValue = '-' + values[0].substr(1);
		} else {
			//positive value
			newValue = values[0].substr(1);
		}
		//to differenciate float values like .8 and .08, transform in .80 and .08
		if (typeof values[1] != 'undefined' && values[1].toString().length < 2) {
			values[1] = 10*values[1];
		}
		if (typeof values[1] != 'undefined' && values[1] > 0) {
			newValue += '.' + fillWithZero(Math.round(values[1]/0.6), 2);
		}
	} else {
		//explode format 12.21 or -12.21
		var regSplit = new RegExp("[.]+");
		var values = value.toString().split(regSplit);
		if (parseFloat(values[0]) < 0 || (parseFloat(values[0]) == 0 && parseFloat(value) < 0)) {
			newValue = (isLat) ? "S":"W";
			newValue += (-1 * (parseFloat(values[0]))) + applicationMessages['degree'];
		} else if (parseFloat(values[0]) > 0 || (parseFloat(values[0]) == 0 && parseFloat(value) > 0)) {
			newValue = (isLat) ? "N":"E";
			newValue += (parseFloat(values[0])) + applicationMessages['degree'];
		}
		//to differenciate float values like .8 and .08, transform in .80 and .08
		if (typeof values[1] != 'undefined' && values[1].toString().length < 2) {
			values[1] = 10*values[1];
		}
		if (typeof values[1] != 'undefined' && values[1] > 0) {
			newValue += fillWithZero(Math.round(values[1]*0.6), 2);
		}
	}
	return newValue;
}
/*get coordinates at current user format for a decimal given value*/
function getUserFormatCoordinates(value,isLat) {
	if (userPreference['coordinatesformat'] == 'sexa') {
		return convertCoordinateFormat(value,'sexa',isLat);
	} else {
		return value;
	}
}
/*get coordinates at decimal format for a current user format given value*/
function getDecimalCoordinates(value,isLat) {
	if (userPreference['coordinatesformat'] == 'sexa') {
		return convertCoordinateFormat(value,'decimal',isLat);
	} else {
		return value;
	}
}
/*serialize a multidimentionnal array (max 3 levels)*/
function serializeArray(arrayValue) {
	var level = (typeof arguments[1] != 'undefined') ? arguments[1] : 0;
	var seps = new Array("||||","|||","||");
    for(var i=0;i<arrayValue.length;i++)
    {
       if(arrayValue[i] instanceof Array)
        {
             arrayValue[i]=serializeArray(arrayValue[i],level+1);
        }
    }
    return arrayValue.join(seps[level]);
}

/**********************************************
* EVENTS FUNCTIONS                            *
**********************************************/

/* Add event on object*/
function addEvent(obj, evType, fn)
{
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
	return true;
}
/*Add click events on form buttons tags*/
function addButtonEvents () {
	var inputs = document.getElementsByTagName('input');
	if (inputs.length > 0) {
		for (i = 0; i < inputs.length; i++) {
			if (inputs[i].type == 'button' || inputs[i].type == 'image') {
				addEvent(inputs[i], 'click', function()
				{
					if (isIE) {
						e = window.event.srcElement;
					} else {
						e = this;
					}
					if (typeof e.id != 'undefined') {
						pr('click ' + e.id);
						return eval(e.id + "();");
					} else {
						raiseError('Function ' + e.id + ' undefined');
						return false;
					}
				});
			}
		}
	}
	return true;
}

/**********************************************
* MESSAGES & ERRORS FUNCTIONS                 *
**********************************************/

/*error function, used for all API errors messages*/
var errorRaided = false;
function raiseError(errorMessage) {
	errorRaided = true;
	if (Debug > 0) {
		var msg = 'Error : ' + errorMessage + '\n\n' + raiseError.caller ;
	} else {
		var msg = 'Error : ' + errorMessage;
	}
	window.alert(msg);
}
/*raise an exception if debug is true*/
function pr(value) {
	if (Debug >= 2) {
		if (typeof(value) != 'string' && typeof(value) != 'undefined' && value != null) {
			value = value.toString();
		}
		if (windowType == 'window') {
			value = '<span style="color:#268302;">'+value+'</span>';
		} else if (windowType == 'frame') {
			value = '<span style="color:#0000FF;">'+value+'</span>';
		} else if (windowType == 'popup') {
			value = '<span style="color:#FF0000;">'+value+'</span>';
		}
		if (getE("prWindow")) {
			getE("prWindow").innerHTML += "<br />"+value;
			show('prWindow');
		} else {
			document.write('<div id="prWindow" onclick="hide(\'prWindow\');getE(\'prWindow\').innerHTML=\'\';">' + value + '</div>');
		}
	}
	return true;
}
/*raise a message for user*/
//fcn parameter must be declared with parameters (ex : "buttonAddToOrder('addToOrder')")
function userMessage(value, fcn) {
	if (typeof(value) != 'string' && typeof(value) != 'undefined') {
		value = value.toString();
	}
	if (getE("userMessage")) {
		hide('innercontent');
		var messageOK = '';
		var messageCancel = '';
		if (windowType == 'window' && document.getElementById('innerframe')) {
			messageOK = getVar('applicationMessages[\'ok\']','frame');
		} else {
			messageOK = getVar('applicationMessages[\'ok\']');
		}
		if (fcn == true) {
//			value = value + '<br /><br /><div class="orange-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return true;" value="' + messageOK +'" /></div>';
            value = value + '<br /><br /><div class="buttonsCenter" align="center"><table  cellspacing="0" cellpadding="0" border="0" width="100%" class="colored-button"><tr><td class="orange-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return true;" value="' + messageOK +'" /></td><td class="orange-button-right">&nbsp;</td></tr></table></div>';
		} else if (fcn == 'goToLogin') { //send user to login page
			value = value + '<br /><br /><div class="buttonsCenter" align="center"><table  cellspacing="0" cellpadding="0" border="0" width="100%" class="colored-button"><tr><td class="orange-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return goToLogin();" value="' + messageOK +'" /></td><td class="orange-button-right">&nbsp;</td></tr></table></div>';
		} else {
			if (windowType == 'window' && document.getElementById('innerframe')) {
				messageCancel = getVar('applicationMessages[\'cancel\']','frame');
			} else {
				messageCancel = getVar('applicationMessages[\'cancel\']');
			}
			value = value + '<br /><br /><div class="buttonsCenter" align="center"><table  cellspacing="0" cellpadding="0" border="0" width="100%" class="colored-button"><tr><td class="orange-button-left"><input type="button" onclick="if ('+fcn+') {hide(\'userMessage\');show(\'innercontent\');return true;}" value="' + messageOK +'" /></td><td class="orange-button-right">&nbsp;</td><td class="red-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return true;" value="' + messageCancel +'" /></td><td class="red-button-right">&nbsp;</td></tr></div>';
		}
		getE("userMessage").innerHTML = value;
		window.scrollTo(0,0);
		show('userMessage');
	} else {
		raiseError(value);
	}
	return true;
}
/*raise a message for user*/
function userConfirmMessage(value, fcnOk, fcnCancel) {
	if (typeof(value) != 'string' && typeof(value) != 'undefined') {
		value = value.toString();
	}
	if (getE("userMessage")) {
		hide('innercontent');
		var messageOK = '';
		var messageCancel = '';
		if (windowType == 'window' && document.getElementById('innerframe')) {
			messageOK = getVar('applicationMessages[\'ok\']','frame');
		} else {
			messageOK = getVar('applicationMessages[\'ok\']');
		}
		if (fcn == true) {
		    value = value + '<br /><br /><div class="buttonsCenter" align="center"><table  cellspacing="0" cellpadding="0" border="0" width="100%" class="colored-button"><tr><td class="orange-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return true;" value="' + messageOK +'" /></td><td class="orange-button-right">&nbsp;</td></tr></table></div>';
		} else if (fcn == 'goToLogin()') {
            value = value + '<br /><br /><div class="buttonsCenter" align="center"><table  cellspacing="0" cellpadding="0" border="0" width="100%" class="colored-button"><tr><td class="orange-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return goToLogin();" value="' + messageOK +'" /></td><td class="orange-button-right">&nbsp;</td></tr></table></div>';
   		} else {
			if (windowType == 'window' && document.getElementById('innerframe')) {
				messageCancel = getVar('applicationMessages[\'cancel\']','frame');
			} else {
				messageCancel = getVar('applicationMessages[\'cancel\']');
			}
			value = value + '<br /><br /><div class="buttonsCenter" align="center"><table  cellspacing="0" cellpadding="0" border="0" width="100%" class="colored-button"><tr><td class="orange-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return '+fcn+';" value="' + messageOK +'" /></td><td class="orange-button-right">&nbsp;</td><td class="red-button-left"><input type="button" onclick="hide(\'userMessage\');show(\'innercontent\');return true;" value="' + messageCancel +'" /></td><td class="red-button-right">&nbsp;</td></tr></div>';
		}
		getE("userMessage").innerHTML = value;
		window.scrollTo(0,0);
		show('userMessage');
	} else {
		raiseError(value);
	}
	return true;
}
/*show user confirmation message*/
function userConfirm(params) {
	if (getE('userConfirmMessage')) {
		getE('userConfirmMessage').innerHTML = params.firstChild.nodeValue;
		show('userConfirm');
	} else {
		userMessage(params.firstChild.nodeValue,true);
	}
}
/*highlight incorrect field*/
function highlightField(id) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	if (isIE && getE(id).tagName == 'SELECT') {
		var element = getE(id).parentNode;
		addEvent(getE(id), 'click', function() {
			if (isIE) {
				e = window.event.srcElement;
			} else {
				e = this;
			}
			e.parentNode.style.border = "";
			return true;
		});
	} else if (getE(id).tagName == 'DIV') {
		var element = getE(id);
		addEvent(getE(id), 'click', function() {
			if (isIE) {
				e = window.event.srcElement;
			} else {
				e = this;
			}
			e.style.border = "";
			return true;
		});
	} else {
		var element = getE(id);
		addEvent(element, 'click', function() {
			if (isIE) {
				e = window.event.srcElement;
			} else {
				e = this;
			}
			e.style.border = "1px solid #305782";
			return true;
		});
	}
	element.style.border="1px solid #FF0000";
	return true;
}
/*timer function*/
function startTimer() {
	var date = new Date();
	return date.getTime();
}
/*timer function, return number of seconds since startTimer*/
function getTimer(label, startTime) {
	var date = new Date();
	var endTime = date.getTime();
	var timeLength = (endTime-startTime)/1000;
	pr('Time for \'' + label + '\' : ' + timeLength + 's');
	return true;
}

/**********************************************
* XML FUNCTIONS                               *
**********************************************/

/*XMLHttpRequest cross browser function*/
function getHTTPObject()
{
	var xmlhttp = false;
	responseXML = null;
	
	//Specific IE code, DO NOT REMOVE
	/*@cc_on
	@if (@_jscript_version >= 5)
		var msxml = new Array('MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP');
		for(var i=0; i<msxml.length; i++){
			try {
				// Instantiates XMLHttpRequest for IE and assign to xmlhttp.
				xmlhttp = new ActiveXObject(msxml[i]);
				if(xmlhttp){
					break;
				}
			} catch(e){}
		}
		
		@else
			xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	if (xmlhttp) {
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					raiseError(xmlhttp.responseText);
				}
			}
		}
	}
	return xmlhttp;
}

/** 
  * Get an XML File (use GET sending)
  * Send it to a given function
  * If fcn value is null, then do nothing, no treatment needed after call
  */
function getXMLFile(xmlUrl, fcn)
{
	var xmlhttp = getHTTPObject();
	var response;
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status && xmlhttp.status == 200 && xmlhttp.responseXML != null && xmlhttp.responseXML.getElementsByTagName('error').length > 0) {
				response = xmlhttp.responseXML;
				var error = response.getElementsByTagName('error').item(0).firstChild.nodeValue;
				if (error != 0) {
					var msg = response.getElementsByTagName('errormessage').item(0).firstChild.nodeValue;
					if (error == 1) {
						userMessage(msg,true);
					} else if (error == 2) { //redirect to login page
						userMessage(msg,'goToLogin()');
					} else if (error == 3) { //confirm sending of search with more than 100 results
						userMessage(msg,'confirmSearch()');
					}
				}
				if (fcn != null && typeof eval(fcn) == 'function') {
					return eval(fcn+"(response);");
				}
				return true;
			} else if(xmlhttp.status) {
				var msg = applicationMessages['servercommunicationerror'];
				if (Debug > 0) {
					msg += '<br />Status : ' + xmlhttp.status;
					if (xmlhttp.responseXML == null) {
						msg += '<br />XML Response is Null !';
					} else if (xmlhttp.responseXML.getElementsByTagName('error').length == 0) {
						msg += '<br />Empty XML response !';
					}
				}
				userMessage(msg,true);
				return false;
			}
		}
	}
	//launch loading function if exists
	if (eval("typeof (" + fcn + "Load)") == 'function') {
		eval(fcn+"Load();");
	}
	//add timestamp at end of query to avoid navigator cache
	var time = new Date();
	xmlUrl += (xmlUrl.indexOf('?') != -1) ? '&time=' + time.getTime() : '?time=' + time.getTime();
	xmlhttp.open("GET", xmlUrl,true);
	xmlhttp.send(null);
	if (Debug >= 3) {
		pr('Ajax call : ' + unescape(xmlUrl));
	}
}
/*set a user preference like map in new window*/
function setUserPreference(preference, value) {
	//set local preference
	userPreference[preference] = value;
	//save new values to server
	var urlParameters = new Array();
	urlParameters['preference'] = preference;
	urlParameters['value'] = value;
	var url = '';
	url = createURL(xmlPreference,urlParameters);
	getXMLFile(url, null);
	pr('<= Set user preference ' + preference + ' : ' + value);
	return true;
}

/**********************************************
* Objects Loading FUNCTIONS                   *
**********************************************/  

/*treat all user preferences*/
function loadPreference (params) {
	if (params.getElementsByTagName('preference').length > 0) {
		var prefValue;
		preferenceObject = params.getElementsByTagName('preference').item(0);
		if (preferenceObject.childNodes.length) {
			for (m = 0; m < preferenceObject.childNodes.length; m++) {
				if (typeof preferenceObject.childNodes[m].tagName != 'undefined') {
					//set all user preferences vars
					eval("userPreference['" + preferenceObject.childNodes[m].tagName + "']='" + preferenceObject.childNodes[m].getAttribute('value') + "';");
				}
			}
		} else {
			raiseError("Malformed element : " + languageObject.tagName);
		}
	}
	if (userPreference['authenticateduser'] == 'false') {
		//check for user autentification
		if (applicationMessages['msg_welcome'] != null)
		{
		// DM 23096
		    getE('welcome').innerHTML = applicationMessages['msg_welcome'];
		}
		else 
		{
		    getE('welcome').innerHTML = '';
		}
		
	}
	return true;
}
/*treat languages*/
function loadLanguage (params) {
	if (params.getElementsByTagName('language').length > 0) {
		languageObject = params.getElementsByTagName('language').item(0);
		if (languageObject.childNodes.length) {
			getE('languageSelect').innerHTML = '';
			for (m = 0; m < languageObject.childNodes.length; m++) {
				if (languageObject.childNodes[m].tagName == 'listbox') {
					populateListBox (languageObject.childNodes[m].getAttribute('id'),languageObject.childNodes[m]);
					//set document language code
					languageCode = languageObject.childNodes[m].getAttribute('selected');
				}
			}
		} else {
			raiseError("Malformed element : " + languageObject.tagName);
		}
	}
	/*display sirius Flash*/
	if (getE('flashsirius')) {
		// Inserting flash
		writeFlashObject('flashsirius', 'flashBanner', 'swf/sirius.swf', 148, 50);
		show('flashsirius');
	}
	return true;
}
/*populate Text Box values*/
function populateTextBox (id,XMLobject) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	if (XMLobject.childNodes.length > 1) {
		raiseError("Malformed element ID : " + id);
		return false;
	}
	var hasValue = false;
	element = getE(id);
	if (XMLobject.getAttribute('disabled') == "true") {
		element.disabled = true;
	}
	if (XMLobject.childNodes.length == 1) {
		element.value = XMLobject.firstChild.nodeValue;
		hasValue = true;
	} else {
		element.value = "";
	}
	return hasValue;
}
/*populate List Box values*/
function populateListBox (id,XMLobject) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	var hasSelectedValues = false;
	var selected = XMLobject.getAttribute('selected');
	if (XMLobject.childNodes.length >= 1) {
		element = getE(id);
		if (XMLobject.getAttribute('disabled') == "true") {
			element.disabled = true;
		}
		if (element.options.length) {
			firstOption = element.options[0];
			element.innerHTML ='';
			if (isIE) {
				element.add(firstOption);
			} else {
				element.add(firstOption,null);
			}
		}
		for (n = 0; n < XMLobject.childNodes.length; n++) {
			itemNode = XMLobject.childNodes[n];
			if (typeof itemNode.tagName != "undefined") {
				if (itemNode.tagName != 'item' || itemNode.childNodes.length == 0) {
					raiseError("Malformed element ID : " + id);
					return false;
				}
				var oOption = document.createElement("OPTION");
				oOption.text = itemNode.firstChild.nodeValue;
				oOption.value= itemNode.getAttribute('value');
				hasSelectedValues = (itemNode.getAttribute('value') == selected) ? true:hasSelectedValues;
				if (isIE) {
					element.add(oOption);
				} else {
					element.add(oOption,null);
				}
				if (itemNode.getAttribute('value') == selected) {
					oOption.selected = true;
				}
			}
		}
	}
	return hasSelectedValues;
}
/*populate Multi List Box values*/
function populateMultiListBox (id,XMLobject) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	var hasSelectedValues = false;
	element = getE(id);
	if (XMLobject.getAttribute('disabled') == "true") {
		element.disabled = true;
	}
	element.innerHTML ='';
	if (XMLobject.childNodes.length >= 1) {
		for (n = 0; n < XMLobject.childNodes.length; n++) {
			itemNode = XMLobject.childNodes[n];
			if (typeof itemNode.tagName != "undefined") {
				if (itemNode.tagName != 'item' || itemNode.childNodes.length == 0) {
					raiseError("Malformed element ID : " + id);
					return false;
				}
				var oOption = document.createElement("OPTION");
				oOption.text = itemNode.firstChild.nodeValue;
				oOption.value = itemNode.getAttribute('value');
				if (isIE) {
					element.add(oOption);
				} else {
					element.add(oOption,null);
				}
				oOption.selected = (itemNode.getAttribute('selected') == 'true') ? true:false;
				hasSelectedValues = (itemNode.getAttribute('selected') == 'true') ? true:hasSelectedValues;
			}
		}
	}
	return hasSelectedValues;
}
/*populate Radio Button values*/
function populateRadioButton (id,XMLobject) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	var hasSelectedValues = false;
	var selected = XMLobject.getAttribute('selected').toLowerCase();
	var isSelected = "";
	var disabled = (XMLobject.getAttribute('disabled') == "true") ? ' disabled="disabled"':'';
	if (XMLobject.childNodes.length >= 1) {
		element = getE(id);
		element.innerHTML = "";
		for (n = 0; n < XMLobject.childNodes.length; n++) {
			itemNode = XMLobject.childNodes[n];
			if (typeof itemNode.tagName != "undefined") {
				if (itemNode.tagName != 'item' || itemNode.childNodes.length == 0) {
					raiseError("Malformed element ID : " + id);
					return false;
				}
				var value = (itemNode.getAttribute('value')) ? itemNode.getAttribute('value') : itemNode.firstChild.nodeValue;
				isSelected = (value.toLowerCase() == selected) ? ' checked="checked"' : '';
				hasSelectedValues = (isSelected) ? true:hasSelectedValues;
				element.innerHTML +='<label for="' + id + value + '"><input type="radio" name="' + id + '" id="' + id + value + '" value="' + value + '"' + isSelected + disabled + ' />' + itemNode.firstChild.nodeValue + '</label>';
			}
		}
	}
	return hasSelectedValues;
}
/*get the entered text box value*/
function getTextBoxValue(id) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	element = getE(id);
	return element.value;
}
/*get the selected list box value*/
function getListBoxValue(id) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	element = getE(id);
	if (element.value != 0) {
		return element.options[element.selectedIndex].text;
	}
	return false;
}
function getMultiListBoxValues(id) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	element = getE(id);
	var values = new Array();
	for (n = 0; n < element.options.length; n++) {
		if (element.options[n].selected == true) {
			values[(values.length)] = element.options[n].text;
		}
	}
	return values;
}
/*get the selected list box value*/
function getRadioButtonValue(name) {
	if (!document.getElementsByName(name).length) {
		pr("Unknown element name in document : " + name);
		return false;
	}
	var selectedElement;
	elements = document.getElementsByName(name);
	for (n = 0; n < elements.length; n++) {
		selectedElement = (elements[n].checked == true) ? elements[n]:selectedElement;
	}
	if (typeof selectedElement != 'undefined') {
		if (selectedElement.checked == true) {
			return selectedElement.nextSibling.nodeValue;
		}
	}
	return false;
}
/* disable a given field*/
function disableField(id) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	getE(id).disabled = true;
	getE(id).className = "disabled";
	return true;
}
/* enable a given field*/
function enableField(id) {
	if (!getE(id)) {
		pr("Unknown element ID in document : " + id);
		return false;
	}
	getE(id).disabled = false;
	getE(id).className = "enabled";
	return true;
}
/**********************************************
* MENU FUNCTIONS                              *
**********************************************/
/*treat menu*/
function loadMenu (params) {
	if (params.getElementsByTagName('menu').length > 0) {
		menuObjects = params.getElementsByTagName('menu').item(0);
		var menuContent = '';
		var menuLevel = 0;
		var n,m;
		for (m = 0; m < menuObjects.childNodes.length; m++) {
			if (menuObjects.childNodes[m].tagName == 'menugroup') {
				for (n = 0; n < menuObjects.childNodes[m].childNodes.length; n++) {
					if (menuObjects.childNodes[m].childNodes[n].tagName == 'menuitem') {
						menuContent += '<div>' + drawItemContent(menuObjects.childNodes[m].childNodes[n],menuLevel,true) + '</div>';
					}
				}
			}
		}
		getE('menu').innerHTML = menuContent;
	}
	//raiseError(menuContent);
	return true;
}
//	top: 17px;
//	right: 195px;

/*draw menu item content, recursive function*/
function drawItemContent (object,level,firstItem) {
	var n,m;
	var menuContent = '';
	var itemLabel = '';
	var itemAlt = '';
	var itemAction = '';
	var itemClass = '';
	var itemAClass = '';
	var itemClassArray = new Array();
	var itemAClassArray = new Array();
	var count = 0;
	for (n = 0; n < object.childNodes.length; n++) {
		if (object.childNodes[n].tagName == 'label') {
			itemLabel = object.childNodes[n].firstChild.nodeValue;
		} else if (object.childNodes[n].tagName == 'menugroup') {
			count = 0;
			for (m = 0; m < object.childNodes[n].childNodes.length; m++) {
				if (object.childNodes[n].childNodes[m].tagName == 'menuitem') {
					menuContent += drawItemContent(object.childNodes[n].childNodes[m],(level+1),(count == 0) ? true:false);
					count++;
				}
			}
			if (level == 0) {
				menuContent = '<br /><ul class="first">' + menuContent + '</ul>';
			} else {
				menuContent = '<ul class="second">' + menuContent + '</ul>';
			}
			itemAClassArray[itemAClassArray.length] = 'sub';
		} else if (object.childNodes[n].tagName == 'alt') {
			itemAlt = object.childNodes[n].firstChild.nodeValue;
		}
	}
	if (level != 0) {
		if (object.getAttribute('enabled') == 'false') {
			itemClassArray[itemClassArray.length] = 'off';
		}
		if (object.getAttribute('newsubgroup') == 'true' && firstItem == false) {
			itemClassArray[itemClassArray.length] = 'group';
		}
		if (firstItem == true) {
			itemClassArray[itemClassArray.length] = 'first';
		}
		if (object.getAttribute('command') != null && object.getAttribute('enabled') == 'true') {
			var itemActionParams = (object.getAttribute('commandparams') != null) ? "'" + object.getAttribute('commandparams') + "'":'';
			itemAction = ' onclick="javascript:' + object.getAttribute('command') + '('+itemActionParams+');return false;"';
		}
		if (itemClassArray.length) {
			itemClass = ' class="' + itemClassArray.join(" ") + '"';
		}
		if (itemAClassArray.length) {
			itemAClass = ' class="' + itemAClassArray.join(" ") + '"';
		}
		menuContent ='<li' + itemClass + '><a' + itemAction + ' href="#"' + itemAClass + ' title="' + itemAlt + '">' + itemLabel + '</a>' + menuContent + '</li>';
	} else {
		menuContent = itemLabel + menuContent;
	}
	return menuContent;
}
/*add some events on menu for IE compatibility only*/
function startMenu() {
	if (isIE) {
		liMenu = getE("menu").getElementsByTagName('li');
		divMenu = getE("menu").getElementsByTagName('div');
		for (var i=0; i<liMenu.length; i++) {
		  	li = liMenu[i];
		  	if (li.nodeName=="LI") {
		  		li.onmouseenter=function() {
		  			this.className += " over";
		    	}
		  		li.onmouseleave=function() {
		  			this.className = this.className.replace(" over", "");
				}
			}
		}
		for (var i=0; i<divMenu.length; i++) {
		  	div = divMenu[i];
		  	if (div.nodeName=="DIV") {
		  		div.onmouseenter=function() {
		  			show(getE('IPU'));
					this.className += " over";
		    	}
		  		div.onmouseleave=function() {
		  			this.className = this.className.replace(" over", "");
					hide(getE('IPU'));
				}
			}
		}
	}
}
/*view page in fullscreen mode*/
function menuFullscreen() {
	if (typeof getVar('currentTab') == 'undefined') {
		return false;
	}
	pr('=> Map in full screen');
	//set preference if needed
	if (userPreference['mapinnewwindow'] != "false") {
		setUserPreference('mapinnewwindow', "false");
	}
	//close window if already exist
	if (popupReference) {
		if (!popupReference.closed) {
			popupReference.close();
		}
	}
	//create master window flash
	writeFlash();
	//then show flash zone
	showFlashZone();
	//set popup mode
	popupMode = false;
	return true;
}
/*view page with map in new window mode*/
function menuMapnewwindows(width) {
	if (typeof getVar('currentTab') == 'undefined') {
		return false;
	}
	//if popup already opened, then exit
	if (popupReference) {
		if (!popupReference.closed) {
			userMessage(getVar('applicationMessages[\'popuperror\']','frame'),true);
			return false;
		}
	}
	pr('=> Map in new window');
	//hide flash zone
	hideFlashZone();
	//and open window
	var pageURL = mapPopUp;
	pageURL += (pageURL.indexOf('?') != -1) ? '&' : '?';
	pageURL += 'size=' + width;
	//set preference if needed
	if (userPreference['mapinnewwindow'] == "false") {
		setUserPreference('mapinnewwindow', width);
	}
	width = parseInt(width);
	switch(width) {
		case 742 :
			var height = 770;
		break;
		case 842 :
			var height = 870;
		break;
		case 942 :
			var height = 970;
		break;
	}
	popupReference = openWindow(pageURL, 'Map', width, height, 'yes', 'no', 'no', 50, 50);
	//set popup mode
	popupMode = true;
	//add event to close window on unload
	addEvent(window, 'unload', function()
	{
		if (popupReference) {
			if (!popupReference.closed) {
				popupReference.close();
			}
		}
		return true;
	});
	return true;
}
/*send results by email*/
function menuEmail() {
	if (getVar('userPreference[\'authenticateduser\']','frame') == 'false') {
		//check for user autentification
		return menuLogin('action=sendEmail,from=' + getVar('currentTab','frame'));
	}
	//check if results are selected
	if (getVar('checkForExports','frame')() && confirm(getVar('applicationMessages[\'sendbyemail\']','frame'))) {
		//send flash context
		setUserPreference('flashcontext', getVar('userPreference[\'flashcontext\']', 'frame'));
		//send send email request
		var urlParameters = new Array();
		var url = createURL(xmlEmailPage,urlParameters);
		getXMLFile(url, null);
	}
	return true;
}
/*print results*/
function menuPrint() {
	if (getVar('checkForPrint','frame')()) {
		//send flash context
		setUserPreference('flashcontext', getVar('userPreference[\'flashcontext\']', 'frame'));
		var pageURL = printPage;
		pageURL += (pageURL.indexOf('?') != -1) ? '&action=print' : '?action=print';
		if (arguments.length) {
			pageURL += '&' + arguments[0].replace(',','&');
		}
		openWindow(pageURL, 'print', 700, 600, 'yes', 'yes', 'yes',50, 50);
	}
	return true;
}
/*export to SCIE format*/
function menuExportSCIE() {
	if (getVar('userPreference[\'authenticateduser\']','frame') == 'false') {
		//check for user autentification
		return menuLogin('action=exportSCIE,from=' + getVar('currentTab','frame'));
	}
	if (getVar('checkForSCIE','frame')()) {
		//send flash context
		setUserPreference('flashcontext', getVar('userPreference[\'flashcontext\']', 'frame'));
		var pageURL = printPage;
		pageURL += (pageURL.indexOf('?') != -1) ? '&action=exportSCIE' : '?action=exportSCIE';
		if (arguments.length) {
		    pageURL += '&' + arguments[0].replace(',','&');
		}
		openWindow(pageURL, 'export', 700, 600, 'yes', 'yes', 'yes',50, 50);
	}
	return true;
}
/*export to RTF format*/
function menuExport() {
	if (getVar('userPreference[\'authenticateduser\']','frame') == 'false') {
		//check for user autentification
		return menuLogin('action=exportRTF,from=' + getVar('currentTab','frame'));
	}
	if (getVar('checkForExports','frame')()) {
		//send flash context
		setUserPreference('flashcontext', getVar('userPreference[\'flashcontext\']', 'frame'));
		var pageURL = printPage;
		pageURL += (pageURL.indexOf('?') != -1) ? '&action=exportRTF' : '?action=exportRTF';
		if (arguments.length) {
		    pageURL += '&' + arguments[0].replace(',','&');
		}
		openWindow(pageURL, 'export', 700, 600, 'yes', 'yes', 'yes',50, 50);
	}
	return true;
}
/*export to Shape format*/
function menuExportSHAPE() {
	if (getVar('userPreference[\'authenticateduser\']','frame') == 'false') {
		//check for user autentification
		return menuLogin('action=exportSHAPE,from=' + getVar('currentTab','frame'));
	}
	if (getVar('checkForExports','frame')()) {
		//send flash context
		setUserPreference('flashcontext', getVar('userPreference[\'flashcontext\']', 'frame'));
		var pageURL = printPage;
		pageURL += (pageURL.indexOf('?') != -1) ? '&action=exportSHAPE' : '?action=exportSHAPE';
		if (arguments.length) {
		    pageURL += '&' + arguments[0].replace(',','&');
		}
		openWindow(pageURL, 'export', 700, 600, 'yes', 'yes', 'yes',50, 50);
	}
	return true;
}
/*export to MIDMIF format*/
function menuExportMIDMIF() {
	if (getVar('userPreference[\'authenticateduser\']','frame') == 'false') {
		//check for user autentification
		return menuLogin('action=exportMIDMIF,from=' + getVar('currentTab','frame'));
	}
	if (getVar('checkForExports','frame')()) {
		//send flash context
		setUserPreference('flashcontext', getVar('userPreference[\'flashcontext\']', 'frame'));
		var pageURL = printPage;
		pageURL += (pageURL.indexOf('?') != -1) ? '&action=exportMIDMIF' : '?action=exportMIDMIF';
		if (arguments.length) {
		    pageURL += '&' + arguments[0].replace(',','&');
		}
		openWindow(pageURL, 'export', 700, 600, 'yes', 'yes', 'yes',50, 50);
	}
	return true;
}
/*export to KML format*/
function menuExportKML() {
	if (getVar('userPreference[\'authenticateduser\']','frame') == 'false') {
		//check for user autentification
		return menuLogin('action=exportKML,from=' + getVar('currentTab','frame'));
	}
	if (getVar('checkForExports','frame')()) {
		//send flash context
		setUserPreference('flashcontext', getVar('userPreference[\'flashcontext\']', 'frame'));
		var pageURL = printPage;
		pageURL += (pageURL.indexOf('?') != -1) ? '&action=exportKML' : '?action=exportKML';
		if (arguments.length) {
		    pageURL += '&' + arguments[0].replace(',','&');
		}
		openWindow(pageURL, 'export', 700, 600, 'yes', 'yes', 'yes',50, 50);
	}
	return true;
}
/*new save*/
function menuNew () {
	var pageURL = savePage;
	pageURL += (pageURL.indexOf('?') != -1) ? '&saveaction=new' : '?saveaction=new';
	if (arguments.length) {
		pageURL += '&' + arguments[0].replace(',','&');
	}
	//reset flash context before creating new context
	if (typeof accountPage == 'undefined' || !accountPage) {
		setVar('userPreference[\'flashcontext\']', 'layers=||extent=-90|-90|90|90', 'frame');
	}
	setUserPreference('flashcontext', 'layers=||extent=-90|-90|90|90');
	return location.replace(pageURL);
}
/*open save*/
function menuOpen () {
	var pageURL = savePage;
	pageURL += (pageURL.indexOf('?') != -1) ? '&saveaction=open' : '?saveaction=open';
	if (arguments.length) {
		pageURL += '&' + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*save*/
function menuSave () {
	var pageURL = savePage;
	pageURL += (pageURL.indexOf('?') != -1) ? '&saveaction=save' : '?saveaction=save';
	if (arguments.length) {
		pageURL += '&' + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*save as*/
function menuSaveas () {
	var pageURL = savePage;
	pageURL += (pageURL.indexOf('?') != -1) ? '&saveaction=saveas' : '?saveaction=saveas';
	if (arguments.length) {
		pageURL += '&' + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*select a new language*/
function selectLanguage() {
	var newLanguage = getE('languageSelect').value;
	var currentPage = window.location.protocol + '//' + window.location.host + window.location.pathname;
	currentPage += (currentPage.indexOf('?') != -1) ? '&language=' + newLanguage : '?language=' + newLanguage;
	return location.replace(currentPage);
}
/*redirect to preference page*/
function menuPreference() {
	var pageURL = preferencePage;
	if (arguments.length) {
		pageURL += ((pageURL.indexOf('?') != -1) ? '&':'?') + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*redirect to login page*/
function menuLogin () {
	var pageURL = loginPage;
	if (arguments.length) {
		pageURL += ((pageURL.indexOf('?') != -1) ? '&':'?') + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*redirect to alerts page*/
function menuAlerts () {
	var pageURL = alertsPage;
	if (arguments.length) {
		pageURL += ((pageURL.indexOf('?') != -1) ? '&':'?') + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*redirect to context page*/
function menuContext () {
	var pageURL = contextPage;
	if (arguments.length) {
		pageURL += ((pageURL.indexOf('?') != -1) ? '&':'?') + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*redirect to alerts page*/
function menuAddresses () {
	var pageURL = addressesPage;
	if (arguments.length) {
		pageURL += ((pageURL.indexOf('?') != -1) ? '&':'?') + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
/*disconnect current user*/
function menuDisconnect () {
	var currentPage = window.location.protocol + '//' + window.location.host + window.location.pathname;
	currentPage += (currentPage.indexOf('?') != -1) ? '&logout=true' : '?logout=true';
	if (arguments.length) {
		currentPage += '&' + arguments[0].replace(',','&');
	}
	//reset flash context before creating new context
	if (typeof accountPage == 'undefined' || !accountPage) {
		setVar('userPreference[\'flashcontext\']', 'layers=||extent=-90|-90|90|90', 'frame');
	}
	setUserPreference('flashcontext', 'layers=||extent=-90|-90|90|90');
	return location.replace(currentPage);
}

// DM 21455 29/04/2008 ajout du lien menu -> PageDownload.aspx
/* redirect to download page */
function menuDownload () {
   var pageURL = downloadPage;
   if (arguments.length) {
		pageURL += ((pageURL.indexOf('?') != -1) ? '&':'?') + arguments[0].replace(',','&');
	}
	return location.replace(pageURL);
}
// FIN DM21455

/*display and activate window tabs*/
function windowTabs() {
	//add a link on available tabs and which not the current one
	if (userPreference['searchTab'] == '1' && getVar('currentTab') != 'search') {
		getE('searchTab').innerHTML = '<a href="#" onclick="javascript:void(gotoSearch());" title="' + applicationMessages['searchTab'] + '">' + applicationMessages['searchTab'] + '</a>';
	} else {
		getE('searchTab').innerHTML = applicationMessages['searchTab'];
	}
	if (userPreference['resultTab'] == '1' && getVar('currentTab') != 'result') {
		getE('resultTab').innerHTML = '<a href="#" onclick="javascript:void(gotoResults());" title="' + applicationMessages['resultTab'] + '">' + applicationMessages['resultTab'] + '</a>';
	} else {
		getE('resultTab').innerHTML = applicationMessages['resultTab'];
	}
	if (userPreference['orderTab'] == '1' && getVar('currentTab') != 'order') {
		getE('orderTab').innerHTML = '<a href="#" onclick="javascript:void(gotoOrder());" title="' + applicationMessages['orderTab'] + '">' + applicationMessages['orderTab'] + '</a>';
	} else {
		getE('orderTab').innerHTML = applicationMessages['orderTab'];
	}
	getE('searchTab').className="";
	getE('resultTab').className="";
	getE('orderTab').className="";
	//set 'on' on current tab 
	if (getVar('currentTab') == 'search') {
		getE('searchTab').className="on";
	} else if (getVar('currentTab') == 'result') {
		getE('resultTab').className="on";
	} else if (getVar('currentTab') == 'order') {
		getE('orderTab').className="on";
	}
}
/*go to search page*/
function gotoSearch() {
	getE('innerframe').src = searchTabpage;
}
/*go to results page*/
function gotoResults() {
	getE('innerframe').src = resultsTabpage;
}
/*go to order page*/
function gotoOrder() {
	getE('innerframe').src = orderTabpage;
}
/**********************************************
* FLASH FUNCTIONS                             *
**********************************************/
/*write flash animation in div element*/
function writeFlash() {
	//if flash already exists, send context but skip flash creation
	if (getE('flashCarto')) {
		return false;
	}
	pr('=> Write Flash');
	//in popup
	if (windowType == 'popup') {
		//get flash size if any
		if (window.location.search.toLowerCase().indexOf('size=') != -1) {
			flashWidth = parseInt(window.location.search.substr((window.location.search.toLowerCase().indexOf('size=')+5),3));
			switch(flashWidth) {
				case 742 :
					flashHeight = 770;
				break;
				case 842 :
					flashHeight = 870;
				break;
				case 942 :
					flashHeight = 970;
				break;
				default:
					flashWidth = 742;
					flashHeight = 770;
				break;
			}
			pr(flashWidth + " / " + flashHeight);
			flashFile = 'swf/carte_' + flashWidth + '.swf';
		}
		// Inserting flash
		writeFlashObject('carto', 'flashCarto', flashFile, flashWidth, flashHeight);
	} else {
		if (userPreference['mapinnewwindow'] == "false") {
			// Inserting flash
			writeFlashObject('carto', 'flashCarto', flashFile, flashWidth, flashHeight);
		} else {
			menuMapnewwindows(userPreference['mapinnewwindow']);
		}
	}
	return true;
}
/*Insert flash object in a given tag id*/
function writeFlashObject(id, flashID, flashFile, flashWidth, flashHeight) {
	var flashTag = new String();
	if (isIE) { 
		flashTag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '; // onmouseover="this.focus();"
		flashTag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ';
		flashTag += 'id="'+flashID+'" ';
		flashTag += 'width="'+flashWidth+'" ';
		flashTag += 'height="'+flashHeight+'">';
		flashTag += '<param name="movie" value="'+flashFile+'"/>';
		flashTag += '<param name="quality" value="high"/>';
		flashTag += '<param name="bgcolor" value="#ffffff"/>';
		flashTag += '<param name="wmode" value="transparent" />';
		flashTag += '<param name="allowScriptAccess" value="always" />';
		flashTag += '</object>';
	} else {
		flashTag += '<embed src="'+flashFile+'" '; // onmouseover="this.focus();"
		flashTag += 'id="'+flashID+'" ';
		flashTag += 'quality="high" '; 
		flashTag += 'bgcolor="#ffffff" ';
		flashTag += 'width="'+flashWidth+'" ';
		flashTag += 'height="'+flashHeight+'" ';
		flashTag += 'wmode="transparent" ';
		flashTag += 'allowScriptAccess="always" ';
		flashTag += 'type="application/x-shockwave-flash" ';
		flashTag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
		flashTag += '</embed>';
	}
	if (getE(id)) {
		getE(id).innerHTML = flashTag;
	} else {
		pr('writeFlashObject : can\'t found element '+id+' to write flash in');
	}
	return true;
}
/*add a onUnload event to recreate a popup in master window if popup is closed*/
function onClosePopup() {
	addEvent(window, 'unload', function()
	{
		if (window.opener.menuFullscreen && (typeof window.opener.menuFullscreen == 'function' || typeof window.opener.menuFullscreen == 'object')) {
			if (getE('flashCarto')) {
				//destroy master window flash
				getE('carto').innerHTML = '';
			}
			window.opener.menuFullscreen();
			return true;
		}
	});
}
/*hide all flash zone*/
function hideFlashZone() {
	//hide flash zone
	hide("carto");
	//then destroy master window flash
	getE('carto').innerHTML = '';
	//set others window visual vars
	getE("frameborder").className="fullscreen";
	getE("innerframe").className="fullscreen";
	getE("userMessage").className += " fullscreen";
	//only for search tab
	if (getVar('currentTab', 'frame') == 'search') {
		getE('mapCoordinateTypeRectangleFields').className="fullscreen";
		getE('mapCoordinateTypePolygonFields').className="fullscreen";
		getE('mapCoordinateTypeCircleFields').className="fullscreen";
		getE('productstable').className="fullscreen";
	}
	return true;
}
/*show flash zone*/
function showFlashZone() {
	//show flash zone
	show("carto");
	//set others window visual vars
	getE("frameborder").className="";
	getE("innerframe").className="";
	getE("userMessage").className="hide";
	//only for search tab
	if (getVar('currentTab', 'frame') == 'search') {
		getE('mapCoordinateTypeRectangleFields').className="";
		getE('mapCoordinateTypePolygonFields').className="";
		getE('mapCoordinateTypeCircleFields').className="";
		getE('productstable').className="";
	}
	return true;
}
/**********************************************
* FROM FLASH FUNCTIONS                        *
**********************************************/
/*flash loading is complete*/
function FHLoadComplete() {
	pr('=> Flash is loaded');
	flashLoaded = true;
	if (windowType == 'popup') {
		if (typeof window.opener.currentTab != 'undefined') {
			//send all selected coordinates to Flash
			if (window.opener.currentTab != 'search') {
				window.opener.sendCoordinatesToFlash();
			}
		} else {
			pr('FHLoadComplete : unknown context.');
		}
	} else {
		if (typeof getVar('currentTab') != 'undefined') {
			//send all selected coordinates to Flash
			if (getVar('currentTab') != 'search') {
				flashCall('sendCoordinatesToFlash');
			}
		} else {
			pr('FHLoadComplete : unknown context.');
		}
	}
	return true;
}
/*serialize all application messages then send it to flash*/
function FHGetapplicationMessages() {
	pr('=> Flash query application Messages');
	var serializedMessages = '';
	for (label in getVar('applicationMessages')) {
		serializedMessages += label + '=' + getVar('applicationMessages')[label] + '||';
	}
	return serializedMessages;
}
/*serialize all datas related messages then send it to flash*/
function FHGetDataMessages() {
	pr('=> Flash query datas Messages');
	var datas = getVar('datasToFlash','frame');
	if (typeof datas == 'undefined' || !datas.length) {
		return '';
	}
	var serializedMessages = '';
	//applicationMessages[columnName+'Label'] = label;
	//applicationMessages[columnName+'TextText'] = labelText;
	for (var i = 0; i < datas.length; i++) {
		serializedMessages += datas[i] + '=' + getVar('applicationMessages')[datas[i] + 'Label'] + '||';
	}
	return serializedMessages;
}
/*receive flash context*/
function FHSetContext(contextArray) {
	pr('=> Flash set new context : '+contextArray);
	//setVar('userPreference[\'flashcontext\']', contextArray[0]+'||'+contextArray[1], 'frame');
	setVar('userPreference[\'flashcontext\']', contextArray.join('||'), 'frame');
	return true;
}
function HFSetContext() {
	pr('=> Send context to flash');
	var regSplit = new RegExp("[|]{2}");
	var flashContext = (! getVar('userPreference[\'flashcontext\']', 'frame')) ? defaultFlashContext : getVar('userPreference[\'flashcontext\']', 'frame');
	var wktContext = (getE('fieldCoordinate') && getE('fieldCoordinate').value) ? getE('fieldCoordinate').value : getVar('userPreference[\'zig\']', 'frame');
	var tabname;
	//get current tabname
	tabname = getVar('currentTab'); 
	//add onglet & zig to context
	//flashContext = 'onglet=' + tabname+'||' + flashContext/* + '||zig=' + wktContext;*/
	flashContext = 'onglet=' + tabname+'||' + flashContext;
	if( flashContext.indexOf('zig=') == -1 ) {
		flashContext = flashContext + '||zig=' + wktContext;
	}
	return getE('flashCarto').i_HFSetContext(serializeArray(flashContext.split(regSplit)));
}
/*send context to flash*/
function FHGetContext() {
	pr('=> Flash query context');
	var regSplit = new RegExp("[|]{2}");
	var flashContext = (! getVar('userPreference[\'flashcontext\']', 'frame')) ? defaultFlashContext : getVar('userPreference[\'flashcontext\']', 'frame');
	var wktContext = (getE('fieldCoordinate') && getE('fieldCoordinate').value) ? getE('fieldCoordinate').value : getVar('userPreference[\'zig\']', 'frame');
	var tabname;
	//get current tabname
	tabname = getVar('currentTab'); 
	//add onglet & zig to context
//alert('wkt'+ wktContext);
	//flashContext = 'onglet=' + tabname+'||' + flashContext/* + '||zig=' + wktContext;*/
	
	flashContext = 'onglet=' + tabname+'||' + flashContext;
	// si la zig n'a pas ete vide du contexte precedent on l enleve
	if (flashContext.indexOf('zig=') != -1)
	{
	    var posZig = flashContext.indexOf('zig=');
	    var firstZig = flashContext.substring(posZig,flashContext.indexOf("||",posZig));
	    var flashContext1 = flashContext.substring(0,posZig) ;
	    var flashContext2 = flashContext.substring(firstZig.length,flashContext.length);
	    flashContext = flashContext1 + flashContext2 ;

	}

	if( flashContext.indexOf('zig=') == -1 ) {
		flashContext = flashContext + '||zig=' + wktContext;
	}
	pr('CHARGEMENT flashContext' + flashContext); 
	return serializeArray(flashContext.split(regSplit));
}
/*get Flash logs*/
function FHAddToLog(logValue) {
	
	if (Debug == 4) {
		pr("=> Flash log : "+logValue);
	}
	return true;
}
/*get coordinates mode*/
function FHGetCoordinatesMode() {
	pr('=> Flash query coordinates format');
	return getVar('userPreference[\'coordinatesformat\']');
}
/* get function (cross frames method)*/
function flashCall (functionName) {
	if (Debug == 4 && functionName != 'FHAddToLog') {
		pr('=> Flash call ' + functionName + ' from '+windowType);
	}
	var argumentString = '';
	var  returnValue = '';
	if (typeof arguments[1] != 'undefined' && arguments[1] != null) {
		for (var i=0; i < arguments[1].length; i++) {
			argumentString += (i==0) ? 'arguments[1][' + i + ']' : ',arguments[1][' + i + ']';
		}
	}
	//call from popup
	if (windowType == 'popup') {
		//in window
		if (eval('typeof window.opener.' + functionName + ' == \'function\' || typeof window.opener.' + functionName + ' == \'object\'')) {
			eval('returnValue =  window.opener.' + functionName + '(' + argumentString + ')');
		} else 
		//in frame
		if (eval('typeof window.opener.document.getElementById(\'innerframe\').contentWindow.' + functionName + ' == \'function\' || typeof window.opener.document.getElementById(\'innerframe\').contentWindow.' + functionName + ' == \'object\'')) {
			eval('returnValue =  window.opener.document.getElementById(\'innerframe\').contentWindow.' + functionName + '(' + argumentString + ')');
		} else {
			pr('flashCall : unknown function ' + functionName);
		}
	} else
	//call in same document
	if (eval('typeof ' + functionName + ' == \'function\'')) {
		eval('returnValue =  ' + functionName + '(' + argumentString + ')');
	} else 
	//call in frame
	if (eval('typeof document.getElementById(\'innerframe\').contentWindow.' + functionName + ' == \'function\'')) {
		eval('returnValue =  document.getElementById(\'innerframe\').contentWindow.' + functionName + '(' + argumentString + ')');
	} else {
		pr('flashCall : unknown function ' + functionName);
	}
	if (Debug == 4 && functionName != 'FHGetapplicationMessages' && functionName != 'FHAddToLog') {
		var debugstring = '<= ' + functionName + ' return ' + returnValue + ' (type : '+typeof returnValue;
		if (typeof returnValue == 'object') {
			debugstring += ' using constructor : '+returnValue.constructor+')';
		} else {
			debugstring += ')';
		}
		pr(debugstring);
	}

	return returnValue;
}
