/**
 * TOOLS
 */
function get_form_element(form_name, element_name) {
	return document.forms[form_name].elements[element_name];
}
function get_form_element_from(p_opener, p_formName, p_elementName) {
	return p_opener.document.forms[p_formName].elements[p_elementName];
}


function get_element(id) {
	if (document.getElementById) { return document.getElementById(id); }
	else if (document.all) { return document.all(id); }
	else if (document.layers) { return document.layers[id]; }
	else { return false; }
}
function get_element_from_opener(opener, id) {
	if (document.getElementById) { return opener.document.getElementById(id); }
	else if (document.all) { return opener.document.all(id); } 
	else if (document.layers) { return opener.document.layers[id]; }
	else { return false; }
}
function get_elements_by_tag_name(p_sName) {
	if (document.getElementsByTagName) { return document.getElementsByTagName(p_sName); }
	else { return false; }
}
function get_elements_by_tag_name_from(p_oFrom, p_sName) {
	if (p_oFrom.getElementsByTagName) { return p_oFrom.getElementsByTagName(p_sName); }
	else { return false; }
}

function set_dispatch_and_submit_form(dispatch_value,form_name,opener) {
	set_element_and_submit_form('dispatch',dispatch_value,form_name,opener);
}

function set_dispatch_with_element_and_submit_form(element_name,form_name,opener) {
	var oDoc;
	var oForm;
	if (opener) { oDoc = opener.document;} else { oDoc = document; }
	if (form_name) { oForm = oDoc.forms[form_name]; } else { oForm = oDoc.forms[0];}
	oForm.elements['dispatch'].value=oForm.elements[element_name].value;
	oForm.submit();
}

/* hides <select> and <applet> objects (for IE only) */
function hideElement( elmID, overDiv ) {
    var elms = get_elements_by_tag_name(elmID);
    if (!elms) {
        return false;
    }
    
    for( i = 0; i < elms.length; i++ ) {
      obj = elms.item(i);
      if( !obj || !obj.offsetParent ) {
        continue;
      }
    
      // Find the element's offsetTop and offsetLeft relative to the BODY tag.
      objLeft   = obj.offsetLeft;
      objTop    = obj.offsetTop;
      objParent = obj.offsetParent;
    
      while( objParent.tagName.toUpperCase() != "BODY" ) {
        objLeft  += objParent.offsetLeft;
        objTop   += objParent.offsetTop;
        objParent = objParent.offsetParent;
      }
    
      objHeight = obj.offsetHeight;
      objWidth = obj.offsetWidth;
    
      if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
      else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
      else if( overDiv.offsetTop >= ( objTop + objHeight ));
      else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
      else {
        obj.style.visibility = "hidden";
      }
    }
}

/*
* unhides <select> and <applet> objects (for IE only)
*/
function showElement( elmID ) {
    var elms = get_elements_by_tag_name(elmID);
    if (!elms) {
        return false;
    }

    for( i = 0; i < elms.length; i++ ) {
      obj = elms.item(i);

      if( !obj || !obj.offsetParent ) {
        continue;
      }

      obj.style.visibility = "";
    }
}

// mets à jour un element du document de la fenetre courante (ou de son opener si renseigné en dernier parametre
// subit de la form
function set_element_and_submit_form(element_name,element_value,form_name,opener) {
	var oDoc;
	var oForm;
	if (opener) { oDoc = opener.document;} else { oDoc = document; }
	if (form_name) { oForm = oDoc.forms[form_name]; } else { oForm = oDoc.forms[0];}
	oForm.elements[element_name].value=element_value;
	oForm.submit();
}

// mets à jour un element du document de la fenetre courante (ou de son opener si renseigné en dernier parametre
// puis met a jour le dispatch de ce meme document
// subit de la form
function set_element_and_submit_with(element_name,element_value,dispatch_value,form_name,opener) {
	var oDoc;
	var oForm;
	if (opener) { oDoc = opener.document;} else { oDoc = document; }
	if (form_name) { oForm = oDoc.forms[form_name]; } else { oForm = oDoc.forms[0];}
	oForm.elements[element_name].value=element_value;
	oForm.elements['dispatch'].value=dispatch_value;
	oForm.submit();
    if (opener) { opener.focus(); }
}


