//--------------------------------------------------------------

function inicio(iResolucion, iIdidioma){
	resolucion(iResolucion);
	obtenerResolucionLinks(iResolucion);
	imgAdjuntas(iIdidioma);
	externalLinks();
	CargarUtilidades();
	//cargarHack();
}

// -------------------------------- ESTADISTICAS: RESOLUCION ----------------------------
//--------------Función para obtener la resolución mediante la "carga" (llamada) de una página oculta
// En el GET no hace falta pasar la ruta completa de la página a llamar
function resolucion(iResolucion){
	var xmlHttp
	if (iResolucion == 0) {
		if (window.ActiveXObject){
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
			xmlHttp.open("GET", "resolucion.asp?resolucion="+screen.width+"*"+screen.height, false);
			xmlHttp.send();
		} else {
			xmlHttp = new XMLHttpRequest();
			xmlHttp.open("GET", "resolucion.asp?resolucion="+screen.width+"*"+screen.height, false);
			xmlHttp.send(null);
		}
	}
}

//--------------------------------------------------------------

// En caso de que el navegador sea antiguo y no funcione el sistema anterior se usa la siguiente función para
// cambiar todos los enlaces de la página principal y poder obtener la resolución
function obtenerResolucionLinks(iResolucion) {
	if (iResolucion == 0){
		var i;
		var screenW = screen.width;
		var screenH = screen.height;
		var host = location.host;
		for (i=0;i<document.links.length;i++) {
			enlace = document.links[i].href;
			// Eliminar aquellos enlaces externos que, por lo tanto, no nos van a ayudar a obtener la resolución
			// eso lo hacemos mediante "host". Consideramos externo todo aquél enlace que no contenga "host"
			if ((enlace.indexOf("javascript") == -1)&&(enlace.indexOf(host) != -1)) {
				// además que no se añada a los enlaces "falsos" y a los que no tienen otros parámetros
				if ((enlace.indexOf("?") != -1)&&(enlace.indexOf("#") == -1)) {
					document.links[i].href=document.links[i].href+'&r='+screenW+'*'+screenH;
				}
			}
		}
	}
}

//--------------------------------------------------------------

//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){

	   	if(iIdidioma==1){
	   		img.alt = img.alt+" (Se abre en ventana nueva)";
	   	}
	   	if(iIdidioma==2){
	   		img.alt = img.alt+" (Open in a new window)";
	   	}
	  }
	}
}

//--------------------------------------------------------------

//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 oServicioVolver, oEnlace, oAlerta;

	oServicioVolver = document.getElementById("atajoVolver");
	if(oServicioVolver) {
		oServicioVolver.style.display = "inline";
		oEnlace = oServicioVolver.getElementsByTagName("A");
		oEnlace[0].href="javascript:volver();"
	}
	
	/*oAlerta = document.getElementById('a_alerta');
	if(oAlerta){oAlerta.className='mensaje';}*/
}
//--------------------------------------------------------------

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");

}

//--------------------------------------------------------------

function mostrarContenido(iIdContenido){

 var windowContenido;
 windowContenido = window.open("/popup/popupcontenido.asp?idcontenido=" + iIdContenido,"Contenido","width=800,height=600,top=10,left=10,scrollbars=yes,resizable=yes");

}

//--------------------------------------------------------------

function comprobarpatron(fBusqueda){
	
	if(fBusqueda.textobusqueda.value.length<3){
		alert("Debe introducir al menos 3 caracteres para realizar la búsqueda.")
		return false;
	}else{return true;}
}

//--------------------------------------------------------------

function cambiaImagen(idImagen, estado){
	
	var oImagen = document.getElementById(idImagen);
	var sRuta = "img/es/aplicaciones/";
	
	if (estado==1)
		oImagen.src= sRuta + idImagen +"_On.gif";
	else
		oImagen.src= sRuta+ idImagen +".gif";
}

function borrartexto(campo, textoinicial){
	if(campo.value==textoinicial){campo.value='';}
}

//--------------------------------------------------------------

