//
// GLOBAL OPTIONS
//

var isSafari = false;
var isMoz = false;
var isIE = false;

if (navigator.userAgent.indexOf("Safari") > 0) {
  isSafari = true;
  isMoz = false;
  isIE = false;
}
else if (navigator.product == "Gecko") {
  isSafari = false;
  isMoz = true;
  isIE = false;
} else {
  isSafari = false;
  isMoz = false;
  isIE = true;
}



function _keyEnter(e) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return false;

  if (keycode == 13) {
    _action('Enregistrer','')
    return true;
  } else {
    return false;
  }
}
function _action(action, parametre) {
	if( action=='Rechercher' || action=='Enregistrer' || action=='EnregistrerPro' || action=='Valider' || 
		 action=='PrendreEnCharge' || action=='Soumettre' || action=='Refuser' || action=='Supprimer' ||
		 action=='Terminer'  ) {
		showWaiting( 'Veuillez patienter SVP...' );
	}

	// Validation
	if (!_validation("form",action)) {
		if (typeof needToConfirm != "undefined") {
			needToConfirm = true;
		}
		hideWaiting( );
		return;	
	}

	var theform;
	// var validationRequired = (typeof(ValidatorOnSubmit) != 'undefined') && !_val_is_ie;
	if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
		theform = document.getElementById("form"); 
	else
		theform = document.forms["form"];
	
	theform._ACTION.value = action;
	theform._ACTION_PARAM.value = parametre;
	// if(validationRequired && ValidatorOnSubmit()) //non-IE
	theform.submit();
	// if(!validationRequired) //IE only
	//	theform.submit();
	return true;
}

function selectVal(id, defaultId) {
	var form;
	if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
		form = document.getElementById("form"); 
	else
		form = document.forms["form"];
	var select = form.elements[id];
	return (select!=null ? select.options[select.selectedIndex].value : defaultId);
}

// Fonction pour la gestion des tableaux : ajout et suppression de lignes, avec validation
function getParent(element, parentTagName) {
	if (!element)
		return null;
	else if (element.nodeType==1 && element.tagName.toLowerCase()==parentTagName.toLowerCase())
		return element;
	else
		return getParent(element.parentNode, parentTagName);
}

function ajouterLigne(element_id, numero_ligne, tr_before) {
	ajouterLigne(element_id, numero_ligne, null) 
}
	
function ajouterLigne(element_id, numero_ligne, tr_before) {
	var tr0 = document.getElementById(element_id);
	var parent = tr0.parentNode;
	
	// On clone la ligne vide
	var tr = tr0.cloneNode(true);
	tr.style.display = "";
	if (tr.id!="" && tr.id.indexOf("%")<0) {
		tr.removeAttribute("id");
	} else {
		tr.id = tr.id.replace("%", ""+numero_ligne);
	}
	
	var	inputs = tr.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) { 
		inputs[i].name = inputs[i].name.replace("%", ""+numero_ligne);
		inputs[i].id = inputs[i].id.replace("%", ""+numero_ligne);
		if (inputs[i].id=="") { 
			inputs[i].id = inputs[i].name;
		}
	}
	var	textareas = tr.getElementsByTagName("textarea");
	for (var i = 0; i < textareas.length; i++) { 
		textareas[i].name = textareas[i].name.replace("%", ""+numero_ligne);
		textareas[i].id = textareas[i].id.replace("%", ""+numero_ligne);
		if (textareas[i].id=="") { 
			textareas[i].id = textareas[i].name;
		}
	}
	var	selects = tr.getElementsByTagName("select");
	for (var i = 0; i < selects.length; i++) { 
		selects[i].name = selects[i].name.replace("%", ""+numero_ligne);
		selects[i].id = selects[i].id.replace("%", ""+numero_ligne);
		if (selects[i].id=="") { 
			selects[i].id = selects[i].name;
		}
	}
	var	as = tr.getElementsByTagName("a");
	for (var i = 0; i < as.length; i++) { 
		as[i].id = as[i].id.replace("%", ""+numero_ligne);
	}
	var	divs = tr.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++) { 
		divs[i].id = divs[i].id.replace("%", ""+numero_ligne);
	}
	var	imgs = tr.getElementsByTagName("img");
	for (var i = 0; i < imgs.length; i++) { 
		imgs[i].id = imgs[i].id.replace("%", ""+numero_ligne);
	}
	var	spans = tr.getElementsByTagName("span");
	for (var i = 0; i < spans.length; i++) { 
		spans[i].id = spans[i].id.replace("%", ""+numero_ligne);
	}
	var	as = tr.getElementsByTagName("a");
	for (var i = 0; i < as.length; i++) { 
		as[i].href = as[i].href.replace("%", ""+numero_ligne);
	}
	var	scripts = tr.getElementsByTagName("script");
	for (var i = 0; i < scripts.length; i++) { 
		scripts[i].text = scripts[i].text.replace("%", ""+numero_ligne);
		scripts[i].text = scripts[i].text.replace("%", ""+numero_ligne);
		scripts[i].text = scripts[i].text.replace("%", ""+numero_ligne);
		scripts[i].text = scripts[i].text.replace("%", ""+numero_ligne);
	}
	var	trs = tr.getElementsByTagName("tr");
	for (var i = 0; i < trs.length; i++) { 
		trs[i].id = trs[i].id.replace("%", ""+numero_ligne);
	}
	
	// Ajout de la nouvelle ligne
	if (tr_before) {
		parent.insertBefore(tr, tr_before);
	} else {
		parent.insertBefore(tr, tr0);
	}
}

