// Variables globales
var ventana; 
var result;
var m_absResDlg;

var url_validador = 'http://80.32.181.204/ABSIS/IDI/CCO/IDICCOFIRMWEB/DLG/CER/dlgValidarCertificado.aspx' // ADRA

/* ----- Funcions d'utilitat ------ */

function myGetCookie(name) { 
	var re=new RegExp(name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		//alert(document.cookie.match(re)[0].split("=")[1]);
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

function mySetCookie(name, value, domain, path, days) {
	if (typeof days!="undefined"){ //if set persistent cookie
		var expireDate = new Date()
		var expstring=expireDate.setDate(expireDate.getDate()+days)
		document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; domain="+domain+"; path="+path;
	}
	else //else if this is a session only cookie
		document.cookie = name+"="+value+"; domain="+domain+"; path="+path;
}

/* --------------- VALIDAR ------------- */

function getTramiteForm() {	
	var myForm = null;
	if (document.getElementById('webform-client-form-535') != null) {
		// tramite: certificado de empadronamiento
		myForm = document.getElementById('webform-client-form-535');
	}
	else if (document.getElementById('webform-client-form-514') != null) {
		// tramite: instancia generica
		myForm = document.getElementById('webform-client-form-514');
	}
	else if (document.getElementById('webform-client-form-532') != null) {
		// tramite: queja y sugerencia
		myForm = document.getElementById('webform-client-form-532');
	}
	else if (document.getElementById('webform-client-form-534') != null) {
		// tramite: uso de instalaciones
		myForm = document.getElementById('webform-client-form-534');
	}
	return myForm;
}

function validar() {
	var params = '?tipoDlg=2&atributo=NIF&atributo=Nombre&atributo=Apellido1&atributo=Apellido2&atributo=EMail&atributo=Emisor&idioma=S';
	abrirDlg(url_validador + params, 520, 360, "Seleccion de certificado", 2, 'no', 'callBackValidar()');
}

function callBackValidar() {
	if (typeof (m_absResDlg) == 'undefined' || m_absResDlg == null) return;
	//alert(m_absResDlg['EMail']);
	
	var myForm = getTramiteForm();
	
	if (myForm != null) {
		myForm.elements['submitted[datos_del_solicitante][nombre_completo][nombre]'].value = m_absResDlg['Nombre'];
		myForm.elements['submitted[datos_del_solicitante][nombre_completo][primer_apellido]'].value = m_absResDlg['Apellido1'];
		myForm.elements['submitted[datos_del_solicitante][nombre_completo][segundo_apellido]'].value = m_absResDlg['Apellido2'];
		myForm.elements['submitted[datos_del_solicitante][dni][numero_de_documento]'].value = m_absResDlg['NIF'];
		myForm.elements['submitted[datos_del_solicitante][datos_de_contacto][email]'].value = m_absResDlg['EMail'];
		
		mySetCookie("acceso_con_certificado", 'si', window.location.hostname, "/");
		
		// IMPORTANTE: lo siguiente tambien hay que hacerlo en firmar.js 
		// porque si al enviar el form hay errores de campos obligatorios entonces este codigo 
		// no se volver? a ejecutar porque el cliente ya se ha validado
		myForm.onsubmit = function(){firmar(); return false}; // firmar() esta en firmar.js
		
		if (m_absResDlg['Nombre'] != null) alert('Certificado validado correctamente.');
		return;
	}
	return;
}

/*
* La funcion abrirDlg se encarga de invocar a la aspx que contiene el applet y 
* recoger el resultado devuelto. Se distinguen dos casos:
* a) IE: se invoca a la aspx mediante la funcion de JavaScript window.showModalDialog 
*    (no se invoca directamente a la aspx, sino a un html intermedio)
* b) Resto de navegadores: se invoca a la aspx mediante la funcion de JavaScript window.open
* 
* Para recoger el resultado, en el caso de navegadores diferentes a IE es necesario ir 
* consultando si se ha cerrado la ventana del applet.
*/
function abrirDlg(location,w,h,title,type,resizable,fnRetEsp,idElemSesion)
{			
	if (resizable==null){resizable="no";}
	
	if (typeof window.showModalDialog != 'undefined') // Navegador IE
	{
		var WinSettings = "dialogHeight:" +h +"px;dialogWidth:" +w +"px ; edge: Raised; center: Yes; help: No; resizable:" + resizable + "; status: No;"
		var theurl=location
		var title=title
		var arg=null;
		var referrer=window.location.pathname
		var MyArgs ={window:window,scroll:true,title:title,url:theurl,referrer:referrer,argument:arg}
		result= window.showModalDialog('DialogHandler.html',MyArgs, WinSettings);  	
    	m_absResDlg=result; 
    	eval(fnRetEsp);	// Invocar a la funcion que tratara los datos devueltos
    	
	}
	else { // Navegador no IE 
	 	result=null;
		ventana=abrirVentanaModal(location,w,h,null,resizable,title);
		// En el caso de navegadores no IE, vamos consultando 
		// cada medio segundo si ya se ha cerrado el applet.
		
		setTimeout("evaluaCierreDialogo("+ type + ",'" + fnRetEsp + "','" + idElemSesion + "')",500);
	}
		
}

// Comprueba si se ha cerrado la ventana indicada
// En caso negativo, espera medio segundo y vuelve a hacer la comprobacion
function evaluaCierreDialogo(type,fnRetEsp,idElemSesion) {
	var dialog = ventana;
	if ( dialog != null ) {
		if ( dialog.closed || result != null ) {
    		m_absResDlg=result; 
    		eval(fnRetEsp);	// Invocar a la funcion que tratara los datos devueltos
		} 
		else {
		  	try { 
		  		if ( dialog.screen.top < 0 ) { 
		  			establecerFoco();
		  			
		  		}
		  		dialog.focus();
		  	}
     		catch(ex) { }
			setTimeout("evaluaCierreDialogo("+ type + ",'" + fnRetEsp + "','" + idElemSesion + "')",500);
		}
	}
}

function abrirVentanaModal(location,w,h,scroll,resizable,title)
{
	var l=0;
	var t=0;

	if (w!=0) l = (screen.availWidth - w) / 2;
	else w=screen.availWidth;
	
	if (h!=0) t = (screen.availHeight - h) / 2;
	else h=screen.availHeight;
	
	if (scroll==null){scroll="yes";}
	if (resizable==null){resizable="no";}
	var winprops = 'title=' + title + ',modal=1,dialog=1,dependant=1,directories=no, toolbar=no,menubar=0, scrollbars='+ scroll+',status=no,resizable=' + resizable +', height='+h+',width='+w+',top='+t+',left='+l+'w';
	var f = window.open(location,"_blank", winprops);
	return f;
}


function establecerFoco(e) {
	var dialog = ventana;
	if ( dialog != null && !dialog.closed ) {
		dialog.focus();
		if ( window.event ) {
			window.event.cancelBubble = true;
		}
		if ( e && e.stopPropagation ) {
			e.stopPropagation();
		}
		if ( typeof ( dialog.establecerFoco ) != "undefined" ) {
			dialog.establecerFoco(e);
		}
		return false;
	}
	return true;
}


