////////////////////

// tbMask v1.1
//
// Textbox 'masking' on client-side in Internet Explorer.
//
// Written By John McGlothlin - April 17th, 2004
// Mask Characters
// 9 = Numeric only
// A = Alpha only
// X = Alphanumeric
//
// All other chars treated as literals.
//
//
var CTRL_PASTE = 22;
var CTRL_COPY = 3;
var CTRL_CUT = 24;
var TAB_KEY = 9;
var DELETE_KEY = 46;
var BACKSPACE_KEY = 8;
var ENTER_KEY = 13;
var RIGHT_ARROW_KEY = 39;
var DOWN_ARROW_KEY = 40;
var UP_ARROW_KEY = 38;
var LEFT_ARROW_KEY = 37;
var HOME_KEY = 36;
var END_KEY = 35;
var PAGEUP_KEY = 33;
var PAGEDOWN_KEY = 34;
var CAPS_LOCK_KEY = 20;
var ESCAPE_KEY = 27;
// --------------------------------------------------------------------
// Main function
// Gets the current keystroke and deals with it....lol
// --------------------------------------------------------------------
function tbMask(textBox) {

var keyCode = event.keyCode;

// get character from keyCode....dealing with the "Numeric KeyPad"
// keyCodes so that it can be used
var keyCharacter = cleanKeyCode(keyCode);


var retVal = false;

// grab the mask
var mask = textBox.mask;

var c = getCursorPos(textBox);

switch(keyCode){
case BACKSPACE_KEY:
	if(c > 0) {
		var currentMaskChar;
		// get next available char to delete except mask chars
		while(c > 0) {
			c--;
			currentMaskChar = mask.charAt(c);
			if(currentMaskChar == '9' || currentMaskChar == 'X' || currentMaskChar == 'A') {
				// found a spot.....replace that char with '_'
				var x = textBox.value.substring(0,c);
				var y = textBox.value.substring(c+1,textBox.value.length);
				textBox.value = x + '_' + y;
				setCursorPos(textBox,c);
				textBox.curPos = c;
				break;
			}
		}
	}
break;
case TAB_KEY: // keep track of cursor b4 tabbing out of field
	textBox.curPos = c;
	retVal = true;
break;
case HOME_KEY: // just move/keep track of cursor
	setCursorPos(textBox,0);
	textBox.curPos = 0;
break;
case END_KEY: // just move/keep track of cursor
	setCursorPos(textBox,textBox.value.length);
	textBox.curPos = textBox.value.length;
break;
case ENTER_KEY:
	retVal = true;
break;
case DELETE_KEY:
	if(c > -1) {
		var currentMaskChar = mask.charAt(c);
		// only allow delete if it's a valid char
		if(currentMaskChar == '9' || currentMaskChar == 'X' || currentMaskChar == 'A') {
			var x = textBox.value.substring(0,c);
			var y = textBox.value.substring(c+1,textBox.value.length);
			textBox.value = x + '_' + y;
			setCursorPos(textBox,c);
			textBox.curPos = c;
		}
	}
break;
case LEFT_ARROW_KEY: // just move/keep track of cursor
	if(c > 0) {
		setCursorPos(textBox,c-1);
		textBox.curPos = c-1;
	}
break;
case RIGHT_ARROW_KEY: // just move/keep track of cursor
	if(c < textBox.value.length) {
		setCursorPos(textBox,c+1);
		textBox.curPos = c+1;
	}
break;
default: // adding a new char somewhere in the field
	var currentMaskChar;
	// get next available to change.....except masking chars

	// **Si le mask est une heure, quand le texte est selectionné on permet d'effacer le champ a la saisie ************ //
	if (document.getSelection) sel = document.getSelection();
	else if (document.selection) sel = document.selection.createRange().text;
	else return;
	if(sel.length == 5) c=0;
	// **************************************************************************************************************** //

	while(c < textBox.value.length) {
		currentMaskChar = mask.charAt(c);
		if(currentMaskChar == '9' || currentMaskChar == 'X' || currentMaskChar == 'A') break;
		c++;
	}
	switch(currentMaskChar){
		case '9': // numeric only
			if('0123456789'.indexOf(keyCharacter) != -1)
				addNewKey(textBox,keyCharacter,c);
			break;
		case 'A': // alpha only
			if('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(keyCharacter) != -1)
				addNewKey(textBox,keyCharacter,c);
			break;
		case 'X': // alphanumeric
			if('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.indexOf(keyCharacter) != -1)
				addNewKey(textBox,keyCharacter,c);
			break;
		default:
			break;
		}
	}

c=getCursorPos(textBox);
return retVal;
}
// --------------------------------------------------------------------
// Accept a TextBox, a keycharacter and an integer position
// adds the key to the position and then sets cursor to next availble spot
// --------------------------------------------------------------------
function addNewKey(tb,key,pos) {
// add the new key to the textbox at pos
var startSel = tb.value.substring(0,pos);
var endSel = tb.value.substring(pos+1,tb.value.length);
tb.value = startSel + key + endSel;

var tbmlen = tb.mask.length;
// advance cursor to next '_'
while(pos < tbmlen) {
	pos++;
	curMChar = tb.mask.charAt(pos);
	if(curMChar == '9' || curMChar == 'X' || curMChar == 'A')
		break;
}

setCursorPos(tb,pos);
tb.curPos = pos;
}
// --------------------------------------------------------------------
// Loops thru pasted value and checks each char against the mask
//
// Leaves old value and return false if *any* char is off
// Creates new masked value if all pasted data is ok
// --------------------------------------------------------------------
function tbPaste(textBox) {

// grab the textBox value and the mask
var pastedVal = window.clipboardData.getData("Text");
var mask = textBox.mask;
var newVal = '';
var curPastedVal = 0;

for(var i=0;i<mask.length;i++){
	var currentMaskChar = mask.charAt(i);
// if current mask pos allows entry
	if(currentMaskChar == '9' || currentMaskChar == 'X' || currentMaskChar == 'A'){
		var currentPastedChar = pastedVal.charAt(curPastedVal);
		// check each current mask char against new keystroke
		// return false if any are out of sync
		if(currentMaskChar == '9') {
			if('0123456789'.indexOf(currentPastedChar) == -1)
				return false;
		} else if(currentMaskChar == 'A') {
			if('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(currentPastedChar) == -1)
				return false;
		} else if(currentMaskChar == 'X') {
			if('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.indexOf(currentPastedChar) == -1)
				return false;
		} else {
			return false;
		}

// add new key
		newVal += currentPastedChar;
		curPastedVal++;
	} else {
// add mask literal
		newVal += currentMaskChar;
	}
}
textBox.value = newVal;
return true;
}
// --------------------------------------------------------------------
// puts masked thingie in tb ie: '(___) ___-____'
// --------------------------------------------------------------------
function tbFocus(textBox) {

var val = textBox.value;
var mask = textBox.mask;
var startVal = '';

// give the tb a property set to current cursor pos...sorta used at this point
// to set cursor pos when re-entering a tb.
// eventually want to use it to get rid of get/setCursorPos functions...if possible
if(textBox.curPos == 'undefined' || textBox.curPos == null)
textBox.curPos = -1;

// if value null....set the starting format ie: '(___) ___-____'
if(val.length == 0 || val == null) {
for(var i = 0; i < mask.length; i++) {
var c = mask.charAt(i);
if(c == '9' || c == 'X' || c == 'A') {
startVal += '_';
if(textBox.curPos == -1) textBox.curPos = i;
}
else {
startVal += c;
}
}
setCursorPos(textBox,0);
textBox.curPos = 0;

textBox.value = startVal;
}

// otherwise just set proper cursor pos
if(textBox.curPos == -1) {
textBox.curPos = textBox.value.length;
}

setCursorPos(textBox,textBox.curPos);

// set just in case.
textBox.maxlength = mask.length;

return true;
}
// --------------------------------------------------------------------
// The Numeric KeyPad returns keyCodes that ain't all that workable.
//
// ie: KeyPad '1' returns keyCode 97 which String.fromCharCode converts to an 'a'.
//
// This way allows the Numeric KeyPad to be used
// --------------------------------------------------------------------
function cleanKeyCode(key)
{
switch(key)
{
case 96: return "0"; break;
case 97: return "1"; break;
case 98: return "2"; break;
case 99: return "3"; break;
case 100: return "4"; break;
case 101: return "5"; break;
case 102: return "6"; break;
case 103: return "7"; break;
case 104: return "8"; break;
case 105: return "9"; break;
default: return String.fromCharCode(key); break;
}
}
// --------------------------------------------------------------------
// Google gems
// --------------------------------------------------------------------
function getCursorPos(el){
	var pos = 0;
	if (el.createTextRange) {
		rg = document.selection.createRange().duplicate();
		rg.moveStart('textedit',-1);
		pos = rg.text.length;
	} else if (el.setSelectionRange) {
		pos = el.selectionEnd;
	}
	return pos;

/*
	var sel, rng, r2, i=-1;

	if(document.selection && el.createTextRange) {
		sel=document.selection;
		if(sel){
			r2=sel.createRange();
			rng=el.createTextRange.duplicate();
			rng.setEndPoint("EndToStart", r2);
			i=rng.text.length;
		}
	}
	return i;
*/
}

function setCursorPos(field,pos) {
if (field.createTextRange) {
var r = field.createTextRange();
r.moveStart('character', pos);
r.collapse();
r.select();
}
}

/* On crée une fonction de verification */
function verifForm(formulaire)
{
if((formulaire.etat_interv.options[formulaire.etat_interv.selectedIndex].text != '<?=MIS_ETAT_TRAITE?>')&&(formulaire.heure_fin.value != 0)&&(formulaire.heure_arrivee.value != 0))
	{
		if(confirm('Etat Visite Non Traité. Voulez Vous Passer en TRAITE')){
		formulaire.etat_interv.options[formulaire.etat_interv.selectedIndex].text = '<?=MIS_ETAT_TRAITE?>';}
		formulaire.submit(); /* sinon on envoi le formulaire */
	}
else
	formulaire.submit();
}

chgSortExtraParam='';
function chgSort(sname, sdir){
	url=document.location.pathname+"?action=list&faction=list"+"&sortname="+sname+"&sortdir="+sdir;
	if(chgSortExtraParam!='')
		url+="&"+chgSortExtraParam
	document.location=url;
}

function switch_expand(act_num_expand){
	var act,leng,limg,args;
	leng=eval("document.getElementById('exp_"+act_num_expand+"')");
	limg=eval("document.getElementById('exp_img_"+act_num_expand+"')");
	if(arguments.length<2)
		act=leng.style.display=="block";
	else
		act=arguments[1]==0;
	if(act){
		leng.style.display="none";
		limg.src="<?=MY_path_img_expand?>";
	}else{
		leng.style.display="block"
		limg.src="<?=MY_path_img_collapse?>";
	}
}

function switch_expand2(act_num_expand){
	var act,leng,args;
	leng=eval("document.getElementById('exp_"+act_num_expand+"')");
	if(arguments.length<2)
		act=leng.style.display=="block";
	else
		act=arguments[1]==0;
	if(act)
		leng.style.display="none";
	else
		leng.style.display="block"
}

function switch_div(nomid1, nomid2) {
	var id1=document.getElementById(nomid1);
	var id2=document.getElementById(nomid2);
	if(!id1 || !id2)
		return;
	if(id1.style.display=='block'){
	 	if(id1!=id2) id2.src = "<?=MY_path_img_expand?>";
		id1.style.display = 'none';
	}else{
	 	if(id1!=id2) id2.src = "<?=MY_path_img_collapse?>";
		id1.style.display = 'block';
	}
}

//The browser detection function.
//This function can be used for other purposes also.

function UserAgent(){
  var b=navigator.appName.toUpperCase();

  if (b=="NETSCAPE") this.b="ns";
  else if (b=="MICROSOFT INTERNET EXPLORER") this.b="ie";
  else if (b=="OPERA") this.b="op";
  else this.b=b;

  this.version=navigator.appVersion;
  this.v=parseInt(this.version);

  this.ns=(this.b=="ns" && this.v>=4);
  this.ns4=(this.b=="ns" && this.v==4);
  this.ns5=(this.b=="ns" && this.v==5);

  this.ie=(this.b=="ie" && this.v>=4);
  this.ie4=(this.version.indexOf('MSIE 4')>0);
  this.ie5=(this.version.indexOf('MSIE 5')>0);
  this.ie55=(this.version.indexOf('MSIE 5.5')>0);
  this.ie6=(this.version.indexOf('MSIE 6')>0);

  this.op = (this.b=="op");
  this.op4 = (this.b=="op" && this.v==4);
  this.op5 = (this.b=="op" && this.v==5);
}

at=new UserAgent();

//if you want to create the frame or layer dynamically, do not
//specify a name, do something like this, new exchanger();

function exchanger(name){
  //hold the dynamically created iframe or layer
  this.lyr = null;
  //to remember if the iframe or layer is created dynamically.
  this.isDynamic = false;

  this.name=name||"";
  this.fakeid=0;

  if (name == null || name==""){
    this.isDynamic = true;
    this.create();
  }else{
    this.name=name;
    if (at.ns4)
      this.lyr = window.document.layers[this.name];
  }
}

//this function should not be called directly
exchanger.prototype.create=function(){
  if (at.ns4){
    this.lyr=new Layer(0);
    this.visibility = "hide";
  }
  else if (at.ie || at.ns5){
    this.lyr=document.createElement("IFRAME");
    this.lyr.width=0;
    this.lyr.height=0;
    this.lyr.marginWidth=0;
    this.lyr.marginHeight=0;
    this.lyr.frameBorder=0;
    this.lyr.style.visibility="hidden";
    this.lyr.style.position="absolute";
//    this.lyr.src="javascript: ;"; // génére un popup sous https
    this.lyr.src="/blank.html";
    this.name="tongIFrame"+window.frames.length;
    //this will make IE work.
    this.lyr.setAttribute("id",this.name);
    //this will make netscape work.
    this.lyr.setAttribute("name",this.name);

    document.body.appendChild(this.lyr);
  }
}

exchanger.prototype.sendData=function(url){
  this.fakeid += 1;
  var newurl = "";
  if (url.indexOf("?") >= 0)
		url=url+"&";
	else
		url=url+"?";
	newurl = url + "fakeId" + this.fakeid;

  if (this.isDynamic||at.ns4)
    this.lyr.src=newurl;
  else
    if (at.ie || at.ns5 || at.op)
      window.frames[this.name].document.location.replace(newurl);
}

exchanger.prototype.retrieveData=function(varName){
  if (at.ns4)
    return eval("this.lyr." + varName);
  else if (at.ie || at.ns5 || at.op)
    return eval("window.frames['" + this.name + "']." + varName);
}


//// actb

// Stop an event from bubbling up the event DOM
function stopEvent(evt){
	evt || window.event;
	if (evt.stopPropagation){
		evt.stopPropagation();
		evt.preventDefault();
	}else if(evt.cancelBubble != undefined){
		evt.cancelBubble = true;
		evt.returnValue = false;
	}
	return false;
}

// Get the obj that starts the event
function getElement(evt){
	if (window.event)
		return window.event.srcElement;
	else
		return evt.currentTarget;
}
// Get the obj that triggers off the event
function getTargetElement(evt){
	if (window.event)
		return window.event.srcElement;
	else
		return evt.target;
}
// For IE only, stops the obj from being selected
function stopSelect(obj){
	if (obj.onselectstart != undefined){
		dw_event.add(obj,"selectstart",function(){ return false;}, false);
	}
}

/*    Caret Functions     */

// Get the end position of the caret in the object. Note that the obj needs to be in focus first
function getCaretEnd(obj){
	if(obj.selectionEnd != undefined){
		return obj.selectionEnd;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToEnd",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// Get the start position of the caret in the object
function getCaretStart(obj){
	if(obj.selectionStart != undefined){
		return obj.selectionStart;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToStart",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// sets the caret position to l in the object
function setCaret_new(obj, pos) {
  if(obj){
    if(obj.createTextRange) {
        /* Create a TextRange, set the internal pointer to
           a specified position and show the cursor at this
           position
        */
        var range = obj.createTextRange();
        range.move("character", pos);
        m.collapse();
        range.select();
    } else if(obj.selectionStart) {
        /* Gecko is a little bit shorter on that. Simply
           focus the element and set the selection to a
           specified position
        */
        obj.focus();
        obj.setSelectionRange(pos, pos);
    }
  }
}
function setCaret(obj,l){
	if(obj){
		obj.focus();
		if (obj.setSelectionRange){
			obj.setSelectionRange(l,l);
		}else if(obj.createTextRange){
			m = obj.createTextRange();
			m.moveStart('character',l);
			m.collapse();
			m.select();
		}
	}
}
// sets the caret selection from s to e in the object
function setSelection(obj,s,e){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(s,e);
	}else if(obj.createTextRange){
		m = obj.createTextRange();
		m.moveStart('character',s);
		m.moveEnd('character',e);
		m.select();
	}
}

/*    Escape function   */
String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');   // "
}
/* --- Escape --- */

/* Offset position from top of the screen */
function curTop(obj){
	toreturn = 0;
	while(obj){
		toreturn += parseInt(obj.offsetTop);
		obj = obj.offsetParent;
	}
	return toreturn;
}
function curLeft(obj){
	toreturn = 0;
	while(obj){
		toreturn += parseInt(obj.offsetLeft);
		obj = obj.offsetParent;
	}
	return toreturn;
}
/* ------ End of Offset function ------- */

/* Types Function */

// is a given input a number?
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

/* Object Functions */

function replaceHTML(obj,text){
	while(el = obj.childNodes[0]){
		obj.removeChild(el);
	};
	obj.appendChild(document.createTextNode(text));
}

function chgro(b, obj, nclass){
	if(b){
		ro=false;
		bcol="#FFF";
		col="#000";
		fsty="";
	}else{
		nclass='';
		ro=true;
		bcol="#eee";
		col="#222";
		fsty="italic";
	}
	setattr(obj, ro, bcol, col, fsty, nclass);
}

function setattr(obj, ro, bcol, col, fstyl, nclass){
	os=obj.style;
	if(nclass!=''){
		os.removeAttribute('backgroundColor',0);
		os.removeAttribute('color',0);
		os.removeAttribute('fontStyle',0);
		obj.className=nclass;
	}else{
		os.backgroundColor=bcol;
		os.color=col;
		os.fontStyle=fstyl;
	}
	obj.readOnly=ro;
	obj.disabled=ro;
}

function chkautofield(o){
// pour permettre des entrées avec remplissage automatique
	if(event.type=='blur'){
		if(o.value=='')
			o.value='<?=MY_AUTO_NUMSTR?>';
	}else if(event.type=='focus')
		if(o.value=='<?=MY_AUTO_NUMSTR?>')
			o.value='';
}