function supprimerLigne(bouton) {
	var tr = getParent(bouton, "tr");
	
	var parent = tr.parentNode;
	parent.removeChild(tr);
	
	// Il faut enlever les r?gles de validation associ?es ? ces lignes
	var	inputs = tr.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) { 
		supprimerValidation(inputs[i].name);
	}

	var	selects = tr.getElementsByTagName("select");
	for (var i = 0; i < selects.length; i++) { 
		supprimerValidation(selects[i].name);
	}

	var	textareas = tr.getElementsByTagName("textarea");
	for (var i = 0; i < textareas.length; i++) { 
		supprimerValidation(textareas[i].name);
	}

}

function ajouterValidation(action, nom_champ, libelle, type_regle, nom_champ2, libelle2) {
	if (dynamicRules[action]==null) dynamicRules[action] = new Array();
	var rule = nom_champ ;
	if (libelle != "" ) rule = rule	+ ":" + libelle 
	rule = rule + "|" + type_regle;
	//if (nom_champ2 != undef) rule = rule + "|$" + nom_champ2;
	if (nom_champ2 != undef) rule = rule + "|" + nom_champ2;
	if (libelle2 != undef) rule = rule + ":" + libelle2;
	dynamicRules[action][nom_champ+"/"+type_regle] = rule;
}

function supprimerValidation(nom_champ) {	
	if (dynamicRules==null) return;
	// Supprime toutes les lignes commen?ant pas le nom du champ, pour toutes les actions
	for (var action in dynamicRules) {
		var regles = dynamicRules[action];
		for (var clef in regles) {
		    if (clef.indexOf(nom_champ+"/")==0) {
			    delete dynamicRules[action][clef];
			}
		}
	}
	el = document.getElementById( nom_champ);
   if (el) highlight(el, inputclassnormal);
}

function supprimerValidations(bouton) {

	/* Egale à la fonction supprimerLigne mais sans supprimer la ligne */
	
	var tr = getParent(bouton, "tr");
	
	var parent = tr.parentNode;
//	parent.removeChild(tr);
	
	// Il faut enlever les r?gles de validation associ?es ? ces lignes
	var	inputs = tr.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) { 
		supprimerValidation(inputs[i].name);
	}

	var	selects = tr.getElementsByTagName("select");
	for (var i = 0; i < selects.length; i++) { 
		supprimerValidation(selects[i].name);
	}

}


