var isIE = false;

//	Creamos una variable para el objeto XMLHttpRequest
var req;

//	Creamos una variable para guardar el div donde se cargará
var div;

//	Creamos una variable para guardar el ancla a la que se hará scroll
var ancla;

//Carga la página correspodiente en un div, y desplaza a un ancla si procede
function cargaXML(url, nombrediv, nombreancla) {
	if(url==''){
		return;
	}

	if(nombrediv && nombrediv!='') div = nombrediv;
	else div="main";

	if(nombreancla) ancla=nombreancla;
	else ancla="";

	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		if (req.overrideMimeType) {
            req.overrideMimeType('text/xml');
        }
		req.onreadystatechange=processReqChange;
		req.open("GET", url, true);
		req.send(null);

	} else if (window.ActiveXObject) { //IE
		try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                req = null;
            }
        }
        if (!req && typeof XMLHttpRequest!='undefined') {
            req = new XMLHttpRequest();
            if (!req){
                req = true;
            }
        }
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("GET", url, true);
			req.send();
		}
	}
}

//Función que procesa los cambios de estado del objeto req (ajax)
function processReqChange() {
    if (req.readyState==1){
        document.getElementById(div).innerHTML =  "<img src='loadingcircle.gif' align='center'>";
	}
	if (req.readyState==4) {
		if(req.status==200)
		{
			document.getElementById(div).innerHTML = req.responseText;
			mostrarFecha('fecha');
			if(ancla!="") irA(ancla);
		}
		else if(req.status==404)
		{
			document.getElementById(div).innerHTML = "La direccion no existe";
		}
		else
		{
			document.getElementById(div).innerHTML = "Error: ".ajax.status;
		}
	}
}

//Muestra la fecha en la capa indicada
function mostrarFecha(capa){
	var nombre_dia = new Array("domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado");
	var nombre_mes = new Array("enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre" ,"noviembre", "diciembre");
	var de = " de ";
	var hoy_es = new Date();
	dia_mes = hoy_es.getDate();
	dia_semana = hoy_es.getDay();
	mes = hoy_es.getMonth() + 1;
	anyo = hoy_es.getYear();

	if (anyo < 100) anyo = '19' + anyo;
	else if ( (anyo>100) && (anyo<999) ) {
		var cadena_anyo=new String(anyo);
		anyo='20' + cadena_anyo.substring(1,3);
	}
	if(document.getElementById(capa) != null)
		document.getElementById(capa).innerHTML = nombre_dia[dia_semana] + ", " + dia_mes + de + nombre_mes[mes - 1] + " de " + anyo + "&nbsp;";
}

//Desplaza hacia el elemento de la página con el id indicado
function irA(elemID) {
	var offsetTrail = document.getElementById(elemID);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined" && navigator.appName=="Microsoft Internet Explorer" ) {
		offsetLeft += parseInt(document.body.leftMargin);
		offsetTop += parseInt(document.body.topMargin);
	}
	window.scrollTo(offsetLeft,offsetTop)
}

//Crea el objeto ajax
function objetus(file) {
    this.xmlhttp=false;
    this.requestFile = file;
    this.encodeURIString = true;
    this.execute = false;
    if (window.XMLHttpRequest) {
        this.xmlhttp = new XMLHttpRequest();
        if (this.xmlhttp.overrideMimeType) {
            this.xmlhttp.overrideMimeType('text/xml');
        }
    }
    else if (window.ActiveXObject) { // IE
        try {
            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e) {
            try {
                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                this.xmlhttp = null;
            }
        }
        if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {
            this.xmlhttp = new XMLHttpRequest();
            if (!this.xmlhttp){
                this.failed = true;
            }
        }
    }
    return this.xmlhttp ;
}

//Procesa un formulario mediante get o post, y carga el resultado en la capa indicada
function procesarFormulario(_pagina,valorget,valorpost,capa){
    ajax=objetus(_pagina);
    if(valorpost!=""){
        ajax.open("POST", _pagina+"?"+valorget+"&tiempo="+new Date().getTime(),true);
    } else {
        ajax.open("GET", _pagina+"?"+valorget+"&tiempo="+new Date().getTime(),true);
    }

    ajax.onreadystatechange=function() {
        if (ajax.readyState==1){
            document.getElementById(capa).innerHTML =
				"<img src='loadingcircle.gif' align='center'>";
        }
        if (ajax.readyState==4) {
            if(ajax.status==200)
            {
				document.getElementById(capa).innerHTML = ajax.responseText;
				mostrarFecha('fecha');
			}
            else if(ajax.status==404)
            {
                document.getElementById(capa).innerHTML = "La direccion no existe";
            }
            else
            {
                document.getElementById(capa).innerHTML = "Error: ".ajax.status;
            }
        }
    }

    if(valorpost!=""){
        ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajax.send(valorpost);
    } else {
        ajax.send(null);
    }
}

//Obtiene el valor seleccionado de una serie de elementos radio de un formulario
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function buscar(_pagina){
    var ajax01 = objetus(_pagina);
	var cadena = document.getElementById('cadena').value;
	var resultadoBusqueda = document.getElementById('listadoEmpresas');
	ajax01.open("POST", "tratamiento_form.php",true);

	ajax01.onreadystatechange=function() {
		if (ajax01.readyState==4) {
			resultadoBusqueda.innerHTML = ajax01.responseText;
		}
	}

	ajax01.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	ajax01.send("action=buscarEmpresa&cadena="+cadena);
}
