/**
* @desc		EVO javascript framework is designed to provide user friendly basic ajax instructions and is based on jquery, www.jquery.com
* @author 	Paul BRIE
* @version	1.058_paul_se_joaca => 1.059 (2008-09-19)
* @date		2007-12-17
* @evo		AL: 1. generalized the callback in load2:
				put the sCallback parameter and verify if the callback come from the DOM object or the function parameter
				2. now you can put the DOM object parameter "callback" to the onchange() function's <select>
* @evo	GP: 1. added callback to updt2
*				2. added url to updt2 (2008-03-19)
*				3. modifications to EVO.submit() -> urlEncodeComponent(value) (2008-04-18)
* @evo	GP: 1. EVO.oTree -> iconopen
* @evo	GP: 1. EVO.createMenus -> default menu loaded, active menu (2008-05-22)
* @evo  AL: 2009-03-17 : EVO.onflyFilterTable used for Table__009 for onfly filter
                         jquery extension with an insensitive Contains selector
                         EVO.confirmation
* @evo  AB: 2009-03-27 :EVO.submit serialize
*/

var EVO = new Object();
//  INTERNAL OBJECT IDENTIFIER ------------------------------------------------------------------ #
	/**
	*   @desc   Each object or process that need internal id will take current value then increment it
	*           Necessary for EVO.oTree
	*/
	EVO.nInternalId = 0;
	
	EVO.getInternalId = function (){
		var nInternalId = EVO.nInternalId;
		EVO.nInternalId++;
		return nInternalId;
	}

//  PARAMS OF THE FRAMEWORK --------------------------------------------------------------------- #
	EVO.sVersion = "0.001";
	EVO.sPath = "";
	EVO.sTimeout = "30000";  // default
	EVO.oOnfly =
			{ success : false,   //true if the last onfly update was with success 
			  successFunction : ""}
	EVO.lockedObj = "";   // last locked object bnfEVO.updt2() (onfly)
//  VARIABLES ----------------------------------------------------------------------------------- #
	EVO.oDays = {
		fr : new Array('dimanche','lundi','mardi','mercredi','jeudi','vendredi','samedi'),
		en : new Array('sunday','monday','tuesday','wednesday','thursday','friday','saturday')
	};
	EVO.oMonths = {
		fr : new Array('janvier','février','mars','avril','mai','juin','juillet','août','septembre','octobre','novembre','décembre'),
		en : new Array('january','february','march','april','may','june','july','august','september','october','november','december')
	};

//  DATE ---------------------------------------------------------------------------------------- #
	EVO.dateTime = function(oObj){  
		var sLang = 'fr';//default
		if(oObj){
			sLang = oObj.lang;
		}  
		var oDate = new Date();
		/*return EVO.oDays[sLang][oDate.getDay()]+' '+
			   oDate.getDay()+' '+
			   EVO.oMonths[sLang][oDate.getMonth()]+' '+
			   oDate.getFullYear()+' '+    */
		return oDate.getHours()+':'+
			   oDate.getMinutes()+':'+
			   oDate.getSeconds()+':'+
			   oDate.getMilliseconds();
	}
//  DEBUG --------------------------------------------------------------------------------------- #
	EVO.dbg = function(osElement){
		if($(osElement).length > 0){
			EVO.dbgTarget = osElement;
			$(osElement).append("<div id='debug'>"+
									'<hr />'+
									'<b>Aelythe Evo '+EVO.sVersion+'</b>'+
									"<table id='a_debug_list' class='debug'></table>"+
									'</div>'); 
			$(osElement).toggle();
			EVO.dbgListen();
		} else {
			alert('target element not found! This element is necessary to show debug.');
		}
	}

	EVO.dbgListen = function(e){ 
		document.onkeypress = function(e){
				sNavigator = navigator.userAgent.toLowerCase();
				var bAlt = false;
				var nKey = "";
				if(sNavigator.indexOf("msie") >= 0){ 
					nKey = event.keyCode;
				} else if(sNavigator.indexOf("firefox") >= 0){
					nKey = e.keyCode;
				}
				if(nKey == 27){
					$(EVO.dbgTarget).toggle();
				}
			}
	}

	EVO.dbgList = function(sType,sUrl,sColor){
		$('#a_debug_list').prepend("<tr><td style='color:"+sColor+"'>"+sType+"</td><td>"+EVO.dateTime()+"</td><td>"+sUrl+"</td></tr>");
	}

	EVO.dbgEvent = function(sType,sColor){
		$('#a_debug_list').prepend('<tr><td style=\'color:'+sColor+'\'>'+sType+'</td><td>'+EVO.dateTime()+'<r>d><td></td></tr>');
	}

//  MESSAGE ------------------------------------------------------------------------------------- #
	EVO.msg = function(sMessage,osTarget,nMilliseconds,sType){
		if(sType.length > 0){                           // message appears only if set
			// color of the message
			var sColor;
			if(sType == 'u'){
				sColor = '#FF8000';
			} else if (sType == 'i'){
				sColor = 'green'; 
			} else if (sType.substr(0,1) == 'e'){
				sColor = 'red'; 
			}
			$(osTarget).html("<span style='font-weight:bold;color:"+sColor+"'>"+sMessage+"</span>");
			sString = "$('"+osTarget+"').html('');";
			setTimeout(sString,nMilliseconds); 
		}
	}

