
var READY_STATE_COMPLETE=4;
var ajax = null;
var zoom = 4;
var speed = 4;
var real = 0;
var intervalIn;
var liIndex = 0;
var activeMenuItem = false;
var currentZIndex = 1000;
var nMenu=10; /* nº elementos del menu principal */
var primera_vez=1;
var array_banderas=new Array("langg_es_ES","langg_en_EN", "langg_de_DE", "langg_fr_FR"); /* Este array tb esta en tpl_header */
var SearchTimeOut = 0;
var Interval = 500;
var CurrentSearchKey = '';

/* Funcion que crea un objeto ajax */
function objetoAjax(){
	var xmlhttp=false;
	if(window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
	}
	else if(window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xmlhttp;
}
/* Funcion que marca el tab activo y el inactivo y les da un estilo preterminado
 * ntabs: numero de tabs que se muestran
 * selected: tab que esta seleccionado (es un numero) 
 * etiquetas: nombre de los titulos que componen los tabs. Estos titulos tienen que ir en el mismo orden que estan los tabs definidos
 * por ejemplo el titulo del tab_1 estara en la posicion 1 del array "etiquetas"
 */
function mostrarTabs(ntabs,selected,etiquetas, img){
	/* definir prefijo de botones (esto con el objetivo de no tener problemas al momento de validarnuestra página.) */
	if (img==0 || img==""){
		pref="tab_";
	}
	else{
		pref="img_";
	}	
	/* Se quita el estilo a todos los botones */
	for(i=0;i<ntabs;i++){
		tit=etiquetas[i];
		btn=document.getElementById(pref+i);
		btn.innerHTML="<span class=\"tab_out\">"+tit+"</span>";
	}
	/* Se da estilo al boton actual */
	btnA = document.getElementById(pref+selected);
	tit=etiquetas[selected];
	btnA.innerHTML="<span class=\"tab_in\">"+tit+"</span>";
}
/* Funcion que compone los tabs
 * en ntabs el numero de tabs que hay en la pagina 
 * en etiquetas, el nombre que va en cada tab. 
 * para pasar la lista con las etiquetas de php a javascript se ha hecho con la funcion split
 * asi se consigue que la funcion sea generica
*/
function componerTabs(selected){
	mostrarTabs(document.getElementById('ntabs').value,selected,document.getElementById('etiquetas').value.split('#'), 0);
}
/* Funcion que muestra el tab seleccionado de las propiedas del modelo */
function showElementModelo(div,pagina,boton){
	/* cont: es el div donde se mostrara la pagina */	
	conte = document.getElementById(div);
	/* Se crea el objeto ajax */
	ajax3=objetoAjax();
	/* Llamamos a la pagina con el metodo GET*/
    ajax3.open("GET",pagina,true);
	ajax3.onreadystatechange = function(){
		if (ajax3.readyState == 4 && ajax3.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont*/
			conte.innerHTML = ajax3.responseText;
		}
	}
	ajax3.send(null);
	nt=3;
	etiq="<img src=\"../images/btPropiedades.gif\" width=\"20px\" />#<img src=\"../images/btEnvasado.gif\" width=\"20px\" />#<img src=\"../images/btCodeBar.gif\" width=\"20px\" />";
	mostrarTabs(nt,boton,etiq.split('#'),'1');
}
/* Funcion que muestra el tab seleccionado */
function showElementTab(div,pagina,boton){
	/* cont: es el div donde se mostrara la pagina */	
	conte = document.getElementById(div);
	/* Se crea el objeto ajax */
	ajax2=objetoAjax();

	/* Llamamos a la pagina con el metodo GET*/
    ajax2.open("GET",pagina,true);
	ajax2.onreadystatechange = function(){
		if (ajax2.readyState == 4 && ajax2.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont*/
			conte.innerHTML = ajax2.responseText;	
			/*if (pagina.substring(0,28)=='../ajax/adminModelo_ajax.php'){
				showElementModelo('datosModeloDcha','../ajax/admin_modeloDatos.php'+pagina.substring(28),'0');
			}*/
		}
	}
	ajax2.send(null);
	componerTabs(boton);
}
/*Las tres funciones siguiente hacen los mismo que las tres anteriores solo que añade en la pagina una etiqueta
input que contiene la informacion de la pestaña activa*/

function mostrarCTabs(ntabs,selected,etiquetas){
	/* definir prefijo de botones (esto con el objetivo de no tener problemas al momento de validarnuestra página.) */
	pref="tab_";
	/* Se quita el estilo a todos los botones */
	for(i=0;i<ntabs;i++){
		tit=etiquetas[i];
		btn=document.getElementById(pref+i);
		btn.innerHTML="<span class=\"tab_out\">"+tit+"</span>";
	}
	/* Se da estilo al boton actual */
	btnA = document.getElementById(pref+selected);
	tit=etiquetas[selected];
	if(btnA)
		btnA.innerHTML="<span class=\"tab_in\">"+tit+"</span><input type='hidden' id=\"tab\" value="+selected+">";
}
/* Funcion que compone los tabs
 * en ntabs el numero de tabs que hay en la pagina 
 * en etiquetas, el nombre que va en cada tab. 
 * para pasar la lista con las etiquetas de php a javascript se ha hecho con la funcion split
 * asi se consigue que la funcion sea generica
*/
function componerCTabs(selected){
	mostrarCTabs(document.getElementById('ntabs').value,selected,document.getElementById('etiquetas').value.split('#'));
}
/* Funcion que muestra el tab seleccionado */
function showElementControlTab(div,pagina,boton,graph){
	/* cont: es el div donde se mostrara la pagina */	
	conte = document.getElementById(div);
	/* Se crea el objeto ajax */
	ajax2=objetoAjax();
	/* Llamamos a la pagina con el metodo GET*/
    ajax2.open("GET",pagina,true);
	ajax2.onreadystatechange = function(){
		if (ajax2.readyState == 4 && ajax2.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont*/
			conte.innerHTML = ajax2.responseText;	
		}
	}
	ajax2.send(null);
	componerCTabs(boton);
}
/* Funcion que evalua la pagina que se pasa por parametro y almacena el resultado en el div "contenido_stock" */
function mostrarProductos(pagina,boton,buscar,modelo,serie,formato,pageNo,sortby,sorttype,mid,fid,sid,div){
	/* cont: es el div donde se mostrara la lista de modelos */	
	cont = document.getElementById('contenido_stock');
	/* Se crea el objeto ajax */
	ajax=objetoAjax();
	/* Se compone la pagina y se añaden las variables $_GET que hay en ese momento */
	url=pagina+"?bt="+encodeURIComponent(boton);
	parametros="?bt="+encodeURIComponent(boton);
	vector_get = new Array('buscar','modelo','serie','formato','pageNo','sortby','sorttype','mid','fid','sid','div');
	for (var i=0;i<vector_get.length;i++){
		if (eval(vector_get[i])!=undefined && eval(vector_get[i])!=null && eval(vector_get[i])!=""){
			url=url+"&"+vector_get[i]+"="+encodeURIComponent(eval(vector_get[i]));
			parametros=parametros+"&"+vector_get[i]+"="+encodeURIComponent(eval(vector_get[i]));
			
		}
	}
	parametros=parametros+"&esc="+document.getElementById('verEscalado').value+"&nocache=" + Math.random();
	url=pagina+parametros;

	/* Llamamos a la pagina con el metodo GET*/
    ajax.open("GET", url,true);
    ajax.onreadystatechange = function(){
		if (ajax.readyState == 4 && ajax.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont*/
			cont.innerHTML = ajax.responseText;
			document.getElementById('bt').value=boton;
			/*if (pagina=='../ajax/adminModelo_ajax.php'){
				showElementModelo('datosModeloDcha','../ajax/admin_modeloDatos.php'+parametros,'0');
			}*/
		}
	}
	ajax.send(null);
	componerTabs(boton);
}
/* Funcion que consulta la disponibilidad de un producto */
function consultarStock(div,boton,mid, fid,sid,unid,valor,un,pageNo,sortby,sorttype){
	/* cont: es el div donde se mostrara la lista de modelos */	
	cont = document.getElementById(div);
	/* Se crea el objeto ajax */
	ajax=objetoAjax();
		
	/* Se compone la pagina y se añaden las variables $_GET que hay en ese momento */
	url="../ajax/adminModelo_ajax.php?bt="+encodeURIComponent(boton);
	vector_get = new Array('mid','fid','sid','unid','valor','un','pageNo','sortby','sorttype','div');
	for (var i=0;i<vector_get.length;i++){
		if (eval(vector_get[i])!=undefined && eval(vector_get[i])!=null && eval(vector_get[i])!=""){
			url=url+"&"+vector_get[i]+"="+encodeURIComponent(eval(vector_get[i]));
		}
	}
	url=url+"&stock=1&nocache=" + Math.random();
	/* Llamamos a la pagina con el metodo GET*/
    ajax.open("GET", url,true);
    ajax.onreadystatechange = function(){
		if (ajax.readyState == 4 && ajax.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont*/
			cont.innerHTML = ajax.responseText;
			//document.getElementById('bt').value=boton;
		}
	}
	ajax.send(null);
	componerTabs(boton);
}
/* Funcion que devuelve el radio button seleccionado */
function radioButtonSelected(valores){
	valor=-1;
	if (valores!=undefined){
		for(var i=0;i<valores.length;i++){
	        if(valores[i].checked){
        		valor=valores[i].value;
        	}
    	}
    }
    return valor;
}
/*
 * Nombre: manageSerie
 * Descripcion: Funcion que controla las series que se van seleccionando y eliminando en la sesion
 * Param. entrada:
 * 		serie_id: id de la serie que se ha marcado en el checkbox
 *		ds: (deleteSerie, id de la serie que se va a eliminar de la sesion desde la parte derecha	
 * Param. salida: el html actualizado con los cambios sufridos en las series almacenadas en la sesion
*/
function manageSerie(serie_id,ds){
	conti = document.getElementById('div_carro');	
	url='../ajax/catalogo_ajax.php';
	/* Se crea el objeto ajax */
	ajax1=objetoAjax();
	
	/* Se compone la url */
	if (serie_id!=null){
		url=url+'?serie_id='+serie_id;
	}
	if (ds!=null){
		if (serie_id!=null){
			url=url+'&ds='+ds;
		}
		else{
			url=url+'?ds='+ds;
		}
	}
	/* Llamamos a la pagina con el metodo GET*/
    ajax1.open("GET",url,true);
    ajax1.onreadystatechange = function(){
		if (ajax1.readyState == 4 && ajax1.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont */
			conti.innerHTML = ajax1.responseText;
			if (ds!==null && ds!="" && ds!='-1'){ /* Se desmarca el checkbox de la serie eliminada */
				document.getElementById('serie_'+ds).checked=false;
			}
			else if (ds=='-1'){
				for (i=0;i<document.f1.elements.length;i++)
      				if(document.f1.elements[i].type == "checkbox")
         				document.f1.elements[i].checked=false; 
			}
		}
	}
	ajax1.send(null);
}

/* Funcion que muestra u oculta los elementos del menu principal */
function showSubMenu(menu,url){
	 /* Se ponen como no visibles todos los submenus */ 
	for(i=0;i<=nMenu;i++){
		pref='sub_menu_';
		menuItem=document.getElementById(pref+i);
		if (menuItem){
				menuItem.style.display = 'none';
		}
	}
	if (document.getElementById(menu)){
		vista = (document.getElementById(menu).style.display == 'none') ? 'block' : 'none';
		document.getElementById(menu).style.display = vista;
	}
}

function parametros_admin_catalogoConfigEdit(){
	var color_fuente_titulo_r = document.getElementById("color_fuente_titulo_r");
	var color_fuente_titulo_g = document.getElementById("color_fuente_titulo_g");
	var color_fuente_titulo_b = document.getElementById("color_fuente_titulo_b");
	var color_fuente_detalle_r = document.getElementById("color_fuente_detalle_r");
	var color_fuente_detalle_g = document.getElementById("color_fuente_detalle_g");
	var color_fuente_detalle_b = document.getElementById("color_fuente_detalle_b");
	var color_linea_r = document.getElementById("color_linea_r");
	var color_linea_g = document.getElementById("color_linea_g");
	var color_linea_b = document.getElementById("color_linea_b");
	var color_fuente_linea_r = document.getElementById("color_fuente_linea_r");
	var color_fuente_linea_g = document.getElementById("color_fuente_linea_g");
	var color_fuente_linea_b = document.getElementById("color_fuente_linea_b");
	var formato_max = document.getElementById("formato_max");
	var tamanyo_min_web = document.getElementById("tamanyo_min_web");
	var tamanyo_min_catalogo = document.getElementById("tamanyo_min_catalogo");
	
	return  'btSave=1&color_fuente_titulo_r='+encodeURIComponent(color_fuente_titulo_r.value)+
			'&color_fuente_titulo_g='+encodeURIComponent(color_fuente_titulo_g.value)+
			'&color_fuente_titulo_b='+encodeURIComponent(color_fuente_titulo_b.value)+
			'&color_fuente_detalle_r='+encodeURIComponent(color_fuente_detalle_r.value)+
			'&color_fuente_detalle_g='+encodeURIComponent(color_fuente_detalle_g.value)+
			'&color_fuente_detalle_b='+encodeURIComponent(color_fuente_detalle_b.value)+
			'&color_linea_r='+encodeURIComponent(color_linea_r.value)+
			'&color_linea_g='+encodeURIComponent(color_linea_g.value)+
			'&color_linea_b='+encodeURIComponent(color_linea_b.value)+
			'&color_fuente_linea_r='+encodeURIComponent(color_fuente_linea_r.value)+
			'&color_fuente_linea_g='+encodeURIComponent(color_fuente_linea_g.value)+
			'&color_fuente_linea_b='+encodeURIComponent(color_fuente_linea_b.value)+
			'&formato_max='+encodeURIComponent(formato_max.value)+
			'&tamanyo_min_web='+encodeURIComponent(tamanyo_min_web.value)+
			'&tamanyo_min_catalogo='+encodeURIComponent(tamanyo_min_catalogo.value)+
			"&nocache=" + Math.random();
}
function parametros_admin_categoriaEdit(){
	url='';
	vector_get = new Array('familia','familia_esp','sortby','sorttype');
	for (var i=0;i<vector_get.length;i++){
		var elemento = document.getElementById(vector_get[i]);
		if (elemento!=undefined && elemento!=null && elemento!=""){
			url=url+"&"+vector_get[i]+"="+encodeURIComponent(elemento.value);
		}
	}
	url=url+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_categoriaEditCampo(){
	url='';
	vector_get = new Array('categoria','orden');
	for (var i=0;i<vector_get.length;i++){
		var elemento = document.getElementById(vector_get[i]);
		if (elemento!=undefined && elemento!=null && elemento!=""){
			url=url+"&"+vector_get[i]+"="+encodeURIComponent(elemento.value);
		}
	}
	url=url+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_categoriaNew(){
	url='';
	vector_get = new Array('categoria','orden','familia');
	for (var i=0;i<vector_get.length;i++){
		var elemento = document.getElementById(vector_get[i]);
		if (elemento!=undefined && elemento!=null && elemento!="" ){
			url=url+"&"+vector_get[i]+"="+encodeURIComponent(elemento.value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_userCatalogo_ajax(){
	url='';
	vector_get = new Array('combo_estancia','combo_formato','combo_tipoProducto');
	for (var i=0;i<vector_get.length;i++){
		var elemento = document.getElementById(vector_get[i]);
		if (elemento!=undefined && elemento!=null && elemento!=""){
			url=url+"&"+vector_get[i]+"="+encodeURIComponent(elemento.value);
		}
	}	
	url=url+"&nocache=" + Math.random();
	return url;
}

function parametros_admincatalogoSerie_ajax(busqueda){
	url='';
	if (busqueda!=2){
		vector_get = new Array('visible','busqueda','novedad','serie_select');
		for (var i=0;i<vector_get.length;i++){
			var elemento = document.getElementById(vector_get[i]);
			if (elemento!=undefined && elemento!=null && elemento!=""){
				if(elemento.value!="")
					url=url+"&"+vector_get[i]+"="+encodeURIComponent(elemento.value);
			}
		}	
		if (document.getElementById('check_todas')!==null && document.getElementById('check_todas').checked==true)
			url=url+'&check_todas=true';
	}
	else
		url=url+"visible=1&novedad=2";
	url=url+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoSerieEdit(){
	url='';
	vector_get = new Array('id','codigo_s');
	for (var i=0;i<vector_get.length;i++){
		var elemento = document.getElementById(vector_get[i]);
		if (elemento!=undefined && elemento!=null && elemento!=""){
			if(elemento.value!="")
				url=url+"&"+vector_get[i]+"="+encodeURIComponent(elemento.value);
		}
	}	
	url=url+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoEstanciaNew(){
	url='';
	for (var j=0;j<document.forms["form1"].elements.length;j++){
		var nombre=document.forms["form1"].elements[j].name;
		if (nombre!=undefined && nombre!=null && nombre!="" ){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoEstanciaEdit(){
	url='';
	for (var j=0;j<document.forms["form1"].elements.length;j++){
		var nombre=document.forms["form1"].elements[j].name;
		if (nombre!=undefined && nombre!=null && nombre!="" ){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoFormatoEdit(){
	url='';
	for (var j=0;j<document.forms["form1"].elements.length;j++){
		var nombre=document.forms["form1"].elements[j].name;
		if (nombre!=undefined && nombre!=null && nombre!="" && document.forms["form1"].elements[j].checked==true){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoProductoNew(){
	url='';
	for (var j=0;j<document.forms["form1"].elements.length;j++){
		var nombre=document.forms["form1"].elements[j].name;
		if (nombre!=undefined && nombre!=null && nombre!="" ){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_user_datosEdit(){
	url='';
	for (var j=0;j<document.forms["form1"].elements.length;j++){
		var nombre=document.forms["form1"].elements[j].name;
		var value = document.forms["form1"].elements[j].value;
		if(nombre.indexOf('notificaciones')!='-1' || nombre.indexOf('mail_facturas')!='-1'){
			if (document.forms["form1"].elements[j].checked==true)
				url=url+"&"+nombre+"="+encodeURIComponent('on');
			else
				url=url+"&"+nombre+"="+encodeURIComponent('false');
		}		
		else if (nombre!=undefined && nombre!=null && nombre!="" ){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}		
		else if (nombre!=undefined && nombre!=null && nombre!="" ){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_user_changePss(){
	url='';
	for (var j=0;j<document.forms["form1"].elements.length;j++){
		var nombre=document.forms["form1"].elements[j].name;
		if (nombre!=undefined && nombre!=null && nombre!="" ){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_user_datosWebEdit(){
	url='';
	vector_get = new Array('nombre','nif','nifcee','direccion','localidad','provincia','pais','telf1','telf2','fax','email','web');
	for (var i=0;i<vector_get.length;i++){
		var elemento = document.getElementById(vector_get[i]);
		if (elemento!=undefined && elemento!=null && elemento!=""){
			url=url+"&"+vector_get[i]+"="+encodeURIComponent(elemento.value);
		}
	}
	
	url=url+"&btSave=1&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoProductoEdit(){
	url='';
	for (var j=0;j<document.forms["form1"].elements.length;j++){
		var nombre=document.forms["form1"].elements[j].name;
		if (nombre!=undefined && nombre!=null && nombre!="" ){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form1"].elements[j].value);
		}
	}
	url=url+'&btSave=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoSerieProductoAdd(){
	url='';
	for (var j=0;j<document.forms["form2"].elements.length;j++){
		var nombre=document.forms["form2"].elements[j].name;
		var checked=document.forms["form2"].elements[j].checked;
		if(nombre.indexOf('producto')!='-1' && checked==true){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
		else if(nombre.indexOf('id')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
		else if(nombre.indexOf('codigo_s')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
	}
	url=url+'&btAdd=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoSerieEstanciaAdd(){
	url='';
	for (var j=0;j<document.forms["form2"].elements.length;j++){
		var nombre=document.forms["form2"].elements[j].name;
		var checked=document.forms["form2"].elements[j].checked;
		if(nombre.indexOf('estancia')!='-1' && checked==true){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
		else if(nombre.indexOf('id')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
		else if(nombre.indexOf('codigo_s')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
	}
	url=url+'&btAdd=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoSerieAmbienteEdit(){
	url='';
	for (var j=0;j<document.forms["form"].elements.length;j++){
		var nombre=document.forms["form"].elements[j].name;
		var checked=document.forms["form"].elements[j].checked;
		if(nombre.indexOf('estancia')!='-1' && checked==true){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form"].elements[j].value);
		}
		else if(nombre.indexOf('id')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form"].elements[j].value);
		}
		else if(nombre.indexOf('codigo_s')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form"].elements[j].value);
		}
		else if(nombre.indexOf('amb')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form"].elements[j].value);
		}
	}
	url=url+'&btAdd=1'+"&nocache=" + Math.random();
	return url;
}
function parametros_admin_catalogoSerieFormatoAdd(){
	url='';
	for (var j=0;j<document.forms["form2"].elements.length;j++){
		var nombre=document.forms["form2"].elements[j].name;
		var checked=document.forms["form2"].elements[j].checked;
		if(nombre.indexOf('formato')!='-1' && checked==true){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
		else if(nombre.indexOf('id')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
		else if(nombre.indexOf('codigo_s')!='-1'){
			url=url+"&"+nombre+"="+encodeURIComponent(document.forms["form2"].elements[j].value);
		}
	}
	url=url+'&btAdd=1'+"&nocache=" + Math.random();
	return url;
}

function enviaPaginaDiv(div,pagina,metodo,parametros){
	/* cont: es el div donde se mostrara la lista de modelos */	
	contenedor = document.getElementById(div);
	/* Se crea el objeto ajax */
	ajax2=objetoAjax();

	if (pagina=='admin_catalogoConfigEdit.php' && parametros=='1'){
		parametros=parametros_admin_catalogoConfigEdit();
	}
	else if(pagina.indexOf('admin_categoriaEdit.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_categoriaEdit();
		pagina=pagina+parametros;
	}
	else if(pagina.indexOf('admin_categoriaEditCampo.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_categoriaEditCampo();
		pagina=pagina+parametros;
	}
	else if(pagina.indexOf('admin_categoriaNew.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_categoriaNew();
	}
	else if(pagina.indexOf('admin_catalogoSerieEdit.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_catalogoSerieEdit();
		pagina=pagina+parametros;
	}
	else if(pagina.indexOf('admincatalogoSerie_ajax.php')!='-1' && parametros!='-1'){
		parametros=parametros_admincatalogoSerie_ajax(parametros);
		pagina=pagina+parametros;
	}
	else if(pagina.indexOf('admin_catalogoEstanciaNew.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_catalogoEstanciaNew();
	}
	else if(pagina.indexOf('admin_catalogoEstanciaEdit.php')!='-1'&& parametros=='1'){
		parametros=parametros_admin_catalogoEstanciaEdit();
	}	
	else if(pagina.indexOf('admin_catalogoFormatoEdit.php')!='-1'&& parametros=='1'){
		parametros=parametros_admin_catalogoFormatoEdit();
	}		
	else if(pagina.indexOf('admin_catalogoProductoNew.php')!='-1'&& parametros=='1'){
		parametros=parametros_admin_catalogoProductoNew();
	}
	else if(pagina.indexOf('admin_catalogoProductoEdit.php')!='-1'&& parametros=='1'){
		parametros=parametros_admin_catalogoProductoEdit();
	}
	else if(pagina.indexOf('admin_catalogoSerieProductoAdd.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_catalogoSerieProductoAdd();
	}
	else if(pagina.indexOf('admin_catalogoSerieEstanciaAdd.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_catalogoSerieEstanciaAdd();
	}
	else if(pagina.indexOf('admin_catalogoSerieAmbienteEdit.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_catalogoSerieAmbienteEdit();
	}
	else if(pagina.indexOf('admin_catalogoSerieFormatoAdd.php')!='-1' && parametros=='1'){
		parametros=parametros_admin_catalogoSerieFormatoAdd();
	}
	else if(pagina.indexOf('user_datosEdit.php')!='-1' && parametros=='1'){
		parametros=parametros_user_datosEdit();
	}
	else if(pagina.indexOf('user_changePss.php')!='-1' && parametros=='1'){
		parametros=parametros_user_changePss();
	}
	else if(pagina.indexOf('user_datosWebEdit.php')!='-1' && parametros=='1'){
		parametros=parametros_user_datosWebEdit();
	}
	else if(pagina.indexOf('userCatalogo_ajax.php')!='-1' && parametros=='1'){
		parametros=parametros_userCatalogo_ajax();
		pagina=pagina+parametros;
	}
	if (div=="traducciones" )
		componerTabs(parametros);
	/* Llamamos a la pagina con el metodo GET*/
    ajax2.open(metodo,pagina,true);
    if (metodo=='post')
    	ajax2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    ajax2.send(parametros);
	
	ajax2.onreadystatechange = function(){
		if (ajax2.readyState == 4 && ajax2.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont*/
			contenedor.innerHTML = ajax2.responseText;
		}
	} 
}
/* Funcion que muestra/oculta la busqueda */
function showBusqueda(element){
	element2=element+'Avanzada';
	
	if (document.getElementById(element2)){
		vista = (document.getElementById(element2).style.display == 'none') ? 'block' : 'none';
		document.getElementById(element2).style.display = vista;
		if (vista =='block'){
			document.getElementById('image_'+element).src='../images/subtractGris.gif';
		}
		else{
			document.getElementById('image_'+element).src='../images/btAmplia.gif';
		}	
	}
}


/*Función que habilita o deshabilita el periodo de busqueda*/
function showPeriodo(element){	
	var FIni = document.getElementById('fechaIni');
	var FFin = document.getElementById('fechaFin');
	var CalIni = document.getElementById('tcalico_0');
	var CalFin = document.getElementById('tcalico_1');
	if (document.getElementById(element)){
		if (document.getElementById(element).checked){
			FIni.removeAttribute('disabled','');
			FFin.removeAttribute('disabled','');
			CalIni.setAttribute('onclick',"A_TCALS['0'].f_toggle()");
			CalFin.setAttribute('onclick',"A_TCALS['1'].f_toggle()");
			CalIni.setAttribute('src','../images/calendar/cal.gif');
			CalFin.setAttribute('src','../images/calendar/cal.gif');		
		}
		else{
			FIni.setAttribute('disabled','');
			FFin.setAttribute('disabled','');
			CalIni.removeAttribute('onclick','');
			CalFin.removeAttribute('onclick','');
			CalIni.setAttribute('src','../images/calendar/no_cal.gif');
			CalFin.setAttribute('src','../images/calendar/no_cal.gif');
			
		}	
	}
}

/*Desactiva el combo modulos si la accion es conexion o desconexion*/
function showModulos(element){	
	var Mod = document.getElementById('modulo');
	if (document.getElementById(element).value == '1' || document.getElementById(element).value == '0')
		Mod.setAttribute('disabled','');
	else
		Mod.removeAttribute('disabled','');
}
/* Funcion que activa/desactiva combos dependiendo de si estan o no activados/desactivados */
function desactivaCombo(combo1,combo2){
	combo1=document.getElementById(combo1);
	combo2=document.getElementById(combo2);
	(combo1.disabled==false)?combo1.disabled=true: combo1.disabled=false;
	(combo2.disabled==false)?combo2.disabled=true: combo2.disabled=false;
}
/* Funcion que limpia la busqueda de admin_searchStock */
function limpiaAdminSearchStock(pagina){
	document.getElementById('buscar').value=document.getElementById('modelo').value='';
	document.getElementById('serie').value=document.getElementById('formato').value='-1';
	location.search="";
	pagina;
}
function limpiaUserCatalogoGrafico(pagina){
	document.getElementById('busqueda').value='';
	location.search="";
	pagina;
}
function limpiaAdminCatalogoSerie(pagina){
	document.getElementById('busqueda').value='';
	document.getElementById('serie_select').value='-1';
	document.getElementById('visible').value='1';
	document.getElementById('novedad').value='2';
	document.getElementById('check_todas').checked=false;
	document.getElementById('visible').disabled=false;
	document.getElementById('novedad').disabled=false;
	location.search="";
	pagina;
}
function limpiarAdminNewUserAdvanced(pagina){
	location.search="";
	location.href=pagina;
}
/*************************** Funciones que se utilizan en admin_catalogoSerie ******************************/
var peticion_http = null;
function cargaContenido(url, metodo, funcion,vis,ambiente,pagina,ambienteDefecto) {
	peticion_http = objetoAjax();
	if(peticion_http) {
		/* Se crea una funcion anonima que llama a muestraContenido con un parametro por valor*/
		peticion_http.onreadystatechange = function(){
			muestraContenido(vis,ambiente,pagina,ambienteDefecto);
		};
		peticion_http.open(metodo, url, true);
		peticion_http.send(null);
	}
}
function muestraContenido(vis,ambiente,pagina,ambienteDefecto) {
	if(peticion_http.readyState == READY_STATE_COMPLETE) {
		if(peticion_http.status == 200) {
			if(ambienteDefecto!=-1){
				enviaPaginaDiv('cuerpo_central_plana','../app/admin_catalogoSerieEdit.php?id='+pagina,'get','');
			}
			else{
				if (vis==1){
					variable="s_visible";
					document.getElementById(variable).value=peticion_http.responseText;
				}
				else if(vis==0){
					variable="s_novedad";
					document.getElementById(variable).value=peticion_http.responseText;
				}
				else if(vis==-1 && ambiente!=-1){
					document.getElementById('fila_'+ambiente).style.display="none";
					enviaPaginaDiv('cuerpo_central_plana','../app/admin_catalogoSerieEdit.php?id='+pagina,'get','');
				}
			}
		}
	}
}
/* Funcion que marca una serie como visible o no visible */
function marca(codigo_s,vis){
	funcion=muestraContenido;
	cad=location.href;
	url=cad.slice(0,cad.indexOf('app'))+"ajax/adminCatalogoSerieEdit_ajax.php?vis="+vis;
	var query_string="&id="+encodeURIComponent(codigo_s)+"&nocache=" + Math.random();
	cargaContenido(url+query_string, "GET", funcion,vis,'-1','-1','-1');
}
/* Funcion que marca una noticia como visible o no visible */
function marcaVisible(id,vis){
	funcion=muestraContenido;
	cad=location.href;
	url=cad.slice(0,cad.indexOf('app'))+"ajax/marcaVisible.php?vis="+vis;
	var query_string="&id="+encodeURIComponent(id)+"&nocache=" + Math.random();
	cargaContenido(url+query_string, "GET", funcion,vis,'-2','-1','-1');

}

/* Funcion que marca una ayuda como visible o no visible */
function marcaVisibleAyuda(id,vis){
	funcion=muestraContenido;
	cad=location.href;
	url=cad.slice(0,cad.indexOf('app'))+"ajax/marcaVisibleAyuda.php?vis="+vis;
	var query_string="&id="+encodeURIComponent(id)+"&nocache=" + Math.random();
	cargaContenido(url+query_string, "GET", funcion,vis,'-2','-1','-1');

}
/* Funcion que borra un ambiente */
function borra_ambiente(ambiente_id,serie_id){
	var entrar = confirm('Do you want to delete the environment?');
	if ( !entrar ) {
		null;
	}
	else{
		funcion=muestraContenido;
		cad=location.href;
		url=cad.slice(0,cad.indexOf('app'))+"ajax/adminCatalogoSerieEdit_ajax.php?borra="+ambiente_id;
		var query_string="&id="+encodeURIComponent(serie_id)+"&nocache=" + Math.random();
		cargaContenido(url+query_string, "GET", funcion,'-1',ambiente_id,serie_id,'-1');
	}
}
function ambienteDefecto(ambiente_id,codigo_s,serie){
	funcion = muestraContenido;
	cad=location.href;
	url=cad.slice(0,cad.indexOf('app'))+"ajax/adminCatalogoSerieEdit_ajax.php?defecto="+ambiente_id;
	var query_string="&id="+encodeURIComponent(serie)+"&codigo_s="+encodeURIComponent(codigo_s)+"&nocache=" + Math.random();
	cargaContenido(url+query_string, "GET", funcion,'-1','-1',serie,ambiente_id);
}
/*************************************************************************************************************/
/* Funcion que realiza la búsqueda del catalogo cuando se pincha sobre estancia y cambia el combo de formato
 * mostrando todos los formatos que estan relacionados con la estancia marcarda.
 * NOTA: Se tiene que poner el combo de los formatos en un div pq si se ponde directamente en la tabla  
 * en ie el objeto td no admite la funcion innerhtml.
*/
function busquedaEstancia(estancia){
	/* Se crea el objeto ajax */
	obj_ajax=objetoAjax();
	/* Llamamos a la pagina con el metodo GET*/
	pagina='../ajax/obtenerFormato.php?estancia='+estancia;
    obj_ajax.open('GET',pagina,true);
	obj_ajax.send(null);
	obj_ajax.onreadystatechange = function(){
		if (obj_ajax.readyState == 4 && obj_ajax.status == 200) {
			/* El resultado que nos devuelve url lo almacenamos en el div cont*/
			document.getElementById('combo_formatos').innerHTML= obj_ajax.responseText;
		}
	} 
	enviaPaginaDiv('contenido_catalogo','../ajax/userCatalogo_ajax.php?buscar='+document.getElementById('busqueda').value,'GET',1);
}
function insertaAmbiente(padre) {
	document.forms["form1"].submit();
	//setTimeout("enviaPaginaDiv('cuerpo_central_plana','"+padre+"','get','')",200);	
}
function modificarCombosGaleriaAmbientes(estancia, serie, formato, selected){
	/* Se crea el objeto ajax */
	obj_ajax=objetoAjax();
	/* Llamamos a la pagina con el metodo GET*/
	pagina='../ajax/user_catalogoGaleriaAmbientes.php?estancia='+estancia+'&serie='+serie+'&formato='+formato+'&selected='+selected;
    obj_ajax.open('GET',pagina+"&nocache=" + Math.random(),true);
	obj_ajax.send(null);
	obj_ajax.onreadystatechange = function(){
		if (obj_ajax.readyState == 4 && obj_ajax.status == 200) {
			res=new Array("combo_estancia","combo_serie","combo_formato");
			var resultado=obj_ajax.responseText;
			resultado=resultado.split('#');
			for(i=0;i<resultado.length;i++){
				document.getElementById(res[i]).innerHTML=resultado[i];
			}		
		}
	} 
}
/* Funciones que mantienen el carrito de la compra */

function llamaCarrito2(div,valor,alerta,xml,pagina,metodo,parametros){
	/* Se crea el objeto ajax */
	obj_ajax=objetoAjax();
	/* Llamamos a la pagina con el metodo GET*/
    obj_ajax.open(metodo,pagina+"&nocache=" + Math.random(),true);
    if (metodo=='post')
    	obj_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    obj_ajax.send(parametros);
	
	obj_ajax.onreadystatechange = function(){
		if (obj_ajax.readyState == 4 && obj_ajax.status == 200) {
			if (div!="")
				document.getElementById(div).innerHTML=obj_ajax.responseText;
			else if (valor!=""){
				if(valor.indexOf('disp')!='-1'){
					document.getElementById(valor).src=obj_ajax.responseText;
				}
				else{
					document.getElementById(valor).value=obj_ajax.responseText;
				}
			}
			else if (alerta!="")
				alert(obj_ajax.responseText);
			else if (xml!=""){
				var doc_xml=obj_ajax.responseXML.documentElement;
				xml=xml.split(',');
				for(i=0;i<xml.length;i++){
					document.getElementById(xml[i]).value=doc_xml.getElementsByTagName(xml[i])[0].firstChild.nodeValue;
				}
			}
			else
				obj_ajax.responseText;
		}
	} 
}

function llamaCarrito(div,valor,alerta,xml,pagina,metodo,parametros){
	/* Se crea el objeto ajax */
	obj_ajax=objetoAjax();
	/* Llamamos a la pagina con el metodo GET*/
    obj_ajax.open(metodo,pagina+"&nocache=" + Math.random(),false);
    if (metodo=='post')
    	obj_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    obj_ajax.send(parametros);

	if (div!="")
		document.getElementById(div).innerHTML=obj_ajax.responseText;
	else if (valor!=""){
		if(valor.indexOf('disp')!='-1'){
			document.getElementById(valor).src=obj_ajax.responseText;
		}
		else{
			document.getElementById(valor).value=obj_ajax.responseText;
		}
	}
	else if (alerta!="")
		alert(obj_ajax.responseText);
	else if (xml!=""){
		var doc_xml=obj_ajax.responseXML.documentElement;
		xml=xml.split(',');
		for(i=0;i<xml.length;i++){
			document.getElementById(xml[i]).value=doc_xml.getElementsByTagName(xml[i])[0].firstChild.nodeValue;
		}
	}
	else
		obj_ajax.responseText;
}

/* Funcion que inserta un elemento en el carrito */
function insertaModeloCarrito(modelo_id){
	llamaCarrito('','','1','','../ajax/userCarrito_ajax.php?mid='+modelo_id+'&inserta=1','get','');
	
	/* Se actualiza el contador de elementos del carrito */
    setTimeout("llamaCarrito('','num','','','../ajax/userCarrito_ajax.php?num=1','get','')",'500');
}
/* Funcion que inserta un elemento en el carrito sin mostrar la alerta */
function insertaModeloCarritoSinAlert(modelo_id){
	llamaCarrito('','','','','../ajax/userCarrito_ajax.php?mid='+modelo_id+'&inserta=1','get','');
	
	/* Se actualiza el contador de elementos del carrito */
    setTimeout("llamaCarrito('','num','','','../ajax/userCarrito_ajax.php?num=1','get','')",'500');
}
/* Funcion que elimina un elementeo del carrito */
function borraElementoCarrito(elemento_id){
	var_xml=new Array("num","total_global");
	
	llamaCarrito('','','','','../ajax/userCarrito_ajax.php?del='+elemento_id,'get','');

	/* Se actualiza el contador y el total de elementos del carrito */
    setTimeout("llamaCarrito('','','','"+var_xml+"','../ajax/userCarrito_ajax.php?todo=1','get','')",'500');

    /* Se actualiza la pagina con los nuevos cambios */
    enviaPaginaDiv("carro","../app/user_seleccionCarro.php?pageNo="+document.getElementById('pageNo').value,"get","");
}
function nl2br(str) {
   return str.replace(/\n/g,"<br>");
}
/* Funcion que actualiza una linea del carrito de seleccion */
function updateModeloCarrito(elemento_id,campo,flag){
	llamaCarrito('','mensaje','','','../ajax/userCarrito_ajax.php?'+campo+'='+nl2br(document.getElementById(campo+'_'+elemento_id).value)+'&el='+elemento_id,'get','');
	if (campo=='precio' || campo=='cant' || campo=='dto'){
		/* Se actualiza el total de elementos del carrito */ 
    	setTimeout("llamaCarrito('','total_global','','','../ajax/userCarrito_ajax.php?total=1','get','')",'500');
    	
    	/* Se actualiza el importe total de la linea del elemento */
    	importeTotalElemento(elemento_id);

    }	
    if(campo=='cant' && flag==1)
    	setTimeout("llamaCarrito('','disp_"+elemento_id+"','','','../ajax/userCarrito_ajax.php?disp=1&el="+elemento_id+"','get','')",'800');
}
/* Funcion que actualiza el carrtio */
function updateCarrito(carrito_id,campo){
	llamaCarrito('','mensaje','','','../ajax/userCarrito_ajax.php?'+campo+'='+nl2br(document.getElementById(campo).value)+'&car='+carrito_id,'get','');
	setTimeout("llamaCarrito('','ref','','','../ajax/userCarrito_ajax.php?ref=1&car="+carrito_id+"','get','')",'500');
}
/* Funcion que elimina todos los elementos del carrito de seleccion*/
function borraAllCarrito(){
	var_xml=new Array("num","total_global","ref");
	
	llamaCarrito('','mensaje','','','../ajax/userCarrito_ajax.php?delAll=1','get','');
	
	/* Se actualiza el contador y el total de elementos del carrito */
    setTimeout("llamaCarrito('','','','"+var_xml+"','../ajax/userCarrito_ajax.php?todo=1','get','')",'500');
    
    /* Se actualiza la pagina con los nuevos cambios */
    enviaPaginaDiv("carro","../app/user_seleccionCarro.php?","get","");
}
/* Funcion que calcula el importe de una linea del carrito */
function importeTotalElemento(elemento_id){
	var total=document.getElementById('cant_'+elemento_id).value*document.getElementById('precio_'+elemento_id).value;	
	if (document.getElementById('dto_'+elemento_id).value!='' && document.getElementById('dto_'+elemento_id).value!=0 && 
		!isNaN(parseFloat(document.getElementById('dto_'+elemento_id).value))){
		var dto=(total*document.getElementById('dto_'+elemento_id).value)/100;
		total=total-dto;
	}
	document.getElementById('total_linea_'+elemento_id).value=total;
}






function llamaPresupuesto(div,valor,alerta,xml,pagina,metodo,parametros){
	/* Se crea el objeto ajax */
	obj_ajax=objetoAjax();
	/* Llamamos a la pagina con el metodo GET*/
    obj_ajax.open(metodo,pagina+"&nocache=" + Math.random(),false);
    if (metodo=='post')
    	obj_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    obj_ajax.send(parametros);

	if (div!="")
		document.getElementById(div).innerHTML=obj_ajax.responseText;
	else if (valor!=""){
		if(valor.indexOf('disp')!='-1'){
			document.getElementById(valor).src=obj_ajax.responseText;
		}
		else{
			document.getElementById(valor).value=obj_ajax.responseText;
		}
	}
	else if (alerta!="")
		alert(obj_ajax.responseText);
	else if (xml!=""){
		var doc_xml=obj_ajax.responseXML.documentElement;
		xml=xml.split(',');
		for(i=0;i<xml.length;i++){
			document.getElementById(xml[i]).value=doc_xml.getElementsByTagName(xml[i])[0].firstChild.nodeValue;
		}
	}
	else
		obj_ajax.responseText;
}



/* Funcion que inserta un elemento en el presupuesto */
function insertaModeloPresupuesto(ejercicio, presupuesto_id, modelo_id){
	llamaPresupuesto('','','','','../ajax/userPresupuesto_ajax.php?mid='+modelo_id+'&inserta=1'+'&ejercicio='+ejercicio+'&presupuesto_id='+presupuesto_id,'get','');
}


/* Funcion que elimina un elementeo del presupuesto */
function borraElementoPresupuesto(elemento_id){
	
	llamaPresupuesto('','','','','../ajax/userPresupuesto_ajax.php?del='+elemento_id+'&ejercicio='+document.getElementById('ejercicio').value+'&presupuesto_id='+document.getElementById('presupuesto_id').value,'get','');

    /* Se actualiza la pagina con los nuevos cambios */
    enviaPaginaDiv("carro",'../app/user_presupuestosViewLineas.php?ejercicio='
    		+document.getElementById('ejercicio').value+'&presupuesto_id='+document.getElementById('presupuesto_id').value,"get","");

    /* Se actualiza el total de elementos del carrito */ 
    setTimeout("llamaPresupuesto('','total_global','','','../ajax/userPresupuesto_ajax.php?total=1&ejercicio='+document.getElementById('ejercicio').value+'&presupuesto_id='+document.getElementById('presupuesto_id').value,'get','')",'500');

}

/* Funcion que actualiza el presupuesto */
function updatePresupuesto(campo){
	llamaPresupuesto('','mensaje','','','../ajax/userPresupuesto_ajax.php?'+campo+'='+nl2br(document.getElementById(campo).value)
			+'&ejercicio='+document.getElementById('ejercicio').value
			+'&presupuesto_id='+document.getElementById('presupuesto_id').value,'get','');
	//setTimeout("llamaCarrito('','ref','','','../ajax/userCarrito_ajax.php?ref=1&car="+carrito_id+"','get','')",'500');
}

/* Funcion que actualiza una linea del presupuesto */
function updateModeloPresupuesto(elemento_id,campo,flag){
	llamaPresupuesto('','mensaje','','','../ajax/userPresupuesto_ajax.php?'+campo+'='+nl2br(document.getElementById(campo+'_'+elemento_id).value)
			+'&el='+elemento_id
			+'&ejercicio='+document.getElementById('ejercicio').value
			+'&presupuesto_id='+document.getElementById('presupuesto_id').value,'get','');
	if (campo=='precio' || campo=='cant' || campo=='dto'){
	/* Se actualiza el total de elementos del carrito */ 
    setTimeout("llamaPresupuesto('','total_global','','','../ajax/userPresupuesto_ajax.php?total=1&ejercicio='+document.getElementById('ejercicio').value+'&presupuesto_id='+document.getElementById('presupuesto_id').value,'get','')",'500');
    	
    /* Se actualiza el importe total de la linea del elemento */
    importeTotalElemento(elemento_id);

    }	
    if(campo=='cant' && flag==1)
    	setTimeout("llamaPresupuesto('','disp_"+elemento_id+"','','','../ajax/userPresupuesto_ajax.php?disp=1&el="+elemento_id+"&ejercicio='+document.getElementById('ejercicio').value+'&presupuesto_id='+document.getElementById('presupuesto_id').value,'get','')",'800');
}

/* Funcion que elimina todos los elementos del presupuesto */
function borraAllPresupuesto(){
	var_xml=new Array("num","total_global","ref");	
	llamaPresupuesto('','mensaje','','','../ajax/userPresupuesto_ajax.php?delAll=1&ejercicio='+document.getElementById('ejercicio').value+'&presupuesto_id='+document.getElementById('presupuesto_id').value,'get','');
	window.location.href='user_presupuestosList.php';
}



/* Funcion que inicializa la bandera */
function inicializaBandera(img,disp,no_disp){
	imagen=img.src;
	(imagen.indexOf('flag_green.png')!=-1)?img.title=disp:img.title=no_disp;
}
function editarFotoColeccion(pagina, metodo, coleccion_id, foto_id, campo, valor){
	/* Se crea el objeto ajax */
	obj_ajax=objetoAjax();
	parametros="?"+campo+"="+valor+"&id="+foto_id+"&cid="+coleccion_id+"&nocache=" + Math.random();
	if (metodo=='get')
		pagina=pagina+parametros;
    obj_ajax.open(metodo,pagina,true);
    if (metodo=='post')
    	obj_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    obj_ajax.send(parametros);
	obj_ajax.onreadystatechange = function(){
		if (obj_ajax.readyState == 4 && obj_ajax.status == 200) {
			if (campo=='cover')
				location.reload();
			else
				document.getElementById(campo+'_'+foto_id).value= obj_ajax.responseText;	
		}
	} 
}
function sincronizar(contenedor,pagina){
	/* Se crea el objeto ajax  */
	var respuesta;
	obj_ajax=objetoAjax();
	obj_ajax.open("get",pagina,true);
	document.getElementById(contenedor).innerHTML="<img src='../images/loader.gif' />";
	/* Se inhabilita el menu */
	for(i=0;i<=nMenu;i++){
		if(document.getElementById(i)!=null){
			enlace=document.getElementById(i).onclick;
			document.getElementById(i).onclick="";
			document.getElementById(i).onmouseover="null";
			if (document.getElementById("sub_menu_"+i)!=null){ // existe el submenu
				j=0;
				submenu="sub_menu_"+i;
				elemento=document.getElementById(submenu+'_'+j);
				while (elemento!=null){
					elemento.onclick="";
					elemento.onmouseover="null";
					j++;
					elemento=document.getElementById(submenu+'_'+j);
				}
			}
		}
	}
	/* Se define la funcion para que si se intenta salir de pagina sin que haya finalizado la sincro muestre un mensaje */
	window.onbeforeunload = function(e) {
		return "El proceso de sincronizacion debe finalizar antes de cerrar la ventana.";
	};
	/* Se inhabilita el carrito, el usuario, las banderas y la navegacion */
	document.getElementById('href_carrito').onclick="";
	document.getElementById('user_logged').removeAttribute('href');
	document.getElementById('lnk_logout').removeAttribute('href');
	document.getElementById('aro').removeAttribute('href');
	document.getElementById('planatec').removeAttribute('href');
	for(i=0;i<array_banderas.length;i++){
		document.getElementById(array_banderas[i]).disabled="true";
	}
	var navegacion=document.getElementById("navegacion").getElementsByTagName("a");
	for(i=0; i<navegacion.length; i++){
		navegacion[i].removeAttribute('href');
	}
	/* Se oculta el btSincro y la accion1 */
	document.getElementById('btSincro').style.display="none";
	document.getElementById('accion1').style.display="none";
	if(document.getElementById('btOpciones')!=null)
		document.getElementById('btOpciones').style.display="none";
	if(document.getElementById('mensaje')!=null)
	document.getElementById('mensaje').style.display="none";
	obj_ajax.onreadystatechange = function(){
		if (obj_ajax.readyState == 4 && obj_ajax.status == 200) {
			document.getElementById(contenedor).innerHTML= obj_ajax.responseText;
			window.onbeforeunload = ""; /* Se quita la funcion que cierra la pag */
			document.getElementById('btFin').style.display="block";
		}
	}
	obj_ajax.send(null);
}
function actualizaEnlace(){
	var textoEscogido = document.form.role.options[document.form.role.selectedIndex].text
	if (textoEscogido=='COMERCIAL')
		document.getElementById('enlace').href='admin_NewUser_Comercial.php?rid='+document.form.role.options[document.form.role.selectedIndex].value
 	else
		document.getElementById('enlace').href='admin_NewUser_Advanced.php?rid='+document.form.role.options[document.form.role.selectedIndex].value
}

/* Funcion para mostrar y ocultar la tabla de edición de publicaciones online en la zona de descargas */

function mostrarTablaPublicacionesOnline(opcion){	
	var tabla = document.getElementById('tablaPublicaciones');
	if (opcion == 'si'){
		tabla.style.visibility = "";
		var descripcion = document.getElementById("descrip").value;
		if (document.getElementById("nombre").value == "")
			{document.getElementById("nombre").value = validarCadenas(descripcion);}
		if (document.getElementById("titulo").value == "")
			{document.getElementById("titulo").value = validarCadenas(descripcion);}
	}
	else {tabla.style.visibility = "hidden";}		
}

/* Funcion para validar el formulario a la hora de subir un archivo a Issuu */

function validacion(){
	
	document.getElementById("descrip").value = quitaacentos(document.getElementById("descrip").value);
	document.getElementById("nombre").value = quitaacentos(document.getElementById("nombre").value);
	document.getElementById("titulo").value = quitaacentos(document.getElementById("titulo").value);
	document.getElementById("tags").value = quitaacentos(document.getElementById("tags").value);
	
	document.getElementById("descrip").value = validarCadenas(document.getElementById("descrip").value);
	document.getElementById("nombre").value = validarCadenasNombre(document.getElementById("nombre").value);
	document.getElementById("titulo").value = validarCadenas(document.getElementById("titulo").value);
	document.getElementById("tags").value = validarCadenas(document.getElementById("tags").value);
	
	var descripcionCorrecta = validacionDescripcion();
	nombreCorrecto = "incorrecto";
	
	habilitado = document.getElementsByName("publicarOnline");
	for(var i=0; i<habilitado.length; i++) {	
		if(habilitado[i].checked && habilitado[i].value == 1) {	 	
			nombre = document.getElementById("nombre").value;
			if( nombre == null || nombre.length == 0 ) {
				document.getElementById("validacionNombre").innerHTML = "Introduzca un nombre";
				document.getElementById("validacionNombre").className = "validacionError";
				document.getElementById("nombreCorrecto").innerHTML = "incorrecto";
				nombreCorrecto = "incorrecto";
			}
			else{
				var comprobar = document.getElementById("nombreRead").style.visibility;
				if (comprobar == "hidden"){ /* Si el archivo ya está dado de alta */
					comprobarDisponibilidadNombre();
					nombreCorrecto = document.getElementById("nombreCorrecto").value;
				}
				nombreCorrecto = "correcto";
			}	
		}else if (habilitado[i].checked && habilitado[i].value == 0){
			nombreCorrecto="correcto"; //Ya que no hay que poner ningun nombre
		}
	}
	
	if (nombreCorrecto == "correcto" && descripcionCorrecta){
		document.getElementById("form1").submit();
		document.getElementById("procesando").style.display = "";
		//document.getElementById("procesando").innerHTML = "Procesando...";
		return true;
	}else {return false;}
}

/* Función para validar el formulario de creación de un nuevo fichero */

function validacionDescargaNuevo(){
	var descripcionCorrecta = validacionDescripcion();
	var ficheroCorrecto = validacionFichero();
	if (descripcionCorrecta && ficheroCorrecto){
		document.getElementById("form1").submit();
		return true;
	}
	else{
		return false;
	}

}

/* Funcion que valida el campo descripción al añadir un archivo a la zona de descargas */

function validacionDescripcion(){
	var descripcion = document.getElementById("descrip").value;
	if (descripcion == null || descripcion.length == 0 ){
		document.getElementById("validacionDescripcion").innerHTML = "No puede estar vacío";
		document.getElementById("validacionDescripcion").className = "validacionError";
		return false;
	}else{
		document.getElementById("validacionDescripcion").innerHTML = " ";
		document.getElementById("validacionDescripcion").className = "validacionOk";
		return true;
	}
}

/* Funcion que valida el campo descripción al añadir un archivo a la zona de descargas */

function validacionFichero(){
	var fichero = document.getElementById("fichero").value;
	if (fichero == null || fichero.length == 0 ){
		document.getElementById("validacionFichero").innerHTML = "Debe introducir el nombre del archivo";
		document.getElementById("validacionFichero").className = "validacionError";
		return false;
	}else{
		document.getElementById("validacionFichero").innerHTML = " ";
		document.getElementById("validacionFichero").className = "validacionOk";
		return true;
	}
}

/* Funcion que comprueba la disponibilidad de un nombre, para ello hace un petición a la base de datos */

function comprobarDisponibilidadNombre() {
	  // Obtener la instancia del objeto XMLHttpRequest
	  if(window.XMLHttpRequest) {
	    peticion_http = new XMLHttpRequest();
	  }
	  else if(window.ActiveXObject) {
	    peticion_http = new ActiveXObject("Microsoft.XMLHTTP");
	  } 
	  
	  CurrentSearchKey = document.getElementById("nombre").value;
	  nombre = document.getElementById("nombre").value;
	  
	  if (nombre == "" || nombre == null){
		  document.getElementById("validacionNombre").innerHTML = "Debe introducir un nombre";
		  document.getElementById("validacionNombre").className = "validacionError";
		  document.getElementById("nombreCorrecto").innerHTML = "incorrecto";
	  }
	  	  
	  // Preparar la funcion de respuesta
	  peticion_http.onreadystatechange = muestraRespuesta;
	 
	  // Realizar peticion HTTP
	  
	  peticion_http.open('GET', '../ajax/disponibilidadNombreFichero.php?nombre=' + nombre , true);
	  peticion_http.send(null);
	 
	  function muestraRespuesta() {
	    if(peticion_http.readyState == 4) {
	      if(peticion_http.status == 200) {
	    	  if (peticion_http.responseText == "true"){
	    		  document.getElementById("validacionNombre").innerHTML = "Ya hay un archivo con ese nombre";
	    		  document.getElementById("validacionNombre").className = "validacionError";
	    		  document.getElementById("nombreCorrecto").innerHTML = "incorrecto";
	    	  }else{
	    		  document.getElementById("validacionNombre").innerHTML = "Nombre disponible";
	    		  document.getElementById("validacionNombre").className = "validacionOk";
	    		  document.getElementById("nombreCorrecto").innerHTML = "correcto";
	    	  }
	      }
	    }
	  }
}


/* Funcion para validar el nombre de un fichero para Issuu */

function validacionNombre(){
	nombre = document.getElementById("nombre").value;
	if (nombre == "" || nombre == null){
		document.getElementById("validacionNombre").innerHTML = "Debe introducir un nombre";
		document.getElementById("validacionNombre").className = "validacionError";
		document.getElementById("nombreCorrecto").innerHTML = "incorrecto";
	}else{
		comprobarDisponibilidadNombre();
	}
}

/* Funcion que elimina los caracteres no permitidos */

function validarCadenas(string) {  
	for (var i=0, output='', validos="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_ "; i<string.length; i++)  
		if (validos.indexOf(string.charAt(i)) != -1)  
			output += string.charAt(i)  
    return output;  
}

/* Funcion que elimina los caracteres no permitidos para los titulos de archivo en Issuu */

function validarCadenasNombre(string) {  
	string = string.toLowerCase();
	for (var i=0, output='', validos="0123456789abcdefghijklmnopqrstuvwxyz.-_"; i<string.length; i++)  
		if (validos.indexOf(string.charAt(i)) != -1)  
			output += string.charAt(i)  
    return output;  
}

/* Funcion que elimina los acentos de una cadena */

function quitaacentos(t){
	á="a";é="e";í="i";ó="o";ú="u";ñ="n";ä="a";ë="e";ï= "i";ö="o";ü="u";
	acentos=/[áéíóúñäëïöü]/g;
	return t.replace(acentos,
	function($1){ return eval($1) } )
}

/* Funcion que habilita la edición del idioma del comunicado */

function editaIdiomaComunicado(){
	document.getElementById("tablaEditar").style.display="";
	ver = document.getElementById("tablaVer");
	if (ver != null)
		document.getElementById("tablaVer").style.display="none";
	
	acciones = document.getElementsByName("editar2");
	acciones[0].style.display="none";
	acciones = document.getElementsByName("guardar2");
	acciones[0].style.display="";
	acciones = document.getElementsByName("cancelar2");
	acciones[0].style.display="";
}

/* Funcion que cancela la edicion del comunicado */

function cancelaIdiomaComunicado(){
	document.getElementById("tablaEditar").style.display="none";
	ver = document.getElementById("tablaVer");
	if (ver != null)
		document.getElementById("tablaVer").style.display="";
	
	acciones = document.getElementsByName("editar2");
	acciones[0].style.display="";
	acciones = document.getElementsByName("guardar2");
	acciones[0].style.display="none";
	acciones = document.getElementsByName("cancelar2");
	acciones[0].style.display="none";
}

/* Funcion que comprueba que se haya seleccionado algun rol */

function compruebaRolesComunicado(error){
	
	selected = 0;
	
	for (i=0;i<document.form1.elements.length;i++)
	      if(document.form1.elements[i].type == "checkbox")
	         if(document.form1.elements[i].checked==true)
	        	 selected = selected + 1;

	if(selected>0)	
		document.form1.submit();
	else{
		document.getElementById("mensajeRoles").innerHTML = error;
	}
}

/* Funcion que habilita la edicion de los roles del comunicado */

function editaRolesComunicado(){
	acciones = document.getElementsByName("volver");
	acciones[0].style.display="none";
	acciones = document.getElementsByName("editar");
	acciones[0].style.display="none";
	acciones = document.getElementsByName("guardar");
	acciones[0].style.display="";
	acciones = document.getElementsByName("cancelar");
	acciones[0].style.display="";	
	
	for (i=0;i<document.form1.elements.length;i++)
	      if(document.form1.elements[i].type == "checkbox")
	         document.form1.elements[i].disabled="";
}

/* Funcion que cancela la edicion de los roles del comunicado */

function cancelaEditaRolesComunicado(){
	acciones = document.getElementsByName("volver");
	acciones[0].style.display="";
	acciones = document.getElementsByName("editar");
	acciones[0].style.display="";
	acciones = document.getElementsByName("guardar");
	acciones[0].style.display="none";
	acciones = document.getElementsByName("cancelar");
	acciones[0].style.display="none";
	
	for (i=0;i<document.form1.elements.length;i++)
	      if(document.form1.elements[i].type == "checkbox")
	         document.form1.elements[i].disabled="disabled";
}


/* Funcion que habilita la busqueda de personas en ARO */

function mostrarCodigoARO(){
	rid = document.form.role.selectedIndex;
	if (rid != 0 && rid != 3){
		document.getElementById("filaCodigoARO").style.display = '';
	}else{
		document.getElementById("filaCodigoARO").style.display = 'none';
	}
	document.getElementById("resultadosPersona").style.display="";
	document.getElementById("rid").value = rid;	
	$( "#buscar" ).val("");
	$( "#codigo" ).val("");
}

function desactivarRol(){
	document.getElementsByName('role')[0].disabled=true;		
}


/* Esta funcion recibe dos parametros
 * key = id del campo de texto que se quiere comprobar
 * f = función a ejecutar con retardo
 * */

function comprobarConRetardo(key, f){
	var keyword = document.getElementById(key).value;

	if(SearchTimeOut > 0)
		ResetSearch();
	if (keyword == ""){
		SearchTimeOut = setTimeout(f, Interval);
	}
	if(CurrentSearchKey == keyword)
		return;
	SearchTimeOut = setTimeout(f, Interval);
}

var	ResetSearch = function() {
	clearTimeout(SearchTimeOut);
	SearchTimeOut = 0;
}

/* Funcion que comprueba que exista el codigo ARO y si existe rellena los campos 
 * del usuario sobre los que contiene informacion ARO */

function comprobarCodigoARO()
{	
	var navegador = navigator.appName;
	
	if ($( "#codigo" ).val() == ""){
		$( "#buscar" ).val("");
		$( "#login" ).val("");
		$( "#email" ).val("");
		$( "#nombre" ).val("");
		$( "#buscar" ).val("");
		$( "#validacionCodigoARO" ).html("");
		return false;
	}
	
	if (navegador == "Microsoft Internet Explorer")
		type = "xml";
	else
		type = "text/xml";
	
	$.ajax({
		type: "GET",
		url: "../ajax/comprobarExistenciaCodigo.php?rid=" + $( "#rid" ).val() + "&codigo=" + $( "#codigo" ).val(),
		dataType: type,
		success: function( respuesta ) {
			
			if (navegador != "Microsoft Internet Explorer"){
				parser = new DOMParser();
				respuesta = parser.parseFromString(respuesta, "text/xml");
			}
			estado = respuesta.getElementsByTagName("estado")[0].childNodes[0].nodeValue;
			if (estado == "false"){
				$( "#validacionCodigoARO" ).html("Código incorrecto");
				$( "#validacionCodigoARO" ).removeClass("validacionOk");
				$( "#validacionCodigoARO" ).addClass("validacionError");
				$( "#login" ).val("");
				$( "#email" ).val("");
				$( "#nombre" ).val("");
				$( "#buscar" ).val("");
			}else if (estado == "true"){
				persona = respuesta.getElementsByTagName("persona")[0];
				$( "#validacionCodigoARO" ).html("Código correcto");
				$( "#validacionCodigoARO" ).removeClass("validacionError");
				$( "#validacionCodigoARO" ).addClass("validacionOk");
				$( "#nombre" ).val(respuesta.getElementsByTagName("nombre")[0].firstChild.nodeValue);
				$( "#buscar" ).val(respuesta.getElementsByTagName("nombre")[0].firstChild.nodeValue);
				comprobarDisponibilidadLogin();
				
				email = respuesta.getElementsByTagName("email")[0].firstChild;
				if (email == null){
					$( "#email" ).val("");
					$( "#login" ).val("");
				}else{
					$( "#email" ).val(respuesta.getElementsByTagName("email")[0].firstChild.nodeValue);
					$( "#login" ).val(respuesta.getElementsByTagName("email")[0].firstChild.nodeValue);
				}
			}else{
				$( "#login" ).val("");
				$( "#email" ).val("");
				$( "#nombre" ).val("");
				$( "#buscar" ).val("");
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//alert(textStatus);
		}		
	});
}

/* Funcion que comprueba que exista el codigo ARO y si existe rellena los campos 
 * del usuario sobre los que contiene informacion ARO 
 * Como comprobarCodigoARO pero no se rellena el campo login */

function comprobarCodigoAROEditar()
{	
	var navegador = navigator.appName;
	
	if ($( "#codigo" ).val() == ""){
		$( "#buscar" ).val("");
		$( "#email" ).val("");
		$( "#nombre" ).val("");
		$( "#buscar" ).val("");
		$( "#validacionCodigoARO" ).html("");
		return false;
	}
	
	if (navegador == "Microsoft Internet Explorer")
		type = "xml";
	else
		type = "text/xml";
	
	$.ajax({
		type: "GET",
		url: "../ajax/comprobarExistenciaCodigo.php?rid=" + $( "#rid" ).val() + "&codigo=" + $( "#codigo" ).val(),
		dataType: type,
		success: function( respuesta ) {
			
			if (navegador != "Microsoft Internet Explorer"){
				parser = new DOMParser();
				respuesta = parser.parseFromString(respuesta, "text/xml");
			}
			estado = respuesta.getElementsByTagName("estado")[0].childNodes[0].nodeValue;
			if (estado == "false"){
				$( "#validacionCodigoARO" ).html("Código incorrecto");
				$( "#validacionCodigoARO" ).removeClass("validacionOk");
				$( "#validacionCodigoARO" ).addClass("validacionError");
				$( "#email" ).val("");
				$( "#nombre" ).val("");
				$( "#buscar" ).val("");
			}else if (estado == "true"){
				persona = respuesta.getElementsByTagName("persona")[0];
				$( "#validacionCodigoARO" ).html("Código correcto");
				$( "#validacionCodigoARO" ).removeClass("validacionError");
				$( "#validacionCodigoARO" ).addClass("validacionOk");
				$( "#nombre" ).val(respuesta.getElementsByTagName("nombre")[0].firstChild.nodeValue);
				$( "#buscar" ).val(respuesta.getElementsByTagName("nombre")[0].firstChild.nodeValue);
				comprobarDisponibilidadLogin();
				
				email = respuesta.getElementsByTagName("email")[0].firstChild;
				if (email == null){
					$( "#email" ).val("");
				}else{
					$( "#email" ).val(respuesta.getElementsByTagName("email")[0].firstChild.nodeValue);
				}
			}else{
				$( "#email" ).val("");
				$( "#nombre" ).val("");
				$( "#buscar" ).val("");
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//alert(textStatus);
		}		
	});
}

/* Funcion que comprueba si el login esta disponible */

function comprobarDisponibilidadLogin()
{	
	if (($( "#login" ).val() == "") || $( "#login" ).val() == $( "#login_actual" ).val()){
		$( "#validacionLogin" ).html("");
		$( "#validacionLogin" ).removeClass("validacionOk");
		$( "#validacionLogin" ).addClass("validacionError");
		return false;
	}else{	
		$.ajax({
			type: "GET",
			url: "../ajax/comprobarDisponibilidadLogin.php?login=" + $( "#login" ).val(),
			dataType: "text",	
			success: function( respuesta ) {
				if (respuesta == "true"){
					$( "#validacionLogin" ).html("Usuario disponible");
					$( "#validacionLogin" ).removeClass("validacionError");
					$( "#validacionLogin" ).addClass("validacionOk");
					return true;
				}else if (respuesta == "false"){
					$( "#validacionLogin" ).html("Usuario ya en uso");
					$( "#validacionLogin" ).removeClass("validacionOk");
					$( "#validacionLogin" ).addClass("validacionError");
					return false;
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				//alert(textStatus);
			}		
		});
	}
}

/* Funcion que habilita la edicion de los datos del usuario */

function editarUsuario(){
	document.getElementById("tablaVer").style.display = "none";
	document.getElementById("tablaEditar").style.display = "";	
	
	acciones = document.getElementsByName("editar");
	acciones[0].style.display="none";
	acciones = document.getElementsByName("guardar");
	acciones[0].style.display="";	
	acciones = document.getElementsByName("volver");
	acciones[0].style.display="none";	
	acciones = document.getElementsByName("cancelar");
	acciones[0].style.display="";		
	acciones = document.getElementsByName("cambiarPwd");
	acciones[0].style.display="none";	
	acciones = document.getElementsByName("borrar");
	acciones[0].style.display="none";	
	acciones = document.getElementsByName("bloquear");
	acciones[0].style.display="none";	
	acciones = document.getElementsByName("historial");
	acciones[0].style.display="none";	
	
}

/* Funcion que deshabilita la edicion de datos del usuario */

function cancelarUsuario(){
	document.getElementById("tablaVer").style.display = "";
	document.getElementById("tablaEditar").style.display = "none";	
	
	acciones = document.getElementsByName("editar");
	acciones[0].style.display="";
	acciones = document.getElementsByName("guardar");
	acciones[0].style.display="none";	
	acciones = document.getElementsByName("volver");
	acciones[0].style.display="";	
	acciones = document.getElementsByName("cancelar");
	acciones[0].style.display="none";		
	acciones = document.getElementsByName("cambiarPwd");
	acciones[0].style.display="";	
	acciones = document.getElementsByName("borrar");
	acciones[0].style.display="";	
	acciones = document.getElementsByName("bloquear");
	acciones[0].style.display="";	
	acciones = document.getElementsByName("historial");
	acciones[0].style.display="";	
	
	resetEditarUsuario();
}

/* Funcion que habilita la edicion de modulos del usuario */

function editarModulos(){
	acciones = document.getElementById("editarModulos");
	acciones.style.display="none";
	acciones = document.getElementById("guardarModulos");
	acciones.style.display="";	
	acciones = document.getElementById("cancelarModulos");
	acciones.style.display="";	
	
	for (i=0;i<document.form2.elements.length;i++)
	      if(document.form2.elements[i].type == "checkbox")
	         document.form2.elements[i].disabled="";
}

/* Funcion que deshabilita la edicion de modulos del usuario */

function cancelarModulos(){
	acciones = document.getElementById("editarModulos");
	acciones.style.display="";
	acciones = document.getElementById("guardarModulos");
	acciones.style.display="none";	
	acciones = document.getElementById("cancelarModulos");
	acciones.style.display="none";	
	
	for (i=0;i<document.form2.elements.length;i++)
	      if(document.form2.elements[i].type == "checkbox")
	         document.form2.elements[i].disabled="disabled";
}

/* Funcion para autocompletar la busqueda de personas en ARO */

function autocompletarPersonas(){
	
	if (navigator.appName == "Microsoft Internet Explorer")
		type = "xml";
	else
		type = "text/xml";
	
	$( "#buscar" ).autocomplete({
		source: function( request, response ) {
			$.ajax({
				url: "../ajax/buscarPersonas.php?rid=" + $( "#rid" )[0].value + "&key=" + $( "#buscar" )[0].value,
				dataType: type,					
				success: function( xmlResponse ) {	
					 response($( "persona", xmlResponse ).map(function() {
				          return {
								value: $( "nombre", this ).text(),
								id: $( "nip", this ).text(),
								email: $( "email", this ).text()
					          };
				      }));
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					//alert(textStatus);
				}
			});
		},

		delay:400,
		minLength: 2,
		select: function( event, ui ) {	
			$( "#login" ).val(ui.item.email);
			$( "#email" ).val(ui.item.email);
			$( "#nombre" ).val(ui.item.value);
			$( "#codigo" ).val(ui.item.id);
			$( "#validacionCodigoARO" ).html("");
			comprobarDisponibilidadLogin();
		}
	});
}

/* Funcion para autocompletar la busqueda de personas en ARO 
 * Como autocompletarPersonas pero no rellena el campo login */

function autocompletarPersonasEditar(){
	
	if (navigator.appName == "Microsoft Internet Explorer")
		type = "xml";
	else
		type = "text/xml";
	
	$( "#buscar" ).autocomplete({
		source: function( request, response ) {
			$.ajax({
				url: "../ajax/buscarPersonas.php?rid=" + $( "#rid" )[0].value + "&key=" + $( "#buscar" )[0].value,
				dataType: type,					
				success: function( xmlResponse ) {	
					 response($( "persona", xmlResponse ).map(function() {
				          return {
								value: $( "nombre", this ).text(),
								id: $( "nip", this ).text(),
								email: $( "email", this ).text()
					          };
				      }));
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					//alert(textStatus);
				}
			});
		},

		delay:400,
		minLength: 2,
		select: function( event, ui ) {	
			$( "#email" ).val(ui.item.email);
			$( "#nombre" ).val(ui.item.value);
			$( "#codigo" ).val(ui.item.id);
			$( "#validacionCodigoARO" ).html("");
			comprobarDisponibilidadLogin();
		}
	});
}



/* Funcion que comprueba si se ha cambiado el nombre de usuario al editar este */

function comprobarCambioLogin(login_actual, login){
	if (login_actual != login)
		comprobarDisponibilidadLogin();
	else
		$( "#validacionLogin" ).html("");
}

/* Funcion que resetea el formulario de edicion de datos del usuario cuando se cancela la edicion
 * Restaura los valores iniciales del usuario */

function resetEditarUsuario(){
	$("#login").val($("#login_actual").val());
	$("#email").val($("#email_actual").val());
	$("#nombre").val($("#nombre_actual").val());
	$("#codigo").val($("#codigo_actual").val());
	$("#buscar").val($("#buscar_actual").val());
	$('#role').attr('disabled',false); 
	$("#role").val($("#rid_actual").val());
	$("#rid").val($("#rid_actual").val());
	$("#locale").val($("#idioma_actual").val());
}

/* Funcion que mediante AJAX muestra las modelos coincidentes con los parametros enviados */

function buscarModelosCoincidentes(orderBy)
{	
	
	if ($( "#nombre" ).val().length < 3)
		if ( $( "#categoria" ).attr("selectedIndex") <= 0 || $( "#formato" ).attr("selectedIndex") <= 0)
			if ( $( "#niel" ).val().length == 0)
				return false;
		
	/* Mensaje de carga */
	document.getElementById('mostrarResultados').innerHTML = "";
	elmDIV = document.createElement('div');
	elmDIV.setAttribute("class", "confirmacionNuevo");
	
	elmIMG = document.createElement('img');
    elmIMG.setAttribute("src", "../images/loader.gif");
    elmDIV.appendChild(elmIMG);
    document.getElementById('mostrarResultados').appendChild(elmDIV);	
	
	var navegador = navigator.appName;	
	if (navegador == "Microsoft Internet Explorer")
		type = "html";
	else
		type = "html";	

	$.ajax({
		type: "GET",
		url: "../app/user_seleccionBusqueda.php?modelo=" + $( "#nombre" ).val() + "&niel=" + $( "#niel" ).val() 
			+ "&formato=" + $( "#formato" ).val() + "&categoria=" + $( "#categoria" ).val() 
			+ "&buscar=1" + "&orderBy=" + orderBy,
		dataType: type,
		success: function( respuesta ){
			document.getElementById('mostrarResultados').innerHTML = respuesta;
		}		
	});
}

/* Funcion que mediante AJAX actualiza el select de categorias que coinciden con los parametros enviados */

function actualizaCategoria(){
	var navegador = navigator.appName;
	
	if (navegador == "Microsoft Internet Explorer")
		type = "xml";
	else
		type = "text/xml";
	

	$.ajax({
		type: "GET",
		url: "../ajax/actualizarCategoria.php?modelo=" + $( "#nombre" ).val() + "&niel=" + $( "#niel" ).val() + "&formato=" + $( "#formato" ).val() ,
		dataType: type,
		success: function( respuesta ) {
			
			if (navegador != "Microsoft Internet Explorer"){
				parser = new DOMParser();
				respuesta = parser.parseFromString(respuesta, "text/xml");
			}
			estado = respuesta.getElementsByTagName("estado")[0].childNodes[0].nodeValue;
			if (estado == "ok"){
				arr = $( "categoria", respuesta ).map(function() {
			          return {
			        	  categoria: $(this).text()
				       };
			      });				
				
				comboCategorias = document.getElementById("categoria");
				
				var opcionAnterior = "";
				if (comboCategorias.selectedIndex >= 0)
					opcionAnterior = comboCategorias[comboCategorias.selectedIndex].value;

				comboCategorias.innerHTML = "";
				
				op = document.createElement("option");
				op.setAttribute("value", "");
		        elmText = document.createTextNode("<todos>");
		        op.appendChild(elmText);
				comboCategorias.appendChild(op);
				
				for (i=0; i<arr.length; i++){
					op = document.createElement("option");
			        elmText = document.createTextNode(arr[i].categoria);
			        op.appendChild(elmText);
					op.setAttribute("value", arr[i].categoria);
					if (opcionAnterior == arr[i].categoria)
						op.setAttribute("selected", "selected");
					comboCategorias.appendChild(op);
				}		
			}			
		},		
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//alert(textStatus);
		}		
	});
}

/* Funcion que mediante AJAX actualiza el select de formatos que coinciden con los parametros enviados */

function actualizaFormato(){
	var navegador = navigator.appName;
	
	if (navegador == "Microsoft Internet Explorer")
		type = "xml";
	else
		type = "text/xml";
	

	$.ajax({
		type: "GET",
		url: "../ajax/actualizarFormato.php?modelo=" + $( "#nombre" ).val() + "&niel=" + $( "#niel" ).val() + "&categoria=" + $( "#categoria" ).val() ,
		dataType: type,
		success: function( respuesta ) {
			
			if (navegador != "Microsoft Internet Explorer"){
				parser = new DOMParser();
				respuesta = parser.parseFromString(respuesta, "text/xml");
			}
			estado = respuesta.getElementsByTagName("estado")[0].childNodes[0].nodeValue;
			if (estado == "ok"){
				arr = $( "formato", respuesta ).map(function() {
			          return {
			        	  formato: $(this).text()
				       };
			      });
				
				var opcionAnterior = "";
			
				comboFormatos = document.getElementById("formato");
				if (comboFormatos.selectedIndex >= 0){
					opcionAnterior = comboFormatos[comboFormatos.selectedIndex].value;
				}
				
				comboFormatos.innerHTML = "";
				
				op = document.createElement("option");
				op.setAttribute("value", "");
		        elmText = document.createTextNode("<todos>");
		        op.appendChild(elmText);
				comboFormatos.appendChild(op);
				
				for (i=0; i<arr.length; i++){
					op = document.createElement("option");
			        elmText = document.createTextNode(arr[i].formato);
			        op.appendChild(elmText);
					op.setAttribute("value", arr[i].formato);
					if (opcionAnterior == arr[i].formato)
						op.setAttribute("selected", "selected");
					comboFormatos.appendChild(op);
				}				
			}			
		},		
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//alert(textStatus);
		}		
	});
}

/* Funcion que actualiza los selects categorias y formato */

function actualizaSelects(){
	actualizaFormato();
	actualizaCategoria();
}

/* Funcion que comprueba que antes de guardar un carrito se le haya asignado una referencia */

function compruebaReferencia($mensaje){
	var referencia = document.getElementById("referencia").value;
	if (referencia == ""){
		var enlace = document.getElementById("guardar");
		enlace.removeAttribute('href');
		document.getElementById('mensajeError').className = "errorNuevo";
		document.getElementById('mensajeError').innerHTML = "La referencia no puede estar vacía";	
		document.getElementById("referencia").value = "";
	}else{
		document.getElementById('mensajeError').className = "sinErrorNuevo";
		document.getElementById('mensajeError').innerHTML = "";
		var enlace = document.getElementById("guardar");
		enlace.setAttribute('href', '../app/user_seleccion.php?crearPedido=1')
	}
}



