/**
  * pagina: URL a la que se realizará la petición
  * funcion_respuesta: Función callback que recibirá el resultado de la petición
  * objeto_json =false. Si se indica a true, se parseará el resultado como un objeto JSON
  * metodo =GET Se puede realizar como POST. Si se utiliza POST, hay que considerar el valor del parámetro comprobarResultadoPOST dependiendo
  *             de qué se desee realizar con el resultado de la petición.
  * postdata ="" Si se utiliza el método POST, aquí pasaremos los datos
  * mostrar_cargando =false Si se desea que se muestre un fondo "cargando" mientras se procesa la petición, pasaremos este parámetro a true
  * comprobarResultadoPOST =true Por defecto, cuando se usa el método POST, se controla que la respuesta sea correcta en el sentido de que
  *                         la página existe y el resultado es "ejecutar:...." o "location:....". Pasando este parámetro a false se omitirá
  *                         esta comprobación
  **/
function EnviaPeticionServidor(pagina, funcion_respuesta, objeto_json, metodo, postdata, mostrar_cargando, comprobarResultadoPOST) {
	objAJAX = new PeticionAJAX();
	objAJAX.funcion_respuesta = funcion_respuesta;
	if (objeto_json != undefined)
		objAJAX.objeto_json = objeto_json;
	if (metodo != undefined)
		objAJAX.metodo = metodo;
	if (postdata != undefined) {
		objAJAX.postdata = "metodo_ajax=1&" + postdata;
		objAJAX.ultima_postdata = postdata;
	}
	if (comprobarResultadoPOST != undefined)
		objAJAX.comprobarResultadoPOST = comprobarResultadoPOST;
		
	objAJAX.pagina = pagina;
	objAJAX.mostrar_cargando = mostrar_cargando;
	
	objAJAX.EnviaPeticion();
}

function serializeForm (form, incluir_labels) {
	if(typeof form == 'string') {
		form = (document.getElementById(form) || document.forms[form]);
	}

	var el, name, val, disabled, data = '', hasSubmit = false;
	for (var i = 0; i < form.elements.length; i++) {
		el = form.elements[i];
		disabled = form.elements[i].disabled;
		name = form.elements[i].name;
		if (name == "") 
			name = form.elements[i].id;
		val = form.elements[i].value;

		if (name){
			switch (el.type)
					{
				case 'select-one':
				case 'select-multiple':
					for (var j = 0; j < el.options.length; j++) {
						if (el.options[j].selected) {
							if (ie) {
								data += encodeURIComponent(name) + '=' + encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
							}
							else {
								data += encodeURIComponent(name) + '=' + encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
							}
						}
					}
					break;
				case 'radio':
					if (el.checked) {
						data += encodeURIComponent(el.id) + '=' + encodeURIComponent(val) + '&';
					}
					break;
				case 'checkbox':
					if (el.checked) {
						data += encodeURIComponent(name) + '=' + encodeURIComponent(val) + '&';
					}
					break;
				case 'file':

				case undefined:

				case 'reset':

				case 'button':

					break;
				case 'submit':
					if(hasSubmit == false) {
						data += encodeURIComponent(name) + '=' + encodeURIComponent(val) + '&';
						hasSubmit = true;
					}
					break;
				default:
					data += encodeURIComponent(name) + '=' + encodeURIComponent(val) + '&';
					break;
			}
		}
	}

	if (incluir_labels) {
		var labels = form.getElementsByTagName('label');
		for (var i = 0; i < labels.length; i++) {
			name = labels[i].name;
			if (name == undefined)
				name = labels[i].id;
			val = labels[i].innerHTML;
			if (val == "&nbsp;") {
				val = "";
			}
			data += encodeURIComponent(name) + '=' + encodeURIComponent(val) + '&';
		}
	}
	data = data.substr(0, data.length - 1);
	return data;
}

