/**
 * @author Fernando Reig Aparicio
 * @copyright 2006
*/

var utiles_js = true;	

	function CLocation(uri){
		this.hash= ''; // String containing the portion of the URL following the hash mark (#), if it exists. (IE3+, N2+, MOZ)
		this.host= ''; // String containing the host name and port of the URL (although some implementations do not include the port). (IE3+, N2+, MOZ)
		this.hostname= ''; // String containing the host name (domain name). (IE3+, N2+, MOZ)
		this.href= ''; // String containing the entire URL. (IE3+, N2+, MOZ)
		this.pathname= ''; // String containing the path (directory) portion of the URL. Always at least "/". (IE3+, N2+, MOZ)
		this.port= ''; //puerto si se ha especificado
		this.protocol = ''; //cadena de texto con el protocolo ( incluido el caracter :)
		this.search = ''; //cadena de consulta (incluido el caracter ?)
		
		this.parse = 
		function(uri){
			//var r = new RegExp("^([^\\:]+)//");
			var r = new RegExp("^(([^:]+:)//([^:\\?#/]+)(:([0-9]+))?)?(/?[^\\?#]*)?(\\?[^#]+)?(#.+)?");
			
			if (uri == "#")
				return false;
			
			try{
				uri.match(r);
			}catch(ex){
				//throw new Error("URI incorrecta");		
				return false;
			}
				
			this.protocol = RegExp.$2;
			this.hostname = RegExp.$3;
			this.port = RegExp.$5;
			this.host = this.hostname+(((this.port=="") || (this.port==undefined))?"":(":"+this.port));
			this.pathname = RegExp.$6;
			this.search = RegExp.$7;
			this.hash = RegExp.$8;
			this.href=this.getURI();

			if (!r.test(uri) || (this.getURI()==''))
				throw new Error("URI incorrecta");			
		}
		
		this.equals = 
		function (loc){
			return (loc.host==this.host) && (this.pathname==loc.pathname);
		}

		this.getURI = 
		function(){
			return ((this.protocol==undefined || this.protocol=="")?"":(this.protocol+"//"))+this.host+this.pathname+this.search+this.hash;
		}
		
		//this.toString = this.getURI;
		
		this.parse(uri);
	}
	

	/**
	 * Copia los elementos del formulario origen al formulario destino
	 * @param HtmlFormElement formo
	 * @param HtmlFormElement formd
	 */
	function copyFormElementsIntoForm(formo, formd){
		var v = formo.elements;
		var e;
		for (var i=0; i<v.length; i++){
			e = v[i];
			//si el elemento ya existe en el formulario destino
			if (formd[e.name]){
				formd[e.name].value = e.value;
			}else{
				formd.appendChild(e.cloneNode(true));
			}
		}
	}
	
	/**
	 * Obtiene una adena de consulta a partir de los campos de un formulario
	 * @param HtmlFormElement frm
	 * @return string
	 */
	function formToQueryString(frm){
		var numberElements =  frm.elements.length;
		var querystring="";
		var e = null, valor;
		for(var i = 0; i < numberElements; i++){
			e = frm.elements[i];
			if ((e.name=='' || e.name==null) ||
			  ((e.type=="checkbox") && !e.checked))
				continue;
			var v = getChildsByAttributes(frm, 'name', e.name);
			if (v!=null && v.length>1)
			{
				valor = "";
				for(var j=0; j<v.length; j++)
				{
					valor += decodeURIComponent(v[j].value) + ((j<v.length-1)?"&":",");
				}
			}
			else
				valor = decodeURIComponent(e.value);
			querystring += (e.name+"="+valor+((i<numberElements-1)?"&":""));
		}
		return querystring;
	}

	/**
	 * Añade una cadena de consulta a la URI especificada y devuelve el resultado
	 * @param string uri
	 * @param string querystring
	 * @return string
	 */
	function appendQueryStringToURI(uri, querystring){
		var oLoc = new CLocation(uri);

		var o = queryStringToCollection(oLoc.search+"&"+querystring);
		var i;
		var s="";
		var j = 0;
		for (i in o){
			if (j==0)
				s = "?";
			else
				s+="&";
			s+=(i+"="+o[i]);
			j++;
		}
		//se asigna la querystring al objeto CLocation
		oLoc.search = s;
		//se retorna la URI resultante
		return oLoc.getURI();
	}
	
	function queryStringToCollection(querystring){
		//se separa la querystring en pares de la forma "nombre=valor"
		var v = querystring.split(/[\?|\&]/);	
		var vAux = null;
		var i, o = new Object();
		var sClave, sValor;
		
		//se van metiendo en un objeto u array asociativo (asi se eliminarán los posibles elementos repetidos de la query)
		for (i=0; i<v.length; i++){
			vAux = v[i].split("=");
			//alert(((vAux[0]==undefined)?"":vAux[0]) +","+ ((vAux[1]==undefined)?"":unescape(new String(vAux[1]))));
			sClave = ((vAux[0]==undefined)?"":decodeURIComponent(vAux[0]));
			sValor = ((vAux[1]==undefined)?"":decodeURIComponent(new String(vAux[1])));
			if (o[sClave] == null && typeof(o[sClave]) == "undefined")
				o[sClave] = sValor;
			else
			{
				if (typeof(o[sClave])=="object")
				{
					o[sClave].push(sValor);
				}
				else
				{
					o[sClave] = [o[sClave], sValor];
				}
			}
		}
		var o2 = new Object();
		for (i in o){
			if ((i=="") || (i==undefined) || 
				(o[i]==undefined) || (o[i]==""))
				continue;
			o2[i] = o[i];
		}
		return o2;
	}
	
	function addCSSClass(elemento, className){
		if (!new RegExp("(^| )"+className+"( |$)").test(elemento.className))
			elemento.className += " "+className;
	}

	function removeCSSClass(elemento, className){
		elemento.className = elemento.className.replace(new RegExp("(^| )"+className+"( |$)"),' ');
	}
	
	/**
	 * Aade una barra invertida a cada uno de los caracteres 
	 * de la cadena indicada y son caracteres especiales de una expresion regular
	 * @param String s
	 * @return String
	 */
	function escapeRegExpString(s){
		var r = "";
		var caracteres = ".?+*-[]()^$";
		var c = '';
		for (var i=0; i<s.length; i++){
			c = s.charAt(i);
			if (caracteres.indexOf(c)>-1)
				r+="\\"+c;
			else
				r+=c;
		}
		return r;
	}

	function getParentNode(element, tagName){
		if (tagName==undefined)
			return element.parentNode;
		
		while(element){
			element = element.parentNode;
			 if (element && (element.tagName.toLowerCase()==tagName.toLowerCase()))
				return element;
		}
		return document.documentElement;
	}
	
	function getChildNode(element, tagName){
		
		if (tagName==undefined)
			return element.firstChild;

		if (element && element.tagName && (element.tagName.toLowerCase()==tagName.toLowerCase())){		
			var j,s,r,ok=true;
			for(j=2; j<arguments.length-1; j+=2){
				s = arguments[j];
				r = new RegExp(arguments[j+1]);

				//si el valor del atributo no coincide con la expresion reg no se sigue mirando
				if (!r.test(element[s])){
					ok=false;
					break;
				}
			}
			if (ok)
				return element;
		}
			
		var i,e,e1,args = new Array();
		for (i=0; i<arguments.length; i++)
			args.push(arguments[i]);
		if (element.hasChildNodes())
			for (i=0; i<element.childNodes.length; i++)
			{
				e = element.childNodes[i];
				args[0] = e;
				e1 = getChildNode.apply(this, args);
				if (e1)			
					return e1;
			}
		return null;
	}	
	
	/**
	 * Obtiene el elemento "hermano" anterior al elemento indicado y
	 * cuya etiqueta HTML coincide con la especificada
	 * @param element Puntero al elemento del que se quiere obtener su hermano
	 * @param sTagName Etiqueta del elemento que se esta buscando
	 * @return HTMLElement Devuelve el elemento encontrado o null si no se encuentra
	 */
	function getPreviousSibling(element, sTagName){
		if (sTagName==undefined){
			return element.previousSibling;
		}else{
			sTagName = sTagName.toLowerCase();
			var eSibling = element.previousSibling;
			do{
				//alert(eSibling.nodeName);
				
				if (eSibling && eSibling.nodeName.toLowerCase()==sTagName)
					return eSibling;
				eSibling = eSibling.previousSibling;
			}while(eSibling!=null);
		}
		return null;
	}	
	
	/**
	 * Obtiene el elemento "hermano" posterior al elemento indicado y
	 * cuya etiqueta HTML coincide con la especificada
	 * @param element Puntero al elemento del que se quiere obtener su hermano
	 * @param sTagName Etiqueta del elemento que se esta buscando
	 * @return HTMLElement Devuelve el elemento encontrado o null si no se encuentra
	 */
	function getNextSibling(element, sTagName){
		if (sTagName==undefined){
			return element.nextSibling;
		}else{
			sTagName = sTagName.toLowerCase();
			var eSibling = element.nextSibling;
			do{
				//alert(eSibling.nodeName);
				
				if (eSibling && eSibling.nodeName.toLowerCase()==sTagName)
					return eSibling;
				eSibling = eSibling.nextSibling;
			}while(eSibling!=null);
		}
		return null;
	}
	
	/**
	 *  Obtiene una serie de elementos que conciden con 
	 * los valores especificadosde de los atributos especificados
	 * @param String/Array  tags  Etiqueta/s HTML de los elementos a obtener
	 * @param String sTagName,... Pares de parametros de la forma "atributo","valor" (expresion reg)
	 * @return Array Vector con los elementos encontrados
	 */
	function getElementsByAttributes(tags){
		var i,j, x;
		
		if (!isArray(tags))
			vTags = [tags];
		else
			vTags = tags;
			
		var v2 = new Array(); //vector de resultados
		
		for (x=0; x<vTags.length; x++)
		{
			var v = document.getElementsByTagName(vTags[x]);
			var s,r = null;

			//recorremos los elementos
			for (i=0; i<v.length; i++){
				for(j=1; j<arguments.length-1; j+=2){
					s = arguments[j];
					r = new RegExp(arguments[j+1]);

					//si el valor del atributo no coincide con la expresion reg
					//se pasa al siguiente elemento
					if (!r.test(v[i][s]))
						break;
					//si se ha cumplido hasta la ultima propiedad
					//agregamos el elemento al vector de resultados
					//y pasamos al siguiente elemento
					if (j>=(arguments.length-2)){
						v2.push(v[i]);
					}
					
				}
			}
		}
		return v2;
	}
	
	function getChilds(padre)
	{
		if (padre == null || !padre.hasChildNodes())
			return [];
		
		var v = padre.childNodes;
		var vr = [];
		for(var i=0; i<v.length; i++)
		{
			vr.push(v[i]);
			vaux = getChilds(v[i]);
			for (var j=0; j<vaux.length; j++)
			{
				vr.push(vaux[j]);
			}
		}
		return vr;
	}
	
	function getChildsByAttributes(parent){
		var i,j;
		var v = getChilds(parent);
		var v2 = new Array(); //vector de resultados
		var s,r = null;

		//recorremos los elementos
		for (i=0; i<v.length; i++){
			for(j=1; j<arguments.length-1; j+=2){
				s = arguments[j];
				r = new RegExp(arguments[j+1]);

				//si el valor del atributo no coincide con la expresion reg
				//se pasa al siguiente elemento
				if (!r.test(v[i][s]))
					break;
				//si se ha cumplido hasta la ultima propiedad
				//agregamos el elemento al vector de resultados
				//y pasamos al siguiente elemento
				if (j>=(arguments.length-2)){
					v2.push(v[i]);
				}
				
			}
		}
		return v2;
	}
	
	/**
	 *
	 */
	function myAlert(x) {
		alert(decodeText(x));
	}
	
	/**
	 * 
	 * @param string mens 
	 * @param string codigo 
	 * @return int
	 */
	function myConfirm(mens, codigo){
		//si no se ha especificado un codigo
		if ((typeof(codigo)=="undefined") || (codigo==null) || (codigo==""))
			return confirm(decodeText(mens));
			
		//se recoge la respuesta del usuario
		var	respuesta = prompt(mens+"\nTeclee '"+codigo+"' (sin las comillas) para confirmar.", "");
		
		//si el usuario cancela o cierra el prompt
		if (respuesta==null)
			return false;

		//si coincide la respuesta del usuario con el codigo
		if (respuesta.toLowerCase()==codigo.toLowerCase())
			return true;
		myAlert('Confirmación incorrecta.');
		return false;
	}
	
	/**
	 * 
	 */
	function myPrompt(mens, value){
		return prompt(decodeText(mens), value);
	}
	
	function decodeText(x){
		// version 040623
		// Spanish - Espa?ol
		// Portuguese - Portugu?s - Portugu?s
		// Italian - Italiano
		// French - Franc?s - Fran?ais
		// Also accepts and converts single and double quotation marks, square and angle brackets
		// and miscelaneous symbols.
		// Also accepts and converts html entities for all the above.
		//	if (navigator.appVersion.toLowerCase().indexOf("windows") != -1) {return x}
		x = x.replace(/&iexcl;/g,"\xA1");
		x = x.replace(/&iquest;/g,"\xBF");
		x = x.replace(/&Agrave;/g,"\xC0");
		x = x.replace(/&agrave;/g,"\xE0");
		x = x.replace(/&Aacute;/g,"\xC1");
		x = x.replace(/&aacute;/g,"\xE1");
		x = x.replace(/&Acirc;/g,"\xC2");
		x = x.replace(/&acirc;/g,"\xE2");
		x = x.replace(/&Atilde;/g,"\xC3");
		x = x.replace(/&atilde;/g,"\xE3");
		x = x.replace(/&Auml;/g,"\xC4");
		x = x.replace(/&auml;/g,"\xE4");
		x = x.replace(/&Aring;/g,"\xC5");
		x = x.replace(/&aring;/g,"\xE5");
		x = x.replace(/&AElig;/g,"\xC6");
		x = x.replace(/&aelig;/g,"\xE6");
		x = x.replace(/&Ccedil;/g,"\xC7");
		x = x.replace(/&ccedil;/g,"\xE7");
		x = x.replace(/&Egrave;/g,"\xC8");
		x = x.replace(/&egrave;/g,"\xE8");
		x = x.replace(/&Eacute;/g,"\xC9");
		x = x.replace(/&eacute;/g,"\xE9");
		x = x.replace(/&Ecirc;/g,"\xCA");
		x = x.replace(/&ecirc;/g,"\xEA");
		x = x.replace(/&Euml;/g,"\xCB");
		x = x.replace(/&euml;/g,"\xEB");
		x = x.replace(/&Igrave;/g,"\xCC");
		x = x.replace(/&igrave;/g,"\xEC");
		x = x.replace(/&Iacute;/g,"\xCD");
		x = x.replace(/&iacute;/g,"\xED");
		x = x.replace(/&Icirc;/g,"\xCE");
		x = x.replace(/&icirc;/g,"\xEE");
		x = x.replace(/&Iuml;/g,"\xCF");
		x = x.replace(/&iuml;/g,"\xEF");
		x = x.replace(/&Ntilde;/g,"\xD1");
		x = x.replace(/&ntilde;/g,"\xF1");
		x = x.replace(/&Ograve;/g,"\xD2");
		x = x.replace(/&ograve;/g,"\xF2");
		x = x.replace(/&Oacute;/g,"\xD3");
		x = x.replace(/&oacute;/g,"\xF3");
		x = x.replace(/&Ocirc;/g,"\xD4");
		x = x.replace(/&ocirc;/g,"\xF4");
		x = x.replace(/&Otilde;/g,"\xD5");
		x = x.replace(/&otilde;/g,"\xF5");
		x = x.replace(/&Ouml;/g,"\xD6");
		x = x.replace(/&ouml;/g,"\xF6");
		x = x.replace(/&Oslash;/g,"\xD8");
		x = x.replace(/&oslash;/g,"\xF8");
		x = x.replace(/&Ugrave;/g,"\xD9");
		x = x.replace(/&ugrave;/g,"\xF9");
		x = x.replace(/&Uacute;/g,"\xDA");
		x = x.replace(/&uacute;/g,"\xFA");
		x = x.replace(/&Ucirc;/g,"\xDB");
		x = x.replace(/&ucirc;/g,"\xFB");
		x = x.replace(/&Uuml;/g,"\xDC");
		x = x.replace(/&uuml;/g,"\xFC");
		
//		x = x.replace(/\"/g,"\x22"); x = x.replace(/&quot;/g,"\x22");
//		x = x.replace(/\'/g,"\x27");
		x = x.replace(/\</g,"\x3C");
		x = x.replace(/\>/g,"\x3E");
		x = x.replace(/\[/g,"\x5B");
		x = x.replace(/\]/g,"\x5D");
	
		x = x.replace(/&cent;/g,"\xA2"); 
		x = x.replace(/&pound;/g,"\xA3");
		x = x.replace(/&euro;/g,"\u20AC"); 
		x = x.replace(/&copy;/g,"\xA9"); 
		x = x.replace(/&reg;/g,"\xAE"); 
		x = x.replace(/&ordf;/g,"\xAA"); 
		x = x.replace(/&ordm;/g,"\xBA");
		x = x.replace(/&deg;/g,"\xB0");
		x = x.replace(/&plusmn;/g,"\xB1");
		x = x.replace(/&times;/g,"\xD7");
		
		return x;
	}
	
	function removeAccents(strAccents){
		strAccents = strAccents.split('');
		strAccentsOut = new Array();
		strAccentsLen = strAccents.length;
		var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
		var accentsOut = ['A','A','A','A','A','A','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z'];
		for (var y = 0; y < strAccentsLen; y++) {
			if (accents.indexOf(strAccents[y]) != -1) {
				strAccentsOut[y] = accentsOut[accents.indexOf(strAccents[y])];
			}
			else
				strAccentsOut[y] = strAccents[y];
		}
		strAccentsOut = strAccentsOut.join('');
		return strAccentsOut;
	}
	
	/**
	 * Marca los checkboxes del vector pasado con el valor de bChecked
	 * @param Array v Vector con referencias a los checkboxes a marcar
	 * @param bool bChecked Valor a marcar
	 */
	function markCheckboxes(v,bChecked){
		for(i=0; i<v.length; i++){
			v[i].checked = bChecked;
		}
	}  	
	
	/**
	 * @param string nombre Nombre de los campos checkbox a cambiar de valor (marcar o desmarcar)
	 * @param bool checked
	 * @return int Devuelve el numero de checkboxes que han cambiado de valor
	 */
	function marcarTodos(nombre, checked, cambiarEstiloTR){
		var i=0, j=0;
		var v = document.getElementsByName(nombre);
		for (var i=0; i<v.length; i++){
			if (!v[i] || (v[i].type!="checkbox"))
				continue;
		
			if (v[i].checked!= checked){
				v[i].checked = checked;
				j++;				
			}
			
			if (cambiarEstiloTR){
				(v[i].checked)?addCSSClass(getParentNode(v[i], 'tr'), 'seleccionado'):removeCSSClass(getParentNode(v[i],'tr'),'seleccionado');			
			}
		}
		return j;
	}
	
	function selectAllOptions(elemento, bSeleccionar)
	{
		if (typeof(bSeleccionar)=="undefined")
			var bSeleccionar = true;
		elemento = getElement(elemento);
		if (!elemento)
			return false;
		if (elemento.type == "select-multiple")
		{
			var v = elemento.options;
			for(var i=0; i<v.length; i++)
			{
				v[i].selected = bSeleccionar;
			}
		}
		else if (elemento.type == "checkbox")
		{
			var v = document.getElementsByName(elemento.name);
			for(var i=0; i<v.length; i++)
			{
				v[i].checked =bSeleccionar;
			}
		}
		return true;
	}
	
	/**
	 *
	 */	
	function lanzarAccion(formu, accion, pregunta){
		if (pregunta!=undefined && pregunta!=null && !confirm(pregunta))
			return false;
		document.getElementById('accion').value=accion; 
		formu.submit();
	}
	
	/**
	 *
	 */
	function lanzarAccionMarcados(formu, nombre, accion, pregunta_confirmacion){
		var v = document.getElementsByName(nombre);
		var cuantos = 0;
		for (var i=0; i<v.length; i++){
			if (v[i].checked)
				cuantos++;
		}//for i
		if (cuantos==0){
			alert("Debe seleccionar antes algunos elementos");
			return false;
		}
		
		if (pregunta_confirmacion!=undefined && pregunta_confirmacion!=null && !confirm(pregunta_confirmacion))
			return false;
		document.getElementById('accion').value=accion; 
		formu.submit();
	}
	
	/**
	 *
	 */
	function printSelect(id, seleccionado, onchange, elementovacio /*, valor1, valor2, valor3*/){
		document.writeln('<select id="'+id+'" name="'+id+'" onchange="'+onchange+'">');
		if (elementovacio)
			document.writeln('<option value="">&lt; Elige &gt;</option>');
		for (var i=4; i<arguments.length; i++){
			document.write('<option value="'+arguments[i]+'" ');
			if (seleccionado==arguments[i])
				document.write(' selected="selected" ');
			document.writeln('>'+arguments[i]+'</option>');
		}//for
		document.writeln('</select>');
	}
	/**
	 *
	 */
	function printSelectRango(id, seleccionado, onchange, desde, hasta){
		if (desde>hasta)
			hasta = desde;
		document.writeln('<select id="'+id+'" name="'+id+'" onchange="'+onchange+'">');
		for (var i=desde; i<=hasta; i++){
			document.write('<option value="'+i+'" ');
			if (seleccionado==i)
				document.write(' selected="selected" ');
			document.writeln('>'+i+'</option>');
		}//for
		document.writeln('</select>');
	}//printSelectRango
	/***********************************/
	//recoge el valor de un elemento
	function getValue(id){
		if (id==undefined)
			return null;
			
		var elemento = getElement(id);
		
		if (elemento==null)
			return null;
		if (elemento.type=="text" || elemento.type=="hidden" || elemento.type=="textarea" || elemento.type=="select-one"){
			return elemento.value;
		}else
		if (elemento.type=="checbox"){
			if (elemento.checked)
				return (element.value);
		}else
		if (elemento.type=="radio"){
			var v = document.getElementsByName(id);
			if (v)
			for(var i=0; i<v.length; i++){
				if (v[i].checked)
					return v[i].value;
			}
		}
		else if (elemento.type=="select-multiple")
		{
			var v = [];
			for(var i=0; i<elemento.options.length; i++){
				if (elemento.options[i].selected)
					v.push(elemento.options[i].value);
			}
			return v;
		}
		else{			
			if (elemento.firstChild==null){
				return "";
			}else{
				return elemento.firstChild.nodeValue;
			}
		}
		return null;
	}
	/***********************************/
	//establece el valor de un documento
	function setValue(elemento, valor){
		elemento = getElement(elemento);
		if (elemento==null || elemento==undefined)
			return false;

		if (typeof(elemento)=="string")
		{
			var nombre = elemento;
			elemento = document.getElementById(nombre);
			if (elemento == null)
			{
				elemento = document.getElementsByName(nombre);
				if (elemento.length>0)
					elemento = elemento[0];
				else
					return false;
			}
		}
		
		if (elemento.type == "radio")
		{
			var v = document.getElementsByName(elemento.name);
			for(var i=0; i<v.length; i++)
			{
				v[i].checked = (v[i].value == valor);	
			}
		}
		else if (elemento.type == "checkbox")
		{
			var v = document.getElementsByName(elemento.name);
			if (v.length>1)
			{
				if (isArray(valor))
				{
					for(var i=0; i<valor.length; i++)
					{
						for(var j=0; j<v.length; j++)
						{
							if (v[j].value == valor[i])
							{
								v[j].checked = true;
								break;
							}
						}
					}
				}
				else
				{
					for(var j=0; j<v.length; j++)
					{
						v[j].checked = (v[j].value == valor);
						break;
					}
				}
			}
			else
			{
				if (valor)
					elemento.checked = true;
				else
					elemento.checked = false;
			}
		}
		else if (elemento.type=="text" || elemento.type=="hidden" || elemento.type=="textarea" || elemento.type == "select-one")
		{
			elemento.value = valor;
		}
		else if (elemento.type=="select-multiple")
		{
			//si se trata de un array
			if (isArray(valor))
			{
				for(var i=0; i<valor.length; i++)
				{
					for(var j=0; j<elemento.options.length; j++)
					{
						var op = elemento.options[i];
						if (op.value == valor[i])
						{
							op.selected = true;
							break;
						}
					}
				}
			}
			else
			{
				for(var i=0; i<elemento.options.length; i++)
				{
					var op = elemento.options[i];
					if (op.value == valor)
					{
						op.selected = true;
						break;
					}
				}
			}
		}
		else
		{
			var t = document.createTextNode(valor);
			if (elemento.firstChild)
				elemento.removeChild(elemento.firstChild);
			if (elemento.appendChild)
				elemento.appendChild(t);
		}
	}
	
	function isArray(valor)
	{
		return (valor!=null && typeof(valor)=="object" && valor.push);
	}
	
	/****************************************/
	//copia el texto en los elementos con el nombre nombre_destino
	function copiarTexto(texto, nombre_destino, pregunta){
		var destinos = document.getElementsByName(nombre_destino);
		
		if (pregunta==undefined)
			var pregunta = "Copiar?";
			
		if (destinos.length==0 || !confirm(pregunta))
			return false;

		for (var i=0; i<destinos.length; i++){
			setValue(destinos[i], texto);
		}//for
		return true;
	}//copiarTexto
	/***********************************/
	//copia el texto del elemento con el id id_origen en los elementos con el nombre nombre_destino
	function copiarValor(id_origen, nombre_destino){
		var origen = document.getElementById(id_origen);
		
		var texto = getValue(id_origen);
	
		return copiarTexto(texto, nombre_destino);
	}

	var timerPrecarga = null;
	var timerPrecarga2 = null;
	
	/** 
	 *  Oculta la capa con el id especificado una vez se haya 
	 * terminado de cargar la pagina (im?genes incluidas) 
	 * @param string idLoadingLayer ID de la capa que muestra un mensaje "cargando..." o similar
 	 */
	function esperarCargaPagina(idLoadingLayer){
		if (new Image().complete==undefined) //si no exciste la propieda complete en las imagenes
			return false;
		timerPrecarga2 = setTimeout("if (timerPrecarga){ var e = document.getElementById('"+idLoadingLayer+"');"
			+"if (e) e.style.display='none'; clearInterval(timerPrecarga);} ", 10000);
		
		timerPrecarga = setInterval(
			"var todasCargadas = true;"
			+"for(var i=0; i<document.images; i++)"
			+"	if (!document.images[i].complete) {todasCargadas = false; break;}"
			+"if (todasCargadas) {var e = document.getElementById('"+idLoadingLayer+"');"
			+"if (e) e.style.display='none'; clearInterval(timerPrecarga);}", 500);
			
	}

	/**
	 *	Establece la pagina de inicio del navegador
	 * @param string url URL de la pagina que se va a establecer como pagina de inicio
	 * @param HTMLAElement link Referencia del link desde donde se va a llamar a esta funcion (necesario s?lo para IExplorer)	
	 */
	function setHomePage(url, link){
		if ((window.netscape) && (window.netscape.security)){
			netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
			var home = navigator.preference('browser.startup.homepage');
			if (home != url){
				netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
				navigator.preference('browser.startup.homepage',url);
			}
		}else
		if (link){
			link.style.behavior = 'url(#default#homepage)';
			link.setHomePage(url);
		}
	}	

	/**
	 *	Dado un nodo padre, busca un nodo hijo cuyo calor de su atributo "attribute" coincida con el especificado en "value"
	 * @param node parentNode Nodo padre
	 * @param string attribute Nombre del atributo
	 * @param string value Valor que debe tener el atributo del nodo hijo
	 * @param bool bStrict Indica si el valor del atributo debe coindicir estrictamente o no 
	 *  (si se indica FALSE, value se tomara como una expresion regular)(por defecto TRUE)
	 * @return	nodeElement
	 */
	function buscarNodo(parentNode, attribute, value, bStrict){
		if (parentNode==null)
			return null;
		if (bStrict==undefined)
			bStrict = true;
		var e,v = parentNode.childNodes;
		for(var i = 0; i<v.length; i++){
			if ((bStrict && v[i][attribute]==value) ||
				(!bStrict && new RegExp(value).test(v[i][attribute]))){
				return v[i];
			}else
			if((e = buscarNodo(v[i], attribute, value, bStrict))!=null){
				return e;
			}
		}
		return null;
	}	
	
	/**
	 * Abre una nueva ventana con el documento especificado
	 * @param sURI
	 * @return Object
	 */
	function abrirVentana(sURI, sNombre, width, height, bResizable) { 
		var iTop = 0, iLeft = 0;
		
		if (width==undefined)
			var width = screen.availWidth;
		else
		if (width < screen.availWidth)		
			iLeft = (screen.availWidth - width)/2;
		
		if (height==undefined)
			var height = screen.availHeight;
		else
		if (height < screen.availWidth)
			iTop = (screen.availHeight - height)/2;
		
		var sOptions = "toolbar=no,directories=no,status=no,scrollbars=yes,menubar=no";
		sOptions += ",resizable=";
		if(bResizable == undefined || bResizable == true)
			sOptions +="no";
		else
			sOptions +="yes";
			
		if (iTop>0) sOptions+=",top="+iTop;
		if (iLeft>0) sOptions+=",left="+iLeft;
		if (width && (width>0)) sOptions+=",width="+width;
		if (height && (height>0)) sOptions+=",height="+height;
		
		var w = window.open(sURI, sNombre, sOptions);
		if (w)
			w.focus();
		return w;
	}

	/**
	 * Devuelve un array asociativo con las variables de GET
	 * @return string
	 */
	function parseGETVars(){
		var qs = location.search.substring(1);
		var nv = qs.split('&');
		var url = new Object();
		for(i = 0; i < nv.length; i++) {
			eq = nv[i].indexOf('=');
			url[nv[i].substring(0,eq).toLowerCase()] = unescape(nv[i].substring(eq + 1));
		}

		return url;
	}
	
	/**
	 * Obtiene el precio en el formato correcto
	 * @param double precio
	 * @return string
	 */
	function formatearPrecio(precio){
		var n = new Number(precio).toFixed(2);
		return n.toLocaleString();
	}
	
	/**
	 * Devuelve el primer valor de los argumentos pasados
	 * distinto de null/undefined/''
	 * @return mixed
	 */
	function chooseValue(){
		var v = arguments;
		for(var i=0; i<v.length; i++){
			if ((v[i]!='') && 
				(v[i]!==null) && 
				(v[i]!==undefined))
				return v[i];
		}
		return null;
	}

	/**
	 * Fuerza el refresco de un iframe aadiendo (cambiando)
	 * el parametro "refresco=timestamp"
	 * @param mixed iframe (string con el id del iframe en el documento )
	 * @return bool
	 */
	function refrescarFrame(frame, vParamsToRemove){
		
		if (frame==null || frame==undefined)
			return false;
			
		var s = frame.location.href;
		var sRefresco = "rfsh="+(new Date().getTime());
		
		if (vParamsToRemove)
		{
			if (!vParamsToRemove.push)
				vParamsToRemove = [vParamsToRemove];
			
			for(var i=0; i<vParamsToRemove.length; i++)
			{
				s = s.replace(new RegExp(vParamsToRemove[i]+"=[^&]*"),"")
			}
		}
		
		if (s.indexOf("rfsh=")>-1){
			s = s.replace(/rfsh=[^&]+/, sRefresco);
		}else{
			if (s.indexOf('#')>=0)
			{
				s = s.replace("#","");
			}

			if (s.indexOf("?")<0)
				s+="?";
			else
				s+="&";
			s+=sRefresco;
		}
		frame.location.href = s;
		return true;
	}

	/**
	 * Obtiene la referencia al iframe especificado
	 * @param mixed iframe
	 * @return HTMLFrameElement 
	 */
	function getIframe(iframe, target){
		if ((typeof(iframe)=="undefined") || (iframe==null))
			return null;
			
		if (typeof(target)=="undefined")
			target = self;
		else
		if (target==null)
			return null;
			
		if (typeof(iframe)=="string"){
			var sIframe = iframe;
			var iframes = getIframes();
			if (iframes == null)
				return null;
			 	
			iframe = getIframes()[iframe];
			if (!iframe)
				return null;
			
			var padre = target.parent;
			if (padre == target)
				return iframe;
				
			if (typeof(padre)=="undefined")
				padre = null;
			//si no se ha encontrado el iframe se busca en el marco padre (si existe)
			if (!iframe && padre)
				iframe = getIframe(sIframe, padre);		
		}
		return iframe;
	}
	
	function getIframes(target)
	{
		if (target == null || typeof(target)=="undefined")
			return [];
			
		if (navigator.isIExplorer()){
			if (target.document)
				return target.document.frames;
		}
		else{
			return target.frames;
		}
		return [];
	}
	
	/**
	 * Obtiene la URL actual en el frame indicado
	 * @param HTMLFrameElement target
	 * @return string
	 */
	function currentURL(target){
		if (typeof(target)=="undefined")
			var target = self;

		return target.location.protocol+"//"+
			target.location.hostname+":"+
			target.location.port+
			target.location.pathname;
	}
	
	/**
	 * Manda imprimir el iframe indicado
	 * @param mixed iframe Nombre del iframe o referencia al mismo
	 * @return bool
	 */
	function imprimirIframe(iframe){
		if (iframe==null || iframe==undefined)
			return false;
		
		iframe.focus();
		iframe.print();
		return true;
	}
	
	/**
	 * 
	 * @return string
	 */
	function URL2URI(sURL, sQueryString){
		if (sURL.indexOf("?")<0)
			sURL+="?";
		sURL+="&"+sQueryString;
		return sURL;
	}
	
	/**
	 * Elimina las marcas HTML de un texto
	 * @param sCodigo
	 * @return String
	 */
	function removeHTMLTags(sCodigo){
		return sCodigo.replace(/<[^>]+>/g, "");
	}
	
   /**
    * Resetea el valor del elemento de formulario indicado
    * @param HTMLElement elem
    * @return string Devuelve el valor por defecto
    */
    function resetValue(elem){
        if (!elem || !elem.type)
            return null;
        var i, v;            switch (elem.type){
        case "checkbox":
            elem.checked = elem.defaultChecked;
            break;
        case "radio":
            v = document.getElementsByName(elem.name);
            for (i=0; i<v.length; i++){
                v[i].checked = v[i].defaultChecked;                                     
			}
            break;
        case "select-one":
        case "select-multiple":
            v = elem.options;
           for(i=0; i<v.length; i++){
               v[i].selected = v[i].defaultSelected;
           }
            break;
        default:
            elem.value = elem.defaultValue;
        }
        return elem.value;
    } 
	
	function printContent(contenido, imprimir){
		window.contenido = contenido;
		var f;
		f = getIframe("frame_impresion");
		if (!f){
			f = document.createElement("iframe");
			f.name = "frame_impresion";
			f.id = "frame_impresion";
			f.style.width = "1px";
			f.style.height = "1px";
			f.style.borderStyle = "none";
			document.body.appendChild(f);
			f = getIframe(f.id);//f.contentWindow;
		}   
		
		try{
			f.document.body.innerHTML = contenido;	
			imprimir=true;   	   
		}catch(ex){
			setTimeout("printContent(window.contenido, true)", 200);
		}

		if (imprimir){
			f.focus();
			f.print();
		}
	} 	
	
	function scan(o){
		var s = "";
		for (var i in o){
			if (typeof(o[i])=="function")
				continue;
			s+=i+" = "+o[i]+"\n";
		}
		alert(s);
	}
	
	
	function desplazarMarquesina(idcontenido, dx, dy, ms, inicial){
		var e = document.getElementById(idcontenido);
		
		if (typeof(desplazarMarquesina.DefaultDX) == "undefined")
		{
			desplazarMarquesina.DefaultDX = dx;
			desplazarMarquesina.DefaultDY = dy;
			desplazarMarquesina.DefaultMS = ms;
			
		}

		//alert(screen.width);
		if (!e)
			return false;
		if (dx != 0)
		{
			if ((inicial==undefined) || (parseInt(e.style.left)<-e.offsetWidth))
				e.style.left = e.offsetParent.offsetWidth+"px";
			try{

			var ancho = parseInt(e.parentNode.style.width);
			if (ancho < e.offsetWidth)
			{		
				var v = getChildsByAttributes(e, 'className', 'elementoMarquesina');
				if (v.length>0)
				{
					var x = e.offsetLeft;
					var elem = null;
					var w1 = null;
					
					if (dx>0)
					{
						elem = v[0];
						w1 = elem.offsetWidth;
						
						if (x+w1<0)
						{
							elem.parentNode.appendChild(elem.cloneNode(true));
							elem.parentNode.removeChild(elem);
							e.style.left = (parseInt(e.style.left) + w1)+"px"; 
						}
					}
					else if (dx<0)
					{
						elem = v[v.length-1];
						w1 = elem.offsetWidth;
						
						if ((x+e.offsetWidth-w1)>ancho)
						{
							//alert(elem.innerHTML);
							elem.parentNode.insertBefore(elem.cloneNode(true),v[0]);
							elem.parentNode.removeChild(elem);
							e.style.left = (parseInt(e.style.left) - w1)+"px"; 
						}
					}
				}
			}
		
			e.style.left = (parseInt(e.style.left) - dx)+"px"; 
			}catch(ex)
			{alert(dx)}
		}
		else 
		if (dy != 0)
		{
			if ((inicial==undefined) || (parseInt(e.style.top)<-e.offsetHeight))
				e.style.top = e.offsetParent.offsetHeight+"px";
			e.style.top = (parseInt(e.style.top) - dy)+"px"; 
		}
		window['timeout_'+idcontenido] = setTimeout("desplazarMarquesina('"+idcontenido+"',"+dx+", "+dy+","+ms+", false)", ms);	
		//throw new Error(e.style.left+" = "+e.offsetWidth+","+e.offsetParent.offsetWidth );
	}
	
	function marqueePlay(idMarquesina, despx, despy, ms)
	{
		if (typeof(despx) == "undefined")
			despx = desplazarMarquesina.DefaultDX;

		if (typeof(despy) == "undefined")
			despy = desplazarMarquesina.DefaultDY;
			
		if (typeof(ms) == "undefined")
			ms = desplazarMarquesina.DefaultMS;
		desplazarMarquesina(idMarquesina, despx, despy, ms, false);
	}

	function marqueeStop(idMarquesina)
	{
		clearTimeout(window['timeout_' + idMarquesina]);
	}
	
	/**
	 * Limpia el valor seleccionado de un conjunto de radiobuttons dado
	 * @param string name Nombre del conjunto de radiobttons
	 */
	function clearRadioButtons(name){
		var v = document.getElementsByName(name);
		for (var i=0; i<v.length; i++){
			if (v[i].type=="radio")
				v[i].checked=false;
		}
	}
	
	/**
	 * Cambia la imagen sobre la que esta situado el cursor por otra con el sufijo _over
	 * @param HTMLImgElement img
	 */
	function imageOver(img){
		var sSrc = img.src;
		var i = sSrc.lastIndexOf("."); //busca el "." de la extension 
		img.src = sSrc.substring(0,i)+"_over"+sSrc.substring(i,sSrc.length);
		//alert(img.src);
	}

	/**
	 *Cambia la imagen sobre la que esta situado el cursor por otra sin el sufijo _over
	 * @param HTMLImgElement img	 
	 */
	function imageOut(img){
		var sSrc = img.src;
		var i1 = sSrc.lastIndexOf("_over");
		if (i1==-1)
			return false;
		var i2 = sSrc.lastIndexOf("."); //busca el "." de la extension
		img.src = sSrc.substring(0,i1)+sSrc.substring(i2,sSrc.length);
		//alert(img.src);
	}
	
	/**
	 * Dado un formlario, pone todos sus elementos a cadena vacia
	 */
	function limpiarFormulario(formu){
		var elem, v,j;

		for (var j=0; j<formu.elements.length; j++){
			elem = formu.elements[j];

			switch (elem.type){
			case "checkbox":
            elem.checked = false;
            break;
			case "radio":
            v = document.getElementsByName(elem.name);
            for (i=0; i<v.length; i++){
					if (v[i].form!=formu)
						continue;
					if (v[i].value=='')
						v[i].checked = true;
					else
						v[i].checked = false;
				}
				break;
         case "select-multiple":
            v = elem.options;
           for(i=0; i<v.length; i++){
					if (v[i].value=='')
						v[i].selected = true;
					else
						v[i].selected = false;
           }
           break;
        case "select-one":
        case "text":
		  case "textarea":
            elem.value = "";
        }
		} 					
	}
	
	function efectoCambiarColor(color,inc){
		var r,g,b;

		if (/([0-9]+)[^,]*,[^0-9]*([0-9]+)[^,]*,[^0-9]*([0-9]+)/.test(color)){
			r = parseInt(RegExp.$1);
			g = parseInt(RegExp.$2);
			b = parseInt(RegExp.$3);		
		} else 
		if (/([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/.test(color)){
			r = new Number('0x'+RegExp.$1);
			g = new Number('0x'+RegExp.$2);
			b = new Number('0x'+RegExp.$3);		
		}
		
		if (r%2==0) r+= Math.abs(inc); else r-= Math.abs(inc);
		if (g%2==0) g+= Math.abs(inc); else g-= Math.abs(inc);
		if (b%2==0) b+= Math.abs(inc); else b-= Math.abs(inc);

		if (r<0) r=0; else if (r>255) r=255;
		if (g<0) g=0; else if (g>255) g=255;
		if (b<0) b=0; else if (b>255) b=255;
		
		color = 'rgb('+r+','+g+','+b+')';
		return color;	
	}
	
	function aplicarEfectoCambiarColor(idelem, incColor, incBack){
		var e = document.getElementById(idelem);	
		if (!e)
			return false;
			
		if (incColor==undefined)
			incColor = 8;
		if (incBack==undefined)
			incBack = 16;
		//alert(cambiarColor(e.style.color,10))
		e.style.color = efectoCambiarColor(e.style.color,incColor);
		e.style.backgroundColor = efectoCambiarColor(e.style.backgroundColor,incBack);
		return true;
	}
	
function getDocumentWidth(win)
{
	if (!win)
		win = window;
	doc = win.document;
		
	if (doc.body.scrollWidth)
		return doc.body.scrollWidth;
	var w = doc.documentElement.offsetWidth;
	if (win.scrollMaxX)
		w += win.scrollMaxX;
	return w;
}

function getViewportWidth()
{
	return getViewportSize().width;
}

function getViewportHeight()
{
	return getViewportSize().height;
}

function getViewportSize()
{
	 var viewportwidth;
	 var viewportheight;
	 
	 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	 
	 if (typeof window.innerWidth != 'undefined')
	 {
		  viewportwidth = window.innerWidth,
		  viewportheight = window.innerHeight
	 }
	 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

	 else if (typeof document.documentElement != 'undefined'
		 && typeof document.documentElement.clientWidth !=
		 'undefined' && document.documentElement.clientWidth != 0)
	 {
		   viewportwidth = document.documentElement.clientWidth,
		   viewportheight = document.documentElement.clientHeight
	 }
	 
	 // older versions of IE
	 
	 else
	 {
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight
	 }
	return {width: viewportwidth, height: viewportheight};
}

function getDocumentHeight(win)
{
	if (win)
		doc = win.document;
	else
		doc = document;
	if (!doc || !doc.body)
		return null;
		
	if (doc.body.scrollHeight)
		return doc.body.scrollHeight;
	return doc.documentElement.offsetHeight;
}

function getDocumentSize()
{
	var h = 0; // height
	var w = 0; // width
	if( typeof( window.innerHeight ) == 'number' ) {
		//no es IE
		h = window.innerHeight;
		w = window.innerWidth;
	} else if( document.body && document.body.clientHeight ) {
		//IE 4 o superior
		h = document.body.clientHeight;
		w = document.body.clientWidth;
	}
	return {width:w, height:h};
}

function ajustarAltoFrame(win, iExtra)
{	
	if (!win)
		win = window;
		
	if (!iExtra)
		iExtra = 80;
		
	var hijo = win;
	var padre = win.parent;

	while (padre)
	{
		var e = null, alto;
		var v = padre.document.getElementsByTagName('iframe');
		for(var i=0; i<v.length; i++)
		{
			e = v[i];

			if (e.contentWindow == hijo)
			{
				alto = getDocumentHeight(hijo);
				if (alto && (alto > 0))
				{
					e.style.height = (alto + iExtra) + "px";
				}
				break;
			}
		}

		if (padre.parent == padre)
			return true;
		hijo = padre;
		padre = padre.parent;
	}
	return true;
}


function precargarImagenes(vImagenes)
{
	if (!vImagenes.push)
		vImagenes = [vImagenes];
		
	var img;
	for(var i=0; i<vImagenes.length; i++)
	{
		img = document.createElement('img');
		img.alt='';
		img.src=vImagenes[i];
		img.style.display='none';
		document.body.insertBefore(img, document.body.firstChild);
	}
}

/**
  * Aplica los elementos max-width y max-height (definidos en los atributos style de cada imagen) en las imágenes con la extensión especificada
  *  (Si no se especifica una extensión se aplicarán las acciones pertinentes sobre todas las imágenes).
  * Debe invocarse a la función una vez se hayan cargado las imágenes del documento (al final del body o en el evento onload del mismo)
  * y (OJO) antes de llamar al script "pngfix" (en caso de usarse éste último).
  */
function fixMaxDimensions(extension)
{
	var iAnchoMax, iAltoMax, img, re;
	var v = document.getElementsByTagName('img');

	for(var i=0; i<v.length; i++)
	{
	
		iAnchoMax = 0;
		iAltoMax = 0;
		img = v[i];	

		if (extension && !(new RegExp('\\.'+extension+'$','gi').test(img.src)))
		{
			continue;
		}

		re = new RegExp('max\\-width\\:[ \t]*([0-9]+)px', "gi");
		if (re.exec(img.style.cssText)!=null)
			iAnchoMax = parseInt(RegExp.$1);

		re.compile('max\\-height\\:[ \t]*([0-9]+)px', "gi");
		if (re.exec(img.style.cssText)!=null)
			iAltoMax = parseInt(RegExp.$1);
		
		iAlto = img.height;
		iAncho = img.width;
		
		/*
		if (iAltoMax > 0 || iAnchoMax > 0)
		{
			alert(
				"style = " + img.style.cssText + "\n" + 
				"complete = " + img.complete + "\n" + 
				"Src = " + img.src + "\n" + 
				"iAncho = " + iAncho + "px\n" + 
				"iAlto = " + iAlto + "px\n" + 
				"iAnchoMax = " + iAnchoMax + "px\n" + 
				"iAltoMax = " + iAltoMax + "px\n"
				);
		}
		/**/
		var bAncho = false;
		
		if (iAnchoMax>0 && iAnchoMax<iAncho)
		{	
			bAncho = true;
			img.style.width = iAnchoMax+"px";
		}
		
		if (iAltoMax>0 && iAltoMax<iAlto)
		{
			if (!bAncho || 
				(iAltoMax<=iAnchoMax && iAlto>iAncho) ||
				(img.height>iAltoMax))
			{
				img.style.width="";
				img.style.height = iAltoMax + "px";
			}
		}
		
		
	}
	return true;
}

function getElement(ident)
{	
	var e = ident;
	if (typeof(ident)=="string")
	{
		e = document.getElementById(ident);
		if (!e)
		{
			var v = document.getElementsByName(ident);
			if (v && (v.length>0))
				e = v[0];
		}
	}
	return e;
}

/**
 * Se debería llamar a esta función desde el evento onkeyup de un cuadro de texto
 * Ejemplo: onkeyup="autotab(this, 'id_siguientecampo');"
 */
function autotab(actual, siguiente, anterior){
	var eSig = getElement(siguiente);
	var eAnt = getElement(anterior);

    if (actual.getAttribute)
	{
		//si hemos llegado al final
		if (eSig && (actual.value.length==actual.getAttribute("maxlength"))) {
			eSig.focus();
			return true;
		}	
		
		if (eAnt && (actual.value.length==0))
		{
			eAnt.focus();
			return true;
		}
		
    }
	return false;
}

