//FUNCIONES CONTENIDO WCM

//Muestra/oculta las imagenes de repositorio del detalle de promociones
function mostrarFotoRepositorioPromos(idDivPadre){
	//Si el div que contiene las fotos, no contiene una foto cargada desde
	//archivo, se muestra la cargada desde repositorio (si existe)
	var divPadre = document.getElementById(idDivPadre);
	var imagenes = divPadre.childNodes;
	var imagenArchivo = null;
	var imagenRepositorio = null;
        var nodo=null;
	var imagenMostrada;
	for(var i=0;i<imagenes.length;i++){
		nodo = imagenes[i];
		var claseNodo = nodo.className;
		//Si es una imagen subida
		if(claseNodo != null && claseNodo.indexOf('fotoSubida')>=0){
			imagenArchivo = nodo;
			imagenMostrada = nodo;
		}else if(claseNodo !=null && claseNodo.indexOf('fotoRepositorio')>=0){
			imagenRepositorio= nodo;
			imagenMostrada = nodo;
		}
	}

	var imagenMostrada;
	if(imagenArchivo != null && imagenRepositorio != null){
		//ocultar la imagen de repositorio porque tiene contribuida
		//una imagen desde archivo, que se le da más prioridad.
		imagenRepositorio.style.display="none";
		imagenMostrada = imagenArchivo;
	}

	//Redimensionados
	if(imagenMostrada != null){
		if(idDivPadre.indexOf("foto-promociones")>=0){
			//imagenMostrada.setAttribute("width", "100");
			//imagenMostrada.removeAttribute("height");
                        imagenMostrada.style.display="block";
  
		}
	
	}

	//Se muestra la imagen
	// Se comenta esta llamada, parece que el explorer 6 no la reconoce
	//divPadre.setAttribute("style","display:block;");
        divPadre.style.display = "block";

}

function mostrarFotoRepositorioPromoLocal(idDivPadre){
	//Si el div que contiene las fotos, no contiene una foto cargada desde
	//archivo, se muestra la cargada desde repositorio (si existe)
	var divPadre = document.getElementById(idDivPadre); 
	var imagenes = divPadre.childNodes;
	var imagenArchivo = null;
	var imagenRepositorio = null;
    var nodo=null;
	var imagenMostrada;
	for(var i=0;i<imagenes.length;i++){
		nodo = imagenes[i];
		var claseNodo = nodo.className;
		//Si es una imagen subida
		if(claseNodo != null && claseNodo.indexOf('fotoSubida')>=0){
			//se añade este if debido a la inclusion de enlaces al detalle
			//de la promocion de la fase 2
			if(nodo.getElementsByTagName("img").length>0) {
				imagenArchivo = nodo;
				imagenMostrada = nodo;
			}			
		}else if(claseNodo !=null && claseNodo.indexOf('fotoRepositorio')>=0){
			
			imagenRepositorio= nodo;
			imagenMostrada = nodo;
		}
	}

	var imagenMostrada;
	if(imagenArchivo != null && imagenRepositorio != null){
		//ocultar la imagen de repositorio porque tiene contribuida
		//una imagen desde archivo, que se le da máprioridad.
		imagenRepositorio.style.display="none";
		imagenMostrada = imagenArchivo;
	}

	//Redimensionados
	if(imagenMostrada != null){
		if(idDivPadre.indexOf("foto-bannerPromociones")>=0){
			//imagenMostrada.setAttribute("width", "100");
			//imagenMostrada.removeAttribute("height");
			
            imagenMostrada.style.display="block";
  
		}
	
	}

	//Se muestra la imagen
	// Se comenta esta llamada, parece que el explorer 6 no la reconoce
	//divPadre.setAttribute("style","display:block;");
     divPadre.style.display = "block";
}


// funcion para mostrar imagenes del repositorio en contenidos genéricos

