/**
*
*	NOTA IMPORTANT: 
*
*	SEMBLA QUE SENSE POSAR-HI ISO-8859-15 NO FUNCIONA AMB ACCENTS OBERTS I ELS SUBSTITUEIX PER L'UNDERSCORE.
*
*/

/**
*	Remove special characters like "$" and "," etc...
*	newChar: the character or string to place when matching
*/
//String.prototype.removeSpecialCharacters=function(newChar) {
//	var re = /\$|,|@|#|·|~|¬|`|\/|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\¿|\||\\|\!|\$|\./g;
//	return this.replace(re, newChar);
//}

/**
*	Treu els espais a l'inici i al final de l'string
*	@return {String}
*/
String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

/**
*	Treu els espais a l'inici  de l'string
*	@return {String}
*/
String.prototype.ltrim=function(){
    return this.replace(/^\s*/g,'');
}

/**
*	Treu els espais al final de l'string
*	@return {String}
*/
String.prototype.rtrim=function(){
    return this.replace(/\s*$/g,'');
}

/**
*	Substitueix els caracters que tenim un equivalent sense accent
*	@return {String}
*/
String.prototype.replaceKnownCharacters=function() {
	var ret=this;
	ret=ret.replace(/\./g," "); //new
	ret=ret.replace(/À|Á|Ä|Â|Ã|Æ|Å/g,"A");
	ret=ret.replace(/È|É|Ë|Ê/g,"E");
	ret=ret.replace(/Ì|Í|Ï|Î/g,"I");
	ret=ret.replace(/Ò|Ó|Ö|Ô|Õ/g,"O");
	ret=ret.replace(/Ù|Ú|Ü|Û/g,"U");
	ret=ret.replace(/Ý|Y|¥|Y/g,"Y");
	ret=ret.replace(/ß|B/g,"B");
	ret=ret.replace(/Ø/g,"O");
	ret=ret.replace(/µ/g,"U");
	ret=ret.replace(/Ð/g,"D");
	ret=ret.replace(/Ñ/g,"NY");
	ret=ret.replace(/Ç/g,"C");
	ret=ret.replace(/·/g,"."); //new
	ret=ret.replace(/'/g," "); //new
	ret=ret.replace(/  /g," "); // treure més de dos espais seguits per deixar-ne un
	return ret;
}

/**
*	Treu els caracters no permesos i deixa només els que queden dins dels rangs a..z, A..Z, 0..9 i _
*	@return {String}
*/
String.prototype.replaceUnwantedCharacters=function() {
	var newText="";
	var len=this.length;
	for (var i=0;i<len;i++ ) {
		var code=this.charCodeAt(i);
		// a..z, A..Z, 0..9, _
		if ( (code>=97 && code<=122) || (code>=65 && code<=90) || (code>=48 && code<=57) || code==95 ) {
			//caracter permes
			newText+=this.charAt(i);
		} else {
			newText+="_";
		}
	}
	return newText;
}


/**
*	Retorna un text preparat per comparar amb un diccionari de la bdd preparat per fer-hi cerques.
*	@return {String}
*/
String.prototype.getTextForDictionary=function() {
	var ret=this;
	ret=ret.trim();
	ret=ret.toUpperCase();
	ret=ret.replaceKnownCharacters();
	//ret=ret.replaceUnwantedCharacters();

	return ret;
	
}

/**
*	Tracta l'string perque sigui un id valid per la base de dades
*	@return {String}
*/
String.prototype.getValidId=function() {
	var ret=this;
	ret=ret.trim();
	ret=ret.toUpperCase();
	ret=ret.replaceKnownCharacters();
	ret=ret.replaceUnwantedCharacters();

	// limitem a 28 caracters
	ret=ret.substr(0,28);

	return ret;
	
}

/**
*	Substitueix els apostrofs i cometes per la seva codificacio.
*	@return {String}
*/
String.prototype.quote=function() {
	var str=this;
	if (typeof(str)=='undefined') return 'undefined';
	var ret;
	ret=str.replace(/\"/g,'&#34;');
	ret=ret.replace(/\'/g,'&#39;');
	return ret;
}

/**
*	Prepara l'string perque no doni errors en tractar-ho en html generat en JS.
*	ex: <input value='l'altre'> --> ERROR HTML
*	@return {String}
*/
String.prototype.getValidString=function() {
	var str=this;
	if (typeof(str)=='undefined') return 'undefined';
	var ret;
	ret=str.replace(/\"/g,'&#34;');
	ret=ret.replace(/\'/g,'&#39;');
	ret=ret.replace(/>/g,'&#62;');
	ret=ret.replace(/\</g,'&#60;');
	
	return ret;
}


/**
*	Calcula la posicion X absoluta del objecto
*	http://www.quirksmode.org/js/findpos.html
*	@param {Object} obj L'objecte input
*	@return {Number}
*/
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

/**
*	Calcula la posicion Y absoluta del objecto
*	http://www.quirksmode.org/js/findpos.html
*	@param {Object} obj L'objecte
*	@return {Number}
*/
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/**
*	Retorna el valor decimal d'un numero hexa.
*	@param {String} x El número en hexa.
*	@return {Number}
*/
function hexValue(x){
		if (!isNaN(x)){
			x=Number(x);
			return x
		}else{
			switch(x){
			case 'A' : return 10 ;break;
			case 'B' : return 11 ;break;
			case 'C' : return 12 ;break;
			case 'D' : return 13 ;break;
			case 'E' : return 14 ;break;
			case 'F' : return 15 ;break;
			case 'a' : return 10 ;break;
			case 'b' : return 11 ;break;
			case 'c' : return 12 ;break;
			case 'd' : return 13 ;break;
			case 'e' : return 14 ;break;
			case 'f' : return 15 ;break;
			}
		}
	}

/**
*	Restringeix l'input als valors hexa(0..9,a..f,A..F)
*	exemple utilització:
*		<input id="myid" type="text" onKeyPress="javascript:return restringirHexa(this,event);"
*	@param {Object} obj L'objecte input
*	@param {Event} obj L'event generat
*/
function restringirHexa(obj,event) {
	var key=getkey(event);
	if ( (key>=48 && key<=57) || (key>=97 && key<=102) || (key>=65 && key<=70) )
		return true;
	else if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )// control keys
		return true;
	else return false;
}

/**
*	Restringeix l'input als valors numerics(0..9)
*	exemple utilització:
*		<input id="myid" type="text" onKeyPress="javascript:return restringirNumeric(this,event);"
*	@param {Object} obj L'objecte input
*	@param {Event} obj L'event generat
*/
function restringirNumeric(obj,event) {
	var key=getkey(event);
	if ( key>=48 && key<=57 )
		return true;
	else if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )// control keys
		return true;
	else return false;
}

/**
*	Restringeix l'input als valors numerics(0..9)
*	exemple utilització:
*		<input id="myid" type="text" onKeyPress="javascript:return restringirNumeric(this,event);"
*	@param {Object} obj L'objecte input
*	@param {Event} obj L'event generat
*/
function restringirReal(obj,event) {
	var key=getkey(event);
	if ( key>=48 && key<=57 )
		return true;
	else if ( key==44 || key==46 || key==45 )// 44:, 46:. 45:-
		return true;
	else if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )// control keys
		return true;
	else return false;
}

/**
*	retorna el numero de l'ultima tecla premuda
*	@param {Event} e l'event
*	@return {Number}
*/
function getkey(e) {
	if (window.event)
		return window.event.keyCode;
	else if (e)
		return e.which;
	else
		return null;
}

/**
*	Comprova que la data tingui el format dd/mm/yyyy
*	@param {String} dtStr la data
*	@return {boolean} true: data correcte. false: data incorrecte
*/
function dateFormatIsCorrect(dtStr) {
	try {
		if (dtStr=="") return true;
		var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
		var returnval=false
		if (!validformat.test(dtStr))
			return false;
		else { //Detailed check for valid date ranges
			var dayfield=dtStr.split("/")[0]
			var monthfield=dtStr.split("/")[1]
			var yearfield=dtStr.split("/")[2]
			var dayobj = new Date(yearfield, monthfield-1, dayfield)
			if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
				return false;
			else
				return true;
		}
	} catch(e) {
		alert("funcionsGlobals.js: dataValida(). Error comprovant data");
		return false;
	}
}

/**
*	Comprova si el parametre valor és un enter. Si es un enter retorna el seu valor com a Float, sinò retorna un string buit.
*	@param {String} valor El valor
*	@return {String/Float}
*	@creator Sandra
*/
function validarEntero(valor){
      //intento convertir a entero.
     //si era un entero no le afecta, si no lo era lo intenta convertir
	 if (valor=="0.0" || valor=="0")return valor;
	 else{
	     valor = parseFloat(valor)
	      //Compruebo si es un valor numérico
  	      if (isNaN(valor)) {
	        //entonces (no es numero) devuelvo el valor cadena vacia
			valor="";
		    return valor;
	      }else{
	        //En caso contrario (Si era un número) devuelvo el valor
		    return valor;
		  }

	  }
}



/**
*    Returns a new XMLHttpRequest object, or false if this browser doesn't support it
*    Codi extret de : http://www-128.ibm.com/developerworks/library/j-ajax1/
*/
function newXMLHttpRequest() {

  var xmlreq = false;

  if (window.XMLHttpRequest) {
    // Create XMLHttpRequest object in non-Microsoft browsers
    xmlreq = new XMLHttpRequest();

  } else if (window.ActiveXObject) {
    // Create XMLHttpRequest via MS ActiveX
    try {
      // Try to create XMLHttpRequest in later versions
      // of Internet Explorer
      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {
      // Failed to create required ActiveXObject
      try {
        // Try version supported by older versions of Internet Explorer
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        // Unable to create an XMLHttpRequest with ActiveX
      }
    }
  }

  return xmlreq;
}


/**
* Returns a function that waits for the specified XMLHttpRequest
* to complete, then passes its XML response
* to the given handler function.
* req - The XMLHttpRequest whose state is changing
* responseXmlHandler - Function to pass the XML response to
*/
function getReadyStateHandler(req, requestObject, responseXmlHandler) {

  // Return an anonymous function that listens to the 
  // XMLHttpRequest instance
  return function () {

    // If the request's status is "complete"
    if (req.readyState == 4) {
      //DebugOut("getReadyStateHandler status: " + req.status,DEBUG);
      // Check that a successful server response was received
      if (req.status == 200) {

        // Pass the XML payload of the response to the 
        // handler function
        responseXmlHandler(requestObject, req.responseXML, req);

      } else {

        // An HTTP problem has occurred
        alert("HTTP error: "+req.status);
      }
    }// else DebugOut("getReadyStateHandler readystate: " + req.readyState,DEBUG);
  }
}

/**
*	Crea un nou document XML
*	@return {XMLDocument}
*/
function newObjectXML(){
   if(window.ActiveXObject){
      xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	  return xmlDoc;
   }else if(document.implementation && document.implementation.createDocument){
      xmlDoc = document.implementation.createDocument("","",null);
	  return xmlDoc;
   }else{
      alert ('newObjectXML: Su navegador no puede soportar este script');
   }
}

/**
*	Afegeix un node amb un text com a valor
*	@param doc El document XML
*	@param {Node} parentNode Node on s'afegirà el fill
*	@param {String} nodeName Nom del node
*	@param {String} nodeValue Text del node
*
*/
function addChild(doc,parentNode,nodeName,nodeValue) {
	var aux=doc.createElement(nodeName);
	var aux2=doc.createTextNode(nodeValue);
	aux.appendChild(aux2);
	//alert ('>>2 :' + aux2.nodeValue);
	parentNode.appendChild(aux);
}

/**
*	Afegeix un node amb un boolea com a valor. Si nodeValue es TRUE posa Y, si es FALSE posa N. Ex: <nodeName>Y</nodeName>
*	@param doc El document XML
*	@param {Node} parentNode Node on s'afegirà el fill
*	@param {String} nodeName Nom del node
*	@param {String} nodeValue Text del node
*
*/
function addBooleanChild(doc,parentNode,nodeName,nodeValue) {
	var v;
	if (nodeValue) v="Y";
	else v="N";
	addChild(doc,parentNode,nodeName,v);
}

/**
*	Retorna un boolea a partir de l'xpath donat. Y|1: true, N|0:false.
*	DEPEN DE SARISSA!
*
*	@param {Document} doc El document xml
*	@param {String} xpath Xpath al valor
*/
function selectBoolean(doc,xpath) {
	try {	
		var objNodeList = doc.selectNodes(xpath);
		//---DEBUG-------------
		for(var i=0;i<objNodeList.length;i++) {
			var v=objNodeList[i].nodeValue;
			//alert("> "+i+" / "+objNodeList.length+"\n"+xpath+"\n\n"+ objNodeList[i].nodeValue );
		}
		//---DEBUG-------------
		var v=objNodeList[0].nodeValue;
		//alert(">loadValue: "+ v );

		if (v=="Y" || v=="1") return true;
		else if (v=="N" || v=="0") return false;
		else {
			alert("Error selectBoolean()\nS'esperava un valor 0/1 i s'ha trobat:"+v+"\n\nXpath: "+xpath);
		}
	
	} catch (e) {
		if (objNodeList.length==0) return false;// si no te valor no es un error.
		alert("Error selectBoolean()\n" + e.message + "\n\n"+xpath);
		return false;
	}
}

/**
*	Retorna un string a partir de l'xpath donat.
*	DEPEN DE SARISSA!
*
*	@param {Document} doc El document xml
*	@param {String} xpath Xpath al valor
*/
function selectString(doc,xpath) {
	try {	
		var objNodeList = doc.selectNodes(xpath);
		//---DEBUG-------------
		for(var i=0;i<objNodeList.length;i++) {
			var v=objNodeList[i].nodeValue;
//			alert("> "+i+" / "+objNodeList.length+"\n"+xpath+"\n\n"+ objNodeList[i].nodeValue );
		}
		//---DEBUG-------------
		var v=objNodeList[0].nodeValue;
		//alert(">loadValue: "+ v );
		//DebugOut(">> selectString :: "+xpath+" = " +v,DEBUG );
		return v;
	
	} catch (e) {
		if (objNodeList!=null && objNodeList.length==0) return "";// si no te valor no es un error.
		alert("Error selectString()\n" + e.message + "\n\n"+xpath);
		return "";
	}
}

/**
*	Retorna un float a partir de l'xpath donat.
*	DEPEN DE SARISSA!
*
*	@param {Document} doc El document xml
*	@param {String} xpath Xpath al valor
*/
function selectFloat(doc,xpath) {
	try {	
		var objNodeList = doc.selectNodes(xpath);
		//---DEBUG-------------
		for(var i=0;i<objNodeList.length;i++) {
			var v=objNodeList[i].nodeValue;
//			alert("> "+i+" / "+objNodeList.length+"\n"+xpath+"\n\n"+ objNodeList[i].nodeValue );
		}
		//---DEBUG-------------
		var v=objNodeList[0].nodeValue;
		//alert(">loadValue: "+ v );
		return parseFloat(v);
	
	} catch (e) {
		if (objNodeList.length==0) return "";// si no te valor no es un error.
		alert("Error selectFloat()\n" + e.message + "\n\n"+xpath);
		return 0;
	}
}


//--------------------------------------------------------
try {
	if (typeof(FILES_LOADED)=='undefined') FILES_LOADED=0;
	FILES_LOADED++;
}
catch (e) {}
//--------------------------------------------------------


/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas) { 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

/**
*	Creacio d'una galeta
*/
function createCookie(name,value,days) {

       if (days) {
              var date = new Date();
              date.setTime(date.getTime()+(days*24*60*60*1000));
              var expires = "; expires="+date.toGMTString();
       }

       else var expires = "";
       document.cookie = name+"="+value+expires+"; path=/";
}


/**
*	llegeix una galeta
*/
function readCookie(name) {

       var nameEQ = name + "=";
       var ca = document.cookie.split(';');
       for(var i=0;i < ca.length;i++) {
              var c = ca[i];
              while (c.charAt(0)==' ') c = c.substring(1,c.length);
              if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
       }
       return null;
}


/**
*	Elimina una galeta
*/
function eraseCookie(name) {
       createCookie(name,"",-1);
}

/**
*	Retorna l'amplada disponible al navegador
*	http://www.quirksmode.org/viewport/compatibility.html
*/
function getAvailableWidth() {
	var x;
	if (self.innerHeight) // all except Explorer
	{
	x = self.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	// Explorer 6 Strict Mode
	{
	x = document.documentElement.clientWidth;
	}
	else if (document.body) // other Explorers
	{
	x = document.body.clientWidth;
	}
	return x;
}

/**
*	Retorna l'amplada disponible al navegador
*	http://www.quirksmode.org/viewport/compatibility.html
*/
function getAvailableHeight() {
	var y;
	if (self.innerHeight) // all except Explorer
	{
	y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	// Explorer 6 Strict Mode
	{
	y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
	y = document.body.clientHeight;
	}
	return y;
}

function UrlParser(sCallingURL) {
	this.init(sCallingURL);
}

UrlParser.prototype.init=function(sCallingURL) {
	this.nMaxVars = 0;
	this.sVarLine = "";
	this.sName = new Array();
	this.sValue = new Array();

	this.parseCallingURL(sCallingURL);

}

UrlParser.prototype.getMaxVars=function() { return this.nMaxVars; }
UrlParser.prototype.getVarString=function() { return this.sVarLine; }
UrlParser.prototype.getNameArray=function() { return this.sName; }
UrlParser.prototype.getValueArray=function() { return this.sValue; }
	
UrlParser.prototype.parseCallingURL=function(sCallingURL) {
	//Get the calling URL and parse out variables
	sCallingURL = String(sCallingURL);
	
	if (sCallingURL.length == 0)
		return;
		
	// Check if there are any variables
	if (sCallingURL.indexOf('?') != -1) {
		this.sVarLine = String(sCallingURL.substring(sCallingURL.indexOf('?') + 1, sCallingURL.length));
	} else {
		// No variables
		return;
	}
	
	var nPos = 0;
	var sChar = "";
	var sWord = "";
	this.nMaxVars = 0;
	
	// Parse
	while (nPos < this.sVarLine.length) {
		sChar = this.sVarLine.substring(nPos, nPos + 1);
		
		if (sChar == "=") {
			this.sName[this.nMaxVars] = sWord;
			sWord = "";
			
		} else if (sChar == "&") {
			this.sValue[this.nMaxVars] = sWord;
			sWord = "";
			this.nMaxVars++;
			
		} else if (nPos == this.sVarLine.length - 1) {
			sWord += this.sVarLine.substring(nPos, nPos + 1);
			this.sValue[this.nMaxVars] = sWord;
			sWord = "";
			this.nMaxVars++;
			
		} else {
			sWord += sChar;
		}
		nPos++;
	}
}

function addFieldToForm(formObj,type,name,value) {
	try {
		var obj = document.createElement('input');
		obj.setAttribute("type",type);
		obj.setAttribute("name",name);
		obj.setAttribute("value",value);
		formObj.appendChild(obj);
	}
	catch (e) {
		alert("Error a addFieldToForm()\n"+e.message);
	}
}

function deleteFormFields(formObj) {
	try {
		while(formObj.elements.length>0) {
			var e=formObj.elements[0];
			formObj.removeChild(e);
		}
	}
	catch (e) {
		alert("Error a addFieldToForm()\n"+e.message);
	}
}
