var g_activeEl;
var g_ID_COUNT = 0;
var g_modalChild;
var g_lastOpenedWnd = null;
var g_Window_Height = null;
var g_Window_Width = null;
var g_MAX_WAIT = 10;
var g_NB_WAIT = 0;

function centerWindow(wnd, w, h)
{
	g_Window_Height = h;
	g_Window_Width = w;
	g_lastOpenedWnd = wnd;	
	
	var mh = 100;           // default height
	var mw = 100;           // default width

  	if( g_lastOpenedWnd == null )
    	return null;

	if( isWindowReady(g_lastOpenedWnd) == false )
	{
		waitForWindowCreation();
		return wnd;
	}	

  	// window border size
	var scrollWidth = wnd.document.body.offsetWidth-wnd.document.body.clientWidth;
	var scrollHeight = wnd.document.body.offsetHeight-wnd.document.body.clientHeight;
	scrollWidth = scrollWidth + scrollWidth/2;

	if( scrollHeight < 38 )				// 38 = Scroolbar value under Windows XP
		scrollHeight = 38;

	if( scrollWidth < 29 )				// 29 = Scroolbar value under Windows XP
		scrollWidth = 29;

	var oContainer = jsFirstChild(wnd.document.body);
	if( oContainer != null )
	{
		mh = oContainer.offsetHeight;
	  	mw = oContainer.offsetWidth;
	  	if( ("" + parseInt(w)) == w ) 		// we got a width
	  	{
	  		if( w > mw )										// greatest than thes we computed ?
		  		mw = w;
	  	}

		if( ("" + parseInt(h)) == h )
		{
			if( h > mh )
		  		mh = h;
		}

	mh = parseInt(mh) + parseInt(scrollHeight);
	mw = parseInt(mw) + parseInt(scrollWidth);
  	}
  	else   // no container...maybe a post, we need to wait a little more
  	{
		return wnd;
  	}

	if( mh > screen.height )
		mh = screen.height;

	if( mw > screen.width )
		mw = screen.width;

// on resize que si c de l'IE
	if (window.ActiveXObject) wnd.resizeTo(mw,mh);
	wnd.moveTo((screen.width/2)-(mw/2) ,(screen.height/2)-(mh/2));

	g_lastOpenedWnd = null;
	return wnd;
}

function getAutoId()
{
	g_ID_COUNT++;
	return "JSID_"+g_ID_COUNT;
}

function openHelpWnd(url)
{
 window.open(url,'help','resizable=yes,scrollbars=yes,menubar=no,status=no,toolbar=no,left=0,top=0,width=1000,height=600');
}

function openCenterWnd(url,name,w,h,size,scroll)
{
 	var str ="width=" + w;
	str += ",height=" + h;
	str+=",left=" + (screen.width-w)/2;
	str+=",top=" + (screen.height-h)/2;
	str+=",resizable=" + ((size) ? "yes" : "no");
	str+=",scrollbars=" + ((scroll) ? "yes" : "no");
	str +=",menubar=no,status=no,toolbar=no";
  	g_lastOpenedWnd = window.open(url,name,str);
	g_lastOpenedWnd.opener = window;
	g_NB_WAIT = 0;
  	return centerWindow(g_lastOpenedWnd, w, h);
}

function isWindowReady(wnd)
{
	var ready = wnd.document.readyState;
	var readyState = 'complete';
	if( ready )
		readyState = ready;
	
	if(wnd.document != null && readyState == 'complete' && wnd.document.body != null && wnd.document.body.offsetWidth > 0)
		return true;
	else
		return false;
}

function waitForWindowCreation()
{
	if( g_NB_WAIT >= g_MAX_WAIT )		// After a too long time we stop the timer to prevent an infinite loop
	{
		g_lastOpenedWnd = null;
		return;
	}
	else
		g_NB_WAIT++;
		
	if( g_lastOpenedWnd == null )
		return;		
	
	if(isWindowReady(g_lastOpenedWnd))
		centerWindow(g_lastOpenedWnd, g_Window_Width, g_Window_Height);
	else
		window.setTimeout('waitForWindowCreation()', 500);
}



function heritFrom(obj)
{
	var fromObj = obj;
	var toObj = heritFrom.caller;
	toObj.prototype.Super = fromObj;
	for(var i in fromObj.prototype)
		if(!eval("toObj.prototype."+i))
				eval("toObj.prototype."+i+"=fromObj.prototype."+i);
		else
				eval("toObj.prototype.Super_"+i+"=fromObj.prototype."+i);
}

//generic component initialization
function NPComponentInit(lstFct)
{
	var elm;
	var fct;
	var param;

	for(var i=0;i<lstFct.size();i++)
	{
		elm = lstFct[i];

		if(elm && elm.size() == 2)
		{
			fct = elm[0];
			param = elm[1];
			if(fct) fct(param);
		}
	}
}