function mostrarFotoRepositorio(idDivPadre){
	//Si el div que contiene las fotos, no contiene una foto cargada desde
	//archivo, se muestra la cargada desde repositorio (si existe)
	var divPadre = document.getElementById(idDivPadre);
	var imagenes = divPadre.childNodes;
	var imagenArchivo = null;
	var imagenRepositorio = null;
    var nodo=null;
	var imagenMostrada;
	for(var i=0;i<imagenes.length;i++){
		nodo = imagenes[i];
		//Si es una imagen
		if(nodo.nodeType == 1 && nodo.tagName.toLowerCase() == 'img'){ 
			var claseNodo = nodo.getAttribute("class");
			//Si es una imagen subida
			if(claseNodo != null && claseNodo.indexOf('fotoSubida')>=0){
				imagenArchivo = nodo;
				imagenMostrada = nodo;
			}
			//O es una imagen de repositorio
			else{
				imagenRepositorio= nodo;
				imagenMostrada = nodo;
			}
		}
	}

	var imagenMostrada;

	if(imagenArchivo != null && imagenRepositorio != null){
		//ocultar la imagen de repositorio porque tiene contribuida
		//una imagen desde archivo, que se le da mÃ¡s prioridad.
		imagenRepositorio.setAttribute("style","display:none;");
		imagenMostrada = imagenArchivo;
	}

	//Redimensionados
	if(imagenMostrada != null){
		var res = idDivPadre.indexOf("foto-noticias-");
		if(idDivPadre.indexOf("foto-noticias-")>=0){
			imagenMostrada.setAttribute("width", "100");
			imagenMostrada.removeAttribute("height");
		}
	
	}

	//Se muestra la imagen
	// Se comenta esta llamada, parece que el explorer 6 no la reconoce
	//divPadre.setAttribute("style","display:block;");
    divPadre.style.display = "block";

}


function generarEnlacePromocionDestacadaHome(origen){
	// En WCM se ha cambiado la llamada a generarEnlacePromocionEstrategica por
	// la llamada a generarEnlacePromocionDestacadaHome en el menu
	// RnRMapfre_MenuPromocionDestacada de las librerias de componentes
       
	var divPathPromocion = origen.nextSibling;
	var pathPromocion = divPathPromocion.innerHTML;
	var linkDetallePromocion = document.getElementById("link-promociones").innerHTML;
	//Por motivos de seo se quiere una url amigable
	//por lo que eliminamos el troncho, dejando sólo
	//los dos parámetros
	var urlSinTroncho = linkDetallePromocion.split("/!ut");
	
	// Si el valor indicado en WCM_GLOBAL_CONTEXT se corresponde con un Contentlink no se muestra correctamente
	// Por eso se realiza este cambio, para apuntar directamente al contenido que esta en la oficina comun.
	//var urlFinal = linkDetallePromocion + "?WCM_GLOBAL_CONTEXT=" + pathPromocion;
	var strInicial = document.getElementById("id-promocion-wcm").innerHTML;
	var path = /\/{0,1}redenred_contenido_\w\w\/oficinaweb\./.exec(strInicial);
	path += "comun/promociones/";
	var nombre = /[\w]*$/.exec(strInicial);
	var urlFinal = urlSinTroncho[0] + "?WCM_GLOBAL_CONTEXT=" + path + nombre + "&presentationtemplate=RedEnRed_Componentes_ES/PP_PromocionDetalleOficina";
	window.location.href = urlFinal;
}

function generarEnlacePromocionEstrategica(origen){
	var divPathPromocion = origen.nextSibling;
	var pathPromocion = divPathPromocion.innerHTML;
	var linkDetallePromocion = document.getElementById("link-promociones").innerHTML;
	//Por motivos de seo se quiere una url amigable
	//por lo que eliminamos el troncho, dejando sólo
	//los dos parámetros
	var urlSinTroncho = linkDetallePromocion.split("/!ut");
	var urlFinal = urlSinTroncho[0] + "?WCM_GLOBAL_CONTEXT=" + pathPromocion + "&presentationtemplate=RedEnRed_Componentes_ES/PP_PromocionDetalleOficina";
	window.location.href = urlFinal;
}

function getEnlaceContacto() {
	var urlNavegador = window.location.href;
	var parteInicioUrl = /http[s]{0,1}:\/\/[\w:\.]+\/[\w\/\.]*\/redoficinasmapfre\/oficina\/[^\/]*\//.exec(urlNavegador);
	
	var urlFinal = parteInicioUrl + "contacto";
	
	return urlFinal;
}

function generarEnlaceContacto(){
	window.location = getEnlaceContacto();
}
	
function getURLContacto(idLineaNegocio) {
	var cadena = "contacto";
	var elemProducto = window.document.getElementById('idLineaNegocio' + idLineaNegocio);
	if (elemProducto == null) {
		elemProducto = window.document.getElementById('idLineaNegocio1');
		var theURL = new String(elemProducto.value);
		var idxContacto = theURL.indexOf(cadena);
		return (theURL.substring(0, idxContacto + cadena.length));
	} 
	return elemProducto.value;
}
function accionLineaNegocio(tipoEnlace, idLineaNegocio) {
	var tipoLink = new String(tipoEnlace);
	var idxTipo = tipoLink.toUpperCase().indexOf('PRESUPUESTO');
	if (idxTipo != -1) {
		//Obtener presupuesto
		var miurl = getURLContacto(idLineaNegocio);
		//window.document.frmLineaNegocio.action = miurl;
		window.location.href = miurl;
		return null;
	} else {
		window.document.frmLineaNegocio.submit();
	}
}