var iframesArrayJS = new Array();
function autocompleteJS(id, popupId, targetId, listFunc, postFunc, progressStyle, minimumCharacters) {
  var inputField = document.getElementById(id);
  var popup = document.getElementById(popupId);
  var targetField = (targetId!=null ? document.getElementById(targetId) : null);
  autocompleteFieldJS(inputField, popup, targetField, listFunc, postFunc, progressStyle, minimumCharacters);
}
function autocompleteFieldJS(inputField, popup, targetField, listFunc, postFunc, progressStyle, minimumCharacters) {

  if (!postFunc) postFunc = function () {};
  if (minimumCharacters == null || minimumCharacters == "null") minimumCharacters = 1;
  var items = new Array();
  var current = 0;
  
  function hidePopup() {
    popup.style.visibility = 'hidden';
    var iframe = iframesArrayJS[inputField.id];
    if (iframe) {
        document.body.removeChild(iframe);
        iframesArrayJS[inputField.id] = null;
    }
  }

  function handlePopupOver() {
    removeListener(inputField, 'blur', hidePopup);
  }

  function handlePopupOut() {
    if (popup.style.visibility == 'visible') {
      addListener(inputField, 'blur', hidePopup);
    }
  }

  function handleClick(e) {
    inputField.value = eventElement(e).innerHTML;
    if (targetField!=null) {
        targetField.value = eventElement(e).getAttribute("id");
    }
    hidePopup();
    inputField.focus();
    postFunc();
  }

  function handleOver(e) {
    items[current].className = '';
    current = eventElement(e).index;
    items[current].className = 'selected';
  }

  function handlerFunc() {
      var list = listFunc(inputField.value);
      var html = "";
      html += "<ul>";
      for (var i=0; i<list.length; i++) {
	      html += '<li id="' + list[i]['en'] + '">';
	      html += list[i]['fr'];
	      html += "</li>";
      }
      html += "</ul>";

      // Set innerHTML for popup
      popup.innerHTML = html;

      setSelected();
  }

  function setSelected() {
    current = 0;
    items = popup.getElementsByTagName("li");
    if ((items.length > 1)
       || (items.length == 1
           && items[0].innerHTML != inputField.value)) {
      setPopupStyles();
      for (var i = 0; i < items.length; i++) {
        items[i].index = i;
        addOptionHandlers(items[i]);
      }
      items[0].className = 'selected';
    } else {
      hidePopup();
    }

    resetProgressStyle();

    return null;
  }

  function setProgressStyle() {
    if (progressStyle != null) {
      addClass(inputField, progressStyle);
    }
  }

  function resetProgressStyle() {
    if (progressStyle != null) {
      removeClass(inputField, progressStyle);
    }
  }
  
  function empty() {
    resetProgressStyle();
    hidePopup();
  }

  function setPopupStyles() {
    var maxHeight
    if (isIE) {
      maxHeight = 200;
    } else {
      maxHeight = window.outerHeight/3;
    }
    if (popup.offsetHeight < maxHeight) {
      popup.style.overflow = 'hidden';
    } else if (isMoz) {
      popup.style.maxHeight = maxHeight + 'px';
      popup.style.overflow = '-moz-scrollbars-vertical';
    } else {
      popup.style.height = maxHeight + 'px';
      popup.style.overflowY = 'auto';
    }
    popup.scrollTop = 0;
    popup.style.visibility = 'visible';
	popup.style.zIndex = "100";	
    
    // Start playing
    popup.style.top = (getElementY(inputField)+inputField.offsetHeight+2) + "px";
    popup.style.left = getElementX(inputField) + "px";
    popup.style.width = inputField.offsetWidth + "px";

    if (isIE) {
	    var iframe = iframesArrayJS[inputField.id];
	    if (!iframe) {
			iframe = document.createElement('IFRAME');
			iframesArrayJS[inputField.id] = iframe;
	    }
		iframe.style.position = "absolute";	
		iframe.style.zIndex = "5";	
		iframe.border='0';
		iframe.style.width = popup.offsetWidth + 'px';
		iframe.style.height = popup.offsetHeight + 'px';
		document.body.appendChild(iframe);
		iframe.style.left = popup.style.left;
		iframe.style.top = popup.style.top;	
	}
  }

  function addOptionHandlers(option) {
    addListener(option, "click", handleClick);
    addListener(option, "mouseover", handleOver);
  }

  var timeout = false;
  
  function start(e) {
    if (timeout)
      window.clearTimeout(timeout);

    var key = 0;
    if (e.keyCode) { key = e.keyCode; }
    else if (typeof(e.which)!= 'undefined') { key = e.which; }
    var fieldLength = inputField.value.length;

    //up arrow
    if (key == 38) {
      if (current > 0) {
        items[current].className = '';
        current--;
        items[current].className = 'selected';
        items[current].scrollIntoView(false);
      }

    //down arrow
    } else if (key == 40) {
      if(current < items.length - 1) {
        items[current].className = '';
        current++;
        items[current].className = 'selected';
        items[current].scrollIntoView(false);
      }

    //enter or tab
    } else if ((key == 13) && popup.style.visibility == 'visible') {
      inputField.value = items[current].innerHTML;
      if (targetField!=null) {
          targetField.value = items[current].getAttribute("id");
      }
      hidePopup();
      inputField.focus();
      if (isIE) {
        event.returnValue = false;
      } else {
        e.preventDefault();
      }
      postFunc();

    //escape
    } else if ((key == 27) || (key == 9)){
      hidePopup();
      if (isIE) {
        event.returnValue = false;
      } else {
        e.preventDefault();
      }
      postFunc();

    } else {
      // increment/decrement fieldLength for correct count
      if (key == 8 || key == 46) {
        fieldLength -= 1;
      } else {
        fieldLength += 1;
      }

      // Check for empty input field or not enough characters
      if (fieldLength < minimumCharacters) {
        // hide popup and return
        hidePopup();
      } else if (key != 9) {
        timeout = window.setTimeout(handlerFunc, 300);
      }
    }
  }

  addKeyListener(inputField, start);
  addListener(popup, 'mouseover', handlePopupOver);
  addListener(popup, 'mouseout', handlePopupOut);
}

