function getXmlHttpRequestObject() {
	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.");
	}
}			

var receiveReq = getXmlHttpRequestObject();		
var funcion_respuesta = "";
var objeto_json = false;
var ultima_postdata = "";
function EnviaPeticionServidor(pagina, pfuncion_respuesta, pobjeto_json, metodo, postdata) {

	funcion_respuesta = pfuncion_respuesta;
	ultima_postdata = "";
	if (pobjeto_json != undefined)
		objeto_json = pobjeto_json;
	if (metodo == undefined)
		metodo = "GET";
	if (postdata == undefined)
		postdata = null;
	else {
		postdata = "metodo_ajax=1&" + postdata;
		ultima_postdata = postdata;
	}
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
		receiveReq.open(metodo, pagina, true);
		receiveReq.onreadystatechange = handleEnviaPeticion; 
		if (metodo == "POST") {
			receiveReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}
		receiveReq.send(postdata);
	}			
}

function handleEnviaPeticion() {

	if (receiveReq.readyState == 4) {
		desc_busc = new String ('404 Not Found')
		eval ( 'var patron = /'+desc_busc+'/i' )
		if ((ultima_postdata != "" && receiveReq.responseText.substring(0, 9) != "location:" && receiveReq.responseText.substring(0, 9) != "ejecutar:") || receiveReq.responseText.substring(0, 9) == "<b>Error:" || (receiveReq.responseText.search(patron) != -1)) {
			divError = document.getElementById("errorAjax");
			if (!divError) {
				alert(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>"+ultima_postdata+"<br><br>";
				divError.innerHTML = divError.innerHTML + 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 (receiveReq.responseText.substring(0, 9) == "ejecutar:") {
				eval (receiveReq.responseText.substring(9, receiveReq.responseText.length));
			} else {
				if (objeto_json) {
					eval ('objRespuesta = '+receiveReq.responseText);
					eval (funcion_respuesta + '(objRespuesta)');
				} else
					eval (funcion_respuesta + '(receiveReq.responseText);');
			}
		}
	}
}


function serializeForm (form) {
	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;
			}
		}
	}

	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
		name = labels[i].name;
		if (name == undefined)
			name = labels[i].id;
		data += encodeURIComponent(name) + '=' + encodeURIComponent(labels[i].innerHTML) + '&';
	}

	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() {
	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.form.appendChild(div);
}
function CrearDivFondo() {
	div = document.createElement('DIV');
	div.id = "div_fondo";
	div.className = "fondo_transp";
	div.style.display = "none";
	document.form.appendChild(div);
}

var _handleTeclaEnter = _handleTeclaEsc = _divModal = "";
var _margenSuperiorDivModal = _margenDerechoDivModal = -1;
function mostrarDivModal(div, handleTeclaEnter, handleTeclaEsc, margen_superior, margen_derecho) {
	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;
		
	_divModal = div;
	
	CambiarVisibilidadCombos(false);
			
	document.getElementById(div).style.display = "";
	if (!document.getElementById('div_fondo'))
		CrearDivFondo();
	document.getElementById("div_fondo").style.display = "";
	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');
		}
	}
}

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 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>';
	
	document.getElementById('div_ayuda_mantenimiento').innerHTML = texto;
	mostrarDivModal('div_ayuda_mantenimiento', '', '');
}
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) {
	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 = '/ViewOffice/class/UI/refrescar_combo.php';
	var pagina = pagina_refrescar + '?'+parametros+'&permitir_seleccionar_todos='+(permitir_seleccionar_todos?'S':'N')+'&'+strCombos;
	EnviaPeticionServidor(pagina, 'handleRefrescarCombo', true, 'GET') ;
}
function handleRefrescarCombo(respuesta) {
	for (i = 0; i < respuesta.length; i ++) {
		eval ('var obj = document.form.'+respuesta[i].nombre+';');
		if (obj == undefined)
			obj = document.getElementById(respuesta[i].nombre);
		if (obj == undefined)
			alert('No se encuentra ' + respuesta[i].nombre);
		if (obj.selectedIndex != undefined) {
			obj.length = 0;
			for (j = 0; j < respuesta[i].valores.length; j ++) {
				obj.options[j] = new Option();
				obj.options[j].value = respuesta[i].valores[j][0];
				obj.options[j].text = respuesta[i].valores[j][1];
				if (respuesta[i].valores[j].length > 1) {
					obj.options[j].datos = respuesta[i].valores[j][2];
				}
			}
		} else {
			var valor = "";
			for (j = 0; j < respuesta[i].valores.length; j ++) {
				valor = valor + respuesta[i].valores[j][1];
			}
			obj.innerHTML = valor;
		}
	}
}

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;
		else
			document.getElementById("div_fondo").style.top = parseInt(window.scrollY, 10) + "px";
		if (_divModal != "") {
			if (_margenSuperiorDivModal != -1) {
				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 (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);
			}
		}
	};
}
