// JavaScript Document
//ruta = "http://localhost/MAI-WEB/";
ruta = "http://www.matelco.com/myc/";

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;
}

function showEmail(){
	document.f1.email_img.src = "imagenes/" + document.f1.destination.value + ".jpg";
	document.getElementById("enlace").href = "mailto:" + document.f1.destination.value;
}

function resetear_select(){
	document.getElementById('destination').options.selectedIndex = 0;
}

function cuenta(){
	limite = 500;
       document.f1.caracteres.value = limite - document.f1.message.value.length;

} 

/******COMPROBANDO EMAIL ****************/
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;

}


var u=0;
var numelementos = 10;
var historial = new Array(numelementos);
var cursor;
function llamar_ajax(url,id_contenedor,atras){

	var pagina_requerida = crear_comunicacion();
	
	// AQUI METEMOS LA FUNCION DE RESPUESTA
    pagina_requerida.onreadystatechange = function(){
        cargarpagina (pagina_requerida, id_contenedor);
    }
	
    pagina_requerida.open ('GET', url, true); // asignamos los métodos open y send
    pagina_requerida.send (null);
	
	if(atras != true){
		// ESTE ES EL CASO EN EL QUE EL CLIENTE HAGA MAS DE 10 ACCIONES, LA ULTIMA ENTRA Y LA PRIMERA SALE
		if(u == numelementos){	
			for(k=0;k<=numelementos-1;k++){
				if(k!=0){
				historial[k-1] = historial[k];
				cursor = numelementos-1;
				}
			}
		historial[u-1] = url;
	
		// SI NO LLEVA 10 ACCIONES VAMOS AÑADIENDO	
		}else{
			if(historial[u-1] != url){
			historial[u] = url;
			cursor = u;
			u++;
			}
		}
	}
	

//alert(u);

/*for(m=0;m<u;m++){
alert(historial[m]);
}*/
}

/********* FUNCION CARGAR AJAX.PHP EN EL DIV ********/
function cargarpagina (pagina_requerida, id_contenedor){
    if (pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1)){
    document.getElementById(id_contenedor).innerHTML = pagina_requerida.responseText;
	window.scrollTo(0,0);
	}
}


function llamar_ajax_imagen(url, id_contenedor){

	pagina_requerida = crear_comunicacion();
   
	
    pagina_requerida.onreadystatechange = function (){
        cargarimagen(pagina_requerida, id_contenedor);
    }
	
    pagina_requerida.open ('GET', url, true); // asignamos los métodos open y send
    pagina_requerida.send (null);
}

/********** FUNCION PARA CARGAR LA IMAGEN ********/
function cargarimagen (pagina_requerida, id_contenedor){

    if (pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1)){
    document.getElementById(id_contenedor).innerHTML = pagina_requerida.responseText;
	window.scrollTo(0,0);
	}
}


/***************BUSCADOR ************************/
function llamar_ajax_buscar(url, id_contenedor){
pagina_requerida = crear_comunicacion();

   if(document.getElementById("buscar").value.length > 1 && document.getElementById("buscar").value != "Escriba para buscar ..."){
   //alert("toc");
   	//var buscar = (document.getElementById("buscar").value);
	//alert(document.getElementById("buscar").value);
	//alert(buscar);
    pagina_requerida.onreadystatechange = function (){
        cargarbuscar(pagina_requerida, id_contenedor);
    }
	

	pagina_requerida.open ('GET', url, true); // asignamos los métodos open y send
    pagina_requerida.send (null);
	
	}else{
	alert("El parámetro de busqueda tiene que tener mínimo 2 carácteres");
	}
}

function cargarbuscar(pagina_requerida, id_contenedor){
	
    if (pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1)){
    document.getElementById(id_contenedor).innerHTML = pagina_requerida.responseText;
	window.scrollTo(0,0);
	}
}

/***** COMPROBAR CAPTCHA ****/
function llamar_ajax_captcha(url){

	pagina_requerida_captcha = crear_comunicacion();
   
	
    pagina_requerida_captcha.onreadystatechange = function (){
        cargarcaptcha(pagina_requerida_captcha);
    }
	
    pagina_requerida_captcha.open ('GET', url, true); // asignamos los métodos open y send
    pagina_requerida_captcha.send (null);
}

