function $(id){ var elem = document.getElementById(id); return elem; }
function ev (x,y,z) { if (document.addEventListener) { x.addEventListener(y,z,false); } else { x.attachEvent('on'+y,z); } }
function parar(x){ (x.preventDefault) ? x.preventDefault() : x.returnValue = false; }

function cargarArchivo(x){
	var peticion = objetoHTTP();
	if(peticion){
		peticion.onreadystatechange = function(){ resultado(peticion); };
		peticion.open('POST', 'contacto/formulario.php', true);
		peticion.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
		peticion.send(x);
	}
}

function resultado(peticion) {
	if (peticion.readyState == 4) {
		if (peticion.status == 200 || peticion.status == 304) {
			var contenido = peticion.responseText;
			var resultados;
			if(!($('resultados'))){
				resultados = document.createElement('fieldset');
				resultados.id = 'resultados';
			} else { resultados = $('resultados'); }
			$('f-contacto').insertBefore(resultados,$('privacidad'));
			$('resultados').innerHTML = contenido;	
			$('b').disabled = false;
			$('b').innerHTML = 'Enviar';
			$('resultados').tabindex = '-1';
			$('resultados').focus();
		}
	}
}

function objetoHTTP() { 
	var xhr = false;
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false;
			}
		}
	}
	return xhr;
}

function procesarFormulario(e){
	parar(e);
	$('b').disabled = true;
	$('b').innerHTML = '<img src="imagenes/cargador.gif" alt="" /> Esperando respuesta del servidor&#8230;';
	var variables = 'nombre='+$('nombre').value+'&mensaje='+$('mensaje').value+'&correo='+$('correo').value;
	cargarArchivo(variables);
}

ev(window,'load',function(){$('b').disabled = false;ev($('b'),'click',procesarFormulario)});
