// JavaScript Document
// AUTOR: Nacho
// FECHA: Sab, 17 de Marzo de 2007
// ----------------------------------

function encodeMas(cadena){
	cadena = cadena.replace(/\+/gi,"<mas>");
	return cadena;
}

function decodeMas(cadena){
	cadena = cadena.replace(/<mas>/gi,"+");
	return cadena;
}

function emailvalidation(entered, alertbox){
	// E-mail-Validation (c) 
	with (entered){
		apos    = value.indexOf("@");
		dotpos  = value.lastIndexOf(".");
		lastpos = value.length-1;
		if ( apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2) {
			if (alertbox) {
				alert(alertbox);
			} 
			return false;
		} else {
			return true;
		}
	}
}

function emptyvalidation(entered, alertbox){
	// Emptyfield-Validation (c) Henrik Petersen / NetKontoret
	with (entered){
		if (value==null || trimAll(value)==""){
			if (alertbox!="") {
				alert(alertbox);
			} 
			return false;
		} else {
			return true;
		}
	}
}

function trimAll(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
return sString;
}

function isMail(Cadena) {

	Punto = Cadena.substring(Cadena.lastIndexOf('.') + 1, Cadena.length);			// Cadena del .com
	Dominio = Cadena.substring(Cadena.lastIndexOf('@') + 1, Cadena.lastIndexOf('.')); 	// Dominio @lala.com
	Usuario = Cadena.substring(0, Cadena.lastIndexOf('@'));					// Cadena lalala@
	Reserv = "@/'+*{}\<>?¿[]áéíóú#·¡!^*;,:";						//Letras Reservadas
	
	// Añadida por El Codigo para poder emitir un alert en funcion de si email valido o no
	valido = true
	
	// verifica qie el Usuario no tenga un caracter especial
	for (var Cont=0; Cont<Usuario.length; Cont++) {
		X = Usuario.substring(Cont,Cont+1)
		if (Reserv.indexOf(X)!=-1)
                	valido = false
	}

	// verifica qie el Punto no tenga un caracter especial
	for (var Cont=0; Cont<Punto.length; Cont++) {
		X=Punto.substring(Cont,Cont+1)
		if (Reserv.indexOf(X)!=-1)
			valido = false
	}
                        
	// verifica qie el Dominio no tenga un caracter especial
	for (var Cont=0; Cont<Dominio.length; Cont++) {
		X=Dominio.substring(Cont,Cont+1)
		if (Reserv.indexOf(X)!=-1)
			valido = false
		}

	// Verifica la sintaxis básica.....
	if (Punto.length<2 || Dominio <1 || Cadena.lastIndexOf('.')<0 || Cadena.lastIndexOf('@')<0 || Usuario<1) {
		valido = false
	}
	return valido;
}


// Cargador de Objeto XMLHttpRequest() (AJAX)
//-------------------------------------------
function nuevoAjax(){
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (E) {
			xmlhttp = false;
		}
	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}
//-------------------------------------------

// cargar contador de visitas
function cargarContadorVisitas(id){
	var contenedor;
	contenedor = document.getElementById(id);
	ajaxVisitas=nuevoAjax();
	ajaxVisitas.open("GET","contador.php",true);

	ajaxVisitas.onreadystatechange=function() {
		if (ajaxVisitas.readyState==4) {
			contenedor.innerHTML = ajaxVisitas.responseText
		} else {
			contenedor.innerHTML = "<center><img src='imagenes/ajax-loader.gif'></center>";
		}
	}

	ajaxVisitas.send(null)

}

// Carga la url pasado por parametro en el Elemento correspondiente al ID
// ----------------------------------------------------------------------
function cargarContenido(url, id){
	var contenedor;
	var cadena;
	var cadenafinal;
	
	contenedor = document.getElementById(id);
	ajax=nuevoAjax();
	ajax.open("GET", url,true);

	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			txt=ajax.responseText;
			txt=txt.replace(/\+/gi,"##mas##");
			txt=unescape(txt);
			txt2=txt.replace(/\+/gi," ");
			txt2=decodeMas(txt2);
			txt2=txt2.replace(/##mas##/gi,"+");
			contenedor.innerHTML = txt2;
			
		} 
	}

//	ajax.setRequestHeader("Content-Type","text/html; charset=iso-8859-1"); 
	ajax.send(null)
}