function unicodeToEscape(str)
{
	var reg1 = new RegExp("%u([A-F0-9][A-F0-9][A-F0-9][A-F0-9])", "g");
	var reg2 = new RegExp("%([A-F0-9][A-F0-9])", "g");

	var res = escape(str);
	res = res.replace(reg1, "\\u$1");
	res = res.replace(reg2, "\\u00$1");

	return escape(res);
}

/***** Get a valid XMLDOM */
function getXMLDOM()
{
	//var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined');
	var moz = !document.all;
 	var ie = (typeof window.ActiveXObject != 'undefined');
	var oDom = null;

 	if(moz)
 		oDom = getMozillaXMLDOM();
 	else
 		if(ie)
 			oDom = getIEXMLDOM();

	return oDom;
}

/***** Get a valid XMLDOM for IE *****/
function getIEXMLDOM()
{
	var arrDOMS = new Array("MSXML4.DOMDocument", "MSXML3.DOMDocument", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XmlDom");
	var oDom = null;

	 	for(var i=0; i<arrDOMS.length; i++)
		{
			try
			{
				oDom = new ActiveXObject(arrDOMS[i]);
				return oDom;
			}
			catch(objException)
			{
				oDom = null;
			}
		}

	return oDom;
}

/***** Get a valid XMLDOM for Mozilla ******/
/***** Bugs in Mozilla 1.4 (known bug) *****/
/***** works fine with Mozilla 1.6 *********/
function getMozillaXMLDOM()
{
  var oDom = document.implementation.createDocument("", "", null);
  oDom.addEventListener("load", _Document_onload, false);

  return oDom;
}

var isMoz = document.implementation && document.implementation.createDocument;

if( isMoz )
{
	/********************************************************************/
	/*********************** DOM Error management ***********************/

	function parseError()
	{
		this.errCode = 0;
		this.errDescription = '';
	}

	parseError.prototype.__defineGetter__("reason", function() {return this.errDescription;} );
	parseError.prototype.__defineGetter__("errorCode", function() {return this.errCode;} );
	parseError.prototype.__defineGetter__("line", function() {return 0;} );
	parseError.prototype.__defineGetter__("url", function() {return '';} );

	parseError.prototype.setError = function(code, description)
	{
		this.errCode = code;
		this.errDescription = description;
	}

/*
	Element.prototype.selectNodes = function(sExpr)
	{
			var doc = this.ownerDocument;
			if(doc.selectNodes)
				return doc.selectNodes(sExpr, this);
	}
*/

	Element.prototype.__defineGetter__("text", function()
																						 {
																							 if( this.firstChild && this.firstChild.nodeType == 3)
																								return this.firstChild.data;
																							else
																								return '';
																						  }
																		)

	Element.prototype.transformNodeToObject = function(xslDoc, oResult)
	{
		var oDoc = document.implementation.createDocument("", "", null);
		oDoc.copyDOM(this);
		oDoc.transformNodeToObject(xslDoc, oResult);
	}

	Node.prototype.__defineGetter__("xml", function _Node_getXML()
																				{
																			    //create a new XMLSerializer
																			    var objXMLSerializer = new XMLSerializer;

																			    //get the XML string
																			    var strXML = objXMLSerializer.serializeToString(this);

																			    //return the XML string
																			    return strXML;
																				}
	)

	XMLDocument.prototype.__defineGetter__("text", function()
																									{

																										var oNode = jsFirstChild(this);
																										while(oNode.nodeValue == null)
																											oNode = jsFirstChild(oNode);

																										//alert(oNode.nodeName + ': ' + oNode.nodeType + ' -> ' + oNode.nodeValue);
																										return oNode.nodeValue;																									}
	)

	XMLDocument.prototype.__load__ = XMLDocument.prototype.load;

	XMLDocument.prototype.load = function (strURL)
	{
		if(this.parseError==null || this.parseError==undefined)
			this.parseError = new parseError();
		this.parseError.setError(0, '');
		//change the readyState
	  //changeReadyState(this, 0);

	  try
		{
			//call the original load method
	    return this.__load__(strURL);
		}
		catch(objException)
		{
		//	changeReadyState(this, 4);
			this.parseError.setError(-99999, objException.message);
			return false;
		}
	}

	//XMLDocument.prototype.readyState = 0;

	XMLDocument.prototype.onreadystatechange = null;

	XMLDocument.prototype.parseError = new parseError();

/*
	XMLDocument.prototype.selectSingleNode = function(sExpr, contextNode)
	{
		var ctx = contextNode?contextNode:null;
		sExpr += "[1]";
		var nodeList = this.selectNodes(sExpr, ctx);
		if(nodeList.length > 0)
			return nodeList[0];
		else
			return null;
	}

	XMLDocument.prototype.selectNodes = function(sExpr, contextNode)
	{
		var oResult = this.evaluate(sExpr, (contextNode?contextNode:this), this.createNSResolver(this.documentElement), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
alert(oResult);
		var nodeList = new Array(oResult.snapshotLength);
		nodeList.expr = sExpr;
		for(i=0;i<nodeList.length;i++)
			nodeList[i] = oResult.snapshotItem(i);
		return nodeList;
	}
*/
    XMLDocument.prototype.selectNodes = function(cXPathString, xNode) {

var modName = "XPath";
var modVer = "3.0";
var conformTest = document.implementation.hasFeature(modName, modVer);

//alert("DOM " + modName + " " + modVer + " supported?: " + conformTest);



        if ( !xNode ) { xNode = this; }   
 var defaultNS = this.defaultNS;

  var aItems = this.evaluate(cXPathString, xNode,{
   normalResolver:
    this.createNSResolver(this),
        lookupNamespaceURI : function (prefix) {
           switch (prefix) {
             case "dflt":
                return defaultNS;
             default:
                return this.normalResolver.lookupNamespaceURI(prefix);
           }
        }
      },XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);

        var aResult = [];   
        for ( var i = 0; i < aItems.snapshotLength; i++) {   
            aResult[i] =  aItems.snapshotItem(i);   
        }   
        return aResult;   
    }   
    XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode) {   
        if( !xNode ) { xNode = this; }

        var xItems = this.selectNodes(cXPathString, xNode);   
        if ( xItems.length > 0 ) { return xItems[0]; }   
        else { return null; }   
    }   
  
    Element.prototype.selectNodes = function(cXPathString) {   
        if (this.ownerDocument.selectNodes) {   
            return this.ownerDocument.selectNodes(cXPathString, this);   
        } else { throw "For XML Elements Only"; }   
    }   
  
    Element.prototype.selectSingleNode = function(cXPathString) {   
        if (this.ownerDocument.selectSingleNode) {   
            return this.ownerDocument.selectSingleNode(cXPathString, this);   
        } else { throw "For XML Elements Only"; }   
    }

	Element.prototype.insertAdjacentElement = function(where,parsedNode)
	{
		switch (where)
		{
			case 'beforeBegin':
				this.parentNode.insertBefore(parsedNode,this)
				break;
			case 'afterBegin':
				this.insertBefore(parsedNode,this.firstChild);
				break;
			case 'beforeEnd':
				this.appendChild(parsedNode);
				break;
			case 'afterEnd':
				if (this.nextSibling)
					this.parentNode.insertBefore(parsedNode,this.nextSibling);
				else
					this.parentNode.appendChild(parsedNode);
			break;
		}
	}



	XMLDocument.prototype.loadXML = function(strXML)
	{
		//change the readystate
	  changeReadyState(this, 1);

	  //create a DOMParser
		var objDOMParser = new DOMParser();

		//create new document from string
		var objDoc = objDOMParser.parseFromString(strXML, "text/xml");

		//make sure to remove all nodes from the document
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);

		//add the nodes from the new document
		for (var i=0; i < objDoc.childNodes.length; i++)
		{
			//import the node
			var objImportedNode = this.importNode(objDoc.childNodes[i], true);
			//append the child to the current document
			this.appendChild(objImportedNode);
		}

		//we can't fire the onload event, so we fake it
		handleOnLoad(this);
	}

	XMLDocument.prototype.transformNode = function(xslDoc)
	{
		var out = document.implementation.createDocument("", "", null);
		this.transformNodeToObject(xslDoc, out);

		var str = null;
		try
		{
			var serializer = new XMLSerializer();
			str = serializer.serializeToString(out);
		}
		catch(e)
		{
			this.parseError.setError(-999999, e.message);
		}

		// need to remove prefix
		var reg = new RegExp('a0:', 'gi');
		str = str.replace(reg, '');
		return str;
	}

	XMLDocument.prototype.transformNodeToObject = function(xslDoc, oResult)
	{
		var xsltProcessor = null;
		try
		{
		    xsltProcessor = new XSLTProcessor();
		    if(xsltProcessor.reset)
		    {
	              // new nsIXSLTProcessor is available
	              xsltProcessor.importStylesheet(xslDoc);
	              var newFragment = xsltProcessor.transformToFragment(this, oResult);
	              oResult.copyDOM(newFragment);
		    }
		    else
		    {
	              // only nsIXSLTProcessorObsolete is available
	              xsltProcessor.transformDocument(this, xslDoc, oResult, null);
		    }
		}
		catch(e)
		{
			if(xslDoc && oResult)
				throw "TransformNodeToObjectException: Failed to transform document. (original exception: "+e+")";
			else if(!xslDoc)
				throw "TransformNodeToObjectException: No Stylesheet Document was provided. (original exception: "+e+")";
			else if(!oResult)
				throw "TransformNodeToObjectException: No Result Document was provided. (original exception: "+e+")";
			else if(xsltProcessor == null)
	              throw "XSLTProcessorNotAvailableException: Could not instantiate an XSLTProcessor object. (original exception: "+e+")";
	          else
	              throw e;
		}
	}

	XMLDocument.prototype.copyDOM = function(oDoc)
	{
		this.clearDOM();
	  if(oDoc.nodeType == Node.DOCUMENT_NODE || oDoc.nodeType == Node.DOCUMENT_FRAGMENT_NODE)
	  {
	      var oNodes = oDoc.childNodes;
	      for(i=0;i<oNodes.length;i++)
	          this.appendChild(this.importNode(oNodes[i], true));
	  }
	  else if(oDoc.nodeType == Node.ELEMENT_NODE)
	      this.appendChild(this.importNode(oDoc, true));
	}

	XMLDocument.prototype.clearDOM = function()
	{
		while(this.hasChildNodes())
			this.removeChild(this.firstChild);
	}

}	// if isMoz

