/**
 * @author <a href = "mailto:albert@nutec.es">Albert C. Casas</a>
 * 
 * ?Objecte on s'emmagatzemen tots els estris per tractar tipus primitius a usar en qualsevol classe. 
 * 
 */

function JsUtils(){
	/**
	 * 
         * Mï¿½tode que partint d'un string(sString), substitueix una coincidència (sReplaceThis)
         * per un patrï¿½ (sWithThis).
         *
         * @param {String} sString->String contenidor.
         * @param {String} sReplaceThis->String a substituir de sString.
         * @param {String} sWithThis->String sustituyente a sReplaceThis.
         * @return {String} 
	 */
	this.replaceAll = function(sString, sReplaceThis, sWithThis){
		if (sReplaceThis != "" && sReplaceThis != sWithThis) {
			var counter = 0;
			var start = 0;
			var before = "";
			var after = "";
			while (counter<sString.length) {
				start = sString.indexOf(sReplaceThis, counter);
				if (start == -1) 
					break;
				else {
					before = sString.substr(0, start);
					after = sString.substr(start + sReplaceThis.length, sString.length);
					sString = before + sWithThis + after;
					counter = before.length + sWithThis.length;
				}
			}
		}
		return sString;
	}
	
	/**
	 * 
         * Mï¿½todo que divideix un string (cadenaADividir) mitjançant un altre string (divisor).
         * Es retorna un array amb cada substring resultant 
	 * 
	 * @param {Object} cadenaADividir
	 * @param {Object} divisor
	 * @return {String}
	 */
	this.utilSplit = function(cadenaADividir, divisor){
		return cadenaADividir.split(divisor);
	}
        
        /**
        * Mètode que compara dues cadenes dient-se si són iguals o no.
        *
        * @param {Object} primer @param
        * {Object} segon
        * @return {Boolean} true: Són iguals | false:són diferents
        */
        this.utilEquals = function(primero, segundo){
            if(primero == segundo) return true;
            return false;
        }
        
        /**
        *
        * Mètode que compara dues cadenes dient-se si comencen de la mateixa forma o no.
        * 
        * @param {String} primer
        * @return {Boolean} true: Comencen igual | false: No comencen igual
        */
        this.utilStartsWith = function(str1, str2) {
            return (str1.match("^" + str2) == str2) 
        }
        
        /**
	 * 
	 * Devuelve el valor de la cookie en la posición dictada por offset
	 * 
	 * @param {int} offset
	 * @return {String}
	 */
        this.getCookieVal = function(offset) {
            var endstr = document.cookie.indexOf (";", offset);
            if (endstr == -1) endstr = document.cookie.length;
            return unescape(document.cookie.substring(offset, endstr));
        }
        
        /**
	 * 
	 * Devuelve el valor de la cookie.
	 * 
	 * @param {String} name
	 * @return {String}
	 */
        this.getCookie = function(name) {
            var arg = name + "=";
            var alen = arg.length;
            var clen = document.cookie.length;
            var i = 0;
            while (i < clen) {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
                i = document.cookie.indexOf(" ", i) + 1;
                if (i == 0) break; 
            }
            return null;
        }
        
        /**
	 * Cambia el valor de la cookie con el nuevo valor (value).
	 * 
	 * @param {String} name
         * @param {String} value
	 * 
	 */
        this.setCookie = function(name, value) {
            var argv = SetCookie.arguments;
            var argc = SetCookie.arguments.length;
            var expires = (2 < argc) ? argv[2] : null;
            var path = (3 < argc) ? argv[3] : null;
            var domain = (4 < argc) ? argv[4] : null;
            var secure = (5 < argc) ? argv[5] : false;
            document.cookie = name + "=" + escape (value) +
                ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
                ((path == null) ? "" : ("; path=" + path)) +
                ((domain == null) ? "" : ("; domain=" + domain)) +
                ((secure == true) ? "; secure" : "");
            //alert( document.cookie )
        }
        
        /**
        * Detecta la altura dentro de la venatan/frame actual, crossbrowser (ver http://www.quirksmode.org/viewport/compatibility.html#link2)
        * @return {number}
        */    	
        this.miInnerHeight = function() {
            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;
        }   
                
        /**
        * Detecta la altura dentro de la venatan/frame actual, crossbrowser (ver http://www.quirksmode.org/viewport/compatibility.html#link2)
        * @return {number}
        */    	
        this.miInnerWidth = function() {
            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;
        }    	
        
        /**
        * Limpia un valor de un combo(si ndx existe). Si no añadimos ndx, vacia el combo de todos sus valores
        * @param {Object} ths Objeto combo (<select>)
        * @param {number} ndx Posición de un valor dentro del combo
        */
        this.limpiarCombo = function (ths, ndx) {
            if (ndx=="undefined") {
                ths.options.length=0;
            }
            else {
                if (ndx>=0) {
                    ths.options[ndx] = null;
                }
            }
        }
        
        /**
        * Función que se encarga de añadir código HTMl a una etiqueta (<span o <div)
        * @param {String} oid Es el id de la etiqueta dónde queremos añadir el código
        * @param {String} m  Es la traza de código que queremos añadir
        */
        this.setInnerHTML = function(oid, m) {
            var omensaje=document.getElementById(oid);
            if (omensaje!="null" && omensaje!= "undefined") {
                omensaje.innerHTML=m;
            }
        }
        
        
        /**
        * Función que se encarga de ejecutar un formulario
        * @param {String} action Acción del formulario
        * @param {String} operation Operación a realizar en el action
        * @param {Object} formulario Formulario a ejecutar
        */
        this.ejecutarFormulario = function(action, operation, formulario, destino, mensajeCarga) {
            formulario.action=action;
            formulario.target=destino;
            formulario.operation.value=operation;
            
            formulario.submit();
        }
        
        /**
        *
        * Método que nos dice si un valor es numérico o no.
        * @param {String} valor->String de tipo numérico o no.
        * @return {Boolean}
        */
        this.esNumero =function (valor){
            return !isNaN(valor);
        }
        
        /**
        *
        * Método que devuelve el valor de una variable.
        * @return {Object} DEvuelve el valor de la variable
        */
        this.getValue = function(variable){
            return variable;
        }
        
        /**
        *
        * Método que asigna un valor (val) a una variable
        * @param {Object} variable de la qual queremos cambiar el valor
        * @param {Object} val valor a cambiar
        */
        this.setValue = function(variable, val){
            variable = val;
        }
        
        /**
        *
        * Método que nos dice si un valor esta vacio o no.
        * @param {String} valor->String a validar.
        * @return {Boolean}
        */
        this.estaVacio = function(valor){
            return (valor == null || typeof valor =='undefined' || typeof valor =='null' || (valor =='' && typeof valor != 'boolean'));
        }
        
        /**
        *
        * Método que nos dice si un objeto XML existe o no.
        * @param {Object} valor->Componente a validar.
        * @return {Boolean}
        */
        this.existeObjetoXml = function(valor){
            var bool = false;
            if(document.all){
                if(valor == null) bool = false;
                else bool = true;
            }else{
                if(valor == undefined) bool = false;
                else bool = true;
            }
            return bool && (valor.getAttribute("null")=="false");
        }
        
        /**
        *
        * Método que nos dice si un objeto existe o no.
        * @param {Object} valor->Componente a validar.
        * @return {Boolean}
        */
        this.existeObjeto = function(valor){
            var bool = false;
            if(document.all){
                if(valor == null) bool = false;
                else bool = true;
            }else{
                if(valor == undefined) bool = false;
                else bool = true;
            }
            return bool;
        }
        
        /**
        *
        * Método que comprueba que un xml devuelto, contiene un objeto y que ese objeto tiene un valor
        * @param {Object} Objeto a verificar
        * @return {Boolean} Retorna true si todo ok /false si hay algun error
        */
        this.hayValorElementoXml = function(xmlElemento) {
            if(objUtiles.existeObjetoXml(xmlElemento)){
                if(objUtiles.estaVacio(xmlElemento.childNodes[0].nodeValue)) return false;
                return true;
            }
            return false;
        }
        
        /**
        *
        * Método que nos dice si un objeto es visible o no.
        * @param {String} id->id del componente a validar.
        * @return {Boolean}
        */
        this.estaHidden = function(id){
            return (document.getElementById(id).style.visibility=="hidden");
        }
               
        /**
        * Método que muestra un componente si éste está display:none;
        * @param {String} id->id del componente
        */
        this.muestraComponente = function(id){
            document.getElementById(id).style.display="block";
        }
        
        /**
        * Método que esconde un componente si éste está display:block/inline;
        * @param {String} id->id del componente
        */
        this.escondeComponente = function(id){
            document.getElementById(id).style.display="none";
        }
        
        /**
        * Convierte un TimeStamp de Oracle a String formato dd/MM/yyyy
        * @param {String} El String en formato TimeStamp a convertir.
        * @return {String} El String en formato dd/MM/yyyy
        */
        this.formateaTimeStamp = function (timeStamp) {
            if (!objUtiles.estaVacio(timeStamp) && timeStamp.length >= 8) {
                var year  = timeStamp.substring(0,4);
                var month = timeStamp.substring(4,6);
                var day   = timeStamp.substring(6,8);
                return (day + "/" + month + "/" + year);
            }
        }
        
        /**
        * Convierte un TimeStamp tipo 1967-03-09 00:00:00.0 a String formato dd/MM/yyyy
        * @param {String} El String en formato TimeStamp a convertir.
        * @return {String} El String en formato dd/MM/yyyy
        */
        this.formateaTimeStamp2 = function (timeStamp) {
            if (!objUtiles.estaVacio(timeStamp) && timeStamp.length >= 10) {
                var year  = timeStamp.substring(0,4);
                var month = timeStamp.substring(5,7);
                var day   = timeStamp.substring(8,10);
                return (day + "/" + month + "/" + year);
            }
        }
        
        /**
        * Método que simula el método String.trim() de Java
        * @param{String} entrada -> El string a 'trimear'
        *
        */
        this.stringTrim = function(entrada){
            return entrada.replace(/^\s*/, "").replace(/\s*$/, "");
        }
        
        /**
        * Método que simula el método String.replace() de Java
        * @param{String} entrada -> El string a inspeccionar
        * @param{String} string_encontrado -> El string a cambiar
        * @param{String} string_nuevo -> El string nuevo a sustituir
        */
        this.stringReplace = function(entrada, string_encontrado, string_nuevo){
            return entrada.replace(string_encontrado, string_nuevo);
        }
        

}