function enviarCorreo(){
	var nombre, mail, asunto, mensaje
	nombre = document.getElementById("contacto_nombre").value;
	mail  = document.getElementById("contacto_mail").value;
	asunto = document.getElementById("contacto_asunto").value;
	mensaje = document.getElementById("contacto_mensaje").value;

	if (nombre == ''){
		alert('Ingrese un nombre en el Formulario');
		return false;
	}
	if (asunto == ''){
		alert('Ingrese un asunto en el Formulario');
		return false;
	}
	if (mail == ''){
		alert('Ingrese un correo electrónico en el Formulario');
		return false;
	}
	else{
		if (!isMail(mail)){
			alert("Por favor indique un e-Mail Válido");
			return false;
		}
	}
	if (mensaje == ''){
		alert('Ingrese un mensaje en el Formulario');
		return false;
	}
	
	// por aca todo OK!
	var contenedor;
	contenedor = document.getElementById('contenedorPrincipal');
	
	ajax=nuevoAjax();
	ajax.open("POST", "contacto_enviar_mail.php",true);

	ajax.onreadystatechange = function(){
			if (ajax.readyState == 1){
					contenedor.innerHTML = "<samp class='subtitulo'>enviando mensaje...</samp>";
			}
			if (ajax.readyState == 4){
					contenedor.innerHTML = ajax.responseText;
			}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("nombre="+nombre+"&mail="+mail+"&asunto="+asunto+"&mensaje="+mensaje);

}

// pedir el formulario de abm info
function pedirAbmFormInfo(contenedorString, idInfo, tipoInfo){
	var contenedor;
	contenedor = document.getElementById(contenedorString);
	
	ajaxForm = nuevoAjax();
	ajaxForm.open("POST","abmInfoForm.php",true);

	ajaxForm.onreadystatechange = function(){
			if (ajaxForm.readyState == 1){
					contenedor.innerHTML = "cargando form...";
			}
			if (ajaxForm.readyState == 4){
					contenedor.innerHTML = ajaxForm.responseText;
			}
	}

	ajaxForm.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajaxForm.send("idInfo="+idInfo+"&tipoInfo="+tipoInfo);

}
// pedir el resultado de una búsqueda
function pedirResultados(tipoInfo){
	var texto;
	var anno;
	var mes;
	var dia;
	var activa;	
	texto = document.getElementById('buscadorTexto').value;
	anno = document.getElementById('buscadorAnno').value;
	mes = document.getElementById('buscadorMes').value;
	dia = document.getElementById('buscadorDia').value;
	activa = document.getElementById('buscadorActiva').checked;

	var contenedor;
	contenedor = document.getElementById('resultados');
	var ajaxBusqueda;
	ajaxBusqueda = nuevoAjax();
	ajaxBusqueda.open("POST", "resultadosInfo.php",true);

	ajaxBusqueda.onreadystatechange = function(){
			if (ajaxBusqueda.readyState == 1){
					contenedor.innerHTML = "buscando resultados...";
			}
			if (ajaxBusqueda.readyState == 4){
					contenedor.innerHTML = ajaxBusqueda.responseText;
			}
	}
	ajaxBusqueda.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajaxBusqueda.send("tipoInfo="+tipoInfo+"&texto="+texto+"&anno="+anno+"&mes="+mes+"&dia="+dia+"&activa="+activa);
}

function subirArchivo(){
	contenedor = document.getElementById('resultado');
	contenedorFrm = document.getElementById('contenedorFormulario'); 
	document.getElementById('frmSubidorArchivos').submit();
	contenedorFrm.style.display = 'none';	
	contenedor.innerHTML = 'Enviando imagen al servidor...<br><img src="../img/barra_espera.gif" border=0>';
}

function enviarABMInfo(contenedorString){
	
	contenedor = document.getElementById(contenedorString);
		
	var idInfo = document.getElementById('idInfo').value;
	var tipoInfo = document.getElementById('tipoInfo').value;
	
	if (document.getElementById('abmIdFoto')){
		var idFoto = document.getElementById('abmIdFoto').value;
	} else {
		idFoto = '';
	}
	
	if (document.getElementById('abmIdFotoAux')) {
		var idFotoAux = document.getElementById('abmIdFotoAux').value;
	} else {
		idFotoAux = '';
	}
	if (document.getElementById('abmTitulo')) {
		var titulo = trimAll(document.getElementById('abmTitulo').value);
		if (titulo == ''){
			alert('El título no puede estar vacío.['+titulo+']');
			exit;
		}

	} else {
		titulo = '';
	}
	if (document.getElementById('abmDescripcion')) {
		var descripcion = document.getElementById('abmDescripcion').value;
	} else {
		decripcion = '';
	}
	if (document.getElementById('abmFecha')) {
		var fecha = document.getElementById('abmFecha').value;
	} else {
		fecha = '';
	}
	if (document.getElementById('abmReferencia')) {
		var referencia = document.getElementById('abmReferencia').value;
		if (trimAll(referencia) == ''){
			alert('La referencia no puede estar vacío.');
			exit;
		}
	} else {
		referencia = '';
	}
	if (document.getElementById('abmRequisitos')) {
		var requisitos = document.getElementById('abmRequisitos').value;
	} else {
		requisitos = '';
	}

	if (document.getElementById('abmActiva').checked == true){
		activa = '1';
	} else {
		activa = '0';
	}

	aux = 'idFoto='+idFoto+'&';
	aux = aux + 'idFotoAux='+idFotoAux+'&';
	aux = aux + 'titulo='+titulo+'&';
	aux = aux + 'descripcion='+descripcion+'&';
	aux = aux + 'referencia='+referencia+'&';
	aux = aux + 'requisitos='+requisitos+'&';

	aux = aux + 'idInfo='+idInfo+'&';
	aux = aux + 'tipoInfo='+tipoInfo+'&';
	aux = aux + 'activa='+activa;

	ajax = nuevoAjax();
	ajax.open("POST", "recibirFormAbmInfo.php",true);

	ajax.onreadystatechange = function(){
			if (ajax.readyState == 1){
					contenedor.innerHTML = "procesando...";
			}
			if (ajax.readyState == 4){
					aux = ajax.responseText;
					cargarContenido('listadoInfo.php','cuerpoAdministracion');
			}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(aux);

}

function eliminarInfo(contenedorString,titulo,id){
	if (confirm('Esta por desactivar "'+titulo+'"\n¿Desea continuar?')){
		contenedor = document.getElementById(contenedorString);
		
		ajax = nuevoAjax();
		ajax.open("POST", "eliminarInfo.php",true);
	
		ajax.onreadystatechange = function(){
				if (ajax.readyState == 1){
						contenedor.innerHTML = "procesando...";
				}
				if (ajax.readyState == 4){
						aux = ajax.responseText;
						alert("La información se ha desactivado.\nSi quiere recuperar su estado puede realizar una búsqueda\ny volver a activarla.")
						cargarContenido('listadoInfo.php','cuerpoAdministracion');
						
				}
		}
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send('idInfo='+id);
	
	}
}

function enviarCorreoElectronico(){
	var correo  = document.getElementById('cnt_mail');
	var nombre  = document.getElementById('cnt_nombre');
	var mensaje = document.getElementById('cnt_mensaje');

	if(emailvalidation(correo,"Direccion de correo incorrecta")==false){
		correo.focus();
		return false;
	}

	if(emptyvalidation(nombre,"No ha ingresado ningun nombre.")==false){
		nombre.focus();
		return false;
	}

	if(emptyvalidation(mensaje,"No ha ingresado ningun comentario.")==false){
			mensaje.focus();
			return false;
	}

	var cnt_contenedor = document.getElementById('cnt_contenedor').value;
	var cnt_referencia = document.getElementById('cnt_referencia').value;
	var empresa        = document.getElementById('cnt_empresa').value;
	var cargo          = document.getElementById('cnt_cargo').value;
	var tel_numero     = document.getElementById('cnt_tel_numero').value;
	var type           = document.getElementById('cnt_type').value;
	
	correo  = correo.value;
	nombre  = nombre.value;
	
	var aux = 'correo='+correo;
	aux = aux + '&empresa='+empresa;
	aux = aux + '&nombre='+nombre;
	aux = aux + '&cargo='+cargo;
	aux = aux + '&tel_numero='+tel_numero;
	aux = aux + '&mensaje='+mensaje.value;
	aux = aux + '&type='+type;
	aux = aux + '&contenedor='+cnt_contenedor;
	aux = aux + '&referencia='+cnt_referencia;
	
	contenedor = document.getElementById(cnt_contenedor);

	var ajax = nuevoAjax();
	ajax.open("POST", "enviarMensaje.php",true);
	
	ajax.onreadystatechange = function(){
			if (ajax.readyState == 1){
					contenedor.innerHTML = "<div class='txtboldrojo' id='respuestaEnvio'>Aguarde por favor mientras<br>se env&iacute;a el mensaje...</div><br>";
			}
			if (ajax.readyState == 4){
				switch (type){
					case 'C':
						window.location = '/agradecimiento.html';
						break;
					case 'RRHH':
						contenedor.innerHTML = ajax.responseText;
						break;
				}
			}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(aux);

}
