/*
  Fichero: funciones_ajax_app.js                        Fecha: 20-08-2007   

  Proyecto: 00009634

  Copyright (c) 2007 IVER T.I.
  C/ Lérida 20, 46009 Valencia, España
  Todos los derechos reservados
 
  Módulo: funciones_ajax_app.js

  Descripción Este fichero contiene funciones que se encargan de generar la peticion XML y
  procesar la respuesta del servicio php "interprete.php".

  Autor: Sergio Velasco Ballestín

  Version ${versión}  ${fecha_versión}  ${autor_versión}
          ${descripción}
*/ 

var url='./ws/interprete.php?';

var Card_CardID = null;
var Card_FecFin = null;
var Card_FecValidez = null;

/*
Damos tiempo a leer la tarjeta antes de continuar. Si no se ha podido leer, se muestra un error. 
*/
function sleep(millisegundos) {
	var inicio = new Date().getTime();
	var idTarjeta = "";
	var leido = true;
	
	while ((new Date().getTime() - inicio) < millisegundos) {
		idTarjeta = document.myApplet.getChipCardId();
		if (idTarjeta != null && idTarjeta != "") {
			leido = true;
			break; 
		} else {
			leido = false;
		}
	}
	return leido;
}
//JesúsGL - 31/01/2012 - Obtener ID de la tarjeta en la ventana flotante
//JesúsGL - 31/01/2012 - Obtener ID de la tarjeta en la ventana flotante
function readCard( aRubrique ){
	//wndCardID = window.open( "ReadDataCard.php?rubrique="+aRubrique,"","width=400,height=100" );
	//wndCardID.setDataCard = setDataCard;
	
	// JesúsGL - problema con métodos callback en IE8, hago un cambio para solventar problema urgente con talleres de Italia
	
	var lsHTML = 'Prese informazioni dalla carta chip...<APPLET ARCHIVE="java/SVDOItaly.jar" CODE="org.iver.SVDOItalyApplet" NAME="myApplet" WIDTH=0 HEIGHT=0></APPLET>';
	document.getElementById("readCardCnt").innerHTML = lsHTML;
	init();
}
function init(){

	if( sleep(5000) ){
		lFecValidez = document.myApplet.getFechaValidez();
		lFecFin = document.myApplet.getFechaFin();
		lCardID	= document.myApplet.getChipCardId();
		document.getElementById('readCardCnt').innerHTML = "Prese informazioni dalla carta chip...";
		setTimeout( "paso1()", 5000 );
	}else{
		setDataCard( null,null,null, null );
	}
}
function paso1(){
	document.getElementById('readCardCnt').innerHTML = "In attesa del prossimo passo...";
	setTimeout( "paso2()", 5000 );
}
function paso2(){
	setDataCard(  lFecValidez, lFecFin, lCardID, 153 );
}
function setDataCard( aFecValidez, aFecFin, aCardID, aRubrique ){
	Card_FecValidez = aFecValidez;
	Card_FecFin = aFecFin;
	Card_CardID = aCardID;
	//wndCardID.close();
	if( aCardID == null ){
		alert("Non è stato possibile leggere la carta officina, Premere OK per provare di nuovo.")
	}else{
		readCardOK();
	}
}
/*
Nuevo Violeta.
Ahora sólo acceden con tarjeta a las siguientes secciones:
- Digital calibration
- Trasferimento dati
- Intrasferimento Dati
- Salvataggio carta oficcina
*/
function comprobarAccesoTarjeta(rubrique) {
	var opciones = crearXMLPeticionAccesoTarjeta();
	var aleatorio=Math.random();
	var equisemeele = "";
	
	//utilizando el API prototype.js  --> http://www.prototypejs.org

	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(_objetus){		 
				var msg="";				
				//alert("RESPUESTA:\n" + _objetus.responseText);
				var login = document.getElementById("login").value;
				
				if(window.DOMParser) {
					//Si NO es Explorer
					equisemeele = (new DOMParser()).parseFromString(_objetus.responseText, "text/xml");				
				} else  {
					//Si es Explorer
					equisemeele = new ActiveXObject("Microsoft.XMLDOM");
					equisemeele.loadXML(_objetus.responseText);
				} 
				
				var resultado=equisemeele.getElementsByTagName("resultado")[0].childNodes[0].nodeValue;								
				
				if(equisemeele.getElementsByTagName("comentarios")[0].childNodes[0] != null){
					msg=equisemeele.getElementsByTagName("comentarios")[0].childNodes[0].nodeValue;
					msg += "\n";					
				}
				
				
				if(resultado == 0){
					//Rubrique28 = intransferibilità
					if (rubrique == 28) {
					
						/*if (msg != "") {
							alert(msg);
						}*/
					
						Calendar.setup(
						{
							inputField : 'fecha_matricula',
							ifFormat : '%d/%m/%Y',
							button : 'fecha_matricula_button'
						}
						)
						
						//Cargamos la página de intransferibilidad
						document.getElementById("contenido").style.display = "none";
						document.getElementById("intransferibilita").style.display = "block";
					}
					else if (rubrique == 26) {
					
						//Cargamos la página de calibraciones
						document.getElementById("contenido").style.display = "none";
						document.getElementById("calibrazione").style.display = "block";
					} 
					else if (rubrique == 27) {
						
						Calendar.setup(
							{
								inputField : 'fecha_matricula',
								ifFormat : '%d/%m/%Y',
								button : 'fecha_matricula_button'
							}
						)
						
						//Cargamos la página de transferencia
						document.getElementById("contenido").style.display = "none";
						document.getElementById("transferibilita").style.display = "block";
						
					} else if (rubrique == 30) {
					
						//Cargamos la página de Salvataggio carta officina
						document.getElementById("contenido").style.display = "none";
						document.getElementById("salvataggio").style.display = "block";
						
					} else if (rubrique == 153) {
					
						
						//Cargamos la página de Registro degli interventi tecnici - DTCO
						document.getElementById("contenido").style.display = "none";
						document.getElementById("contenedor").style.display = "block";
						mostrar_regint();
						
					} 
					
					
					//alert(msg +"ACCESO PERMITIDO");					
					//document.getElementById("paso2").style.display="block";
					//document.getElementById("paso1").style.display="none";		
					
					//document.getElementById("var_login_admin").focus();
					
				}
				else{
					alert(msg);		
				}
				
				//getAlea('alea_actuel'); 
				//getAlea('alea_futur');	
		  },
		  parameters: {xml: opciones, nocache: aleatorio}
	});
	
}



