//---------------- 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){
	imgAdjuntas(iIdidioma);
	externalLinks();
	cargarUtilidades();
}

//--------------------------------------------------------------
//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, validacionextra, etiquetas, sRutaActual;

	bOk = true;
	nombrefichero = oFormulario.nombrefichero.value
	validacionextra = oFormulario.validacionextra.value;
	etiquetas = oFormulario.etiquetas.value; 
	sParametros = "";
	
	for(var i=0;i<oFormulario.elements.length;i++){

	 	sTipo = oFormulario.elements[i].type;
	 	
	 	if(sTipo == "hidden" && oFormulario.elements[i].name == "contenidoActual") sRutaActual = oFormulario.elements[i].value;
	 	
	 	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+"&etiquetas="+etiquetas;
	
	ajax("/formularios/validar.asp",sRutaActual + "&" + sParametros,"a_alerta_"+oFormulario.id,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) {
		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] ? 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_"+oFormulario.id;
					}
				}
			}
		}
	}
}

//---------------------------------------------------------------------
// 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 #)
// - Valor para el parámetro flashVars
// - Parámetros (separados por ;)
function escribirFlash(sRuta,sAncho,sAlto,sColorFondo,sFlashVars,sParametros,sTextoAlternativo) {

      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 += sTextoAlternativo;

      sGenerado += '</object>';
	  
	  document.write(sGenerado);
}

function escribirFlashVideo(sRutaVideo,sAncho,sAlto,sColorFondo, sParametros) {
	
	sRuta = "/inc/multimedia/reproductor_video.swf";

	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 + '" />';
	sGenerado += '<param name="flashVars" value="' + sRutaVideo + '&idioma=' + sIdioma + '" />';
		
	if (sParametros){
	
		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);
	
}

function escribirFlashTarificador(sRuta,sAncho,sAlto,sColorFondo,sFlashVars,sParametros,sTextoAlternativo,sId,sName) {

      if (sColorFondo == "") {sColorFondo = '000000';
      } 

      if(navigator.appName=="Microsoft Internet Explorer") {
            var sGenerado = '<object type="application/x-shockwave-flash" width="' + sAncho + '"  height="' + sAlto + '" id="' + sId + '" name="' + sName + '">';
      } else {
            var sGenerado = '<object type="application/x-shockwave-flash" data="' + sRuta + '" width="' + sAncho + '"  height="' + sAlto + '" id="' + sId + '" name="' + sName + '">';
      }

      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 += sTextoAlternativo;

      sGenerado += '</object>';
	  
	  document.write(sGenerado);
}

function addLoadEvent() {

		var func	   = arguments[0];
		var parametros = arguments[1]? arguments[1] : "";
		
	    var oldonload = window.onload;
	    
	    if (typeof window.onload != 'function') {
	        window.onload = func;
	        
	    } else {
	        window.onload = function() {
	           
	            if (oldonload) {
	                oldonload();
	            }
	            func(parametros);
	            
	        }
	    }
	}

function validarTeLlamamos(f)
{
	if ((f.nombre.value == "") || (f.nombre.value == "Nombre")) {
		alert("Por favor, introduzca su nombre");
		f.nombre.focus();
		return false;
	}
	if ((f.telefono.value == "") || (f.telefono.value == "Teléfono")) {				
		alert("Por favor, introduzca su número de teléfono");
		f.telefono.focus();
		return false;
	}
	if (isNaN(Number(f.telefono.value))) {
		alert("Por favor, introduzca un número de teléfono válido");
		f.telefono.focus();
		return false;
	}	
	if (f.telefono.value.length < 9){
		alert("El número de teléfono debe tener 9 digitos.");
		f.telefono.focus();
		return false;
	}
	if ((f.telefono.value.charAt(0) != "6") && (f.telefono.value.charAt(0) != "9")) { 
		alert("El número de teléfono debe empezar por 6 ó 9");
		f.telefono.focus();
		return false;
	}	
	
	var pagina = urlencode(f.pagina.value);
	var nombre = f.nombre.value;
	var telefono = f.telefono.value;	
	var enlace = "https://www.nectar.es/seguros/comunicaciones/Clicktocall.aspx?pagina="+pagina+"&nombre="+nombre+"&telefono="+telefono;	
	
	return GB_showCenter(' ', enlace, 415, 505);
}

function urlencode(str) {
	return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}