/**
 * ERROR
 */
function onSessionTimeout() {
    // url
    var href = window.location.href;

    // fenêtre principale
    var firstOpener = returnFirstOpener(window);
    var parentFrame = firstOpener.parent;

    if (firstOpener == window && parentFrame == window) {
        return true;
    }

    // vérifie l'existance de frames
    if (parentFrame) {
        firstOpener.parent.location.href = href;
    }
    else {
        firstOpener.location.href = href;
    }
}

function returnFirstOpener(p_window) {
    if (p_window.opener) {
        p_window.close();
        p_window.opener.focus();
        return returnFirstOpener(p_window.opener);
    }
    else {
        return p_window;
    }
}


// appellée sur le onSubmit de la page d'erreur
// vérifie que l'utilisateur ne se trouve pas sur une popup -> fermeture popup
function checkWindow(p_oForm) { if (window.opener) { window.opener.parent.location.href = p_oForm.action; window.close(); window.opener.focus(); } return true; }

/**
 * SELCTIONNER Tous / Aucun
 */
// coche toutes les cases p_sElementName de p_sFormName
function selectAll(p_sElementName, p_sFormName) { checked(true, p_sElementName, p_sFormName); }
// décoche toutes les cases p_sElementName de p_sFormName
function unselectAll(p_sElementName, p_sFormName) { checked(false, p_sElementName, p_sFormName); }
function checked(value, p_sElementName, p_sFormName) { var form = document.forms[p_sFormName]; for (var i=0; i<form.length; i++) {	var element = form.elements[i]; if (element.name==p_sElementName && element.type=="checkbox") { element.checked = value; } } }



/**
 * MENU
 */
function menuOnClick(p_oElement) {
	var aLink = get_elements_by_tag_name("a");
	if (!aLink) { return false; }
	for (var i=0; i<aLink.length; i++) { if (aLink[i].className == "treeView2") { aLink[i].style.color = ""; } }
	p_oElement.style.color = "red";
}


/**
 * FRAME REFRESH
 */
function windowLocation(p_sUrl) { parent.location.href = p_sUrl; }

function topRefresh() { parent.frames[0].location.href = "top.do?dispatch=load"; }

function openHomol() { parent.frames[0].location.reload(); parent.frames[1].location.reload(); }
function openPhase() { parent.frames[0].location.reload(); }
function ReloadTop() { parent.frames[0].location.reload(); }
function ReloadMenu() { parent.frames[1].location.reload(); }

function afterSave() { 
	window.close();
	var previousHref = "";
	if (afterSave.arguments[0]) 
	{
		previousHref = arguments[0];
	}
	else 
	{
		previousHref = window.opener.location.href;
		if (previousHref.indexOf("dispatch")==-1) {
			previousHref += "?dispatch=load";
		}
	}
	// si la page précédente a été affichée après un 'POST' le paramètre dispatch n'existe pas
	window.opener.location.href = previousHref;
	window.opener.focus(); 
}

/*******************************************
	TOOLS POUR LES LISTES (collectionItems)
*******************************************/

// synchronise le checkbox gauche (num=1) ou droite (num=2) avec la valeur de l'objet checkbox passé en parametre
function updateCheckboxFromDiv(num,checkboxObj) {
	get_element('selectDiv'+num+'_'+checkboxObj.value).getElementsByTagName('input')[0].checked=checkboxObj.checked;
}

/**
 * affichage des info descriptives correspondant a l'action sélectionnée
 * pour actions accompagnées d'une table avec des tr ayant pour id chaque nom d'action de la liste d'actions.
 */
function updateDesc(p_oElement, p_sForm) {

	var dispatch = p_oElement.value;
	var table = get_element("action");
	var trs = get_elements_by_tag_name_from(table, "tr");
	if (!trs) { return false; }
	for (var i=0; i<trs.length; i++) {
		var tr = trs[i];
		if (tr.id == dispatch) { tr.style.display = ""; }
		else if (tr.id) { tr.style.display = "none"; }
	}
}


/**
 * POPUP
 */
