// CAMBIA EL COLOR DE FONDO Y BORDE EL OBJETO SELECCIONADO
// EJEMPLO: onmouseover(this); onmouseout(this);

// --- TR mouseOver/mouseOut	multi/color
rrbgbackup = '';
function rOver(obj){ rrbgbackup = obj.style.backgroundColor; obj.style.backgroundColor = '#f0f0f0'; }
function rOut(obj){ obj.style.backgroundColor = rrbgbackup; }


function popup_redimensionar() {
	ancho =  document.getElementById('popup_redimensionar').offsetWidth;
	alto =  document.getElementById('popup_redimensionar').offsetHeight;
	if(ancho >= screen.width){ ancho = screen.width; }
	if(alto >= screen.height){ alto = screen.height; }
	top.resizeTo(ancho,alto);
	window.resizeBy(24,47);
	// Centrando Ventana
	iz=(screen.width-document.body.clientWidth) / 2; 
	de=(screen.height-document.body.clientHeight) / 2; 
	moveTo(iz,de);
}
	

/*---------------------------------------------------------------------------------------------*/
/* Los inputs deben tener unos nombres predefinidos y fijos el formulario: fila, estiloselec y */
/* estiloactual. Tambien se le pasa el identificador de la fila actualmente seleccionada.      */
/* Ejemplo: listaClick(document.seleccion, this.id); (el resultado es igual q el anterior)     */
/* *NOTA: si no se desea que se pueda desmarcar una fila marcada, basta con quitar el 'if'     */
/*        principal y toda la parte del 'else'.                                                */
/*---------------------------------------------------------------------------------------------*/
function listaClick (formulario, idfila) {
	if (formulario.fila.value!=idfila) {		/* Comprobamos si la fila no se encuentra marcada.*/
		if (formulario.estiloselec.value!=''){	/* Comprobamos si habia una fila marcada 		  */									
			document.getElementById(formulario.fila.value).className=formulario.estiloselec.value;
		} 
		formulario.fila.value=document.getElementById(idfila).id;	/* Almacenamos el id de la fila marcada. */
		formulario.estiloselec.value=formulario.estiloactual.value;		/* Almacenamos el estiloselec actual.         */
		document.getElementById(idfila).className='lista_select_marcada';/* Marcamos la fila seleccionada.   */
	}else{  							/* si se marca una fila ya marcada, se desmarca. */
		document.getElementById(formulario.fila.value).className=formulario.estiloselec.value;
		formulario.estiloactual.value=formulario.estiloselec.value;		   
		formulario.fila.value='';			/* ponemos el estiloselec anterior  */
		formulario.estiloselec.value='';
		//parent.bt_limpia();		
	}
}
/*-------------------------------------------------------------------------------------------*/   
/* Gestiona la pasada del ratón sobre las filas de la tabla.					   */
/*-------------------------------------------------------------------------------------------*/   
function listaOver (formulario, idfila) {
	if (document.getElementById(idfila).id!=formulario.fila.value) { // Si la fila no esta marcada.
		/* Antes de asignarle la clase de selección (!!ojo!! no la clase de fila marcada), es	*/
		/* decir, la clase de cuando se mueve el ratón sobre la fila, guardamos la clase que	*/
		/* tiene la fila antes de asignar la clase de selección.						*/
		formulario.estiloactual.value=document.getElementById(idfila).className;	 /* Guardamos y   */
		
		/* asignamos a la fila la clase de selección. */
		if(document.getElementById(idfila).className == 'lista_select') {
			document.getElementById(idfila).className = 'lista_select_over';
		}else{
			document.getElementById(idfila).className = 'lista_over';
		}		
	}else{
		//formulario.estiloactual.value=formulario.estiloselec.value;
		formulario.estiloactual.value=document.getElementById(idfila).className;	
	}
	
}
/*-------------------------------------------------------------------------------------------*/      
/* Gestiona cuando el puntero del ratón sale de la fila.                                     */
/*-------------------------------------------------------------------------------------------*/   
function listaOut (formulario, idfila) {
	/* Si el ratón sale de una fila no marcada, le pone la clase */
	/* que tenía antes de entrar						 */
	if (document.getElementById(idfila).id!=formulario.fila.value) {  
		document.getElementById(idfila).className=formulario.estiloactual.value; /* Le ponemos su clase normal*/
	}
}
/*-------------------------------------------------------------------------------------------*/      
/* Gestiona cuando se limpia el formulario de operaciones                                    */
/*-------------------------------------------------------------------------------------------*/   
function listaDesmarca (formulario) {
	if (document.getElementById(formulario.fila.value)) {
		document.getElementById(formulario.fila.value).className=formulario.estiloselec.value;
	}
	formulario.fila.value='';	
	formulario.estiloselec.value='';	
}
/*-------------------------------------------------------------------------------------------*/   
/*-------------------------------------------------------------------------------------------*/   
/*-------------------------------------------------------------------------------------------*/   
/*-------------------------------------------------------------------------------------------*/   
/*-------------------------------------------------------------------------------------------*/   
function countLines(strtocount, cols) {
	var hard_lines = 1;
	var last = 0;
	while ( true ) {
		last = strtocount.indexOf("\n", last+1);
		hard_lines ++;
		if ( last == -1 ) break;
	}
	var soft_lines = Math.round(strtocount.length / (cols-1));
	var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
	if ( hard ) soft_lines = hard_lines;
	return soft_lines;
}