// Affiche la popup d'attente
function showWaiting( msg ) {
	showMask();
	
	// Affichage du message patientez
	var w = 200;
	var h = 50;
	var waitDiv = document.createElement( 'DIV' );
	waitDiv.id = 'waitDiv';
	waitDiv.style.zIndex = 1000;
	waitDiv.style.position = 'absolute';
	if (isIE) {
		waitDiv.style.left = ( document.documentElement.scrollLeft + (document.documentElement.offsetWidth - w) / 2) + 'px';
		waitDiv.style.top = ( document.documentElement.scrollTop + (document.documentElement.offsetHeight - h) / 2) + 'px';
	} else {
		waitDiv.style.left = ((window.pageXOffset + window.innerWidth - w) / 2) + 'px';
		waitDiv.style.top = (window.pageYOffset + (window.innerHeight - h) / 2) + 'px';
	}
	waitDiv.style.width = w + 'px';
	waitDiv.style.height = h + 'px';
	waitDiv.style.border = '2px solid #808080';
	waitDiv.style.backgroundColor = '#FFF';
	waitDiv.innerHTML  = '<table><tr><td align="center" width="50px" height="50px"><img src="images/loader.gif"/></td><td align="center" valign="middle" width="150px">' + msg + '</td></tr></table>';	
	document.body.appendChild(waitDiv);	

	if (isIE) {
		var iframe = document.createElement('IFRAME');
		iframe.style.position = "absolute";
		iframe.style.zIndex = "5";
		iframe.border='0';
		iframe.style.width = waitDiv.offsetWidth + 'px';
		iframe.style.height = waitDiv.offsetHeight + 'px';
		document.body.appendChild(iframe);
		iframe.style.left = waitDiv.style.left;
		iframe.style.top = waitDiv.style.top;
		waitDiv.iframe = iframe;
	}
}

// Cache la popup d'attente
function hideWaiting() {
	var waitDiv = document.getElementById("waitDiv");
	if (waitDiv) {
		if (waitDiv.nodeName == 'DIV') {
			if (waitDiv.iframe) {
				var parent = waitDiv.iframe.parentNode;
				parent.removeChild( waitDiv.iframe );
			}
			var parent = waitDiv.parentNode;
			parent.removeChild( waitDiv );
		}
	}
	hideMask();
}


// Affiche le masque de page
function showMask( ) {
	var maskDiv = document.getElementById("maskDiv");
	if ( ! maskDiv) {
		var maskDiv = document.createElement( 'DIV' );
		maskDiv.id = 'maskDiv';
		maskDiv.style.zIndex = 990;
		maskDiv.style.position = 'absolute';
		maskDiv.style.left = '0px';
		maskDiv.style.top = '0px';
		maskDiv.style.backgroundColor = '#FFF';
	
		if (isIE) {
			maskDiv.style.width = document.body.scrollWidth + 'px';
			var h = document.body.scrollHeight;
			maskDiv.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=60)';
		} else {
			maskDiv.style.width = document.width + 'px';
			//var h = document.height;
			var h = window.innerHeight
			maskDiv.style.opacity = 0.6;
		}
		if (h == 0) h = 1000 ;
		maskDiv.style.height = h + 'px';
		document.body.appendChild(maskDiv);	
	
		if (isIE) {
			var iframe = document.createElement('IFRAME');
			iframe.style.position = "absolute";
			iframe.style.zIndex = "5";
			iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=10)';
			iframe.border='0';
			iframe.style.width = maskDiv.offsetWidth + 'px';
			iframe.style.height = maskDiv.offsetHeight + 'px';
			document.body.appendChild(iframe);
			iframe.style.left = maskDiv.style.left;
			iframe.style.top = maskDiv.style.top;
			maskDiv.iframe = iframe;
		}
	}
}