//Devuelve la versiÃ³n de Internet Explorer, o para cualquier otro browser -1
function getInternetExplorerVersion() {
	var rv = -1; // Return value assumes failure.
	try {
		if (navigator.appName == 'Microsoft Internet Explorer') {
			var ua = navigator.userAgent;
			var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
			if (re.exec(ua) != null) {
				rv = parseFloat( RegExp.$1 );
			}
		}
	}catch(err){}
	return rv;
}

function getUrlLineaNegocio() {
	var urlDoc = document.URL;

	var strUrl = new String(urlDoc);
	var strTmp = new String(urlDoc);

	var indiceWPS = strTmp.indexOf("/wps/");
	var indiceTmp = strTmp.indexOf("oficina/");
	var indiceUrl = indiceTmp;

	strTmp = strTmp.substring(indiceTmp);

	for(var i=0; i<2; i++) {
		indiceTmp = strTmp.indexOf("/") +1;
		indiceUrl += indiceTmp;
		strTmp = strTmp.substring(indiceTmp);
	}
	strTmp = strUrl.substring(indiceWPS, indiceUrl) + "productos/lineanegocio";
	return strTmp;
}
		
function accionAmpliarSolucion(frm, codigo_canal, id_linea_negocio, id_solucion, url) {
	frm.codigo_canal.value = codigo_canal;
	frm.id_linea_negocio.value = id_linea_negocio;
	frm.id_solucion.value = id_solucion;
	frm.miurl.value = url;
	frm.action=getUrlLineaNegocio();//strUrl.substring(indiceWPS, indiceUrl) + "productos/lineanegocio";
	frm.submit();
}

function accionAmpliarLineaNegocio(frm, id_linea_negocio, nombre_linea_negocio, url) {
	frm.id_linea_negocio.value = id_linea_negocio;
	frm.nombre_linea_negocio.value = nombre_linea_negocio;
	frm.miurl.value = url;
	
	frm.action=getUrlLineaNegocio();//strUrl.substring(indiceWPS, indiceUrl) + "productos/lineanegocio";
	frm.submit();
}


// FUNCIONES DE PARSEO DE LINKS DE PRODUCTOS
function seleccionar(codigo_canal, nombre_linea_negocio, id_linea_negocio, id_solucion, id_producto, url) {
	document.confirm_cambios.codigo_canal.value = codigo_canal;
	document.confirm_cambios.nombre_linea_negocio.value = nombre_linea_negocio;
	document.confirm_cambios.id_linea_negocio.value = id_linea_negocio;
	document.confirm_cambios.id_solucion.value = id_solucion;
	document.confirm_cambios.id_producto.value = id_producto;
	document.confirm_cambios.miurl.value = url;
	document.confirm_cambios.submit();
}

function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById(id)){
        newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}


function buscarElemento(link, arrMenu) {
	var strLink = new String(link);
	if(strLink.charAt(strLink.length -1) != '/') {
		strLink += '/';
	}
	for(var ind=0; ind<arrMenu.length; ind++) {
		var strUrl = new String(arrMenu[ind].web_url);
		if(strUrl.charAt(strUrl.length -1) != '/') {
			strUrl += '/';
		}
		if(strUrl.indexOf(strLink) >= 0) {
			return arrMenu[ind];
		}
	}
	return null;
}

function redoficinasmapfre_parse_links(docu, arrMenu) {
	try {
		var elements = docu.getElementsByTagName("A");
		for ( var i = 0; i < elements.length; i++) {
			var link = elements[i];
			var lnHref = new String(link.href);
			if(buscarElemento(link, arrMenu) != null) {
				var valueLink = link.href;
				link.href = '#null';

				link.onclick = new Function ("window.parent.actionLinkProducto('" + valueLink + "');");
			} else if(lnHref.toLowerCase().indexOf("datoscontacto") >= 0) {
				link.href = '#null';
				link.onclick = new Function ("window.parent.irContacto('" + getEnlaceContacto() + "');");
			}
		}
	} catch(err) {
		alert(err.name + ": " + err.message + "<br/>");
	}
}
// FIN FUNCIONES DE PARSEO DE LINKS DE PRODUCTOS