/********** FUNCION PARA CARGAR LA IMAGEN ********/
function cargarcaptcha(pagina_requerida_captcha){

    if (pagina_requerida_captcha.readyState == 4 && (pagina_requerida_captcha.status == 200 || window.location.href.indexOf ("http") == - 1)){
	//alert("BIEN.");
	//alert(pagina_requerida.responseText+".");
	//alert(pagina_requerida.responseText+".");
	//document.getElementById("estado").innerHTML = pagina_requerida.responseText;
	var comprobado = pagina_requerida_captcha.responseText;
    	if(comprobado=="BIEN "){
			if(tipo==1)
			document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#0000FF'>  Adjuntando archivo y enviando mensaje, por favor espere unos instantes (el tiempo dependerá de su conexión) ...</font>";
			else
			document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#0000FF'>  Enviando mensaje, por favor espere unos instantes ...</font>";
		
		document.f1.submit();
		}else{
		document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#FF0000'>  Ha introducido mal el código de seguridad, recuerde que son mayúsculas, por favor inténtelo de nuevo</font>";
		}
	}
	
}

	numero_categorias_desplegables = 14;

	var miArray = new Array(numero_categorias_desplegables);
	miArray[0] = "valvulas";
	miArray[1] = "tratamiento-de-aire";
	miArray[2] = "actuadores";
	miArray[3] = "accesorios";
	miArray[4] = "valvulas-de-proceso22";
	miArray[5] = "valvulas-de-proceso32";
	miArray[6] = "valvulas-de-proceso52";
	miArray[7] = "valvulas-de-proceso33-53";
	miArray[8] = "conectores-y-bobinas";
	miArray[9] = "presostatos-y-transmisores-de-presion";
	miArray[10] = "hfiltros";
	miArray[11] = "niveles";
	miArray[12] = "minimess";
	miArray[13] = "otros-elementos";
	
	repeticion = 1;

function desplegar_menu_cookie(nombre){

//id = document.cookie.substring(document.cookie.indexOf(nombre + '=') + nombre.length + 1,document.cookie.length);
cookie = getCookie(nombre);
if(cookie != null)
		
		for (i=0;i<numero_categorias_desplegables;i++){
	    document.getElementById(miArray[i]).style.display = 'none';
		}
		document.getElementById(cookie).style.display = 'block';
  		repeticion = 0;

}

function desplegar_menu(id,cerrar,solomostrar){
//alert(repeticion);
if(solomostrar == "FALSO"){

	anterior = getCookie("MENU");
	if(anterior != id){
	
		// SI EL CLICK ES DIFERENTE AL PREVIO
		if(cerrar == "FALSO"){
			for (i=0;i<numero_categorias_desplegables;i++){
		    document.getElementById(miArray[i]).style.display = 'none';
			}
			document.getElementById(id).style.display = 'block';
			repeticion = 1;
		
		document.cookie="MENU = "+id+";" 
		}else{
			for (i=0;i<numero_categorias_desplegables;i++){
		    document.getElementById(miArray[i]).style.display = 'none';
			}
			repeticion = 0;
		}
		
	}else{
		if(repeticion%2 == 1)
		document.getElementById(anterior).style.display = 'none';
		else
		document.getElementById(anterior).style.display = 'block';
		
	
	repeticion++;
	}
	
}else{
	for (i=0;i<numero_categorias_desplegables;i++){
	document.getElementById(miArray[i]).style.display = 'none';
	}
	document.getElementById(id).style.display = 'block';
}

}