//  ON CHANGE VALUE OF A SELECT ----------------------------------------------------------------- #
	EVO.onchange = function(osElement){
		var sCallback = '';
		sParams         = 'selid=' + $(osElement).attr('selid');    // unique ID for a select  
		sParams         += '&value=' +  $(osElement).attr('value'); // the current choosen value    
		sParams         += '&recid=' +  $(osElement).attr('recid'); // the record id on which we apply changes
		
		if($(osElement).attr('callback')) sCallback = $(osElement).attr('callback');          // detected callback
		
		EVO.load2('',EVO.sPath + 'onflyselect.php',sParams,'',$(osElement).children(".select"),'',sCallback);
	}

//  LOAD ---------------------------------------------------------------------------------------- #
    EVO.loader_stack = 0;
    EVO.sLoaderType = 'modal';//modal or target
    EVO.load2 = function(osElement,sUrl,sParams,sMethod,sTarget,sTimeout,sCallback,sLoaderType){  
        var sDefLoadTarget = '#load';
        var sMessageId;                                      //  set a variable for the Message node
        var sUrl;
        var sParams;
        var sMethod; 
        var sTimeout;
        var sCallback;
        
        //show
        //EVO.loader('show');
        
        if(sUrl == undefined || sUrl == ''){
            sUrl = $(osElement).attr('url');                // detected url
        }
        //alert(sUrl);
        if(sParams == undefined || sParams == ''){
            sParams = $(osElement).attr('params')+"&internDateTime="+EVO.dateTime();          // detected params
        }  
        if(sMethod == undefined || sMethod == '' ){
            sMethod = $(osElement).attr('method');          // detected method
            if(sMethod == undefined || sMethod ==''){
                sMethod = 'POST';
            }
        }
        if(sTarget == undefined || sTarget ==''){
            sTarget = $(osElement).attr('target');          // detected method
        } else {
            sTarget = sTarget;  // added 20071001 PB
        }
        
        //  PB 20090310 --- start
        //  this enhancement allows to simulate of the keyword this in the target attribute and transform
        //  the string 'this' in this as an object (current node)
        if(sTarget == 'this'){
            sTarget = osElement;
        }
        //  PB 20090310 --- end
        
        //alert(sTarget); 
        if(sTimeout == undefined || sTimeout == '' ){
            sTimeout = $(osElement).attr('timeout');          // detected timeout
            if(sTimeout == undefined || sTimeout ==''){
                sTimeout = EVO.sTimeout;
            }
        } 
        //callback function  to call after request ended
        if(sCallback == undefined || sCallback ==''){
            sCallback = $(osElement).attr('callback');          // detected callback
        }
        //loader type: modal or inside target
        if(sLoaderType == undefined || sLoaderType ==''){
            sLoaderType = $(osElement).attr('loadertype');          // detected callback
        }
        if(sLoaderType == undefined || sLoaderType ==''){
            sLoaderType = EVO.sLoaderType;          // default callback
        }

        var nTimeout = parseInt(sTimeout);
          
        if($(osElement).attr('message') == 'null' || $(osElement).attr('message') == ''){
            sMessageId = sDefLoadTarget;                        //  if none is set use default 'message'
        } else {
            sMessageId = sTarget;
        }
        
        $.ajax({
                url: sUrl,
                data: sParams, // detected parameters
                type: sMethod,
                dataType: 'html',
                timeout: nTimeout,
                error: function(object,message){
                    $(sMessageId).html("<span style='color:red;'>Erreur de chargement! "+message+"</span>");
                    EVO.dbgList('error',sUrl+' - bad file or loading problem'+object,'red');
                },
                success: function(html){
                    //$(sTarget).html('');   // detected target
                    $(sTarget).html(html);   // detected target
                    $(sDefLoadTarget).html("");
                    EVO.dbgList('success','url:'+sUrl,'green');
                    if(sCallback) try{eval("" + sCallback + "");}catch (e) {};
                },
                complete: function(){
                    EVO.loader_stack --;
                    EVO.loader('hide',200); 
                    EVO.writeToDbg("<br/>Loader Stack --: "+EVO.loader_stack);   
                }, 
                beforeSend: function(){
                    if(sLoaderType=='modal')
                    {
                        EVO.loader('show');
                    }
                    else if (sLoaderType=='target')
                    {
                        $(sTarget).html('Loading html...');
                        $(sMessageId).html("<img src='" + EVO.sPath + "img/load.gif' border='0' alt='chargement' />");
                    }
                    EVO.dbgList('ask','url:'+sUrl+' - params:'+sParams+' - method:'+sMethod+' - target:'+sTarget,'blue');
                }
        });
    }
    
    EVO.writeToDbg = function(text)
    {
        $('#dbg').append(text);//"<br/>Loader stack: "+EVO.loader_stack);
    }
    
    EVO.setLoaderHeight = function()
    {
        $('#loader').css('height',$(document).height());
    }
    
    EVO.loader = function(action,timeout)
    {
         if($('#loader').length>0)
         {
            if(action=='hide')
            {
                /*if(EVO.loader_stack==0)
                {
                    if(timeout>0) setTimeout("$('#loader')."+action+"();",timeout);
                    else $('#loader').hide();
                } */
                //stop the loader when all ajax requests ended
                $("#loader").ajaxStop(function(){
                   $(this).hide();
                }); 
            }
            else
            {
                EVO.setLoaderHeight();
                $('#loader').show();
                EVO.loader_stack++;
                EVO.writeToDbg("<br/>Loader Stack ++: "+EVO.loader_stack);
            }
         }
    }