// FUNCIONES PARA OCULTAR AMPLIAR INFORMACION CARRUSEL PRODUCTOS DE HOME
function getElementsByNameIE6(name){
    var temp = document.all;
    var matches = [];
    for(var i=0;i<temp.length;i++){
      if(temp[i].name == name){
        matches.push(temp[i]);
      }
    }
    return matches;
}

function actualizarHermanosIE6(obj) {
    var parentObj = obj.parentNode;
    var arrHijos = parentObj.childNodes;
    for(var ih in arrHijos) {
        var hijo = arrHijos[ih];
        if(hijo != null && (hijo.className == 'Particulares'
                      || hijo.className == 'Empresas')) {
            hijo.style.height= "100px";
        }
    }
}

function ocultarIE6() {
        var x = getElementsByNameIE6("ampliar_informacion");
	for(var i=0; i<x.length; i++) {
                var strId = new String(x[i].id);
                // 9 es la longitud de solucion_
		if(strId.length < 10) {
                        x[i].style.display = "none";
                        actualizarHermanosIE6(x[i]);
                }
	}
}

function necesitaOcultarSegunIE6() {
	if(getInternetExplorerVersion() <= 1.0) {
		return false;
	}
	if(getInternetExplorerVersion() <= 8.0) {
	    return true;
	}

	return false;
}

function ocultarAmpliarInformacionCarruselProductos() {
    if(necesitaOcultarSegunIE6()) {
         ocultarIE6();
    } else {
		var x=document.getElementsByName("ampliar_informacion");
		for(var i=0; i<x.length; i++) {
	            var strId = new String(x[i].id);
	            // 9 es la longitud de solucion_
	            if(strId.length < 10) {
	                x[i].style.display = "none";
	            }
		}
    }
}
// FIN FUNCIONES PARA OCULTAR AMPLIAR INFORMACION CARRUSEL PRODUCTOS DE HOME

/*
Funcion que oculta los objetos indicados por id_boton_prev y id_boton_next si el numero de elementos <li> contenidos por la lista con identificador id_objeto, es menor o igual a num_limite
*/
function ocultarFlechasSegunNumFotos(id_objeto, id_boton_prev, id_boton_next, num_limite) {
    var carrusel = document.getElementById(id_objeto);
    if(carrusel) {
        var arrLi = carrusel.getElementsByTagName("li");
//alert("La prueba de JS: " + arrLi.length + " -- " + num_limite);
        if(arrLi.length <= num_limite) {
            var botonPrev = document.getElementById(id_boton_prev);
            var botonNext = document.getElementById(id_boton_next);
            botonPrev.style.display = "none";
            botonNext.style.display = "none";
        }
    }
}

//FUNCIONES PARA OCULTAR EL BOTON DE AMPLIAR INFORMACION DE LAS PROMOCIONES
if(!document.getElementsByName) {
   document.getElementsByName = function(name) {
       var temp = document.all;
       var matches = [];
       for(var i=0;i<temp.length;i++){
         if(temp[i].name == name){
           matches.push(temp[i]);
         }
       }
       return matches;
   }
}

function mostrarEnlaceMasInformacion(nombreEnlaceMasInfo, enlaceMasInfo, idCuerpo) {
   // Descomentar para habilitar/deshabilitar el boton Mas Info en función del texto  contribuido. Comentado para deshabilitar siempre.
	var elementsByName = jQuery('div[name='+nombreEnlaceMasInfo+']'); 
	if(elementsByName == null) {
	    return false;
	}
	
	for(var i=0; i<elementsByName.length; i++) {
	    var element = elementsByName[i];
	    var hijos = element.childNodes;
	    var hijoCuerpo = null;
	    var hijoEnlace = null;
	    for(var j=0; j<hijos.length; j++) {
	        if(hijos[j].id == enlaceMasInfo) {
	            hijoEnlace = hijos[j];
	        }
	        if(hijos[j].id == idCuerpo) {
	            hijoCuerpo = hijos[j];
	        }
	    }
	    if(hijoCuerpo != null && hijoCuerpo.innerHTML.toUpperCase().indexOf("<XMP")<0) {
	        if(hijoEnlace != null) {
	            hijoEnlace.style.display = "block";
	        }
	    }
	}
	
	return true;
}
//FIN FUNCIONES PARA OCULTAR EL BOTON DE AMPLIAR INFORMACION DE LAS PROMOCIONES