function CierraErrorAjax() {
	document.getElementById("errorAjax").style.display = "none";
	document.getElementById("div_fondo").style.display = "none";
}
function MuestraCargando() {
	if (!document.getElementById('div_cargando'))
		CrearDivCargando();
	if (!document.getElementById('div_fondo'))
		CrearDivFondo();
	document.getElementById('div_cargando').style.display = "";
	document.getElementById('div_fondo').style.display = "";
	moverDivFondo();
	if (ie) {
		document.getElementById("div_cargando").style.posTop = document.body.scrollTop + (document.body.clientHeight - document.getElementById("div_cargando").offsetHeight) / 2 - 50;
		document.getElementById("div_cargando").style.posLeft = (document.body.clientWidth - document.getElementById("div_cargando").offsetWidth) / 2 ;
	} else {
		document.getElementById("div_cargando").style.top = parseInt(window.scrollY) + (parseInt(document.body.clientHeight) - parseInt(document.getElementById("div_cargando").offsetHeight)) / 2 - 50 + "px";
		document.getElementById("div_cargando").style.left = (parseInt(document.body.clientWidth) - parseInt(document.getElementById("div_cargando").offsetWidth)) / 2 + "px";  
	}
}
function OcultaCargando() {
	if (!document.getElementById('div_cargando'))
		var div_cargando_visible = false;
	else
		var div_cargando_visible = (document.getElementById('div_cargando').style.display == "");
	if (div_cargando_visible) {
		document.getElementById('div_cargando').style.display = "none";
		document.getElementById('div_fondo').style.display = "none";
	}
}

function CrearDivCargando() {
	div = document.createElement('DIV');
	div.id = "div_cargando";
	div.className = "indicador_cargando";
	div.style.display = "none";
	div.innerHTML = "Cargando...";
	document.body.appendChild(div);
}
function CrearDivFondo() {
	div = document.createElement('DIV');
	div.id = "div_fondo";
	div.className = "fondo_transp";
	div.style.display = "none";
	document.body.appendChild(div);
}
function divFondoVisible() {
	if (!document.getElementById('div_fondo'))
		return false;
	return (document.getElementById('div_fondo').style.display == "");
}
var _handleTeclaEnter = _handleTeclaEsc = _divModal = "";
var _margenSuperiorDivModal = _margenDerechoDivModal = -1;
var _resizeDivModal = false;
function mostrarDivModal(div, handleTeclaEnter, handleTeclaEsc, margen_superior, margen_derecho, resize_div) {
	if (handleTeclaEnter === undefined)
		_handleTeclaEnter = "";
	else
		_handleTeclaEnter = handleTeclaEnter;
	if (handleTeclaEsc === undefined)
		_handleTeclaEsc = "";
	else
		_handleTeclaEsc = handleTeclaEsc;
	if (margen_superior === undefined)
		_margenSuperiorDivModal = -1;
	else
		_margenSuperiorDivModal = margen_superior;
	if (margen_derecho === undefined)
		_margenDerechoDivModal = -1;
	else
		_margenDerechoDivModal = margen_derecho;
	if (resize_div === undefined)
		_resizeDivModal = false;
	else
		_resizeDivModal = resize_div;
	_divModal = div;
	
	CambiarVisibilidadCombos(false);
			
	document.getElementById(div).style.display = "";
	muestraDivFondo();
	scrollHandle();
}
function ocultarDivModal(div) {
	_handleTeclaEnter = _handleTeclaEsc = _divModal = "";
	CambiarVisibilidadCombos(true);
	document.getElementById(div).style.display = "none";
	if (document.getElementById('div_fondo'))
		document.getElementById("div_fondo").style.display = "none";
}
function CambiarVisibilidadCombos(visibles) {
	if (document.all) {
		var combos = document.getElementsByTagName('select');
		for (i = 0; i < combos.length; i ++) {
			combos[i].style.visibility = (visibles ? '' : 'hidden');
		}
	}
}
function muestraDivFondo() {
	if (!document.getElementById('div_fondo'))
		CrearDivFondo();
	document.getElementById("div_fondo").style.zIndex = 1;
	document.getElementById("div_fondo").style.display = "";
	moverDivFondo();
}
function ocultaDivFondo() {
	if (!document.getElementById('div_fondo'))
		CrearDivFondo();
	document.getElementById("div_fondo").style.display = "none";
}
var campo_ayuda = "";
function MuestraAyudaMantenimiento(ruta, campo) {
	campo_ayuda = campo;
	EnviaPeticionServidor('/ViewOffice/class/Ayuda/cargar_ayuda_mantenimiento.php?ruta_ayuda='+ruta+'&campo_ayuda='+campo, 'RespuestaAyudaMantenimiento');
}