// ouvre une modal
function openPopup(p_sUrl, p_sWidth, p_sHeight, p_iLevel) {
	var x = (screen.availWidth - p_sWidth) / 2;
	var y = (screen.availHeight - p_sHeight) / 2;
	var popup = window.open("blank.html", 'popup'+p_iLevel, 'scrollbars=1, directories=0, location=0, menubar=0, status=1, toolbar=0, resizable=1, width=' + p_sWidth + ', height=' + p_sHeight + ', top=' + y + ', left=' + x); 	
    popup.document.location.href = p_sUrl;
	popup.scrollbars = true;
	popup.focus();
}

function closePopup() {
    window.close();
    if (window.opener) {
        window.opener.focus();
    }
}

function maxWidth(minWidth) {
	var screenWidth = screen.width;
	if (screenWidth<minWidth) {
		return screenWidth-20;
	}
	else {
		return minWidth;
	}
}


/**
 * Affiche et masque les infos bulles
 */
function showDiv(div,element,dx,dy){
	var objCommun = get_element("divInfoBulleCommun");
	if (!objCommun) {
		//var objCommun = document.createElement("div");
		alert("not exists");
	}
	
	var obj = get_element(div);
	objCommun.innerHTML = obj.innerHTML;
	
	/*if (obj.offsetParent != "BODY") {	
		var body = get_elements_by_tag_name("BODY").item(0);
		var copy = obj;		
		body.appendChild(obj);
	}*/
	
	if (element) {
        var x=0;
	    var y=-30;
	    if (dx){x+=dx;};
	    if (dy){y+=dy;};

	    move(objCommun, element, x, y);
	}

	objCommun.style.visibility = "visible";
   hideElement("select", objCommun);
}

function hideDiv(div){
	var obj = get_element(div);
	obj.style.visibility = "hidden";
   showElement("select");
   //alert(obj);
}

function showInfoBulle(){
	var objCommun = get_element("divInfoBulleCommun");
	objCommun.style.visibility = "visible";
   hideElement("select", objCommun);
}

function hideInfoBulle() {
	var objCommun = get_element("divInfoBulleCommun");
	objCommun.style.visibility = "hidden";
   showElement("select");
}


function move(obj_div, element, dx, dy) {
	var aTag = element;
   var leftpos	= 0;
   var toppos	= 0;
	do {
	    aTag = aTag.offsetParent;
		 leftpos	+= aTag.offsetLeft;
	    toppos += aTag.offsetTop;
	    // cas du overflow-y
	    if (aTag.tagName=="DIV" && aTag.scrollTop > 0) {
	    	toppos -= aTag.scrollTop;
	  	 }
	    
   } while(aTag.tagName!="BODY");

   var left =  element.offsetLeft + leftpos + dx;
   var top = element.offsetTop + element.offsetHeight + toppos + dy;

	obj_div.style.left = left + "px";
	obj_div.style.top = top + "px";
}

/* fonction de resize des div des collections struts */

function resizeDiv(tableId,divId,maxheigth){ 
	oTable = get_element(tableId);
	if (oTable != null) {
		h = oTable.clientHeight;
		if (h <= maxheigth )  maxheigth = h;
		get_element(divId).style.height = maxheigth; 
	}
}


/**
 * CALENDAR
 */
var calendar_handler = false;

function oCal(cal_id, form_name, element_name)
{
	this.id           = cal_id;
	this.form_name    = form_name;
	this.element_name = element_name;

	this.coordX = 0;
	this.coordY = 0;

	this.date     = new Date();
	this.nav_date = new Date();

	this.div_id        = 'cal_contener';
	this.nav_form_name = 'cal_nav';

	// action executée lors du choix d'une date
	this.action = '';

	this.months = new Array(12);
	this.months[0] = 'Janvier';
	this.months[1] = 'F&eacute;vrier';
	this.months[2] = 'Mars';
	this.months[3] = 'Avril';
	this.months[4] = 'Mai';
	this.months[5] = 'Juin';
	this.months[6] = 'Juillet';
	this.months[7] = 'Aout';
	this.months[8] = 'Septembre';
	this.months[9] = 'Octobre';
	this.months[10]= 'Novembre';
	this.months[11]= 'D&eacute;cembre';

	this.days = new Array(6);
	this.days[7] = 'D';
	this.days[1] = 'L';
	this.days[2] = 'M';
	this.days[3] = 'M';
	this.days[4] = 'J';
	this.days[5] = 'V';
	this.days[6] = 'S';

	this.init    = oCal_init;
	this.initNav = oCal_initNav;
	this.navSynchro = oCal_navSynchro;
	this.changeNavDate = oCal_changeNavDate;
	this.chooseDate    = oCal_chooseDate;
	this.buildMonth = oCal_buildMonth;
	this.build      = oCal_build;
	this.show = oCal_show;
	this.hide = oCal_hide;
	this.move = oCal_move;

}

