var ScrollActivo = false;
var loop = false;
var bola;
var contenedor;
var texto;
var DistanciaScroll,CantidadScroll;
var IEY,AntY,RatonPulsado=false;
var sDominioSOAP = "dyn.prevenrisk.es"; // dominio donde está alojado el CGI
var sPrefURL = "http://www.prevenrisk.es/";
function GetEvento(){
	var evento = event;
	if (!evento)
		evento = top.event;
	return evento;
}
function SubeScroll (velocidad) {
//	if (contenedor.Document.style.posTop < 0) {
		contextos.scrollBy(0, - velocidad);
		bola.style.posTop = PosBola();
		if (loop) setTimeout ("SubeScroll(" + velocidad + ")",0);
//	}
}
function BajaScroll (velocidad) {
//	if (texto.style.posTop > - CantidadScroll) {
		contextos.scrollBy(0, velocidad);
		bola.style.posTop = PosBola();
		if (loop) setTimeout ("BajaScroll(" + velocidad + ")",0);
//	}
}
function HazScroll (velocidad) {
	var evento = GetEvento();
	if (evento.button==1) {
		loop=true;
		if (velocidad > 0) {
			BajaScroll (velocidad) }
		else {
			SubeScroll (velocidad * -1) }
	}
}
function ParaScroll () {
	loop = false;
}


function InicioArrastre () {
	var evento = GetEvento();
	if (evento.button==1) {
		AntY = bola.style.pixelTop;
		IEY=evento.clientY;
		RatonPulsado = true;
		top.document.onmousemove=Arrastrar;
		return false;
	}
}
function FinArrastre () {
	var evento = GetEvento();
	if (evento.button==1) {
		RatonPulsado=false;
		return false;
	}
}

function Arrastrar () {
	var nuevaPos;
	if (RatonPulsado) {
		nuevaPos = AntY + top.event.clientY - IEY;
		if (nuevaPos < 0) {
			nuevaPos = 0; }
		else {
			if (nuevaPos > DistanciaScroll) {
				nuevaPos = DistanciaScroll;}
		}
		bola.style.posTop = nuevaPos;
//		contenedor.Document.scrollTop = Math.ceil((nuevaPos * CantidadScroll) / DistanciaScroll);
		contextos.scroll(0,Math.ceil((nuevaPos * CantidadScroll) / DistanciaScroll));
		return false;
	}
}
function PosBola (){
	var nuevaPos = (contenedor.scrollTop * DistanciaScroll) / CantidadScroll;
	if (nuevaPos > DistanciaScroll)
		nuevaPos = DistanciaScroll;
	return nuevaPos;
}

function CalculaValores(){
//	DistanciaScroll = contenedor.offsetHeight - bola.offsetHeight;
	DistanciaScroll = top.document.getElementById("contbola").offsetHeight - bola.offsetHeight;
	CantidadScroll = (texto.offsetHeight - contenedor.offsetHeight) + (contenedor.offsetWidth - texto.offsetWidth);
	if (top.navigator.userAgent.indexOf("Opera") > -1) {
		contenedor.style.overflow = "auto";
		bola.style.visibility = "hidden";
	} else {
		contenedor.style.overflow = "hidden";
		if (texto.offsetHeight + (contenedor.offsetWidth - texto.offsetWidth) > contenedor.offsetHeight) {
			bola.style.visibility = "visible";
			bola.style.posTop = PosBola();
		} else {
			bola.style.visibility = "hidden";}
		top.document.getElementById ("f_arriba").style.visibility = bola.style.visibility;
		top.document.getElementById ("f_abajo").style.visibility = bola.style.visibility;
	}
}

function Iniciar(){
	top.document.onmouseup=FinArrastre;
	document.onmouseup=FinArrastre;
	contenedor = top.document.getElementById ("contextos");
	texto = contenedor.Document.getElementById ("texto");
	bola = top.document.getElementById ("bolascroll");
	if (navigator.userAgent.indexOf("Opera") == -1) {
		contenedor.style.overflow = "auto";
		contenedor.style.height = "100%";
	}
	CalculaValores();
}
function Plegar(nombre){
	document.getElementById ("texto_" + nombre).style.height = "0px";
	document.getElementById ("im_" + nombre).src = "../imag/imagenes/f_derecha.gif";
}

function Plegar_Todo(){
	Plegar ("servicios");
	Plegar ("actuaciones");
	Plegar ("modalidades");
	Plegar ("aplicacion");
}

function Desplegar (nombre,alto){
	if (document.getElementById ("texto_" + nombre).style.height == "0px") {
		Plegar_Todo();
		document.getElementById ("texto_" + nombre).style.height = alto + "px";
		document.getElementById ("im_" + nombre).src = "../imag/imagenes/f_abajo.gif";
	} else {
		Plegar (nombre);
	}
}
function CompruebaCampo(campo,longitud,nomcampo,longmax){
	if (campo.value == "" && longitud > 0) {
		alert ("El campo " + nomcampo + " es obligatorio");
		return false; }
	else {
		if (campo.value.length < longitud) {
			alert ("La longitud del campo " + nomcampo + " debe ser de un mínimo de " + longitud);
			return false;
		} else if (longmax > 0 && campo.value.length > longmax) {
			alert ("La longitud del campo " + nomcampo + " no debe exceder de " + longmax);
			return false;
		}
		else
			return true;
	}
}

