// JavaScript Document
var AltoPantalla = screen.Height / 2;
var AnchoPantalla = screen.Width / 2;

function cargaPagina(url,div,parametros)
{
	//alert(url  + ' -- ' + div + ' -- ' + parametros)
	new Ajax(url,{method: 'post', postBody:parametros, update:div}).request();
	//if(url != "login2.php" && url != "situacion.php")
		//setTimeout("cargaPagina('login2.php', 'div_caja_login', 'a=0');", 700);
		//cargaPagina('login2.php', 'div_caja_login', 'a=0');
}
function mail_valido(cadena)
{
	var b=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;	
	if (!b.test(cadena))
		return false;
	return true;
}
function AbrePopup(Ruta, Nombre, Ancho, Alto) {
	var AltoMostrar = AltoPantalla - (Alto / 2);
	var AnchoMostrar = AnchoPantalla - (Ancho / 2);	
	var PopUpW = window.open(Ruta, Nombre, "width=" + Ancho + ", height=" + Alto + ", top=" + AltoMostrar + ", left=" + AnchoMostrar + ", scrollbars=no, titlebar=no, menubar=no, directories=no, status=no, location=no");
	PopUpW.focus();
	return false;
}
function AbrePopupConScroll(Ruta, Nombre, Ancho, Alto) {
	var AltoMostrar = AltoPantalla - (Alto / 2);
	var AnchoMostrar = AnchoPantalla - (Ancho / 2);	
	var PopUpW = window.open(Ruta, Nombre, "width=" + Ancho + ", height=" + Alto + ", top=" + AltoMostrar + ", left=" + AnchoMostrar + ", scrollbars=yes, titlebar=no, menubar=no, directories=no, status=no, location=no");
	PopUpW.focus();
	return false;
}
function telefono_valido(numero)
{
	var tfno= parseInt(numero);
	var error = "";
	if ( isNaN(tfno) )
	{	
		alert("El teléfono introducido no es válido");
		error="q";
	}
	else
	{
		if ( !( (tfno >= 900000000) && (tfno < 1000000000) || (tfno >= 600000000) && (tfno < 700000000) ) )  
		{	
			alert("El teléfono introducido no es válido");
			error="q";
		}
	}
	if(error == "")
		return true;
	return false;

}
var antSub = 0;
var antSub2 = 0;
var antFam = 0;

function abreSubMenu(codigo)
{
	var i;
	var total = $('totalSubMenu').value;
	if (codigo != antSub)
	{
		for (i=1; i<= total; i++)
		{
			if($("sub_" + codigo + "_" + i))
			{
				$("sub_" + codigo + "_" + i).style.display = "inline";
				$("mas_" + codigo).src = "imagenes/ico-menos.gif";
			}
			
			if (antSub != 0 && $("sub_" + antSub + "_" + i))
			{
				$("sub_" + antSub + "_" + i).style.display = "none";
				$("mas_" + antSub).src = "imagenes/ico-mas.gif";
				
				abreFamilia(antSub, i, 1, 0);
			}
		}
		antSub = codigo;
	}
	else
	{
		for (i=1; i<=total; i++)
		{
			if($("sub_" + codigo + "_" + i))
			{
				$("sub_" + codigo + "_" + i).style.display = "none";
				$("mas_" + codigo).src = "imagenes/ico-mas.gif";
				abreFamilia(codigo, i, 1, 0);
			}
		}
		antSub = 0;
	}
}

function abreFamilia(cat, codigo, tipo, familia)
{	
	var i;
	var total = $('totalFamilia').value;
	if (codigo != antFam && tipo != 1)
	{
		for (i=1; i<=total; i++)
		{
			if($("fam_" + cat + "_" + codigo + "_" + i))			
			{
				$("fam_" + cat + "_" + codigo + "_" + i).style.display = "inline";
				if($("flecha_" + codigo)) $("flecha_" + codigo).innerHTML = " &#9660; ";
			}
			else if (antFam != 0 && $("fam_" + cat + "_" + antFam + "_" + i))
			{
				$("fam_" + cat + "_" + antFam + "_" + i).style.display = "none";
				if($("flecha_" + antFam)) $("flecha_" + antFam).innerHTML = " &#9658; ";
			}
		}
		antFam = codigo;
		antSub2 = antSub;
	}
	else
	{
		for (i=1; i<=total; i++)
		{
			if($("fam_" + cat + "_" + codigo + "_" + i))			
			{
				$("fam_" + cat + "_" + codigo + "_" + i).style.display = "none";
				if($("flecha_" + codigo))
					$("flecha_" + codigo).innerHTML = " &#9658; ";
			}
		}
		antFam = 0;
	}
}