function RespuestaAyudaMantenimiento(respuesta) {
	if (document.getElementById('div_ayuda_mantenimiento') == null) {
		CargaDivAyudaMantenimiento();
	}
	var div_ayuda = document.getElementById('div_ayuda_mantenimiento');
	var texto = '<div style="position:absolute; height: 260px; width:435px; overflow: auto">';
	
	if (document.getElementById('lbl'+campo_ayuda) != null) {
		var titulo = document.getElementById('lbl'+campo_ayuda).innerHTML;
		titulo = titulo.substring(0, titulo.length - 1);
		texto = texto + '<center><b><u>' + titulo + '</u></b></center><br><br>';
	}
	
	texto = texto + respuesta + '</div>';

	var boton = '<button class="boton_aceptar" onClick="CerrarAyudaMantenimiento()">Cerrar</button>';
	
	texto = texto + '<div style="position:absolute; top: 265px; height: 260px; overflow: visible">' + boton + '</div>';
	
	div_ayuda.innerHTML = texto;
	if (document.all) {
		div_ayuda.style.posTop = document.body.scrollTop + 50;
		document.getElementById("div_fondo").style.height = document.body.clientHeight;
	} else
		div_ayuda.style.top = (parseInt(window.scrollY, 10) + 50) + "px";

	mostrarDivModal('div_ayuda_mantenimiento', '', '');
}
function centrarDiv(id_div) {
	var div = document.getElementById(id_div);

	if (div.offsetHeight != 0)
		var height = div.offsetHeight;
	else
		var height = div.style.height;
	if (div.offsetWidth != 0)
		var width = div.offsetWidth;
	else
		var width = div.style.width;
	if (document.all) {
		div.style.top = (parseInt(document.body.clientHeight) - height) / 2 + document.body.scrollTop;
		div.style.left = (parseInt(document.body.clientWidth) - width) / 2 + document.body.scrollLeft;
	} else {
		div.style.top = (parseInt(document.body.clientHeight) - height) / 2 + parseInt(window.scrollY, 10) + "px";
		div.style.left = (parseInt(document.body.clientWidth) - width) / 2 + parseInt(window.scrollX, 10) + "px";
	}
}
function CerrarAyudaMantenimiento() {
	ocultarDivModal('div_ayuda_mantenimiento');
}
function CargaDivAyudaMantenimiento() {
	var divAyuda = document.createElement("div");
	divAyuda.setAttribute('id',"div_ayuda_mantenimiento");
//	divAyuda.className = "div_ayuda";
	divAyuda.style.display = "none";
	divAyuda.style.backgroundImage = 'url(/ViewOffice/fons2.jpg)';
	divAyuda.style.zIndex = 5;
	divAyuda.style.position = "absolute";
	divAyuda.style.left = "50px";
	divAyuda.style.top = "50px";
	divAyuda.style.width = "450px";
	divAyuda.style.height = "300px";
	divAyuda.style.border = "2px #0099CC solid";
	divAyuda.style.overflow = "hidden";
	divAyuda.style.paddingLeft = "5px";
	divAyuda.style.paddingTop = "5px";
    document.body.appendChild(divAyuda);
}