function atras(){
direccion_ajax = "http://www.matelco.com/myc/ajax.php?categoria=";
split_categoria_1 = historial[cursor-1].split('=');

	if(historial[cursor-1] != direccion_ajax+"neumatica" || historial[cursor-1] != direccion_ajax+"automatizacion-de-procesos" || historial[cursor-1] != direccion_ajax+"hidraulica"){
		if(historial[cursor-1] == direccion_ajax+"valvulas" || historial[cursor-1] == direccion_ajax+"tratamiento-de-aire" || historial[cursor-1] == direccion_ajax+"actuadores" || historial[cursor-1] == direccion_ajax+"accesorios" || historial[cursor-1] == direccion_ajax+"valvulas-de-proceso22" || historial[cursor-1] == direccion_ajax+"valvulas-de-proceso32" || historial[cursor-1] == direccion_ajax+"valvulas-de-proceso52" || historial[cursor-1] == direccion_ajax+"valvulas-de-proceso33-53" || historial[cursor-1] == direccion_ajax+"conectores-y-bobinas" || historial[cursor-1] == direccion_ajax+"presostatos-y-transmisores-de-presion" || historial[cursor-1] == direccion_ajax+"hfiltros" || historial[cursor-1] == direccion_ajax+"niveles" || historial[cursor-1] == direccion_ajax+"minimess" || historial[cursor-1] == direccion_ajax+"otros-elementos"){
		desplegar_menu(split_categoria_1[1],"FALSO","FALSO");
		}else{
		t4(split_categoria_1[1]);
		}
	}
	llamar_ajax(historial[cursor-1],'der',true);
	cursor--;
}

function adelante(){
direccion_ajax = "http://www.matelco.com/myc/ajax.php?categoria=";
split_categoria_1 = historial[cursor+1].split('=');

	if(historial[cursor+1] != direccion_ajax+"neumatica" || historial[cursor+1] != direccion_ajax+"automatizacion-de-procesos" || historial[cursor+1] != direccion_ajax+"hidraulica"){
		if(historial[cursor+1] == direccion_ajax+"valvulas" || historial[cursor+1] == direccion_ajax+"tratamiento-de-aire" || historial[cursor+1] == direccion_ajax+"actuadores" || historial[cursor+1] == direccion_ajax+"accesorios" || historial[cursor+1] == direccion_ajax+"valvulas-de-proceso22" || historial[cursor+1] == direccion_ajax+"valvulas-de-proceso32" || historial[cursor+1] == direccion_ajax+"valvulas-de-proceso52" || historial[cursor+1] == direccion_ajax+"valvulas-de-proceso33-53" || historial[cursor+1] == direccion_ajax+"conectores-y-bobinas" || historial[cursor+1] == direccion_ajax+"presostatos-y-transmisores-de-presion" || historial[cursor+1] == direccion_ajax+"hfiltros" || historial[cursor+1] == direccion_ajax+"niveles" || historial[cursor+1] == direccion_ajax+"minimess" || historial[cursor+1] == direccion_ajax+"otros-elementos"){
		desplegar_menu(split_categoria_1[1],"FALSO","FALSO");
		}else{
		t4(split_categoria_1[1]);
		}
	}
	llamar_ajax(historial[cursor+1],'der',true);
	cursor++;
}