function CompruebaFormulario(form){
	var retorna = true;
	if (!CompruebaCampo (form.edEmpresa,5,"Empresa"))
		retorna = false;
	if (!CompruebaCampo (form.edContacto,5,"Persona de Contacto"))
		retorna = false;
	if (!CompruebaCampo (form.edTelefono,9,"Teléfono"))
		retorna = false;
	return retorna;
}


function LetraNIF (nif) {
   var cadena = "TRWAGMYFPDXBNJZSQVHLCKET";
   var posicion = nif % 23;
   return cadena.charAt(posicion);
}

function ValidaCIFNIF (ncifnif) {
   var dignif1 = ncifnif.substring (0,1);
   var dignif9 = ncifnif.substring (8,9);
   var letra;
   if (/^[0-9X]/.test(ncifnif)) {
      if (dignif1 == "X"){
         letra = LetraNIF ("0" + ncifnif.substring (1,8));
         if (dignif9 == letra)
             return true;
         else
             return false;
      } else {
         letra = LetraNIF (ncifnif.substring (0,8));
         if (dignif9 == letra)
             return true;
         else
             return false;
      }
   } else {
      if (!/^[ABCDEFGHKLMNPQS]/.test(dignif1)) {
         return false;
      } else {
        var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
        var temp = 0;
        var temp1;
        for( i = 2; i <= 6; i += 2 ) {
           temp = temp + v1[ parseInt(ncifnif.substr(i-1,1)) ];
           temp = temp + parseInt(ncifnif.substr(i,1));}
        temp = temp + v1[ parseInt(ncifnif.substr(7,1)) ];
        temp = (10 - ( temp % 10));
        if( temp == 10 ) {
           if (dignif9 == "J" || dignif9 == "0")
              return true;
           else
              return false;
        } else {
           if (dignif9 == temp)
              return true;
           else
              return false;
        }
      }
   }
}
function CompruebaFormAttCliente(form){
	var retorna = true;
	form.edDocumento.value = form.edDocumento.value.toUpperCase();
    if (form.edTipoDoc.value == "CIF" || form.edTipoDoc.value == "NIF" || form.edTipoDoc.value == "NIE") {
		if (form.edDocumento.value.length != 9) {
			alert ("La longitud del campo Documento debe ser de 9 caracteres. Recuerde que no debe escribir signos de puntuación");
			retorna = false;
		}
		else {
			if (!ValidaCIFNIF (form.edDocumento.value)) {
				alert ("El número de documento introducido no es correcto");
				retorna = false;
			}
		}
	} else {
		if (!CompruebaCampo (form.edDocumento,9,"Documento",20))
			retorna = false;
	}
	if (!CompruebaCampo (form.edRazonSocial,0,"Razón Social",100))
		retorna = false;
	if (!CompruebaCampo (form.edContacto,5,"Persona de Contacto",100))
		retorna = false;
	if (!CompruebaCampo (form.edemail,0,"E-mail",50))
		retorna = false;
	if (!CompruebaCampo (form.edtelefono,0,"Teléfono",15))
		retorna = false;
	if (!CompruebaCampo (form.edObserva,1,"Texto explicativo",4000))
		retorna = false;
	if (!CompruebaCampo (form.edProvincia,1,"Provincia"))
	    retorna = false;
	return retorna;
}

function postData(Url, Data, Action) {
	var oHttpReq = new ActiveXObject("Msxml2.XMLHTTP.4.0");
  	oHttpReq.open("POST", Url, false);
  	oHttpReq.setRequestHeader("Man", "POST" + Url + "HTTP/1.1");
    oHttpReq.setRequestHeader("MessageType", "CALL");
    oHttpReq.setRequestHeader("Content-Type", "text/xml");
    oHttpReq.setRequestHeader("SOAPACtion", Action);
    oHttpReq.send(Data);
	return oHttpReq;
}


function SendMail(From, To, Asunto, Mensaje) {
	var sUrl = "http://dyn.prevenrisk.es/email/pServerEmail.dll/soap/IEMailService";

	var sData =
			'<?xml version="1.0"?>' +
			'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" '+
			'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '+
			'xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> '+
			'<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+
			'<NS1:SendMail xmlns:NS1="urn:EmailServiceIntf-IEmailService">' +
			'<ToAddress xsi:type="xsd:string">' + To + '</ToAddress>' +
			'<FromAddress xsi:type="xsd:string">' + From + '</FromAddress>' +
			'<ASubject xsi:type="xsd:string">' + Asunto + '</ASubject>'+
			'<MsgBody xsi:type="xsd:string">' + Mensaje + '</MsgBody></NS1:SendMail></SOAP-ENV:Body></SOAP-ENV:Envelope>';
			
	var oResponse = postData(sUrl, sData, "urn:EmailServiceIntf-IEmailService#SendMail");
	if (oResponse.status == 200)
	  	{	
			//alert (oResponse.responseText);
			posicion = oResponse.responseText.indexOf("</return>");
			if (oResponse.responseText.charAt(posicion-1) == "0")
				return true; 
			else
				return false;
    	}
	else 
    	return false;
	oHttpReq = null;
}