//  SUBMIT ---------------------------------------------------------------------------------------- # 
	EVO.submit = function(osElement){
    
		$(osElement).attr('method','post'); // force the method

		var sUrl = $(osElement).attr('action');               // detected url
		var sParams = $(osElement).attr('params')+'&';        // detected params
		var aParams = new Array();                            // in this array we will keep the params (in this format: parameter_name=parameter_value)
		var nNrParams = 0;                                    // nr of parameters
       try
       {
            /*$(osElement)
            .find("input, select, textarea")
            .filter(":enabled")
            .each(function(){
            //ert($(this).attr('value'));
            if($(this).attr('value')!=undefined) sValue = encodeURIComponent($(this).attr('value'))//);//asl($(this).attr('value'));//escape(encodeURI());    //.replace(/\n/g,"\r\n");
            else sValue = "";
            aParams[nNrParams] = $(this).attr('name') + "=" + sValue;         //save the parameter
            nNrParams++;   // increase the number of parameters
            });

            sParams += aParams.join("&");        // join parameters in string, separate with '&'
            */
                    sParams += $(osElement).serialize();
            //sParams += '&value='+sValue;
                    //alert(sParams);
            EVO.load2(osElement,sUrl,sParams);
       }
       catch(e) {}
       return false;
	}

//  DATA ON FLY MANIPULATION -------------------------------------------------------------------- #
	EVO.updt = function(osElement){
		//  if the actual element is not "locked" and there is no input or textarea activated(with id '#locked')
		if($(osElement).attr('status') != 'locked' && $('#locked').length == 0){;
			// lock of the element : no other element can be modified until this is unlocked
			$(osElement).attr({status:"locked"});
			//  puts the data into an input 
			//$(osElement).html("<input id='locked' type='text' name='' value='" + $(osElement).html() + "' />");
			$(osElement).html("<textarea id='locked' style='background-color:#FFFFC0'>" + $(osElement).html() + "</textarea>");
		} else if($(osElement).attr('status') == 'locked'){
			//  generate the param string for the query
			var sValue = escape($('#locked').attr('value'));
			if(sValue == 'undefined'){
				sValue = '';
			}
			//  DEBUG // $('#message').html(sParams);
			sParams     = 'value=' + sValue;
			sParams     += '&tbl=' + $(osElement).attr('tbl');
			sParams     += '&fld=' + $(osElement).attr('fld');
			sParams     += '&idfld=' + $(osElement).attr('idfld');
			sParams     += '&recid=' + $(osElement).attr('recid');
			sParams     += '&type=' + $(osElement).attr('type');
			sParams     += '&fx=' + $(osElement).attr('fx'); 
			EVO.load2('',EVO.sPath + 'onfly.php',sParams,'',osElement,'');
			//$(osElement).html($('#locked').attr('value'));
			$(osElement).attr({status:""});
		}
	}