function form_contacto(){
var cadena_captcha = document.f1.tmptxt.value;
//alert(ruta+"captcha.php?cadena="+cadena_captcha);
	if(document.f1.subject.value.length == 0 || document.f1.email.value.length == 0 || document.f1.message.value.length == 0){
	//alert("Se ha dejado algún campo obligatorio por rellenar, los campos obligatorios están marcados por *");
	document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#FF0000'> Se ha dejado algún campo obligatorio por rellenar, los campos obligatorios estan marcados con * </font>";
	}else{
		if(document.f1.message.value.length < 25){
		//alert("El contenido del mensaje debe contener 25 carácteres como mínimo");
		document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#FF0000'> El contenido del mensaje debe contener 25 carácteres como mínimo </font>";
		}else{
			if(document.f1.message.value.length > 500){
			//alert("El contenido del mensaje debe contener 500 carácteres como máximo");
			document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#FF0000'> El contenido del mensaje debe contener 500 carácteres como máximo </font>";
			}else{
			respuesta = comprobar_email(document.f1.email.value);
				if(respuesta == false){
				//alert("El email que propuso no tiene un formato válido, ej: empresa@empresa.com");
				document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#FF0000'> El email que propuso no tiene un formato válido, ej: empresa@empresa.com </font>";
				}else{
				
					if(document.f1.condiciones.checked == false){
					document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#FF0000'> No ha aceptado las condiciones de uso del formulario </font>";
					}else{
				
						if(document.f1.excel.value.length>0){
							length_excel = document.f1.excel.value.length;
							extension_excel = document.f1.excel.value.substring(length_excel-4,length_excel);
							//COMPRABANDO SI LA EXTENSION ES EXCEL del 2007
							if(extension_excel == 'xlsx'){
							tipo=1;
							llamar_ajax_captcha(ruta+"captcha.php?cadena="+document.f1.tmptxt.value);
							// HERE!!! NO PERDER
							}else{
								////COMPRABANDO SI LA EXTENSION ES EXCEL ANTES DEL 2007
								if(extension_excel.substring(1,4) == 'xls'){
								tipo=1;
								llamar_ajax_captcha(ruta+"captcha.php?cadena="+cadena_captcha);
								}else{
								document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <font color='#FF0000'> Usted ha adjuntado un archivo diferente a una hoja de excel ("+extension_excel.substring(1,4)+"), por favor, inténtelo de nuevo </font>";
								}
							}
							
							
							//document.f1.submit();
							//document.getElementById("estado").innerHTML = "<b>&raquo; Estado del formulario:</b> <img src='"+ruta+"imagenes/cargador.gif'><font color='#0000FF'>  Adjuntando archivo y enviando mensaje, por favor espere unos instantes (el tiempo dependerá de su conexión) ...</font>";
					
					
					}else{
					tipo=0;
					llamar_ajax_captcha(ruta+"captcha.php?cadena="+document.f1.tmptxt.value);
					}
				}
				//alert("TODO OK!!");
				}
			}
		}
		
			
	}
//document.f1.submit()
}

//GALERIA DE LA PORTADA



var imagen=1;

function change(direccion,total_imagenes) {
//alert(total_imagenes);

//var imagen = aleatorio(1,total_imagenes);

//alert(imagen);
	if(direccion == "+"){
		if(imagen == total_imagenes)
		imagen = 1;
		else
		imagen++;
	}else{
		if(imagen == 1)
		imagen = total_imagenes;
		else
		imagen = imagen -1;
	}
	//numero = aleatorio(1,7);
	//alert(numero);
	//imagen = numero;

  document.getElementById("r2").style.backgroundImage = "url("+ruta+"fotos/portada/"+(imagen)+".jpg)";
  transparency=0;


}

//a=0;
function efecto(){  
	
	// MIRAMOS SI TERMINO EL PERIODO, TRUE = DEJA DE CONTAR, FALSE = aumenta la transparencia en 10
	if(transparency == 100){
	//a=1;
	clearInterval(time);
	document.getElementById("+").disabled = false;
	document.getElementById("-").disabled = false;
	//alert("FUERA INTERVALO");
	//transparency = (transparency == 100) ? clearInterval(time) : transparency;
	}else{
	transparency = transparency + 10;
	document.getElementById("+").disabled = true;
	document.getElementById("-").disabled = true;
	//setTimeOut('alert("yea")',550-(a*50));
	//alert(a);
	
	//COGEMOS EL ELEMENTO
	obj = document.getElementById('r2');
  
		// Asigna transparencia al elemento para IE y CIA.
		if (document.all){ 
    	//esto es para IE, como siempre hay q programarlo a parte
   		obj.style.filter = 'alpha(opacity='+transparency+')';
	
  		}else{
    	// Safari 1.2, posterior Firefox y Mozilla, CSS3
    	obj.style.opacity = transparency /100;
	
    
   		// anteriores Mozilla y Firefox
    	obj.style.MozOpacity = transparency /100;
	
    
   		// Safari anterior a 1.2, Konqueror
    	obj.style.KHTMLOpacity = transparency /100;  
	
		} 
	}
	

}


