//---------------- MENSAJES DE ALERTA DE JAVASCRIPT -----------------
// Primero el IDIOMA y después el NÚMERO DE ALERTA

var aArrayAlertasCastellano =  new Array();
var aArrayAlertasIngles  =  new Array();

aArrayAlertasCastellano[1] = "Debe introducir al menos 3 caracteres para realizar la búsqueda.";
aArrayAlertasIngles[1] = "You must introduce at least 3 characters to make the search.";

aArrayAlertasCastellano[2] = " (Se abre en ventana nueva)";
aArrayAlertasIngles[2] = " (Open in a new window)";

var aArrayAlertas = new Array();
aArrayAlertas[1] = aArrayAlertasCastellano;
aArrayAlertas[2] = aArrayAlertasIngles;

//-------------------- FUNCIÓN QUE SE CARGA EN EL ONLOAD DEL BODY ---------------------------
function inicio(iResolucion, iIdidioma){
	resolucion(iResolucion);
	imgAdjuntas(iIdidioma);
	externalLinks();
	cargarUtilidades();
}

// Función para obtener la resolución mediante la "carga" (llamada) de una página oculta
function resolucion(iResolucion){
	var xmlHttp
	if (iResolucion == 0) {
		ajax("/resolucion.asp","?resolucion="+screen.width+"*"+screen.height);
	}
}

//--------------------------------------------------------------
//Esta función modifica el alt de la imagenes que tiene imagen adjunta, advirtiendo que la amplicación se abrirá en ventana nueva
function imgAdjuntas(iIdidioma){
	 var imgs = document.getElementsByTagName("img");
	 for (var i=0; i<imgs.length; i++) {
		var img = imgs[i];
		var sClass = img.className
		if (sClass.indexOf("cursorAdjunto") != -1){

   		img.alt = img.alt + aArrayAlertas[iIdioma][2];
	  }
	}
}

//--------------------------------------------------------------
//Como el atributo target no esta permitido usamos esta función para poder abrir enlaces en ventanas nuevas
//en el enlace debemos añadir el atributo rel="external", esta funcion lo detectará y pondrá el target mediante javascript
function externalLinks(){
	if (!document.getElementsByTagName) return;
 	var anchors = document.getElementsByTagName("a");
 	for (var i=0; i<anchors.length; i++) {
   		var anchor = anchors[i];
   		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external"){
       		anchor.target = "_blank";
	   }
	}
}

//--------------------------------------------------------------
//Esta función se encarga de mostrar las utilidades que utilizan javascript (que viene ocultas mediante css por defecto)
//además de mostrar los botones les añade el evento onclick con la funcion correspondiente,
//Esto es debido a que en el front utilizamos un <a href=""> para poder asignar un accesskey, a parte de que sería obligatorio usar eventos duplicados
function cargarUtilidades(){

	var oEnlace;

	oServicioVolver = document.getElementById("atajoVolver");
	if(oServicioVolver) {
		oServicioVolver.style.display = "inline";
		oEnlace = oServicioVolver.getElementsByTagName("A");
		oEnlace[0].href="javascript:volver();"
	}

}
//--------------------------------------------------------------
// Función que se utiliza para mostrar las imágenes adjuntas que se insertan en los contenidos
function VerImagen(iIdImagen){

	var windowImagen;
	windowImagen = window.open("/popup/popupimagen.asp?idimagen=" + iIdImagen,"Imagen","width=100,height=100,top=10,left=10,scrollbars=yes,resizable=yes");

}

//--------------------------------------------------------------
// Comprueba que el campo textobusqueda del formulario que se pasa por parámetro, tenga al menos 3 caracteres
// Esto es muy importante si la búsqueda se realiza mediante index server.
function comprobarPatron(fBusqueda){

	if(fBusqueda.textobusqueda.value.length < 3){
		alert(aArrayAlertas[iIdioma][1])
		return false;
	}else{
		return true;
	}
}

//--------------------------------------------------------------
// Función que se llama en los onsubmit de los formularios.
// Se encarga de la validación AJAX
function validarFormulario(oFormulario){
	

	var sParametros, sTipo, sNombre, sValor, bOk, nombrefichero, oCapa;

	bOk = true;
	nombrefichero = oFormulario.nombrefichero.value
	sParametros = "?"
	oCapa = document.getElementById('a_alerta')
	
	for(var i=0;i<oFormulario.elements.length;i++){

	 	sTipo = oFormulario.elements[i].type;

	 	if(sTipo=="text" || sTipo=="password" || sTipo=="checkbox" || sTipo=="textarea" || sTipo=="select-one" || sTipo=="radio") {

			if (sTipo != "checkbox" &&  sTipo != "radio" ){
				sNombre = oFormulario.elements[i].name;
				sValor  = oFormulario.elements[i].value;
			}
			else {

				sNombre = oFormulario.elements[i].name;

				if(oFormulario.elements[i].checked){
					sValor  = oFormulario.elements[i].value;
				}else {
					sValor = "";
				}

			}

			//Problemas con los radios (todos con el mismo nombre)
			if( sTipo != "radio" || sValor != "" ) {
				sParametros +=sNombre+"="+sValor;
				sParametros +="&";
			}

		}
	}

	sParametros += "nombrefichero=" + nombrefichero;

	ajax("/recursos/formularios/validar.asp",sParametros,"a_alerta",true,oFormulario);

	return false;
}