function RefrescarCombo(combos, parametros, permitir_seleccionar_todos, pagina_refrescar, funcion_callback, valores_seleccionados) {
	var strCombos = "";
	for (var i = 0; i < combos.length; i ++) {
		if (i != 0)
			strCombos+=",";
		strCombos+='"'+combos[i]+'"';
	}
	strCombos = 'datos={"combos" : ['+strCombos+']}';

	if (pagina_refrescar == undefined || pagina_refrescar == "")
		pagina_refrescar = '/ViewOffice/class/UI/refrescar_combo.php';

	var pagina = pagina_refrescar + '?'+parametros+'&'+strCombos;
	if (permitir_seleccionar_todos.length !== undefined) {
		var seleccionar = "";
		for (var i = 0; i < permitir_seleccionar_todos.length; i ++) {
			seleccionar = seleccionar + (permitir_seleccionar_todos[i] ? "S" : "N");
		}
		pagina = pagina +'&permitir_seleccionar_todos='+seleccionar;
	} else
		pagina = pagina +'&permitir_seleccionar_todos='+(permitir_seleccionar_todos?'S':'N');
	if (funcion_callback !== undefined)
		pagina = pagina + '&funcion_callback='+funcion_callback;
	if (valores_seleccionados !== undefined) {
		var strValores = "";
		for (var i = 0; i < valores_seleccionados.length; i ++) {
			if (i != 0)
				strValores+=",";
			var aux = valores_seleccionados[i].split(":");
			strValores+='{"campo":"'+aux[0]+'", "valor":"'+aux[1]+'"}';
		}
		pagina = pagina + '&valores_seleccionados=['+strValores+']';
	}
	EnviaPeticionServidor(pagina, 'handleRefrescarCombo', true, 'GET') ;
}
function handleRefrescarCombo(respuesta) {
	if (respuesta.error !== undefined)
		alert(respuesta.error);
	for (i = 0; i < respuesta.combos.length; i ++) {
		eval ('var obj = document.form.'+respuesta.combos[i].nombre+';');
		if (obj == undefined)
			obj = document.getElementById(respuesta.combos[i].nombre);
		if (obj == undefined)
			alert('No se encuentra ' + respuesta.combos[i].nombre);
		if (respuesta.combos[i].valor_seleccionado !== undefined)
			var valor_seleccionado = respuesta.combos[i].valor_seleccionado;
		else
			var valor_seleccionado = null;
		if (obj.selectedIndex != undefined) {
			obj.length = 0;
			for (j = 0; j < respuesta.combos[i].valores.length; j ++) {
				obj.options[j] = new Option();
				obj.options[j].value = respuesta.combos[i].valores[j][0];
				obj.options[j].text = respuesta.combos[i].valores[j][1];
				if (respuesta.combos[i].valores[j].length > 1) {
					obj.options[j].datos = respuesta.combos[i].valores[j][2];
				}
				if (valor_seleccionado !== null) {
					if (obj.options[j].value == valor_seleccionado)
						obj.selectedIndex = j;
				}
			}
		} else {
			var valor = "";
			for (j = 0; j < respuesta.combos[i].valores.length; j ++) {
				valor = valor + respuesta.combos[i].valores[j][1];
			}
			obj.innerHTML = valor;
		}
	}

	if (respuesta.funcion_callback != "")
		eval (respuesta.funcion_callback+'(respuesta);');
}

function EjecutarConsultaSQL(consulta_sql, funcion_resultado) {
	var pagina = '/ViewOffice/class/UI/ajax_consulta_sql.php?consulta_sql='+consulta_sql;
	EnviaPeticionServidor(pagina, funcion_resultado, true, 'GET') ;
}

function scrollHandle(e){
	if (!e) 
		e = window.event;
	if (!document.getElementById('div_fondo'))
		CrearDivFondo();
	moverDivFondo();
}

function moverDivFondo() {
	if (document.getElementById('div_fondo').style.display == "") {
		if (document.all) {
			document.getElementById("div_fondo").style.posTop = document.body.scrollTop;
			document.getElementById("div_fondo").style.height = document.body.clientHeight;
		} else
			document.getElementById("div_fondo").style.top = parseInt(window.scrollY, 10) + "px";
		if (_divModal != "") {
			if (_margenSuperiorDivModal != -1) {
				if (_resizeDivModal) {
					if (document.all) {
						document.getElementById(_divModal).style.height = document.body.clientHeight - (_margenSuperiorDivModal * 3);
					} else
						document.getElementById(_divModal).style.height = parseInt(document.body.clientHeight, 10) - (_margenSuperiorDivModal * 3) + "px";
				}
				if (document.all)
					document.getElementById(_divModal).style.posTop = document.body.scrollTop + _margenSuperiorDivModal;
				else
					document.getElementById(_divModal).style.top = parseInt(window.scrollY, 10) + _margenSuperiorDivModal + "px";
			}
			if (_margenDerechoDivModal != -1) {
				if (_resizeDivModal) {
					if (document.all) {
						document.getElementById(_divModal).style.width = document.body.clientWidth - (_margenDerechoDivModal * 2);
					} else
						document.getElementById(_divModal).style.width = parseInt(document.body.clientWidth, 10) - (_margenDerechoDivModal * 2) + "px";
				} 
				if (document.all) {
					document.getElementById(_divModal).style.posLeft = document.body.clientWidth + document.body.scrollLeft - document.getElementById(_divModal).style.width.replace(/px/, '') - _margenDerechoDivModal;
				} else
					document.getElementById(_divModal).style.left = parseInt(document.body.clientWidth, 10) + parseInt(window.scrollX, 10) - document.getElementById(_divModal).style.width.replace(/px/, '') - _margenDerechoDivModal + "px";
			}
		}
	}

}
window.onscroll = scrollHandle;