var i;
var imagenes = new Array(ruta+"fotos/portada/1.jpg",ruta+"fotos/portada/2.jpg",ruta+"fotos/portada/3.jpg",ruta+"fotos/portada/4.jpg",ruta+"fotos/portada/5.jpg",ruta+"fotos/portada/6.jpg",ruta+"fotos/portada/7.jpg",ruta+"fotos/portada/8.jpg",ruta+"fotos/portada/9.jpg",ruta+"fotos/portada/10.jpg",ruta+"fotos/portada/11.jpg",ruta+"fotos/portada/12.jpg",ruta+"fotos/portada/13.jpg");
var lista_imagenes = new Array(); 
function cargarimagenes(){

	for(i in imagenes){
	lista_imagenes[i] = new Image();
	lista_imagenes[i].src = imagenes[i];

	
	}

} 

function contar() {
  //alert("trala");
  time = setInterval('efecto()',50);
}

function pasar(total_imagenes){
time2 = setInterval('change("+",'+total_imagenes+');contar();efecto();',5000);
}


function aleatorio(a,b){
return Math.round(Math.random()*(b-a)+a);
} 

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

var inicial = "";
function t4(categoria){

	if(inicial == ""){
	document.getElementById("p-"+categoria).innerHTML = "&#8226; ";
	}else{

		if(categoria != inicial){
		document.getElementById("p-"+categoria).innerHTML = "&#8226; ";
		document.getElementById("p-"+inicial).innerHTML = "";
		}
	}
	
	inicial = categoria;
}

/*var u=0;
var numelementos = 10;
var historial = new Array(numelementos);
var historialnombre = new Array(numelementos);
var historialarriba = new Array(numelementos);
var historialencima = new Array(numelementos);
var marcar_atras;
var nombre_atras;
var hist_arriba;
function memoria(archivo,nombre,arriba,encima){

	// ESTE ES EL CASO EN EL QUE EL CLIENTE HAGA MAS DE 10 ACCIONES, LA ULTIMA ENTRA Y LA PRIMERA SALE
	if(u == numelementos){	
		for(k=0;k<=numelementos-1;k++){
			if(k!=0){
			historial[k-1] = historial[k];
			historialnombre[k-1] = historialnombre[k];
			historialarriba[k-1] = historialarriba[k];
			historialencima[k-1] = historialencima[k];
			}
		}
	historial[u-1] = archivo;
	historialnombre[u-1] = nombre;
	historialarriba[u-1] = arriba;
	historialencima[u-1] = encima;
	// SI NO LLEVA 10 ACCIONES VAMOS AÑADIENDO	
	}else{
		if(historial[u-1] != archivo){
		historial[u] = archivo;
		historialnombre[u] = nombre;
		historialarriba[u] = arriba;
		historialencima[u] = encima;

		u++;
		}
	}

}*/

/*function atras(){

	if(u == 1){
	document.getElementById("back").innerHTML = '<img src="'+ruta+'imagenes/atras-disabled.png" border="0" align="absmiddle" />Volver';
	}else{
	marcar_atras = historial[u-2];
	nombre_atras = historialnombre[u-2];
	arriba_atras = historialarriba[u-2];
	encima_atras = historialencima[u-2];
	
	// MARCAR AL KE SE VA
	t4(marcar_atras,nombre_atras);
	
	if(historialarriba[u-2] == 'TRUE')
	desplegar_menu(historialencima[u-2]);
	
	//alert(historialarriba[u-1]);
	
		//alert(historialarriba[u-2]);
	//if(historialarriba[u-1] != 0){
	//	if(hist_arriba != historialarriba[u-1])
		//desplegar_menu(hist_arriba);
		//alert(hist_arriba);}
	//}
	
	// MOSTRAMOS AJAX
	llamar_ajax(ruta+'ajax.php?categoria='+historial[u-2],'der');
	u=u-1;
	}
	
			
}*/
function getCookie(name){
  var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
    if (begin != -1) {           
      begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}

function parartimes(url){
	if(url == ruta || url == ruta+'#'){
	clearInterval(time2);
	}
}