//---------------------------------------------------------------------
// Carga una página web mediante AJAX.
// Parámetros:
// - Url a cargar
// - Parámetros para la url
// - Capa para cargar el resultado (NO OBLIGATORIO)
// - Petición asincrona (true/false) (NO OBLIGATORIO, ASINCRONO POR DEFECTO) 
//		ATENCIÓN -- EN EL FIREFOX FUNCIONA DE FORMA ASINCRONA --
// - Objeto representando al formulario a validar (NO OBLIGATORIO)
//---------------------------------------------------------------------
function ajax(){
	
	var sFichero	= arguments[0];
	var sParametros	= arguments[1];
	var sDiv		= arguments[2];
	var bAsincrono	= arguments[3] ? arguments[3] : true;
	var oForm		= arguments[4];
	
	var peticion = false;
	if (window.XMLHttpRequest){
		peticion = new XMLHttpRequest();
	}else if (window.ActiveXObject) {
		peticion = new ActiveXObject("Microsoft.XMLHTTP");
	}

	//prompt('',fichero+parametros);

	if(peticion) {
	  	peticion.open("GET", sFichero+sParametros, bAsincrono);
	  	if (sDiv!=""){devolverResultado(peticion, sDiv, oForm);}
		peticion.send(null);
	}
}

//---------------------------------------------------------------------
// Devuelve el resultado de la petición AJAX.
// Parámetros:
// - Objeto httpRequest
// - Nombre de la capa para escribir los resultados
// - Objeto representado al formulario a validar (NO OBLIGATORIO)
//		Submita el formulario si no hay errores de validación
//---------------------------------------------------------------------
function devolverResultado(){
	
	var peticion	= arguments[0];
	var sDiv		= arguments[1];
	var oFormulario	= arguments[2];
	
	var obj = document.getElementById(sDiv);
	if(obj){
		peticion.onreadystatechange = function(){
			if (peticion.readyState == 4){
				
				// Submitar el formulario
				if (!peticion.responseText && oFormulario) oFormulario.submit();
				else {
					obj.innerHTML = peticion.responseText;
					
					if(oFormulario!="") {
						// Ocultar la capa de los errores de ASP
						if(document.getElementById("errorvalidacion") && obj.innerHTML=="") document.getElementById("errorvalidacion").style.display = "none";
		
						// Mostrar alertas 
						obj.style.display='block';
						location.hash = "a_alerta";
					}
				}
			}
		}
	}
}

//---------------------------------------------------------------------
// Función volver al contenido anterior.
// Se utiliza en el botón volver de los atajos.
//---------------------------------------------------------------------
function volver() {
 history.back(-1);
}

//---------------------------------------------------------------------
// Función para escribir un flash.
// Parámetros:
// - Ruta del flash
// - Ancho del flash
// - Alto del flash
// - Color de fondo (Sin la #)
// - Parámetros (separados por ;)
function escribirFlash(sRuta,sAncho,sAlto,sColorFondo,sFlashVars,sParametros) {

      if (sColorFondo == "") {
            sColorFondo = '000000';
      } 

      if(navigator.appName=="Microsoft Internet Explorer") {
            var sGenerado = '<object type="application/x-shockwave-flash" width="' + sAncho + '"  height="' + sAlto + '" >';
      } else {
            var sGenerado = '<object type="application/x-shockwave-flash" data="' + sRuta + '" width="' + sAncho + '"  height="' + sAlto + '" >';
      }

      sGenerado += '<param name="movie" value="' + sRuta + '" />';
	  	sGenerado += '<param name="allowScriptAccess" value="sameDomain" />';
      sGenerado += '<param name="quality" value="high" />';
      sGenerado += '<param name="bgcolor" value="' + sColorFondo + '" />';
	  
	  if(sFlashVars) sGenerado += '<param name="flashVars" value="' + sFlashVars + '" />';
	  
      if (sParametros.indexOf(';')>-1) {
            var array_parametros = sParametros.split(';');
            for (var i=0; i<array_parametros.length-1; i++) {
                  sGenerado += '<param name="'+array_parametros[i].split("=")[0]+'" value="'+array_parametros[i].split("=")[1]+'" />';
            }
      }     

      sGenerado += '</object>';
	  
	  document.write(sGenerado);
}