//  DATA ON FLY MANIPULATION WITH ONFLY TABLE-------------------------------------------------------------------- #
	EVO.updt2 = function(oObj){
		var oElement;
		var bIsDomParameter;      // true - Dom object, false - Javascript object
		  
		// verify the object parameter type: javascript object or dom object, and set the oElement
		if ($(oObj)[0].tagName == undefined || $(oObj)[0].tagName == 'undefined')
		{
			oElement = oObj.domElement;
			bIsDomParameter = false;
		}
		else
		{
			oElement = oObj;
			bIsDomParameter = true;
		}   
		EVO.lockedObj = oElement;
		//  if the actual element is not "locked" and there is no input or textarea activated(with id '#locked')
		if($(oElement).attr('status') != 'locked' && $('#locked').length == 0){;
			// lock of the element : no other element can be modified until this is unlocked
			$(oElement).attr({status:"locked"});
			
			//  puts the data into an input
			switch ($(oElement).attr('type'))
			{
				case 'text':
					$(oElement).html("<input id='locked' type='text' name=''  style='background-color:#FFFFC0' value='" + $(oElement).html() + "' />");
					break;
				case 'datepicker':
					$(oElement).html("<input id='locked' type='text' name=''  style='background-color:#FFFFC0' value='" + $(oElement).html() + "' />");
					//$('#locked').calendar({autoPopUp: 'focus', yearRange: '-5:+5'});
					break;
				default:     // textarea
					// previous version
					//$(oElement).html("<textarea id='locked' style='background-color:#FFFFC0;"+$(oElement).attr('style')+"'>" + $(oElement).html() + "</textarea>");
					$(oElement).html("<textarea id='locked' class='"+$(oElement).attr('class')+"' style='background-color:#FFFFC0;"+$(oElement).attr('style')+";"+$(oElement).attr('textareastyle')+"'>" + $(oElement).html() + "</textarea>");//.css('width',$(oElement).offsetWidth).css('height',$(oElement).offsetHeight)
			}
			
		} else if($(oElement).attr('status') == 'locked'){
			//  generate the param string for the query
			var sValue = escape($('#locked').attr('value'));
			if(sValue == 'undefined'){
				sValue = '';
			}
			//  DEBUG // $('#message').html(sParams);
			sParams     = 'value=' + sValue; 
			sParams     += '&onfid=' + $(oElement).attr('onfid');
			sParams     += '&recid=' + $(oElement).attr('recid');
			sParams     += '&recid2=' + $(oElement).attr('recid2');
			sParams     += '&datatype=' + $(oElement).attr('datatype');
			sParams     += '&fx=' + $(oElement).attr('fx');
			sParams     += '&callback=' + $(oElement).attr('callback');
			var sCallback;
			sCallback = $(oElement).attr('callback');
			if(sCallback == 'undefined') sCallback = '';

			// if we have a success function
			if (!bIsDomParameter)
			{
				EVO.oOnfly.success = false;
				EVO.oOnfly.successFunction = oObj.onSuccess;
			}
			var url = 'onfly2.php';
			if($(oElement).attr('url')) url = $(oElement).attr('url');
			EVO.load2('',EVO.sPath + url,sParams,'',oElement,'',sCallback);
			//$(oElement).html($('#locked').attr('value'));
			$(oElement).attr({status:""});

			// if we have a success function
			if (!bIsDomParameter)
			{
				setTimeout("if(EVO.oOnfly.success){EVO.oOnfly.successFunction();EVO.oOnfly.success = false;}",1000);
			}
		}
	}

//  AUTOMATIC SELECT ACTIONS -------------------------------------------------------------------- #
	EVO.sendValue = function(osElement){
		//alert($(osElement).attr('value'));
		sName       = $(osElement).attr('name');     
		sParams     = sName + '=' + $(osElement).attr('value');
		sUrl        = $(osElement).attr('url');
		soTarget    = $(osElement).attr('target');
		EVO.load2('',sUrl,sParams,'',soTarget,'');
	}
	
//  LAYOUT -------------------------------------------------------------------------------------- #
	EVO.showHide = function(osElement,display){
		
		if($(osElement).css('display') == 'none'){
			$(osElement).show("slow");
		} else {
			$(osElement).hide("slow"); 
		}
		//alert($(osElement).css('display'));
	}

	EVO.rollOverCss = function(osElement,sClassName){
		$(osElement).className = sClassName;
	}

//  WIDGET -------------------------------------------------------------------------------------- #
	EVO.createMenus = function(sDefault){
		/**
		*   @desc   We will scan all the document and search for menus elements
		*/
		try{
			var currenthash = parent.location.hash.replace('#','');
			sDefault = 'div_menu_'+currenthash;
			if($('#'+sDefault).html()==null)
			{
				if(defaultMenu==undefined) sDefault = undefined;
				else sDefault = defaultMenu;
			}
		}catch(e){};
		
		var oAllDivElements = $('div');                              // alls div list
		for(i = 0;i < oAllDivElements.length; i++){                  // scanning the div list...
			if(oAllDivElements[i].getAttribute('type') == 'menu'){   // if type is 'menu'
				var oMenu   = oAllDivElements[i].getElementsByTagName("div");  // we scan the menu items
				var sMenuid = oAllDivElements[i].getAttribute("id");
				//alert(sMenuid);
				var sMenu   = "<table border='0' cellpadding='0' cellspacing='0'><tr>";
				for(j = 0 ;j < oMenu.length;j++){                    // create menu items
					var sOnClick = oMenu[j].getAttribute("onclick");
					sMenu += "<td class='menuItem";
					//$('#message').append(oMenu[j].getAttribute('id')+"\t");
					if(sDefault!=undefined && sDefault==oMenu[j].getAttribute('id'))
					{
						sMenu += " menuActive";
					}
					sMenu += "' ";
					//sMenu += " ondblclick='EVO.debug(this.parentNode);'";
					sMenu += " target='" + oMenu[j].getAttribute('target') + "'";
					sMenu += " url='" + oMenu[j].getAttribute('url') + "'";
					sMenu += " params='" + oMenu[j].getAttribute('params') + "'";
					sMenu += " method='" + oMenu[j].getAttribute('method') + "'";
					sMenu += " timeout='" + oMenu[j].getAttribute('timeout') + "'";
					sMenu += " message='" + oMenu[j].getAttribute('message') + "'";
					sMenu += " id='smenu_" + oMenu[j].getAttribute('id') + "'";
					sMenu += " hash='" + oMenu[j].getAttribute('hash') + "'";
					if(sOnClick==undefined) sMenu += " onclick=\"EVO.load2(this);\"";
					else sMenu += " onclick=\""+sOnClick+"\"";
					sMenu += " >" + oMenu[j].innerHTML + '</td>';
				}
				//  render the menu
				with(oAllDivElements[i]){ // create the menu
					innerHTML = "<div class='menu'>" + sMenu + "</tr></table></div>"; // + "<div class='menuShadow' />"; 
					//style.width     = '100%';
					//style.height    = '100px';
				}
				//  hover and click effect
				$(document).ready(function() {
					//hover effect
					$("#" + sMenuid + " div table tr > td").hover(function() {
						try{
							if(sDefault!=undefined && $(this).attr('id')=='smenu_'+sDefault) $(this).addClass("menuActive");
							$(this).addClass("menuItem menuOver");
						}catch(e){};
					},function(){
						try{
							$(this).removeClass("menuOver");
						}catch(e){};
					});
					//click effect
					$("#" + sMenuid + " div table tr > td").click(function() {
						try{
							sDefault = undefined;
							parent.location.hash = ''+$(this).attr('hash');
							$("#" + sMenuid + " div table tr > td").removeClass("menuActive");
							$(this).addClass("menuItem menuActive");
						}catch(e){};
					});
					//onload effect
					try{
						if(sDefault!=undefined)
						{
							parent.location.hash = ''+$('#smenu_'+sDefault).attr('hash');
							EVO.load2('#smenu_'+sDefault);
						}
					}catch(e){};
				});
			}
		}
	}