function ActualizaSituacion(cat, subcat, fam)
{
	/*var texto = "";
	texto = texto + 'categoria=' + cat;
	if(typeof(subcat) != "undefined")
		texto = texto + '&subcategoria=' + subcat;
	if(typeof(fam) != "undefined")
		texto = texto + '&familia=' + fam;
	cargaPagina('situacion.php','div_situacion', texto);*/
}

function ajustaDiv()
{
	/*//$('div_central').style.height = "auto";
	$('div_menu').style.height = "auto";
	if($('div_menu').offsetHeight < 218)
		$('div_menu').style.height = "218px";
	if($('div_interior').offsetHeight > ($('div_menu').offsetHeight) )
		$('div_menu').style.height = $('div_interior').offsetHeight;
	else
		$('div_menu').style.height = "218px";*/
}

function logado()
{
	if ($('usuario').value == "" || $('passw').value == "")
	{
		$('logadomsg').effect('opacity').custom(1,0);
		
		msg = "<div id='div_login'>";
		msg += "<div id='div_login_titulo'>Alerta</div>";
		msg += "<div id='div_login_usuario' style='width: 245px;'>Por favor tiene que rellanar los campos<br />de Usuario y Pass para poder logarse.</div>";
		msg += "<div id='div_login_entrada' style='width: 245px; cursor: pointer;''><img id='div_bot_aceptar' src='imagenes/bot_aceptar.png' border='0' onmouseover='this.src=\"imagenes/bot_aceptar_over.png\";' onmouseout='this.src=\"imagenes/bot_aceptar.png\";' style='cursor: pointer;' onclick='aceptar();' /></div>";
		msg += "</div>";
		
		var he = window.getScrollTop() + (window.getHeight()/2) - 88, we = window.getScrollLeft() + (window.getWidth()/2) - 162;
		
		$('logadoAlerta').setStyles({'top':he - 15+'px','left':we + 25+'px','display':'block'}).setHTML(msg);
		$('logadoAlerta').effect('opacity').custom(0,1);
	}
	else
	{
		var usuario = $('usuario').value;
		var pass = $('passw').value;
		$('div_login').setHTML("");
		cargaPagina("http://www.cyrtek.es/login.php","div_login","usuario=" + usuario + "&pass=" + pass + "")
	}
}

function aceptar()
{
	$('logadoAlerta').effect('opacity').custom(1,0);			
	$('logadomsg').effect('opacity').custom(0,1);
}
function muestraDetalle()
{
	$('div_detalle_producto').style.display='inline';
	$('imagen_categoria').style.display='none';
	/*if ( navigator.appName == 'Netscape')
		$('div_detalle_producto').style.display='table'; 
	else 
		$('div_detalle_producto').style.display='block';*/
}
function ilumina(n)
{
	var total = $('total').value;
	$('seleccionado').value = n;
	for (i=1;i<=total;i++)
	{
		if(i==n)
			$('producto_'+i).className='listado_productos_fila_on';
		else
			$('producto_'+i).className='listado_productos_fila';
	}
}
function login2()
{
	if($('nombre').value == "" || $('pass').value == "" || $('nombre').value == "Usuario" || $('pass').value == "*******")
		alert('Rellene todos los campos');
	else
		cargaPagina('login2.php', 'cabecera_izquierda', 'n=' + $('nombre').value + '&p=' + $('pass').value );
}
function registro()
{
	var error = "";
	if($('nom').value == "" || $('ape').value == "" || $('mail').value == "" || $('cont').value == "" || $('cont2').value == "" )
	{
		//alert($('nom').value + " -" + $('ape').value + " -" + $('mail').valu + " -" + $('cont').value + " -" + $('cont2').value)
		alert("Rellene los campos marcados con (*)");
		error = "a";
	}
	else
	{
		if (!mail_valido( $('mail').value ) )
		{
			alert("El formato del correo electrónico no es válido");
			error = "a";
		}
		if($('tlf').value != "" && !telefono_valido( $('tlf').value ) )
			error = "a";
		if($('cont').value != $('cont2').value )
		{
			alert("Las contraseñas no coinciden");
			error = "a";
		}
		if($('cont').value.length < 6)
		{
			alert("La contraseña debe tener al menos 6 caracteres");
			error = "a";
		}
	}
	if(error == "")
		cargaPagina('registro.php', 'registromsg', 'nom=' + $('nom').value + '&ape=' + $('ape').value + '&mail=' + $('mail').value + '&cont=' + $('cont').value + '&tlf=' + $('tlf').value + '&des=' + $('des').value);
}
var IE = document.all?true:false;
/*if (!IE) document.captureEvents(Event.MOUSEMOVE)
	document.onmousemove = getMouseXY;*/
