/*************************************************************/
/*******************JAVASCRIPT INCOMPANY 1.0******************/
/*************************************************************/
//ruta = "http://localhost/incompany/";
//ruta = "http://www.igngroup.com/incompany/";
ruta = "http://www.incompanydesign.com/";

//FUNCION STANDARD PARA EL XMLREQUEST
function crear_comunicacion(){
 var pagina_requerida = false;
    if (window.XMLHttpRequest)
    {
        // Si es Mozilla, Safari etc
        pagina_requerida = new XMLHttpRequest ();
    } else if (window.ActiveXObject)
    {
        // pero si es IE
        try 
        {
            pagina_requerida = new ActiveXObject ("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            // en caso que sea una versión antigua
            try
            {
                pagina_requerida = new ActiveXObject ("Microsoft.XMLHTTP");
            }
            catch (e)
            {
            }
        }
    }
	return pagina_requerida;
}

//FUNCION QUE COMPRUEBA QUE EL USUARIO NO EXISTA EN EL SISTEMA
var respuesta;
function comprobar_usuario_registro(usuario){

	var req = crear_comunicacion();
 
	req.open('GET', ruta+"ajax/comprobar-usuario.php?usuario="+usuario, false);   
	req.send(null);  
	
	if(req.status == 200){
	
		if(req.responseText == "BIEN")
		respuesta = true;
		else
		respuesta = false;
		
	}
	
	return respuesta;
	
}


//FUNCION QUE COMPRUEBA EL REGISTRO DE UN USUARIO
function comprobar_registro(){

	if(document.registro.usuario.value.length == 0 || document.registro.password.value.length == 0 || document.registro.password2.value.length == 0 || document.registro.telefono.value.length == 0 || document.registro.empresa.value.length == 0){
	document.getElementById("error").innerHTML = "<b>Estado del formulario:</b> <font color='#FF0000'>Se ha dejado algún campo obligatorio (*) por rellenar</font>";
	}else{
		//COMPROBAMOS USUARIO CON EXPRESION REGULAR
		var patron_usuario = /^([0-9a-z\-]{4,15})$/
		if(!patron_usuario.test(document.registro.usuario.value)){
		document.getElementById("error").innerHTML = "<b>Estado del formulario:</b> <font color='#FF0000'>El nombre de usuario debe tener al menos <b>4 caracteres</b> y un <b>máximo de 15</b>. Sólo se permiten caracteres de la <b>a-z</b> minúscula y números <b>0-9</b>, también se permiten guiones <font size='+1'><b>-</b></font>, no se admiten espacios</font>";
		}else{
		existe_usuario = comprobar_usuario_registro(document.registro.usuario.value);
			//alert(existe_usuario);
			//SI EL NOMBRE DE USUARIO YA EXISTE
			if(existe_usuario == false){
			document.getElementById("error").innerHTML = "<b>Estado del formulario:</b> <font color='#FF0000'>Este nombre de usuario ya existe en el sistema, elija otro</font>";
			}else{
			
				//COMPROBAMOS PASSWORD CON EXPRESION REGULAR
				var patron_password = /^[A-Za-z\d]{4,15}$/
				if(!patron_password.test(document.registro.password.value)){
				document.getElementById("error").innerHTML = "<b>Estado del formulario:</b> <font color='#FF0000'>La contraseña debe tener al menos <b>4 caracteres</b> y un <b>máximo de 15</b>. Sólo se permiten caracteres de la <b>a-z</b> minúscula y mayúscula <b>A-Z</b> y números <b>0-9</b>, no se admiten espacios</font>";
				}else{
					//SI LAS CONTRASEÑAS NO COINCIDEN
					if(document.registro.password.value != document.registro.password2.value){
					document.getElementById("error").innerHTML = "<b>Estado del formulario:</b> <font color='#FF0000'>Las contraseñas no coinciden</font>";
					}else{
					email_comprobado = comprobar_email(document.registro.email.value);
						//SI EL EMAIL ES VALIDO
						if(document.registro.email.value.length != 0 && email_comprobado == false){
						document.getElementById("error").innerHTML = "<b>Estado del formulario:</b> <font color='#FF0000'>El E-mail propuesto no es válido</font>";
						}else{
						document.registro.password.value = '';
						document.registro.password2.value = '';
						document.registro.submit();
						
						}
					}
				}
			}
		}
	}
						
}

//FUNCION QUE COMPRUEBA EL LOGIN DEL USUARIO
function comprobar_login(user,password){


	if(user == "" || password == "d41d8cd98f00b204e9800998ecf8427e"){
	document.getElementById("loginerror").innerHTML = "<b>Error</b>: Te has dejado algun campo vacío";
	}else{
	pagina_requerida = crear_comunicacion();
	//alert(password);
		pagina_requerida.onreadystatechange = function (){
			if(pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1)){
				if(pagina_requerida.responseText == "BIEN"){
				document.login.encryptedpassword.value = password;
				document.login.contraseña.value = '';
				document.login.submit();
				}else{
				document.getElementById("loginerror").innerHTML = "<b>Error</b>: Los datos no son correctos";
				}
			}	
   		}
	
    pagina_requerida.open ('GET', ruta+"ajax/comprobar-login.php?user="+user+"&password="+password, true); // asignamos los métodos open y send
    pagina_requerida.send (null);
	}
}