function oCal_init()
{
	var element_date = get_form_element(this.form_name, this.element_name);
	if (!element_date)
	{
		return alert('Erreur: élement date absent du formulaire !');
	}

	var date_value = element_date.value;
	var date_split = date_value.split("/");
	if (date_split.length==3)
	{
		var day   = date_split[0];
		var month = Number(date_split[1]) - parseInt(1);
		var year  = date_split[2];
		this.date.setDate(day);
		this.date.setMonth(month);
		this.date.setYear(year);
	}
}

function oCal_navSynchro()
{
	var day   = this.date.getDate();
	var month = this.date.getMonth();
	var year  = this.date.getYear();
	if(parseInt(year)<200) year += parseInt(1900);
	this.nav_date.setDate(day);
	this.nav_date.setMonth(month);
	this.nav_date.setYear(year);
}

function oCal_initNav(day, month, year)
{
	this.nav_date.setDate(day);
	this.nav_date.setMonth(month);
	this.nav_date.setYear(year);
}

function oCal_changeNavDate(year_diff)
{
	var month = get_form_element(this.nav_form_name, 'month').value;
	var year = get_form_element(this.nav_form_name, 'year');
	year = parseInt(year.value) + parseInt(year_diff);

	this.initNav(1, month, year);
	
	this.show();	
}

function oCal_chooseDate(day, month, year)
{
	month = parseInt(month) + parseInt(1) ;

	if (day<10)
	{
		day = "0" + day;
	}

	if (month<10)
	{
		month = "0" + month;
	}

	var date_format = day + "/" + month + "/" + year;
	get_form_element(this.form_name, this.element_name).value = date_format;

	this.hide();
}

function oCal_buildMonth(current_month)
{
	var html = '';

	for(var i=0; i<12; i++)
	{
		if (i==current_month) var selected = ' selected';
		else                  var selected = '';
		html += '<option value="' + i + '"' + selected + ' class="option_month">' + this.months[i] + '</option>'
	}
	return html;
}