//  DATA ---------------------------------------------------------------------------------------- #
	EVO.test = function(oThisNode){
		//  ! : works only with input, textarea elements and group of checkboxes yet
		//  get the parameters first
        var oFormItems;
		with($(oThisNode)){
			var sId         = attr('id');
			var sType       = attr('type');
			var sGroup      = attr('group');
			var sDestination= attr('target');
		}
		switch (sType) 
		{
			case 'text':  // input-text
			case 'textarea':      // textarea
				// if is not set the empty attribute, it will be set to false
				if ($(oThisNode).attr('empty') == undefined){
					$(oThisNode).attr({empty:'false'});
				}
				with($(oThisNode)){
					var sRegexp     = attr('regex');  //  regular expression 
					var sEmpty      = attr('empty');  //   true - empty field validation is activ, false - oherwise
					var sText       = attr('value');  //  text to be evaluated
				}
				//  create regexp
				eExpression = new RegExp(sRegexp,'g');
				if(sText != undefined)
				{
					bResult = sText.search(eExpression);
				} else
				{
					// the value attribute is empty
					if(sEmpty == 'true') { 
						bResult = -1;
					}
					else
					{
						bResult = 1;
					}
				} 
				
				// if empty field validation is activ then set the message visibility
				if(sEmpty == 'true')
				{
					if (bResult == -1)
					{
						$('#'+sId+' + span').css('visibility','visible'); 
					}
					else
					{
						$('#'+sId+' + span').css('visibility','hidden');
					}
				}
				// check the current value... (validation result store in test attribute: true - current value is valid, false - otherwise)
				if(bResult == -1){
					$(oThisNode).css('color','#B90000');
					$(oThisNode).attr({test:"false"});
				} else {   
					$(oThisNode).css('color','#008000');
					$(oThisNode).attr({test:"true"});
				}
				break;

			case 'checkbox':
				alert('test checkboxes'); 
				//  if no checkbox is selected we will give false to test attribute of element with id: <sGroup>_hidden
				var sFinalStatus;
				oFormItems = $('*[group='+sGroup+'][type!=submit]:checked');
				if(oFormItems.length != 0){
					$('#'+sGroup+'_hidden').attr({test:"true"});                  // found selected checkbox, test = true 
					$('#'+sGroup+'_hidden + span').css('visibility','hidden');    // hide the error message
				} else {
					$('#'+sGroup+'_hidden').attr({test:"false"});                 // not found selected checkbox, test = false
					$('#'+sGroup+'_hidden + span').css('visibility','visible');   // show the error message
				}

				// change the sGroup from the checkboxes's group to the form's group
				sGroup = $('#'+sGroup+'_hidden').attr('group');
				
				break;
			//added by SC
			case 'password':
				
				if ($(oThisNode).attr('value') != undefined)
				{               
					if ($(oThisNode).attr('value').length < 6)
					{   
						bResult = -3;
					}
					else
					{
						bResult = 1;
						var aAllInputPassword = $('input[group='+sGroup+'][type=password]')
						for (i=0;i<aAllInputPassword.length;i++)
						{                        
							if (($(aAllInputPassword[i]).attr('value') != undefined)&&($(aAllInputPassword[i]).attr('value') != $(oThisNode).attr('value')))
							{
								bResult = -2;
							}
						}
					}
				}
				else
				{
					bResult = -1;
				}
				
				if (bResult == -1)
				{
					$('#'+sId+' + span').css('visibility','visible'); 
					$('#'+sId+' + span').html('empty field');
					$(oThisNode).css('color','#B90000');
					$(oThisNode).attr({test:"false"});
				} 
				else if (bResult == -2)
				{
					$('#'+sId+' + span').css('visibility','visible');
					$('#'+sId+' + span').html('not the same password');
					$(oThisNode).css('color','#B90000');
					$(oThisNode).attr({test:"false"});
				}
				else if (bResult == -3)
				{
					$('#'+sId+' + span').css('visibility','visible');
					$('#'+sId+' + span').html('password should have minimum 6 characters');
					$(oThisNode).css('color','#B90000');
					$(oThisNode).attr({test:"false"});
				}
				else
				{
					$('#'+sId+' + span').css('visibility','hidden');
					$(oThisNode).css('color','#008000');
					$(oThisNode).attr({test:"true"});
				}
				break;
		}
		//  if only one field has a false verification we disable the submit button
		var sFinalStatus;
		oFormItems = $('*[group='+sGroup+'][type!=submit][test=false]');
        if(oFormItems.length == 0){
            sFinalStatus = true;
		} else {
			sFinalStatus = false;
		}
		if(sFinalStatus != false){
			$('input[group='+sGroup+'][type=submit]').attr({disabled:""});
		} else {
			$('input[group='+sGroup+'][type=submit]').attr({disabled:"disabled"});
		}
	}