var ie = 1;
if(navigator.appName.indexOf("Netscape")>(-1)||navigator.appName.indexOf("Konqeror")>(-1))
	ie = 0;

function CacheElementos() {
	this.campos_cache = Array();
	
	this.getElemento = function(campo, indice) {
		return this.campos_cache[campo][indice];
	};
	this.inicializaCacheElementos = function(campo, numero_elementos) {
		if (this.campos_cache[campo] == undefined)
			this.campos_cache[campo] = Array();
		if (this.campos_cache[campo].length != numero_elementos) {
			for (var i = 0; i < numero_elementos; i ++) {
				this.campos_cache[campo][i] = document.getElementById(campo + "_" + i);
			}
		}
	};
}
function PeticionAJAX() {

	this.getXmlHttpRequestObject = function() {
		if (window.XMLHttpRequest) {
			return new XMLHttpRequest(); //Not IE
		} else if(window.ActiveXObject) {
			return new ActiveXObject("Microsoft.XMLHTTP"); //IE
		} else {
			alert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade to Firefox.");
		}
	}		

	this.receiveReq = this.getXmlHttpRequestObject();
	this.funcion_respuesta = "";
	this.objeto_json = false;
	this.ultima_postdata = "";
	this.metodo = "GET";
	this.postdata = null;
	this.pagina = "";
	this.comprobarResultadoPOST = true;
	
	this.EnviaPeticion = function() {
		if (this.mostrar_cargando) {
			MuestraCargando();
		}
		if (this.receiveReq.readyState == 4 || this.receiveReq.readyState == 0) {
			this.receiveReq.open(this.metodo, this.pagina, true);
			this.receiveReq.onreadystatechange = (function(objAJAX){
					return function() {
						if (objAJAX.receiveReq.readyState == 4) {
							OcultaCargando();
							desc_busc = new String ('404 Not Found')
							eval ( 'var patron = /'+desc_busc+'/i' )
							if ((!objAJAX.objeto_json && objAJAX.ultima_postdata != "" && objAJAX.comprobarResultadoPOST && objAJAX.receiveReq.responseText.substring(0, 9) != "location:" && objAJAX.receiveReq.responseText.substring(0, 9) != "ejecutar:") || objAJAX.receiveReq.responseText.substring(0, 8) == '<b>Error' || (objAJAX.receiveReq.responseText.search(patron) != -1)) {
								divError = document.getElementById("errorAjax");
								if (!divError) {
									alert(objAJAX.receiveReq.responseText);
								} else {
									divFondo = document.getElementById("div_fondo");
									if (divFondo) {
										divFondo.style.display = "";
									}
									divError.innerHTML = "Ha ocurrido un error al procesar los datos.<br><br>Datos completos del error:<br>"+objAJAX.ultima_postdata+"<br><br>";
									divError.innerHTML = divError.innerHTML + objAJAX.receiveReq.responseText;
									divError.innerHTML = divError.innerHTML + "<br><br><button type='button' class='boton_cancelar' onClick='CierraErrorAjax()'>Cerrar</button>";
									divError.style.display = "";
								}
							} else {
								var regExp = /"/gi;
								if (objAJAX.receiveReq.responseText.substring(0, 9) == "ejecutar:") {
									eval (objAJAX.receiveReq.responseText.substring(9, objAJAX.receiveReq.responseText.length));
								} else {
									if (objAJAX.objeto_json) {
										eval ('objRespuesta = '+objAJAX.receiveReq.responseText);
										eval (objAJAX.funcion_respuesta + '(objRespuesta)');
									} else
										eval (objAJAX.funcion_respuesta + '(objAJAX.receiveReq.responseText);');
								}
							}
						}
					}
				})(this);
			if (this.metodo == "POST") {
				this.receiveReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			}
			this.receiveReq.send(this.postdata);
		}
	}

}