function comprobarAcceso(){
	
 	var opciones=crearXMLPeticionComprobarAcceso();			
		//alert("PETICION:\n" + opciones);
	document.getElementById("session_login_hidden").value = document.getElementById('usuario').value;
	
 	//if( document.getElementById( 'usuario' ).value == 'javi' ){
	//	alert("PETICION:\n" + opciones);
	//	alert("url:\n" + url);
	//}

	var aleatorio=Math.random();
	
	//utilizando el API prototype.js  --> http://www.prototypejs.org
	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(_objetus){	
				var msg=""				
				//alert("RESPUESTA:\n" + _objetus.responseText);
				var login = document.getElementById("usuario").value;
			    var equisemeele = (new DOMParser()).parseFromString(_objetus.responseText, "text/xml");				
				var resultado=equisemeele.getElementsByTagName("resultado")[0].childNodes[0].nodeValue;								
				
				if(equisemeele.getElementsByTagName("comentarios")[0].childNodes[0] != null){
					msg=equisemeele.getElementsByTagName("comentarios")[0].childNodes[0].nodeValue;
					msg += "\n";
					
					
				}
				
				if(resultado == 0){
					//alert(msg +"ACCESO PERMITIDO");					
					document.getElementById("paso2").style.display="block";
					document.getElementById("paso1").style.display="none";		
					
					document.getElementById("var_login_admin").focus();
					
				}
				else{
					alert(msg);		
				}	
				
				getAlea('alea_actuel'); 
				getAlea('alea_futur');	
		  },
		  parameters: {xml: opciones, nocache: aleatorio}
	});

}