var tempX = 0;
var tempY = 0;
var ancho = 0;
function getMouseXY(e) 
{
	if (IE) 
	{ // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.documentElement.scrollLeft + 10; //document.body.scrollLeft
		tempY = event.clientY + document.documentElement.scrollTop + 18;
		altura = document.body.clientHeight;
		anchura = document.body.clientWidth;
	}
	else 
	{  // grab the x-y pos.s if browser is NS
		tempX = parseInt(e.pageX + 10) + "px";
		tempY = parseInt(e.pageY + 18) + "px";
		altura = window.innerHeight;
		anchura = window.innerWidth;
	}  
	if (tempX < 0) tempX = 0;
	if (tempY < 0) tempY = 0;	
	if( document.getElementById('div_descripcion').offsetHeight + parseInt(tempY) + 20 > altura )
	{
		document.getElementById('div_descripcion').style.top = (parseInt(parseInt(tempY) - document.getElementById('div_descripcion').offsetHeight)-18)+ "px";
		if (parseInt(document.getElementById('div_descripcion').style.top) < 0 )
		{
			document.getElementById('div_descripcion').style.top = 10 + "px";
		}
	}
	else 
	{
		document.getElementById('div_descripcion').style.top=tempY;
	}
	document.getElementById('div_descripcion').style.left=tempX;
	
	return true;
}

function mueve(cod)
{
	if (!IE) document.captureEvents(Event.MOUSEMOVE);
		document.onmousemove = getMouseXY;
	document.getElementById('div_descripcion').innerHTML = "<div style='padding:5px;'>" + $('descripcion_'+cod).value + "</div>";
	document.getElementById('div_descripcion').style.display = "block";
	document.getElementById('div_descripcion').style.visibility = "visible";
}
function oculta()
{	
	document.onmousemove = "";
	document.getElementById('div_descripcion').style.display = "none";
	document.getElementById('div_descripcion').style.visibility = "hidden";
	document.getElementById('div_descripcion').style.top = "-1000px";	
	document.getElementById('div_descripcion').style.left = "-1000px";
}
function EnviaConsulta()
{
	var error="";
	if( $('f_nom').value=="" || $('f_mail').value=="" || $('f_duda').value=="" )
	{
		alert('Rellene todos los campos')
		error = "a";
	}
	else
		if(!mail_valido($('f_mail').value))
		{
			error="a";
			alert('Formato de mail no válido');
		}
	if(error=="")
		document.consulta.submit();
}
function MuestraDuda(n)
{
	var ver;
	if ( navigator.appName == 'Netscape')
		ver ='table'; 
	else 
		ver='block';
	for(i=1;i<=$('total').value;i++)
	{
		if(i==n && $('solucion_'+i).style.display == "none")
			$('solucion_'+i).style.display = ver;
		else
			$('solucion_'+i).style.display = "none";
	}		
}
function MuestraNormativa(n)
{
	var ver;
	if ( navigator.appName == 'Netscape')
		ver ='table'; 
	else 
		ver='block';
	for(i=1;i<=$('total').value;i++)
	{
		if(i==n && $('desc_'+i).style.display == "none")
			$('desc_'+i).style.display = ver;
		else
			$('desc_'+i).style.display = "none";
	}		
}
function cargaMapa() {
	if (GBrowserIsCompatible()) {
	  var map = new GMap2(document.getElementById("map"));
	var geocoder = new GClientGeocoder();
	var address = $('direccion').value;
	var texto = $('nombre_a_mostrar').value
	var LatLng = new GLatLng(geocoder.getLatLng(
		address,
		function(point) {
		  if (!point) {
			alert(address + " not found");
		  } else {
			map.setCenter(point, 15);
			var blueIcon = new GIcon(G_DEFAULT_ICON);
			blueIcon.image = "http://new.komtesproteccion.com/imagenes/icono_mapa_google_komtes.png";
			markerOptions = { icon:blueIcon }
			var marker = new GMarker(point, markerOptions);
			map.addOverlay(marker);
			//marker.openInfoWindowHtml(address);
			//var myHtml = "<center><font style='font-size: 14px;'>" + texto + "</font></center>";
			//map.openInfoWindowHtml(point, myHtml);
		  }
		}
	  )
	);
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	//map.setCenter(LatLng);
	}
 }
	