/********************************************************************/
/*********************** Mozilla DOM functions **********************/

function changeReadyState(objDOMDocument, iReadyState)
{
  //change the readyState
  if(objDOMDocument.readyState==undefined || objDOMDocument.readyState == null)
  	objDOMDocument.readyState = iReadyState;

  //if there is an onreadystatechange event handler, run it
  if(objDOMDocument.onreadystatechange != null && typeof objDOMDocument.onreadystatechange == "function")
  {
  		//alert(objDOMDocument.onreadystatechange);
      objDOMDocument.onreadystatechange();
  }
}

function _Document_onload()
{
	handleOnLoad(this);
}

function handleOnLoad(objDOMDocument)
{
	//check for a parsing error
  if(!objDOMDocument.documentElement )
  {
    	objDOMDocument.parseError.setError(-999999, 'no documentElement');
	}
	else
	{
		if( objDOMDocument.documentElement.nodeName == "parsererror" )
		{
		objDOMDocument.parseError.setError(-999999, objDOMDocument.documentElement.firstChild.data);
		}
	}

	//change the readyState
  changeReadyState(objDOMDocument, 4);
}

/********************************************************************/
/************************** DOM functions ***************************/

function is_all_ws( nod )		// test if the node is empty
{
  // Use ECMA-262 Edition 3 String and RegExp features
  if( nod )
  	return !(/[^\t\n\r ]/.test(nod.data));
  else
  	return true;
}