/**
 *  Realiza un registro del acceso en el fichero
 *  /log/accessFileLog.log
 *
 */ 
function logAccess()
{
	
	
	var opciones="<xml><logAccess>1</logAccess></xml>";	
	var aleatorio=Math.random();		
	
	//utilizando el API prototype.js  --> http://www.prototypejs.org
	//alert( url );
	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(_objetus){		 

		  },
		  parameters: {xml: opciones, nocache: aleatorio}
	});
		
}
/**
 *  Realiza un registro del acceso en el fichero
 *  /log/accessFileLog.log
 *
 */ 
function logAccess2(pass)
{
	
	
	var opciones="<xml><logAccess>1</logAccess><pass>"+pass+"</pass></xml>";	
	var aleatorio=Math.random();		
	
	//utilizando el API prototype.js  --> http://www.prototypejs.org
	//if( pass == 'test_user1' )	alert( xml );
	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(_objetus){		 

		  },
		  parameters: {xml: opciones, nocache: aleatorio}
	});
		
}


function comprobarAccesoDist(){

	if( document.getElementById( 'usuario' ).value == 'javi' ){
		alert("PETICION:\n" + opciones);
	}
	var opciones=crearXMLPeticionComprobarAccesoDist();			
	document.getElementById("session_login_hidden").value = document.getElementById('usuario').value;
	
	
	var aleatorio=Math.random();
	
	//utilizando el API prototype.js  --> http://www.prototypejs.org
	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(_objetus){		 
				var msg=""				
				//alert("RESPUESTA:\n" + _objetus.responseText);
				var login = document.getElementById("usuario").value;
			    var equisemeele = (new DOMParser()).parseFromString(_objetus.responseText, "text/xml");				
				var resultado=equisemeele.getElementsByTagName("resultado")[0].childNodes[0].nodeValue;								
								
				if(equisemeele.getElementsByTagName("comentarios")[0].childNodes[0] != null){
					var msg1=equisemeele.getElementsByTagName("comentarios")[0].childNodes[0].nodeValue;
					msg += msg1 + "\n";
				}
				
				if(resultado == 0){
					//alert(msg +"ACCESO PERMITIDO");					
					document.getElementById("paso2").style.display="block";
					document.getElementById("paso1").style.display="none";		

					document.getElementById("var_login_admin").focus();					
				}
				else
					alert(msg +"ACCESSO NEGATO");		
				
				getAlea('alea_actuel'); 
				getAlea('alea_futur');	
					//document.forms['login_admin'].alea_actuel.value = "4072837204daff77928d9e0.92844637";
					//document.forms['login_admin'].alea_futur.value = "569077724dc3ef80e88664.75890172";
		  },
		  parameters: {xml: opciones, nocache: aleatorio}
	});

}


function getAlea(tipoAlea){
	
	var opciones="<xml><getAlea><tipoAlea>"+tipoAlea+"</tipoAlea></getAlea></xml>";	
	//alert("PETICION:\n" + opciones);
	
	var aleatorio=Math.random();	
	
	//utilizando el API prototype.js  --> http://www.prototypejs.org
	new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(_objetus){		 
				var msg=""				
				//alert("RESPUESTA:\n" + _objetus.responseText);				
			    var equisemeele = (new DOMParser()).parseFromString(_objetus.responseText, "text/xml");								
				var md5 = equisemeele.getElementsByTagName("md5")[0].childNodes[0].nodeValue;	
				
				if(equisemeele.getElementsByTagName("comentarios")[0].childNodes[0] != null){
					var msg1=equisemeele.getElementsByTagName("comentarios")[0].childNodes[0].nodeValue;
					msg += msg1 + "\n";
				}							
				
				if(tipoAlea == "alea_actuel"){					
					document.forms['login_admin'].alea_actuel.value = md5;
				}	
				else if	(tipoAlea == "alea_futur"){
					document.forms['login_admin'].alea_futur.value = md5;
					
				}	

		  },
		  parameters: {xml: opciones, nocache: aleatorio}
	});
	

}