// Cache le masque de page
function hideMask() {
	var maskDiv = document.getElementById("maskDiv");
	if (maskDiv) {
		if (maskDiv.nodeName == 'DIV') {
			if (maskDiv.iframe) {
				var parent = maskDiv.iframe.parentNode;
				parent.removeChild( maskDiv.iframe );
			}
			var parent = maskDiv.parentNode;
			parent.removeChild( maskDiv );
		}
	}
}


// Parse un ensemble xml vers les champs dont les id sont passés sous forme de tableau
function parseXmlItem2Fields( item, fields ) {
	var child = item.firstChild;
	for (var i=0; i<fields.length; i++) {
		s = child.firstChild.nodeValue;
		el = document.getElementById( fields[i] );
		if (el) {
			el.value = s.trim();
		}
		child = child.nextSibling;
	}

}

function swapDisplayBlockTr(clsName) {
	document.getElementsByClassName = function(clsName) {
		var retnode = [];
		var myclass = new RegExp('\\b'+clsName+'\\b');
		var elem = this.getElementsByTagName('*');
		for (var i = 0; i < elem.length; i++) {
			var classes = elem[i].className;
			if (myclass.test(classes)) retnode.push(elem[i]);
		}
		return retnode;
	};
	
	var init = new Array();
	init = document.getElementsByClassName(clsName + '_Show');
	if (init.length > 0) {
		for (var j=0; j< init.length; j++) {
			init[j].className = clsName + '_NoShow';
		}	
	} else {
		var init = document.getElementsByClassName(clsName + '_NoShow');
		if (init.length > 0) {
			for (var j=0; j< init.length; j++) {
				init[j].className = clsName + '_Show';
			}	
		}
	}
	return;
}	


function setSelectByText(id, text) {
	var select = document.getElementById(id);
	
	for(var i=0; i<select.options.length; i++) {
		if(select.options[i].text == text) {
			select.selectedIndex = i;
			if(!select.options[i].selected ) {
				select.options[i].selected=true;
			}
			return;
		}
	} 
}

function setSelectByValue(id, value) {
	var select = document.getElementById(id);
	
	for(var i=0; i<select.options.length; i++) {
		if(select.options[i].value == value) {
			select.selectedIndex = i;
			if(!select.options[i].selected ) {
				select.options[i].selected=true;
			}
			return;
		}
	} 
}

/* Calcul de la différence entre deux heures au format hh:mm:ss */
function differenceHeure(heuredeb,heurefin){
	hd=heuredeb.split(":");
	hf=heurefin.split(":");
	hd[0]=eval(hd[0]);
	hd[1]=eval(hd[1]);
	hd[2]=eval(hd[2]);
	hf[0]=eval(hf[0]);
	hf[1]=eval(hf[1]);
	hf[2]=eval(hf[2]);
	if(hf[2]<hd[2]){hf[1]=hf[1]-1;hf[2]=hf[2]+60;}
	if(hf[1]<hd[1]){hf[0]=hf[0]-1;hf[1]=hf[1]+60;}
	if(hf[0]<hd[0]){hf[0]=hf[0]+24;}
	var heure = (hf[0]-hd[0]);
	if( heure.toString().length == 1 ) heure = '0'+heure;
	var minute = (hf[1]-hd[1]);
	if( minute.toString().length == 1 ) minute = '0'+minute;
	var seconde = (hf[2]-hd[2]);
	if( seconde.toString().length == 1 ) seconde = '0'+seconde;
	return (heure + ":" + minute + ":" + seconde);
}

// workaround pour IE de façon à ne pas pouvoir sélectionner un élément de niveau parent
function checkNotParent(select) {
	if (select.options[select.selectedIndex].value == -999) {
		select.options[0].selected = true;
	/*
		if (select.selectedIndex < select.options.length-1) {
			select.options[select.selectedIndex+1].selected = true;
		} else {
			select.options[select.selectedIndex-1].selected = true;
		}
	*/	
	} 
}
	
function checkIsUnique(select, tab, message) {
	var selectValue = select.options[select.selectedIndex].value;
	if (typeof tab[selectValue] != 'undefined' && selectValue != 0) {
		alert (message);
		select.selectedIndex = select.initIndex;
	} else {
		if (select.options[select.selectedIndex] != 0) {
			if (typeof select.options[select.initIndex] != "undefined") {
				delete tab[select.options[select.initIndex].value];
			}
			tab[selectValue] = selectValue;
		}
	}
}

function updateTDTitle(select) {
	td = getParent(select, "TD");
	td.title = "Nouveau descriptif survol";
}

