// wForms - a javascript extension to web forms.
// see http://www.formassembly.com/wForms
// This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
overaide = false
function wHELPERS() {};

// addEvent adapated from http://ejohn.org/projects/flexible-javascript-events/
// and  Andy Smith's (http://weblogs.asp.net/asmith/archive/2003/10/06/30744.aspx)
wHELPERS.prototype.addEvent = function(obj, type, fn) {
	if(!obj) { return; }
	
	if (obj.attachEvent) {
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
		obj.attachEvent( 'on'+type, obj[type+fn] );
	} else if(obj.addEventListener) {			
		obj.addEventListener( type,fn, false );
	} else {
		var originalHandler = obj["on" + type]; 
		if (originalHandler) { 
		  obj["on" + type] = function(e){originalHandler(e);fn(e);}; 
		} else { 
		  obj["on" + type] = fn; 
		} 
	}
}

wHELPERS.prototype.removeEvent = function(obj, type, fn) {
	if (obj.detachEvent) {
		if(obj[type+fn]) {
			obj.detachEvent( 'on'+type, obj[type+fn] );
			obj[type+fn] = null;
		}
	} else if(obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else {
		obj["on" + type] = null;
	}
}

// Returns the event's source element 

wHELPERS.prototype.getSourceElement = function(e) {	
	if(!e) e = window.event;	
	if(e.target)
		var srcE = e.target;
	else
		var srcE = e.srcElement;
	if(!srcE) return null;
	if(srcE.nodeType == 3) srcE = srcE.parentNode; // safari weirdness		
	
	if(!browser.isFF) {
			if(srcE.tagName.toUpperCase()=='LABEL' && e.type=='click') { 
				// when clicking a label, firefox fires the input onclick event
				// but the label remains the source of the event. In Opera and IE 
				// the source of the event is the input element. Which is the 
				// expected behavior, I suppose.		
				if(srcE.getAttribute('for')) {
					srcE = document.getElementById(srcE.getAttribute('for'));
				}
			}
	}
	return srcE;
}



// getTop / getLeft  
// Returns pixel coordinates from the top-left window corner.
wHELPERS.prototype.getTop = function(obj) {
	var cur = 0;
	if(obj.offsetParent) {		
		while(obj.offsetParent) {
			if((new wHELPERS()).getComputedStyle(obj,'position') == 'relative' ) {
				// relatively postioned element
				return cur;
			}
			cur+=obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	return cur;
}
wHELPERS.prototype.getLeft = function(obj) {
	var cur = 0;
	if(obj.offsetParent) {		
		while(obj.offsetParent) {
			if((new wHELPERS()).getComputedStyle(obj,'position') == 'relative' ) {
				// relatively postioned element
				return cur;
			}
			cur+=obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	return cur;
}

wHELPERS.prototype.getComputedStyle = function(element, styleName) {
	if(window.getComputedStyle) {
		return window.getComputedStyle(element,"").getPropertyValue(styleName);
	} else if(element.currentStyle) {	
		return element.currentStyle[styleName];
	}
	return false;
}
// backward compatibility
	var wHelpers = wHELPERS;   


   /* 
	* MISC FUNCTIONS 
   /* ------------------------------------------------------------------------------------------ */

// Push implementation for IE5/mac
if (!Array.prototype.push) { 
	Array.prototype.push = function() { 
		for (var i = 0; i < arguments.length; ++i) { 
			this[this.length] = arguments[i]; 
		} 
		return this.length; 
	}; 
}


  if(wHELPERS) {
	  var wFORMS = { 
	  
	  debugLevel     : 0, /* 0: Inactive, 1+: Debug Level */
	  
	  helpers        : new wHELPERS(),     
	  behaviors      : {},
	  onLoadComplete : new Array(),  /* stack of functions to call once all behaviors have been applied */
	  processedForm  : null,
	  
	  onLoadHandler  : function() {
		  for(var behaviorName in  wFORMS.behaviors) {
			   wFORMS.debug('wForms/loaded behavior: ' + behaviorName);
		  }
		 
		  for (var i=0;i<document.forms.length;i++) {
			  wFORMS.debug('wForms/initialize: '+ (document.forms[i].name || document.forms[i].id) );
			  	wFORMS.processedForm = document.forms[i];
			  wFORMS.addBehaviors(document.forms[i]);
		  }
	  },
	  
	  addBehaviors : function (node) {
		 if(!node) return;
		 
		 var deep = arguments[1]?arguments[1]:true;
		 if(!node.nodeType) {
			 // argument is not a node. probably an id string. 
			 // (typeof not used for IE5/mac compatibility)
			 node = document.getElementById(node);
		 }
			if(!node || node.nodeType!=1) return;
			
			deep=(arguments.length>1)?arguments[1]:true;	
				   
			wFORMS._addBehaviors(node, deep);					
		  },
		  
	  _addBehaviors : function (node, deep) {
		  if(node.getAttribute('rel')=='no-behavior') {
		  	return false;
		  }
		
		 // Process element nodes only
		 if(node.nodeType == 1) { 
			  for(var behaviorName in wFORMS.behaviors) {
				  wFORMS.behaviors[behaviorName].evaluate(node);
			  }
			 
			  if(deep) {
				  for (var i=0, l=node.childNodes.length, cn=node.childNodes; i<l; i++) {
				  	 if(cn[i].nodeType==1)
					 	wFORMS._addBehaviors(cn[i], deep);
				  }
			  }
			  
			  if(node.tagName.toUpperCase() == 'FORM') {
				  // wFORMS.debug('wForms/processed: ' + node.id);
				  // run the init stack
				  for (var i=0;i<wFORMS.onLoadComplete.length;i++) {
					  wFORMS.onLoadComplete[i]();
				  }
				  // empty the stack					  
				  if(wFORMS.onLoadComplete.length > 0) {
					  wFORMS.onLoadComplete = new Array();
				  }
			  }
		  }
	  },
	  
	  hasBehavior: function(behaviorName) {
		  if(wFORMS.behaviors[behaviorName]) return true;
		  return false;
	  },
	  
	  /* 
	   * DEBUG FUNCTIONS 
	   * ------------------------------------------------------------------------------------------ */

	  debug : function(txt) { 
		msgLevel = arguments[1] || 10; 	// 1 = least importance, X = most important
		
		if(wFORMS.debugLevel > 0 && msgLevel >= wFORMS.debugLevel) {
			if(!wFORMS.debugOutput)
				wFORMS.initDebug();
			if(wFORMS.debugOutput)
				wFORMS.debugOutput.innerHTML += "<br />" + txt;
		}
	  },
	  
	  initDebug : function() {
		var output = document.getElementById('debugOutput');
		if(!output) {
			output = document.createElement('div');
			output.id = 'debugOutput';
			output.style.position   = 'absolute';
			output.style.right      = '10px';
			output.style.top        = '10px';
			output.style.zIndex     = '300';
			output.style.fontSize   = 'x-small';
			output.style.fontFamily = 'courier';
			output.style.backgroundColor = '#DDD';
			output.style.padding    = '5px';
			if(document.body) // if page fully loaded
				wFORMS.debugOutput = document.body.appendChild(output);
		}
		if(wFORMS.debugOutput)
			wFORMS.debugOutput.ondblclick = function() { this.innerHTML = '' };
	}
  };

  wFORMS.NAME     = "wForms";
  wFORMS.VERSION  = "2.0";
  wFORMS.__repr__ = function () {
	return "[" + this.NAME + " " + this.VERSION + "]";
  };
  wFORMS.toString = function () {
	return this.__repr__();
  };
 
 
  // For backward compatibility
  wFORMS.utilities = wFORMS.helpers;
  var wf           = wFORMS; 
  wf.utilities.getSrcElement				= wFORMS.helpers.getSourceElement;
  wf.utilities.XBrowserPreventEventDefault	= wFORMS.helpers.preventEvent;
  
  // Initializations:
  
  // Attach JS only stylesheet.
  //wFORMS.helpers.activateStylesheet('wforms-jsonly.css');
  // Parse document and apply wForms behavior
  wFORMS.helpers.addEvent(window,'load',wFORMS.onLoadHandler);
  } 

// ------------------------------------------------------------------------------------------
// Field Hint / Tooltip Behavior
// ------------------------------------------------------------------------------------------

if(wFORMS) {

       // Component properties 
       wFORMS.idSuffix_fieldHint					= "-aide";                     			// a hint id is the associated field id (or name) plus this suffix
       wFORMS.idSuffix_fieldHint_popup				= "-popup";                     		// a hint id is the associated field id (or name) plus this suffix
       wFORMS.idSuffix_fieldHint_pictoaide			= "-pictoaide";                     	// a hint id is the associated field id (or name) plus this suffix
	   wFORMS.idSuffix_dessus_select				= "dessus-select";                     	// a hint id is the associated field id (or name) plus this suffix
	   wFORMS.idSuffix_reserrer						= "reserrer";                     		// a hint id is the associated field id (or name) plus this suffix
	   
       wFORMS.className_inactiveFieldHint			= "field-hint-inactive";    			// visual effect depends on CSS stylesheet
       wFORMS.className_activeFieldHint				= "field-hint-active";             		// visual effect depends on CSS stylesheet
       wFORMS.className_activeFieldHint_ie_select	= "field-hint_ie_select";             	// visual effect depends on CSS stylesheet pour IE et select	   
	          
       wFORMS.behaviors['hint'] = {
           name: 'hint', 
           
		   // evaluate: check if the behavior applies to the given node. Adds event handlers if appropriate
             evaluate: function(node) {
               if(node.id) {
               	   if(node.id.indexOf(wFORMS.idSuffix_fieldHint)>0) {               	   
               	     // this looks like a field-hint. See if we have a matching field.               	    
               	     // try first with the id, then with the name attribute.
               	     var id     = node.id.replace(wFORMS.idSuffix_fieldHint, '');               	     
               	     var hinted = document.getElementById(id) || wFORMS.processedForm[id];
					 //document.title += " " + hinted.name
               	   }
				   
				   if(node.id.indexOf(wFORMS.idSuffix_fieldHint_popup)>0) {               	   
               	     // this looks like a field-hint. See if we have a matching field.               	    
               	     // try first with the id, then with the name attribute.
               	    var id     = node.id.replace(wFORMS.idSuffix_fieldHint_popup, '');               	     
					var hinted_pictoaide = document.getElementById(id + wFORMS.idSuffix_fieldHint_pictoaide);
					
					//document.title = id+"-pictoaide"
               	   }
				                      
				   if(hinted) {
					   
					   // is hint placed on a radio group using the name attribute?
					   if(hinted.length > 0 && hinted[0].type=='radio') {
						   
						   var hintedGroup = hinted;
						   l = hinted.length;
					   } else if ( hinted.type == "radio" ) {
						   
						   // pour IE qui voit les radios differement
						   var hintedGroup = wFORMS.processedForm.elements[hinted.name];
						   l = wFORMS.processedForm.elements[hinted.name].length;
						
					   } else {
						   var hintedGroup = new Array(hinted);
						   l = 1;
					   }
					   
					   					   
					   for(var i=0;i<l;i++) {
						   
						   hinted = hintedGroup[i];
														
						   wFORMS.debug('hint/evaluate: '+ (node.id || node.name));
						   switch(hinted.tagName.toUpperCase()) {
							   case 'SELECT':
									wFORMS.helpers.addEvent(hinted,'focus',wFORMS.behaviors['hint'].run);
									wFORMS.helpers.addEvent(hinted,'blur' ,wFORMS.behaviors['hint'].remove);
									if ( typeof(verifchampunique) != "undefined" ) wFORMS.helpers.addEvent(hinted,'change' ,verifchampunique); // add par aurel
									if ( typeof(verifchampunique) != "undefined" ) wFORMS.helpers.addEvent(hinted,'blur' ,verifchampunique); // add par aurel
									break;
							   case 'TEXTAREA':						   
							   case 'INPUT':
									wFORMS.helpers.addEvent(hinted,'focus',wFORMS.behaviors['hint'].run);
									wFORMS.helpers.addEvent(hinted,'blur' ,wFORMS.behaviors['hint'].remove);
									if ( typeof(verifchampunique) != "undefined" ) wFORMS.helpers.addEvent(hinted,'blur' ,verifchampunique); // add par aurel		
 									break;
							   default:
									wFORMS.helpers.addEvent(hinted,'mouseover',wFORMS.behaviors['hint'].run);
									wFORMS.helpers.addEvent(hinted,'mouseout' ,wFORMS.behaviors['hint'].remove);
									break;
						   }
						   
						   
						   
					   }
                   } 
				   if (hinted_pictoaide) {
					   
					   wFORMS.helpers.addEvent(hinted_pictoaide,'click',popupDIV);
				   }
               }
           },

		   
           // run: executed when the behavior is activated
           run: function(e) {
               var element   = wFORMS.helpers.getSourceElement(e);
			   			   
               var fieldHint = document.getElementById(element.id   + wFORMS.idSuffix_fieldHint);
               if(!fieldHint) // try again with the element's name attribute
                   fieldHint = document.getElementById(element.name + wFORMS.idSuffix_fieldHint);
               if(fieldHint) {
				   					
					//var dessus_select = fieldHint.className.indexOf(wFORMS.idSuffix_dessus_select)>0 && browser.isIE  ? true : false;
					var dessus_select 		= fieldHint.className.indexOf(wFORMS.idSuffix_dessus_select)>0 ? true : false;
					var reserrer 			= fieldHint.className.indexOf(wFORMS.idSuffix_reserrer)>0 ? true : false;
				
					if(dessus_select){
	                   	fieldHint.className = fieldHint.className.replace(wFORMS.className_inactiveFieldHint, wFORMS.className_activeFieldHint_ie_select);
					}else {
                   		fieldHint.className = fieldHint.className.replace(wFORMS.className_inactiveFieldHint,wFORMS.className_activeFieldHint);
					}
					
					var hauteurAide = fieldHint.clientHeight
					var margeHaut = dessus_select ? (-26 - hauteurAide) : (-26 - hauteurAide);
				   // Field Hint Absolute Positionning
				   fieldHint.style.top  =  (wFORMS.helpers.getTop(element)+ element.offsetHeight + margeHaut).toString() + "px";
	
					// add par aurelien
				   if(browser.isSafari) fieldHint.style.top  =  (element.offsetTop+ element.offsetHeight + margeHaut).toString() + "px";
				   if(browser.isFF)     fieldHint.style.top  =  (wFORMS.helpers.getTop(element) - 30 + element.offsetHeight + margeHaut).toString() + "px";
				   
				   
				  
					var value_left 																							= element.offsetLeft + 19;
					if (dessus_select) value_left 																			= value_left - 260;
					if (reserrer) value_left 																				= value_left + 50;
					if(element.tagName.toUpperCase() == 'INPUT' && element.type == "radio" && browser.isIE) value_left 	= value_left + 330;
					
					fieldHint.style.left  =  (value_left).toString() + "px"; /* + element.offsetWidth */
				   
				   //ajouter le changement de varible sur la bulle pour faire le focus du champ en dessous
				   
				   	wFORMS.helpers.addEvent(fieldHint,'mouseover', function () { overaide=true; });
					wFORMS.helpers.addEvent(fieldHint,'mouseout' , function () { overaide=false; });
					//wFORMS.helpers.addEvent(fieldHint,'click' , focus_en_dessous_des_bulles_d_aide);
					
				}
			   		if (browser.isIE6up) WCH.Apply(element.id+'-aide', element.id+'-ligne'); // pour IE6 passe le select en dessous
           },
		   
           // remove: executed if the behavior should not be applied anymore
           remove: function(e) {
			
				var element   = wFORMS.helpers.getSourceElement(e);
				
				if (overaide) { focus_en_dessous_des_bulles_d_aide(element);return true; }
			   		   
               var fieldHint = document.getElementById(element.id   + wFORMS.idSuffix_fieldHint);
               if(!fieldHint) // try again with the element's name attribute
                   fieldHint = document.getElementById(element.name + wFORMS.idSuffix_fieldHint);
				   
					//var dessus_select = fieldHint.className.indexOf(wFORMS.idSuffix_dessus_select)>0  && browser.isIE  ? true : false;
					var dessus_select 	= fieldHint.className.indexOf(wFORMS.idSuffix_dessus_select)>0 ? true : false;
					var reserrer		= fieldHint.className.indexOf(wFORMS.idSuffix_reserrer)>0 ? true : false;
				
               if(fieldHint && dessus_select) {
                   fieldHint.className = fieldHint.className.replace(wFORMS.className_activeFieldHint_ie_select,wFORMS.className_inactiveFieldHint);
				   //fieldHint.className = wFORMS.className_inactiveFieldHint;
			   }else{
                   fieldHint.className = fieldHint.className.replace(wFORMS.className_activeFieldHint,wFORMS.className_inactiveFieldHint);
				   //fieldHint.className = wFORMS.className_inactiveFieldHint;
			   }
				   
				if (browser.isIE6up) WCH.Discard(element.id+'-aide', element.id+'-ligne'); // pour IE6 passe le select en dessous
				   
//			   wFORMS.debug('hint/remove: ' + (element.id || element.name) , 5);				   
           }
       }
   }