function comprueba_buscador(){

	if(document.buscador.buscar.value.length < 3){
	alert('La búsqueda debe tener como mínimo 3 caracteres');
	}else{
	
		/*if(document.buscador.tipo.value == 'Por tipo...'){
		alert('Elige un tipo de busqueda');
		}else{
		
			if(document.buscador.comunidad.value == 'Por comunidad...'){
			alert("Elige una comunidad autónoma");
			}else{
			
				if(document.buscador.perfil.value == 'Por perfil...'){
				alert("Elige un perfil de partner I+D+i");
				}else{*/
				document.buscador.submit();
				//}
			
			//}
		
		//}
	}
}

function cambia_canal(canal){
	
	switch(canal){
	case 'Open innovation':
	document.getElementById('recomendaciones').style.display = 'none';
	document.getElementById('credenciales').style.display = 'none';
	document.getElementById('open-innovation').style.display = 'block';
	document.getElementById('1').style.backgroundColor = '#444444';
	document.getElementById('2').style.backgroundColor = '#d4d0c8';
	document.getElementById('3').style.backgroundColor = '#d4d0c8';
	document.getElementById('1').style.color = '#e0e0e0';
	document.getElementById('2').style.color = '#000000';
	document.getElementById('3').style.color = '#000000';
	break;
	
	case 'Recomendaciones':
	document.getElementById('recomendaciones').style.display = 'block';
	document.getElementById('credenciales').style.display = 'none';
	document.getElementById('open-innovation').style.display = 'none';
	document.getElementById('1').style.backgroundColor = '#d4d0c8';
	document.getElementById('2').style.backgroundColor = '#444444';
	document.getElementById('3').style.backgroundColor = '#d4d0c8';
	document.getElementById('1').style.color = '#000000';
	document.getElementById('2').style.color = '#e0e0e0';
	document.getElementById('3').style.color = '#000000';
	break;
	
	case 'Credenciales':
	document.getElementById('recomendaciones').style.display = 'none';
	document.getElementById('credenciales').style.display = 'block';
	document.getElementById('open-innovation').style.display = 'none';
	document.getElementById('1').style.backgroundColor = '#d4d0c8';
	document.getElementById('2').style.backgroundColor = '#d4d0c8';
	document.getElementById('3').style.backgroundColor = '#444444';
	document.getElementById('1').style.color = '#000000';
	document.getElementById('2').style.color = '#000000';
	document.getElementById('3').style.color = '#e0e0e0';
	break;
	}
	
}

function cuenta(){
limite = 500;
document.solicitud.caracteres.value = limite - document.solicitud.presentacion.value.length;

	if(document.solicitud.presentacion.value.length > limite){
	document.solicitud.presentacion.value = document.solicitud.presentacion.value.substr(0,limite);
	document.solicitud.caracteres.value = 0;
	//alert("ddd");
	}

}

//CUENTA DEL APARTADO DE CONTACTO
function cuenta_contacto(){
limite = 500;
document.repositorio.caracteres.value = limite - document.repositorio.mensaje.value.length;

	if(document.repositorio.mensaje.value.length > limite){
	document.repositorio.mensaje.value = document.repositorio.mensaje.value.substr(0,limite);
	document.repositorio.caracteres.value = 0;
	//alert("ddd");
	}

}

//FUNCION KE COMPRUEBA KE TODO VAYA BIEN EN CONTACTO.PHP
function comprobar_repositorio(){

	if(document.repositorio.nombre.value.length <= 0 || document.repositorio.telf.value.length <= 0 || document.repositorio.titulo.value.length <= 0 || document.repositorio.mensaje.value.length <= 0){
	document.getElementById("errorrepositorio").innerHTML = 'Estado del formulario: <font color="#FF0000">Se ha dejado algún campo en blanco, todos son obligatorios y están marcados con (*)</font>';
	}else{
		if(document.repositorio.mensaje.value.length < 25){
		document.getElementById("errorrepositorio").innerHTML = 'Estado del formulario: <font color="#FF0000">El contenido del mensaje debe contener 25 caracteres como mínimo</font>';
		}else{
		//alert("as");
		document.repositorio.submit();
		}

	}

}

//FUNCION PARA VALIDAR EL EMAIL POR JAVASCRIPT
function comprobar_email(texto){
var respuesta = true;            
var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
		    
var arroba = texto.indexOf("@",0);
if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
		    
var punto = texto.lastIndexOf(".");
		                
for (var contador = 0 ; contador < texto.length ; contador++){
	if (cadena.indexOf(texto.substr(contador, 1),0) == -1){
	respuesta = false;
	break;
	}
}
		
if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (respuesta == true) && (texto.indexOf("..",0) == -1))
respuesta = true;
else
respuesta = false;
		                
return respuesta;

}

function abrir_ventana(pagina){
var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600, top=85, left=140";
window.open(pagina,"",opciones);
}

/*function valida_user(usuario) {
    //expresion regular para telefonos
    //permite campos vacios y guiones
    var patron = /^([0-9a-z\-]{4,10})$/

    //comprueba campo tlfono de formu
    //usa el metodo test de expresion regular
    if(!patron.test(usuario))
    alert('Campo usuario no válido.')
	else
    alert('WHOO')
	
}*/