function oCal_build()
{
	var current_date  = this.date.getDate();
	var current_month = this.date.getMonth();
	var current_year  = this.date.getYear();
	if (parseInt(current_year)<200) current_year += parseInt(1900);

	var nav_month = this.nav_date.getMonth();
	var nav_year  = this.nav_date.getYear();
	if (parseInt(nav_year)<200) nav_year += parseInt(1900);

	var new_date   = new Date(nav_year, nav_month, 1);
	var first_day  = new_date.getDay();
	if (first_day==0) first_day=7;
	var this_date   = 1;

	var html = '';

	html += '<FORM name="' + this.nav_form_name + '"><TABLE class="calendar">';

	// navigation
	html += '<TR><TD class="calendar_head" align="center">';
	html += '<TABLE><TR>';
	html += '<TD><SELECT name="month" onchange="calendar_handler.changeNavDate(0);" class="calendar_month">' + this.buildMonth(nav_month) + '</SELECT></TD>';
	html += '<TD><INPUT name="year" value="' + nav_year + '" size="6" readonly class="calendar_year"><INPUT type="button" value="-" onclick="calendar_handler.changeNavDate(-1);" class="calendar_nav"><INPUT type="button" value="+" onclick="calendar_handler.changeNavDate(1);" class="calendar_nav"></TD>';
	html += '</TR></TABLE>';
	html += '</TD></TR>';

	html += '<TR><TD align="center">';
	html += '<TABLE width="100%" class="calendar_day">';
	html += '<TR>';
	for(var weekday=1; weekday<8; weekday++)
	{	
		html += '<TD class="calendar_day_label">' + this.days[weekday] + '</TD>';
	}
	html += '</TR>';
	for(var week=0; week<6; week++)
	{
		html += '<TR>';
		for (var weekday=1; weekday<8; weekday++)
		{
			var aDate = new Date(nav_year, nav_month, this_date);

			if ((week==0 && weekday<first_day) || (aDate.getMonth()!=nav_month))
			{
				var print_date = '&nbsp; ';
			}
			else
			{
				var print_date = '<A href="javascript:calendar_handler.chooseDate(' + this_date + ', ' + nav_month + ' , ' + nav_year + ');'+ this.action +'" class="calendar">' + this_date + '</A>';
				//var print_date = '<A href="javascript:calendar_handler.chooseDate(' + this_date + ', ' + nav_month + ' , ' + nav_year + ')" class="calendar">' + this_date + '</A>';

				this_date++;
			}

			if (weekday==6 || weekday==7)
				var class_name = "calendar_day_date_week";
			else
				var class_name = "calendar_day_date";

			if (aDate.getDate()==current_date && nav_month==current_month && nav_year==current_year)
				class_name += " this_day";

			html += '<TD class="'+class_name+'">' + print_date + '</TD>';
		}
		html += '</TR>';
	}
	html += '</TABLE>';
	html += '</TD></TR>';

	html += '<TR><TD class="calendar_close"><A href="javascript:void(0);" onclick="calendar_handler.hide();" class="calendar_close">Fermer</A>&nbsp;';
	html += '</TD></TR>';

	html += '</TABLE></FORM>';

	
	var lo = get_element(this.div_id);

	
	lo.innerHTML = html;
	
	
	
}

function oCal_show(event)
{
	this.build();

	var div_contener = get_element(this.div_id);

	if (!div_contener)
	{
		return alert('Erreur: object de navigation non défini !');
	}

	div_contener.style.visibility = "visible";

	if (event)
	{
		this.move(div_contener, event);
	}

}

function oCal_hide()
{
	get_element(this.div_id).style.visibility = "hidden";
}

function oCal_move(element_div, event)
{
	if (event.pageX)        var left = event.pageX;
	else if (event.clientX) var left = event.clientX;
	else                    var left = 100;

	if (event.pageY)        var top = event.pageY;
	else if (event.clientY) var top = event.clientY;
	else                    var top = 100;

	if (!event.pageY)
	{
		left -= document.body.scrollLeft;
		top  += document.body.scrollTop;
	}

/*	left = left - 200; // afin d'afficher le pickup date dans la colonne des libellés (empeche l'affichage sous un <SELECT>)
	top = top + 10;*/
	left = left + this.coordX;
	top = top + this.coordY;

	element_div.style.left = left + "px";
	element_div.style.top = top + "px";
}

function calendar_show(cal_id, form_name, element_name, event, x, y,action)
{
	var coordX = 0;
	if (calendar_show.arguments[4]) coordX = x;
	else                            coordX = -200;
	var coordY = 0;
	if (calendar_show.arguments[5]) coordY = y;
	else                            coordY = 10;


	calendar = new oCal(cal_id, form_name, element_name);
	calendar.coordX = coordX;
	calendar.coordY = coordY;
	calendar.action=action;
	calendar_handler = calendar;
	calendar_handler.init();
	calendar_handler.navSynchro();
	calendar_handler.show(event);
}


/* fonction utilitaire RECAP FR */

	/* retourne la value &param=param_value d'un champs issue d'un critere de recherche a une chaine de request qui sera passé en lien direct */
	/* seulement si le param est non vide bien sur */
	function add_critere_to_request_string(form,field,attribute_name) {
		var valeur = get_form_element(form,field).value;
		if (valeur != null && valeur != '' && valeur != 'undefined') {
			if (attribute_name!=null && attribute_name != '')
				return '&'+attribute_name+'='+valeur;
			else
				return '&'+field+'='+valeur;
		} else return '';
		
	}