function Enviar2(){
   var form = document.getElementById("formulario");
   if (CompruebaFormAttCliente(form)) {
      var From = "Presupuestos@WebPrevenRisk";
      var To = "atencion.cliente@prevenrisk.es";
      var Asunto = "Información solicitada por : " + form.edContacto.value;
		var Mensaje = "- Tipo de documento : "+ form.edTipoDoc.value + "\n" + 
                              "- Documento "  + form.edDocumento.value + "\n" + 
                              "- Razón Social : " + form.edRazonSocial.value + "\n" + 
                              "- Persona de Contacto : " +  form.edContacto.value + "\n" + 
                              "- E-mail : " + form.edemail.value + "\n" + 
                              "- Teléfono : " + form.edtelefono.value + "\n" + 
                              "- Texto explicativo : " + form.edObserva.value + "\n" +  
                              "- Provincia : " + form.edProvincia.value;


					  
		var oForm = document.getElementById ("myForm");
	 	if ( oForm ) {
			oForm.removeNode (true);
		}
		var oForm = document.createElement ('form');
		with (oForm) {
			setAttribute("method", "POST");
			setAttribute("action", "http://" + sDominioSOAP + "/callsoap/callsoap.exe/sendmail");
		}
		var vHidden;
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "a");
			setAttribute ("type", "hidden");
			setAttribute ("value", To);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "de");
			setAttribute ("type", "hidden");
			setAttribute ("value", From);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("type", "hidden");
			setAttribute ("name", "tema");
			setAttribute ("value", Asunto);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "texto");
			setAttribute ("type", "hidden");
			setAttribute ("value", Mensaje);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "webok");
			setAttribute ("type", "hidden");
			setAttribute ("value",sPrefURL + "es/correcto.html");
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "weberror");
			setAttribute ("type", "hidden");
			setAttribute ("value",sPrefURL + "es/incorrecto.html");
		}
		oForm.appendChild(vHidden);
		document.body.appendChild(oForm);
		oForm.submit();

   }
}
function Enviar (){
	var form = document.getElementById("formulario");
	if (CompruebaFormulario(form)) {
		var vigilancia = (form.edVigilancia.checked) ? "SI" : "NO";
		var asistencia = (form.edAsistencia.value) ? "SI" : "NO";
		var From = "Presupuestos@WebPrevenRisk";
		var To = "atencion.cliente@prevenrisk.es";
		var Asunto = 'Presupuesto solicitado por la empresa ' + form.edEmpresa.value;
		var Mensaje = "- Razón Social : " + form.edEmpresa.value + "\n" +
					  "- Actividad : " + form.edActividad.value + "\n" +
					  "- Persona de Contacto : " + form.edContacto.value + "\n" +
					  "- Cargo que Ocupa : " + form.edCargo.value + "\n" +
					  "- Dirección : " + form.edDireccion.value + "\n" +
					  "- Código Postal : " + form.edCP.value + "\n" +
					  "- Población : " + form.edPoblacion.value + "\n" +
					  "- Provincia : " + form.edProvincia.value + "\n" +
					  "- Teléfono : " + form.edTelefono.value + "\n" +
					  "- Fax : " + form.edFax.value + "\n" +
					  "- E-mail : " + form.edEmail.value + "\n" +
					  "- Nº de Trabajadores : " + form.edTrabajadores.value + "\n" +
					  "- Vigilancia de la Salud : " + vigilancia + "\n" +
					  "- Asistencia Técnica : " + asistencia + "\n" +
					  "- Observaciones : " + form.edObservaciones.value;

		var oForm = document.getElementById ("myForm");
	 	if ( oForm ) {
			oForm.removeNode (true);
		}
		var oForm = document.createElement ('form');
		with (oForm) {
			setAttribute("method", "POST");
			setAttribute("action", "http://" + sDominioSOAP + "/callsoap/callsoap.exe/sendmail");
		}
		var vHidden;
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "a");
			setAttribute ("type", "hidden");
			setAttribute ("value", To);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "de");
			setAttribute ("type", "hidden");
			setAttribute ("value", From);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("type", "hidden");
			setAttribute ("name", "tema");
			setAttribute ("value", Asunto);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "texto");
			setAttribute ("type", "hidden");
			setAttribute ("value", Mensaje);
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "webok");
			setAttribute ("type", "hidden");
			setAttribute ("value",sPrefURL + "es/correcto.html");
		}
		oForm.appendChild(vHidden);
		vHidden = document.createElement("input");
		with (vHidden) {
			setAttribute ("name", "weberror");
			setAttribute ("type", "hidden");
			setAttribute ("value",sPrefURL + "es/incorrecto.html");
		}
		oForm.appendChild(vHidden);
		document.body.appendChild(oForm);
		oForm.submit();
	}
}