function escribeflash(url,anchoswf,altoswf){
document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="https://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+anchoswf+'" height="'+altoswf+'"  align="middle">');
document.write('<param name="allowScriptAccess" value="sameDomain" />');
document.write('<param name="movie" value="'+url+'" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><embed wmode="transparent" src="'+url+'" quality="high" width="'+anchoswf+'" height="'+altoswf+'"  align="middle"  type="application/x-shockwave-flash" pluginspage="https://www.macromedia.com/go/getflashplayer" />');
document.write('</object>');}

function verAdjunto(codigo)
{
	for(i = 0; i <= $('totalADJ').value; i++)
	{
		if(i == codigo)
			$('adj_' + i).setStyle('display', 'inline');
		else
			$('adj_' + i).setStyle('display', 'none');
	}
}
function cargaDelegacion(tipo)
{
	var valor = 0;
	
	if(tipo == 1 )
		valor = $('companias').value;
	if(tipo == 2 )
		valor = $('delegaciones').value;
	if(tipo == 3 )
		valor = $('internacional').value;
		
		
	
	if(valor != '')
	{
		cargaPagina('Carga_mapa.php', 'div_datos_empresa', 'cod=' + valor);
		
		if(tipo != 1 )
			$('companias').selectedIndex = 0;
		if(tipo != 2 )
			$('delegaciones').selectedIndex = 0;
		if(tipo != 3 )
			$('internacional').selectedIndex = 0;
	}	
}

function Comprobar()
{
	var error = "";
	
	if($('txtnombre').value=="" && error == "")
	{
		error = "Es obligatorio poner el nombre.";
		$('txtnombre').focus();
	}
	if($('txtproducto').value=="" && error == "")
	{
		error = "Es obligatorio seleccionar un producto.";
		$('txtproducto').focus();
	}	
	if(($('txtmail').value == "" || !validaMail($('txtmail').value)) && error == "")
	{
		error = "El e-mail de respuesta no es valido.";
		$('txtmail').focus();
	}
	if($('txtconsulta').value=="" && error == "")
	{
		error = "Es obligatorio escribir la consulta.";
		$('txtconsulta').focus();
	}
	if(!document.form1.acepto.checked && error == '')
	{
		error = "Debe aceptar la política de privacidad y el aviso legal.";
		document.form1.acepto.focus();
	}
	if(error != "")
		alert(error);
	else
		document.form1.submit();
}

function validaMail(txtmail)
{
    var mailres = true;            
    var cadena = "abcdefghijklmnnopqrstuvwxyzABCDEFGHIJKLMNNOPQRSTUVWXYZ1234567890@._-";
	var arroba = txtmail.indexOf("@",0);
	var contador = 0;

    if ((txtmail.lastIndexOf("@")) != arroba) arroba = -1;

    var punto = txtmail.lastIndexOf(".");

     for (contador = 0 ; contador < txtmail.length ; contador++)
	 {
        if (cadena.indexOf(txtmail.substr(contador, 1),0) == -1)
		{
            mailres = false;
            break;
    	}
    }

    if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (txtmail.length)) && (mailres == true) && (txtmail.indexOf("..",0) == -1))
    	mailres = true;
    else
    	mailres = false;

	return mailres;
}

function cam(id, imagen) {
	$(id).src = 'imagenes'+imagen;
}