//  HOVER for .updt ----------------------------------------------------------------------------- #
	EVO.hoverUpdt = function(){
		$('td.updt').hover(function(){
		   $(this).addClass("coin_hd");
		 },function(){
		   $(this).removeClass("coin_hd");
		 });
	}

//  SELECT ALL CHECKBOXES ----------------------------------------------------------------------- #
	EVO.selectAll = function(oThisNode){
		/**
		*   @desc   We will change the checked status for all the checkboxes having the name sCheckboxName, with the new status gived by the checkbox with id sCheckboxId
		*/
		with($(oThisNode)){
			var sCheckboxId         = attr('sId');
			var sCheckboxName       = attr('sName');
		}
		alert('ID '+sCheckboxId+' Name '+sCheckboxName);
		$(document).ready(function(){  
			$('#'+sCheckboxId).click(function(){
				var checked_status = this.checked;
				$('input[name*='+sCheckboxName+']').each(function(){
					$(this).attr({checked:checked_status});
				});  
				alert($(oThisNode).attr('success'));
			});
		});
	}
//  TREE WIDGET --------------------------------------------------------------------------------- //
	EVO.oTree = new Object();                                                                     //
	/**                                                                                           //
	*   @desc   This object will construct a tree view starting from :                            //
	*           - a given node in the dom (discovery mode)                                        //
	*           - a list of organised nodes with stamp and pstamp atributes (list mode)           //
	*           For each node, you can specify following options using atributes in source nodes  //
	*           - icon : will show a specific node for a node - ex icon='myicon.png'              //
	*           - display : if set to 'none' will hide all children  - ex display='none'          //
	*               if the atribute is missing all children will be visible                       //
	*           - count : count number of children - ex : count='yes'                             //
	*           - fx : will allow you to pass to the tree javascript actions to be executed on    //
	*               onclick actions                                                               //
	*               ex : fx="alert('ok');"                                                        //
	*           The delicate part was about initiating counting and display from a child towards  //
	*           his parent                                                                        //
	*   @author PB
	*   @version 1.0
	*   @date  20080323
	*/
	/**
	*   @desc   The following array is used to count each node in normal mode (discovery)
	*/
	EVO.oTree.aTreeIdNodeCounter = new Array();
	
	/**
	*   @desc   This function counts following children
	*/
	EVO.oTree.fxCountChildren = function(oNode){ 
		//alert($(oNode).html());
		$(oNode).children('span').children('span').children('span').html('('+$(oNode).children('div[countme!=no]').length+')');
	} 
	
	/**
	*   @desc   Show or hide children nodes
	*/
	EVO.oTree.fxHideChildren = function(osElement){ 
		$(osElement).filter('div').css('display','none');
	}
	
	/**
	*   @desc   Builds icons for the tree
	*/
	EVO.oTree.fxIcons = function(oNode){
		if($(oNode).attr('icon') && $(oNode).attr('iconopen')){
			if($(oNode).css('display')=='none') sIcon = "<img src='"+$(oNode).attr('iconopen')+"' icon='"+$(oNode).attr('icon')+"' iconopen='"+$(oNode).attr('iconopen')+"'/>";
			else sIcon = "<img src='"+$(oNode).attr('icon')+"' icon='"+$(oNode).attr('icon')+"' iconopen='"+$(oNode).attr('iconopen')+"'/>";
		}
		else if($(oNode).attr('icon')){
			sIcon = "<img src='"+$(oNode).attr('icon')+"' icon='"+$(oNode).attr('icon')+"' iconopen='"+$(oNode).attr('icon')+"'/>";
		} else { // else default icons...
			if($(oNode).children().length > 0)
			{
				if($(oNode).css('display')=='none') sIcon = "<img src='images/folder.png' icon='"+$(oNode).attr('icon')+"' iconopen='"+$(oNode).attr('icon')+"'/>";
				else sIcon = "<img src='images/folder_open.png' icon='"+$(oNode).attr('icon')+"' iconopen='"+$(oNode).attr('icon')+"'/>";
			}
			else
			{
				sIcon = "<img src='images/page_white_text.png' />";
			}
		}
		return sIcon;
	}

	EVO.oTree.fxBuild = function(oSource,oContainer,nInternalId,sStamp){
		//  ex : EVO.oTree.fxBuild('#source','#target'); 
		//  !!! sStamp is an internall variable, you must not use it!
		//  !!! nInternalId is an internal variable, you must not use it!
		/*  INTERNAL ID ----------------------------- */   
		if(typeof(nInternalId) == 'undefined'){
			nInternalId = EVO.getInternalId();
			EVO.oTree.aTreeIdNodeCounter[nInternalId] = 0; 
			var sStamp = nInternalId+'_'+EVO.oTree.aTreeIdNodeCounter[nInternalId];
			$(oContainer).attr({'stamp':sStamp});
			setTimeout("EVO.oTree.fxShowHide('div[stamp="+sStamp+"] span img')",500);
		}

		var sParentStamp = sStamp;  // set the parent stamp for following children
		$(oSource).each(function(){ 
			EVO.oTree.aTreeIdNodeCounter[nInternalId]++;
		/*  GET THE TEXT ---------------------------- */
			var sText;
			if(this.firstChild){
				var sText = this.firstChild.nodeValue;
			}

		/*  BUILD ICON ------------------------------- */
			var sIcon = EVO.oTree.fxIcons(this);
			
		/*  SET A NEW ID    -------------------------- */    
			var sStamp = nInternalId+'_'+EVO.oTree.aTreeIdNodeCounter[nInternalId];
			
		/*  CREATE THE NODE ------------------------ */
			var sNode = "<div count_children='"+$(this).attr('count')+"' "+
							 "countme='"+$(this).attr('countme')+"' "+
							 "stamp='"+sStamp+"' "+
							 "pstamp='"+sParentStamp+"'>"+
							 "<span>"+sIcon+
								 "<span> "+sText+" "+
									 "<span></span>"+
								 "</span>"+
							 "</span>"+
						"</div>";

		/*  APPEND THE NODE -------------------------- */
			$('div[stamp='+sParentStamp+']').append(sNode);
			
		/*  ACTIONS -------------------------------- */
			if($(this).attr('fx')){
				var sEvent = $(this).attr('fxevent');
				var sFx = $(this).attr('fx');
				//  next line does not work in IE7
				//$('div[stamp='+sStamp+'] span span').attr($(this).attr('fxevent'),$(this).attr('fx')).css('cursor','pointer');
				$('div[stamp='+sStamp+'] span span').css('cursor','pointer');
				$('div[stamp='+sStamp+'] span span').click(function(){
					eval(sFx);
				})
				//$('div[stamp='+sStamp+']').attr({$(this).attr('fxevent'):($(this).attr('fx'))});
			}

		/*  COUNT CHILDREN OPTION ------------------ */
			if($("div[stamp="+sStamp+"]").parent().attr('count_children') == 'yes'){
				EVO.oTree.fxCountChildren($("div[stamp="+sStamp+"]").parent());
			}

		/*  DISPLAY -------------------------------- */
			if($(this).parent().attr('display') == 'none'){
				EVO.oTree.fxHideChildren('div[stamp='+sStamp+']');
			}
			
		/*  RECURSIVE PARSING ---------------------- */
			if($(this).children().length > 0){   
				EVO.oTree.fxBuild($(this).children(),oContainer,nInternalId,sStamp);
			}
		});

		EVO.oTree.fxShowHide = function(osElement){
			// osElement is here the full list of span tags
			$(osElement).each(function(){
				// memorise locally the span
				var oCurrentNode = $(this);
				$(this).click(function(){
					//$(oCurrentNode).parent().children('div').css({'background-color':'red'});
					$(oCurrentNode).parent().parent().children('div').toggle();
					
					//get icon
					var sImgIcon = $(oCurrentNode).filter('img').attr('icon');
					var sImgIconOpen = $(oCurrentNode).filter('img').attr('iconopen');
					
					//set icon
					if($(oCurrentNode).parent().parent().children('div').css('display')=='none')
					{
						if(sImgIcon!=undefined) $(oCurrentNode).filter('img').attr('src',''+sImgIcon);
						else $(oCurrentNode).filter('img').attr('src','images/folder.gif');
					}
					else
					{
						if(sImgIconOpen!=undefined) $(oCurrentNode).filter('img').attr('src',''+sImgIconOpen);
						else $(oCurrentNode).filter('img').attr('src','images/folder_open.gif');
					}
					//alert($(oCurrentNode).filter('img').html());/*:'folder.png'});*/
				})
			})
		}
	}

	EVO.oTree.fxBuildNumbered = function(oSource,oContainer){
		if(!$($(oSource)[0]).attr('pstamp')){
			alert('EVO.oTree.fxBuildNumbered : can not find pstamp attr.!');
		}

		var nInternalId = EVO.getInternalId();
	   
		var sStamp = nInternalId+'_'+$(oSource).attr('pstamp');
		$(oContainer).attr({'stamp':sStamp}); 
		setTimeout("EVO.oTree.fxShowHide('*[stamp="+sStamp+"] span img')",500);
		$(oSource).each(function(){
		/*  GET THE TEXT ---------------------------- */
			var sText;
			if(this.firstChild){
				var sText = this.firstChild.nodeValue;
			}

		/*  BUILD ICON ------------------------------- */
			var sIcon = EVO.oTree.fxIcons(this);
		 
			var sStamp = nInternalId+"_"+$(this).attr('stamp');
			var sParentStamp = nInternalId+"_"+$(this).attr('pstamp');
		 
			var sNode = "<div display_children='"+$(this).attr('display')+"' "+
							 "count_children='"+$(this).attr('count')+"' "+
							 "stamp='"+sStamp+"' "+
							 "pstamp='"+sParentStamp+"'>"+
							 "<span>"+sIcon+
								 "<span>"+sText+
									"<span></span>"+
								 "</span>"+
							 "</span>"+
						"</div>";

		 /*  APPEND THE NODE -------------------------- */
			$('div[stamp='+sParentStamp+']').append(sNode);
			
		 /*  DISPLAY -------------------------------- */
			if($('div[stamp='+sParentStamp+']').attr('display_children') == 'none'){
				EVO.oTree.fxHideChildren('div[stamp='+sStamp+']');
			} 
			
		 /*  COUNT CHILDREN OPTION ------------------ */
			if($("div[stamp="+sStamp+"]").parent().attr('count_children') == 'yes'){
				EVO.oTree.fxCountChildren($("div[stamp="+sStamp+"]").parent());
			}
			
		/*  ACTIONS -------------------------------- */
			if($(this).attr('fx')){
				var sEvent = $(this).attr('fxevent');
				var sFx = $(this).attr('fx');
				$('div[stamp='+sStamp+'] span span').css('cursor','pointer');
				$('div[stamp='+sStamp+'] span span').click(function(){
					eval(sFx);
				})
			}
		})
	}
    