function cleanForm() {	
   
	for ( var n_form in document.forms ) {	    				    		    
		the_form = document.forms[n_form];
		//alert (the_form.name);			
			    
		for ( var x in the_form ) {
		  if ( ! the_form[x] ) continue;
		  if( typeof the_form[x].rows != "number" ) continue;
		  the_form[x].rows = countLines(the_form[x].value,the_form[x].cols) + 1;
		}
	
	}		    
	setTimeout("cleanForm();", 300);	    
}




function popup(url,ancho,alto) { 
	// Abre una ventana y la centra
	var win = null;
	LeftPosition = (screen.width) ? (screen.width-ancho)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-alto)/2 : 0;
	settings = 'height='+alto+',width='+ancho+',top='+TopPosition+',left='+LeftPosition+',toolbar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=1,copyhistory=0,dependent=0,channelmode=0';
	win = window.open(url,'',settings);
	//window.open(url , "" , "width="+ancho+",height="+alto+",toolbar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=1,copyhistory=0,dependent=0,channelmode=0"); 
}



function button_op(form,op){
	eval("document."+form+".op.value=op");
	eval("document."+form+".submit()");
}



// Busca un valor en un array
Array.prototype.in_array = function(search_term) {
  var i = this.length;
  if (i > 0) {
	 do {
		if (this[i] === search_term) {
		   return true;
		}
	 } while (i--);
  }
  return false;
}




// ----------------------------------------------------------------------------------------------
//
// FUNCIONES AJAX
//
// ----------------------------------------------------------------------------------------------

function nuevoAjax(){ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
}


if(navigator.userAgent.indexOf("MSIE")>=0) navegador=0; // IE
else navegador=1; // Demas

function traerDatos(url_apps,variables,id_div){
	// Obtendo la capa donde se muestran las respuestas del servidor
	var capa=document.getElementById(id_div);
	// Creo el objeto AJAX
	var ajax=nuevoAjax();
	// Coloco el mensaje "Cargando..." en la capa
		//capa.innerHTML="Cargando...";
		capa.innerHTML='<img src="themes/default/img/loading_16x16.gif" border="0">';
	// Abro la conexión, envío cabeceras correspondientes al uso de POST y envío los datos con el método send del objeto AJAX
	ajax.open("POST", url_apps, true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	//ajax.send("d="+variables);
	ajax.send(variables);

	ajax.onreadystatechange=function(){
		if(ajax.readyState==4){
			// Obtengo el XML y separo sus nodos
			var resp=ajax.responseXML;
			var javascript=resp.getElementsByTagName("javascript")[0].childNodes[0].data;
			var css=resp.getElementsByTagName("css")[0].childNodes[0].data;
			var html_string=resp.getElementsByTagName("html_string")[0].childNodes[0].data;

			// Creo el nuevo JS
			var etiquetaScript=document.createElement("script");
			document.getElementsByTagName('head')[0].appendChild(etiquetaScript);
			etiquetaScript.text=javascript;
			
			// Creo el nuevo CSS
			var etiquetaStyle=document.createElement("style");
			document.getElementsByTagName('head')[0].appendChild(etiquetaStyle);
			
			/*
			if(navegador==0){
				var contenidoCSS=css.split("{");
				var ultimaEtiquetaStyle=document.styleSheets[document.styleSheets.length-1];
				ultimaEtiquetaStyle.addRule(contenidoCSS[0], "{"+contenidoCSS[1]);
			}else{
				var contenidoCSS=document.createTextNode(css);
				etiquetaStyle.appendChild(contenidoCSS);
			}
			*/
			
			capa.innerHTML = html_string;
		}
	}
}





// --------------------------------------------------------------------------------------------------------------------
// --- Creacion de pestañas organizadas por grupos
// --------------------------------------------------------------------------------------------------------------------

function ps_grupo(ps_array, grupo){
	// --- Devuelve un array con las pestañas del grupo seleccionado
	// --- var ps_array -> 'grupo:pestaña1,pestaña2,pestaña3'
	for (i=0; i < ps_array.length; i++) {
		linea = ps_array[i];
		partes = linea.split(':');
		//alert(i+' - '+partes[1]);
		if(grupo == partes[0]){
			return partes[1].split(',');
			break;
		}
	}
}
	
function ps_active(ps_array,grupo,ps){
	// --- Activa la pestaña del grupo seleccionado, y oculta el resto
	// --- ps_array contiene el array con los grupos y pestañas de cada grupo
	// --- Usa dos estilos para representar las pestañas, psc_boton y psc_boton_on
	// --- el id de los div a mostrar/ocultar tiene que ser del tipo: capa_nombreGrupo_nombrePestaña
	// --- el id de las pestañas a activar/desactivar tiene que ser del tipo: ps_nombreGrupo_nombrePestaña
	// --- Ejemplo:
	// ---	var ps_array = new Array(
	// ---			'grupo_uno:datos,envio,envio_2',
	// ---			'grupo_dos:presupuestos,notas',
	// ---			'grupo_tres:facturacion,contrato'
	// ---			);
	
	
	pes_array = ps_grupo(ps_array, grupo);
	for (i=0; i < pes_array.length; i++) {
		caja_obj = document.getElementById('caja_'+grupo+'_'+pes_array[i]);
		
		if(caja_obj){ document.getElementById('caja_'+grupo+'_'+pes_array[i]).style.display = 'none'; }
		document.getElementById('ps_'+grupo+'_'+pes_array[i]).className = 'psc_boton';
	}
	if(caja_obj){ document.getElementById('caja_'+grupo+'_'+ps).style.display = 'block'; }
	document.getElementById('ps_'+grupo+'_'+ps).className = 'psc_boton_on';
}