function ValidarFormulario(oFormulario){

	var sParametros, sTipo, sNombre, sValor, bOk, nombrefichero, oCapa, validacionextra;

	bOk = true;
	nombrefichero = oFormulario.nombrefichero.value
	sParametros = ""
	validacionextra = oFormulario.validacionextra.value;
	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  = escape(oFormulario.elements[i].value);
			}
			else {

				sNombre = oFormulario.elements[i].name;

				if(oFormulario.elements[i].checked){
					sValor  = escape(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+"&validacionextra="+validacionextra;
	
	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]? 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) {
			if(!oForm){
	  		peticion.open("GET", sFichero+sParametros, bAsincrono);
	  	}else{
	  		peticion.open("POST", sFichero);
	  		peticion.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			}
	  	if (sDiv!=""){devolverResultado(peticion, sDiv, oForm);}
		if(!oForm){
			peticion.send(null);
		}else{
			peticion.send(sParametros); 
		}
		
	}
}

//---------------------------------------------------------------------
// 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";
					}
				}
			}
		}
	}
}*/
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 { 
                                         
                                        // Caso especial para los select en Explorer 
                                        if (obj.type == "select-one") { 
                                                select_innerHTML(obj, peticion.responseText); 
                                                if(obj.name.split("_")[0] == "area") { recargaTitulaciones(obj); } 
                                                if(obj.name == "idzona") { recargaPoblaciones(obj); } 
                                        } 
                                        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 para escribir un flash.
// Parámetros:
// - Ruta del flash
// - Ancho del flash
// - Alto del flash
// - Color de fondo (Sin la #)
// - Valor para el parámetro flashVars
// - Parámetros (separados por ;)
// - Capa donde incluimos el código
function escribirFlash(sRuta,sAncho,sAlto,sColorFondo,sFlashVars,sParametros, sCampo) {

    if (sColorFondo == "") {
          sColorFondo = 'ffffff';
    }

    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>';
    
		// Validamos que esté activado el activex
		var bActiveX = ActivexOn();
		document.getElementById(sCampo).style.display = 'block';
		if (bActiveX) document.getElementById(sCampo).innerHTML = sGenerado;
}

function ActivexOn(){
		var xmlDoc;
		
		try{
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		}
		catch(e){
			try{xmlDoc=document.implementation.createDocument("","",null);}
			catch(e){}
		}
		
		if(xmlDoc){
			return true;
		}else{
			return false;
		}
}

function select_innerHTML(objeto,innerHTML){
/******
* select_innerHTML - innerHTML to add option(s) to select(s)
* Problem: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Creative Commons license
* Versão: 1.0 - 06/04/2006
* Author: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br - elmicoxcodes.blogspot.com
* Parametros:
* objeto(tipo object): the select
* innerHTML(tipo string): the new innerHTML
*******/
    objeto.innerHTML = ""
    //creating phantom element to receive temp innerHTML
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.toLowerCase().indexOf("<option")<0){//if not option, convert do option
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML
    //transfering childs of phantom element to options
    for(var i=0;i<selTemp.childNodes.length;i++){
        if(selTemp.childNodes[i].tagName){
            opt = document.createElement("OPTION")
            for(var j=0;j<selTemp.childNodes[i].attributes.length;j++){
                opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true))
            }
            opt.value = selTemp.childNodes[i].getAttribute("value")
            opt.text = selTemp.childNodes[i].innerHTML
            if(document.all){ //IEca
                objeto.add(opt)
            }else{
                objeto.appendChild(opt)
            }                    
        }    
    }
    //clear phantom
    document.body.removeChild(selTemp)
    selTemp = null
}

/*function cargarHack(){
	var sEstilo;
	sEstilo = '<style type="text/css" media="screen">';
	sEstilo += '.listado_tipo1 .mitad2, x:-moz-any-link, x:default {margin-left:50%}';
	sEstilo += '</style>';
	
	document.getElementById("contenedorcuerpo").innerHTML = sEstilo + document.getElementById("contenedorcuerpo").innerHTML;
	
}*/