function is_ignorable( nod )
{
  if( nod )
  	return ( nod.nodeType == 8) || ( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws
  else
  	return true;
}

function jsFirstChild(oNode)
{
  if( oNode == null ) return null;

  var res=oNode.firstChild;
  while (res)
  {
    if (!is_ignorable(res)) return res;
    res = res.nextSibling;
  }
  return null;
}

function jsLastChild(oNode)
{
  if( oNode == null ) return null;

  var res=oNode.lastChild;
  while (res)
  {
    if (!is_ignorable(res)) return res;
    res = res.previousSibling;
  }
  return null;
}

function jsPreviousSibling(oNode)
{
	if( oNode == null ) return null;

	while ((oNode = oNode.previousSibling))
	{
	  if (!is_ignorable(oNode)) return oNode;
	}
	return null;
}

function jsNextSibling(oNode)
{
  if( oNode == null ) return null;

  while ((oNode = oNode.nextSibling))
  {
    if (!is_ignorable(oNode)) return oNode;
  }
  return null;
}

function jsParentNode(oNode)
{
	if( oNode == null ) return null;

	var res=oNode.parentNode;
	while (res)
	{
	  if (!is_ignorable(res)) return res;
	  res = res.parentNode;
	}
	return null;
}

function jsChildNodes(oNode)
{
var arrChilds = oNode.childNodes;
var arrResult = new Array();
var i = 0;

	for(var j=0; j<arrChilds.length; j++)
	{
		if( !is_ignorable(arrChilds[j]) )
			arrResult[i++] = arrChilds[j];
	}

	return arrResult;
}

function jsParentElement(oNode)
{
	return jsParentNode(oNode);
}

/********************************************************************/
/********************************************************************/

function LTrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(0)) != -1) {
      var j=0, i = s.length;
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      s = s.substring(j, i);
   }
   return s;
}

function RTrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;       // Get length of string
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }
   return s;
}

function Trim(str)
{
   return RTrim(LTrim(str));
}