//  CODE BUILDER -------------------------------------------------------------------------------- #
    EVO.oCode = new Object();    
    EVO.oCode.fxShow = function(){
        var sCodeTagId = 'EVO_code_helper';
        if($('#EVO_code_helper').length == 1){
            $('#EVO_code_helper').toggle();
        } else {
            $(body).prepend("<div style='position:absolute;top:0px;left:0px;z-index:1000;background-color:white;width:600px;height:200px;border:1px solid black;' id='"+sCodeTagId+"'></div>");
            setTimeout("EVO.load2('','js/help/"+EVO.sVersion+".html','','','#"+sCodeTagId+"');",500);
            //alert("EVO.load2('','js/help/"+EVO.sVersion+".html','','#"+sCodeTagId+"')");
        }
    }    
    
    EVO.oCode.fxListen = function(e){ 
        document.onkeypress = function(e){
                sNavigator = navigator.userAgent.toLowerCase();
                var bAlt = false;
                var nKey = "";
                if(sNavigator.indexOf("msie") >= 0){ 
                    nKey = event.keyCode;
                } else if(sNavigator.indexOf("firefox") >= 0){
                    nKey = e.keyCode;
                }
                //alert(nKey);
                if(nKey == 27){ // escape
                    EVO.oCode.fxShow();
                }
            }
    }
      
      
    // AL: extend jquery with an insensitive contains selector
    $.extend($.expr[":"], {  
         "Contains": function(elem, i, match, array) {  
             return (elem.textContent || elem.innerText || "").toLowerCase  
     ().indexOf((match[3] || "").toLowerCase()) >= 0;  
         }  
     });  
    
    EVO.onflyFilterTable = function(oNode,sTableId){  
         // detect the navigator and set the display property value
         sNavigator = navigator.userAgent.toLowerCase();
         var sDisplay = "";
         if(sNavigator.indexOf("msie") >= 0){ 
            sDisplay = "block";
         } else if(sNavigator.indexOf("firefox") >= 0){
            sDisplay = "table-row"; 
         } else {
            sDisplay = "block";
         }
         // current filter
         var sValue = $(oNode).attr('value');
         
         // hide tr
         $("#"+sTableId+" td[onflyfilter='true']:not(Contains('"+sValue+"'))").parent().css('display','none');
         $("#"+sTableId+" td[onflyfilter='true']:Contains('"+sValue+"')").parent().css('display',sDisplay);    
           
    }
    
    EVO.confirmation = function(oNode,sMsg){
        if (confirm(sMsg)) { 
            EVO.load2(oNode);
        }
    }
