// Event listener by Scott Andrew (www.scottandrew.com):
function setInnerHTMLAndExecScript (element, html) { 
  var newElement = element.cloneNode(false); 
  newElement.innerHTML = html; 
  element.parentNode.replaceChild(newElement, element); 
  //eval(html);
  //document.execCommand(eval(html),false);
  

} 
 var e = {
            addEvent : function(obj, evType, fn, useCapture){
                        if (obj.addEventListener){
                                   obj.addEventListener(evType, fn, useCapture);
                                   return true;
						} else if (obj.attachEvent){
                                   var r = obj.attachEvent("on"+evType, fn);
                                   return r;
						} else {
                                   return false;
						}
           
			}
}
 
var loadGenerico={
            
            load: function (){
            	
					if (document.getElementById) {
                        if(document.getElementById("contenedor_inferior_ficha")){e.addEvent(window, 'load', fichaProductos.load, false);}
                       if(document.getElementById("listado_canales_tv")){menu.load("strCapa");}
                    if(document.getElementById("consumo_actual_paso1") || document.getElementById("facturas_emitidas_paso1") ){gestionSubFormularios.load("fila","fila_nombre_asociado","cuerpo_body");}
						if(document.getElementById("paso3_contratacion")){DESPLEGAR.load("link_mas_datos","link_mas_datos3","domicilio_distinto");}
						
						//alert("Hemos ejecutado la funcion");
					}
            
            
            }
}

e.addEvent(window, 'load', loadGenerico.load, false);




//----------- gestion de filas - Ejemplo: Consumo Actual --------------------//
var gestionSubFormularios = {
	load: function (idClick,idCapaMostrar,padre){
		enlace=idClick;
		capa=idCapaMostrar;
		padre=padre;
		totalOpciones=parseInt(document.getElementById(padre).childNodes.length/2)
		//alert("totalOpciones: "+totalOpciones);
		for (var i=0;i<totalOpciones;i++){ 
			document.getElementById(capa + i).style.display = "none";
			document.getElementById(enlace+ i).onclick=gestionSubFormularios.desplegarFila
		}
	},	
	desplegarFila: function (){
		var capaSubformulario=capa + this.id.toString().substring(4,this.id.toString().length);
		miFila = document.getElementById(capaSubformulario).style;
		miFila.display=(miFila.display=="none")? "block" : "none";
		return false;
	}
}

//----------- Plegar y desplegar  - Ejemplo: Programación canales tv --------------------//
var menu = {
 load: function (strCapa){
 for(var yy=0;yy<8;yy++){
   var idUl=null;
   var elem=document.getElementById(strCapa + yy ).childNodes;
   var icono=elem[0].childNodes[0].childNodes[0];
   elem[0].childNodes[0].onclick=menu.desplegar
   var idUl=(elem[1].tagName=="UL")? 1:2;
   if(yy!=0){
    elem[idUl].style.display="none"
    icono.src="../../../images/ico_mas.gif"
   }else{
    icono.src="../../../images/ico_menos.gif"
   }
  }
 }, 
 desplegar: function (){
	subElem=this.parentNode.parentNode.childNodes
	idSubElem=(subElem[1].tagName=="UL")? 1:2;
	if(subElem[idSubElem].style.display=="none"){
		subElem[idSubElem].style.display="block"
		this.childNodes[0].src="../../../images/ico_menos.gif"
	}else{
		subElem[idSubElem].style.display="none"
		this.childNodes[0].src="../../../images/ico_mas.gif"
	}
  return false;
 }
}

//----------- Plegar y desplegar partes de formularios  - Ejemplo: Pasos de Contratación (HOGAR/Internet) --------------------//

var DESPLEGAR = {
	
	load: function ()
	{
		var aBloques = ["contratar_domicilio_desplegable1","contratar_domicilio_desplegable2","contratar_domicilio_desplegable3"];
		for(var i=0; i<aBloques.length; i++)
		{ document.getElementById(aBloques[i]).style.display="none"; }
		document.getElementById("domicilio_distinto").checked=false;
		
		document.getElementById("link_mas_datos").onclick = DESPLEGAR.intermediario; //("contratar_domicilio_desplegable1");return false;
		document.getElementById("link_mas_datos3").onclick = DESPLEGAR.intermediario;
		document.getElementById("domicilio_distinto").onclick = DESPLEGAR.envioDistinto;
	},
	
	intermediario: function()
	{
		var aElementos = [
			["link_mas_datos","contratar_domicilio_desplegable1"],
			["link_mas_datos3","contratar_domicilio_desplegable3"]
		];
		
		for(var i=0; i<aElementos.length; i++ )
		{
			if(aElementos[i][0]==this.id)
				DESPLEGAR.mostrar(aElementos[i][1]);
		}
		return false;
	},
	
	mostrar: function (elemento)
	{
		if(document.getElementById(elemento).style.display=="none")
			document.getElementById(elemento).style.display="block";
		else
			document.getElementById(elemento).style.display="none";
	},
	
	envioDistinto: function ()
	{
		DESPLEGAR.mostrar("contratar_domicilio_desplegable2");
		document.getElementById("contratar_domicilio_desplegable3").style.display="none";
	}
}

//----------- Redimiensionamiento iframes --------------------//
var gestionIframes={
	padreIframe:parent,
	aireVertical:25,
	redimension:function(frmDestino,frmOrigen,frm,aire){
		aire=(aire!=null)? aire:gestionIframes.aireVertical;
		document.getElementById(frmDestino).style.height = parseInt(parent.eval(frm).document.getElementById(frmOrigen).offsetHeight +aire)+ "px";
	},
	load: function(){
	window.document.scrollHeight = 0;
	}
}

//----------- Ficha de productos (ajax) --------------------//
var fichaProductos={

	script:"ficha.php",
	ordenImpresion:false,
	icoImp:"",
	v_pestania:"",
	num_pestania:"",
	load:function(){
		
		//alert("Funcion load FichaProductos");
		
		if(document.getElementById("iconos_servicios")) {
			document.getElementById("iconos_servicios").style.display="block"
			fichaProductos.icoIpr=document.getElementById("iconos_servicios").innerHTML;
		}
		
		//Modificado para pestania activa
		num_pestania=document.getElementById("pestania_activa");
		if (num_pestania != null)
		{
			v_pestania=num_pestania.value;
		
			PESTANIAS.load(v_pestania,"pestanias",null)
		
			e.addEvent(document.getElementById("iconos_servicios"), 'click', fichaProductos.imprimir, false);
			httpRequest.inicio()
		
			precargaTotal(v_pestania)	
		}				
	}, 
	estaPrecargado:function(){
		var cont=0;
		for (i in httpRequest.arrCompletados) {

			if(cont==PESTANIAS.totalPestanias.length-1){
				if(httpRequest.arrCompletados[i]==true){return true;
				}else{return true;}
				break;
			}
			cont++
		}
		return false;
	},
	imprimir:function (){
	//alert("Funcion imprimir FichaProductos");
		fichaProductos.ordenImpresion=true;
		document.getElementById("iconos_servicios").innerHTML=fichaProductos.icoIpr;
		
		if(fichaProductos.estaPrecargado()){
			
			if(document.getElementById("c1"))document.getElementById("c1").style.display="none"
			document.getElementById("contenedor_impresion").style.display="block"

			
			var txt="";
			for(x in httpRequest.arrCotentText){
				txt+="<div style='margin:5px;height:1%;'>" + httpRequest.arrCotentText[x] + "</div>"
			}

			//document.getElementById("contenedor_inferior_ficha").style.display="none"
			document.getElementById("contenedor_propio").style.display="none"
			document.getElementById("contenedor_impresion").innerHTML =txt

			window.print()
			
			document.getElementById("contenedor_impresion").style.display="none"
			//document.getElementById("contenedor_inferior_ficha").style.display="block"
			document.getElementById("contenedor_propio").style.display="block"
			
		}else{
			document.getElementById("iconos_servicios").innerHTML=document.getElementById("iconos_servicios").innerHTML + "<div id='c1' style='font:normal 0.625em Arial;color:#333'/> Carga...</div>"
		}
		
	
	}
}

e.addEvent(window, 'load', fichaProductos.load, false);
var est="";

function precargaTotal(p){
	//alert("Funcion precargaTotal FichaProductos: "+p);
	httpRequest.cargaDatosExternos(p,false,true)
}	

var	contPestania=0;

var httpRequest={

	obj:null,	                	   									
	idCapa:"",																																															
	id:0,	
	arrCotentText:[],
	arrCompletados:[],
	v_producto:"",
	codigo:"",
	valoridioma:"",
	v_idioma:"",
	valorseg:"",
	v_segmento:"",
	valorver:"",
	v_version:"",
	valorPrev:"",
	indPrev:"",
	v_pestania:"",
	num_pestania:"",
	v_contenido:"",
	
	inicio: function (){
		if(window.XMLHttpRequest){
			//alert("XMLHttpRequest");
			httpRequest.ajax= new XMLHttpRequest();
			
		}else if (window.ActiveXObject) {
			httpRequest.ajax= new ActiveXObject("Microsoft.XMLHTTP");
			//alert("Microsoft.XMLHTTP");
		}else{
			//alert("return false");
			return false;										
		}
		return true;											
	}, 

	
	
	
	cargaDatosExternos: function(id,escribir,precarTodo){
		
		idPeticion=(! isNaN(arguments[0]))? id:PESTANIAS.actual.substring(6,PESTANIAS.actual)
		//alert("Funcion cargaDatosExternos: "+idPeticion);
		codigo=document.getElementById("cod_producto")
		v_producto=codigo.value
		
		valoridioma=document.getElementById("idioma_producto")
		v_idioma=valoridioma.value 
		
		valorver=document.getElementById("version_producto")
		v_version=valorver.value 
		
		valorPrev=document.getElementById("previsualizacion_producto")
		indPrev=valorPrev.value 
		
		valorseg=document.getElementById("segmento_producto")
		v_segmento=valorseg.value
		
		num_pestania=document.getElementById("pestania_activa");
		v_pestania=num_pestania.value;
		
		//httpRequest.ajax.open("GET", "/on/jsp/onIntermedioProducto?ficha="+idPeticion+"&script=S&v_producto="+v_producto+"&v_idioma="+v_idioma+"&v_version="+v_version+"&v_segmento="+v_segmento+"&indPrev="+indPrev+"&menu_cab_sup="+menu_cab_sup+"&menu_izq="+menu_izq+"&nodo_izq="+nodo_izq,true);
		httpRequest.ajax.open("POST", "/on/jsp/onIntermedioProducto?ficha="+idPeticion+"&script=S&v_producto="+v_producto+"&v_idioma="+v_idioma+"&v_version="+v_version+"&v_segmento="+v_segmento+"&indPrev="+indPrev,true);
		
		try
		{
				httpRequest.ajax.onreadystatechange=function() {
					
					//alert("Funcion onreadystatechange FichaProductos");
					if (httpRequest.ajax.readyState==4 && httpRequest.ajax.responseText) {
						//alert("rellenamos: datos" + contPestania);
						//alert(httpRequest.ajax.responseText);
						httpRequest.arrCotentText["datos" + idPeticion]=httpRequest.ajax.responseText;
						httpRequest.arrCompletados["datos" + idPeticion]=true;
						//if(escribir || (precarTodo && idPeticion==0 )){
						if(escribir || (precarTodo && idPeticion==v_pestania )){	
						
							//document.getElementById("contenedor_inferior_ficha").innerHTML = httpRequest.arrCotentText["datos" + id]
							if (id == 2)
							{
								document.getElementById("contenedor_propio").innerHTML = httpRequest.arrCotentText["datos" + idPeticion]
							}
							else
							{
								//document.getElementById("contenedor_propio").innerHTML = "<div id='contenedor_inferior_ficha'>" + httpRequest.arrCotentText["datos" + idPeticion] + "</div>"
								setInnerHTMLAndExecScript(document.getElementById("contenedor_propio"),"<div id='contenedor_inferior_ficha'>" + httpRequest.arrCotentText["datos" + idPeticion] + "</div>");
							}
										
						}
						contPestania=parseInt(contPestania+1); 
						if(precarTodo && idPeticion<3){	
							aaa=parseInt(idPeticion+1);
							precargaTotal(aaa)
						}
						if(id==3 && fichaProductos.ordenImpresion){
							fichaProductos.imprimir()
						}
					}
				}
		
				//httpRequest.ajax.send(null)
				httpRequest.ajax.setRequestHeader('Content-Type','text/html; charset=ISO-8859-1');
				httpRequest.ajax.send("ficha="+idPeticion+"&script=S")
		}
		catch (err)
		{
			httpRequest.cargaDatosExternos(id,escribir,precarTodo)
		};         
	}, 
	escribe:function (id){
		id=(! isNaN(arguments[0]))? id:PESTANIAS.actual.substring(6,PESTANIAS.actual.length)
		//alert("Procesar id: "+id);
				
		if(httpRequest.arrCompletados["datos" + id]){	
			//document.getElementById("contenedor_inferior_ficha").style.display ="block"
			
			//
			
			//alert("El id que recibimos es: "+id);
			
			if (id == 2)
			{
				document.getElementById("contenedor_propio").innerHTML = httpRequest.arrCotentText["datos" + id]
			}
			else
			{
				document.getElementById("contenedor_propio").innerHTML = "<div id='contenedor_inferior_ficha'>" + httpRequest.arrCotentText["datos" + id] + "</div>"
			//document.getElementById("contenedor_inferior_ficha").style.display ="block"
			}
			
			//
			
			
			//document.getElementById("contenedor_inferior_ficha").innerHTML = httpRequest.arrCotentText["datos" + id]		
			
			//
			//var texto = document.getElementById("contenedor_propio").innerHTML	
			
			
			
			
			
			
		}else{
			//document.getElementById("contenedor_inferior_ficha").innerHTML = "<div style='position:relative;left:100px;margin:20px'><img src='/on/images/es/cargando.gif' alt='cargando datos, espere unos instantes'></div>"
			
			document.getElementById("contenedor_propio").innerHTML = "<div style='position:relative;left:100px;margin:20px'><img src='/on/images/es/cargando.gif' alt='cargando datos, espere unos instantes'></div>"
			httpRequest.cargaDatosExternos(id,true)
		}
	}
}


var PESTANIAS={	
	lasPestanias:null,
	classePestaniaActiva:"activo",
	classePestaniaOculta:"oculto",
	classePestaniaUltima:"ultimo_elemento",
	textos:[],
	totalPestanias:0,
	actual:-1,
	nodosValidos:null,
	nodosValidosH:null,
	nodosDef:null,
  destino:"",
  
	load:function(opcionActual,listadoPestanias,iframeDestino,otrasAcciones){	
		//alert("Funcion PESTANIAS FichaProductos");
		PESTANIAS.lasPestanias=document.getElementById(listadoPestanias);
		PESTANIAS.totalPestanias=PESTANIAS.lasPestanias.childNodes;
		
		var j = 0;
			
		while( j < PESTANIAS.totalPestanias.length ) {
			if ((PESTANIAS.totalPestanias[j].nodeName == "#text") || (PESTANIAS.totalPestanias[j].nodeName == "#comment"))
			{	
				PESTANIAS.lasPestanias.removeChild(PESTANIAS.totalPestanias[j]); 
			}
			else
			{
				j++;
			}	
		}
			
		
		var v = 0;
		
		for(var h=0;h<PESTANIAS.totalPestanias.length;h++){
		
			nodosValidos = PESTANIAS.totalPestanias[h].childNodes;
					
			while (v < nodosValidos.length)
			{
				if ( (nodosValidos[v].nodeName == "#text") || (nodosValidos[v].nodeName == "#comment"))
				{
					PESTANIAS.totalPestanias[h].removeChild(nodosValidos[v]);
				}
				else
				{
					v++;
				}
			}
			
			v = 0;
		}
		
		for(var x=0;x<PESTANIAS.totalPestanias.length;x++){		
		
			PESTANIAS.totalPestanias[x].childNodes[0].id="opcion" + x;
			
			PESTANIAS.textos[x]=PESTANIAS.totalPestanias[x].childNodes[0].firstChild.nodeValue;	
					
			PESTANIAS.totalPestanias[x].childNodes[0].onclick= PESTANIAS.marcado;
			
			e.addEvent(PESTANIAS.totalPestanias[x].childNodes[0], 'click', httpRequest.escribe, false);
			
		}
		
		PESTANIAS.totalPestanias[opcionActual].className=PESTANIAS.classePestaniaActiva;
		if(iframeDestino!=null){
			i_frame=eval(iframeDestino);
			i_frame.location.href=PESTANIAS.totalPestanias[0].childNodes[0].href;
		}
		
	},	

	marcado: function(init){
		//modificaciones realizadas para la redireccion con anclas 14/f/2007 10ok
		//alert("Funcion marcado FichaProductos");
		if(PESTANIAS.destino==""){
		    PESTANIAS.actual=this.id;
	  }else{
		    PESTANIAS.actual=PESTANIAS.destino;
		 }
		
		
		for(var y=0;y<PESTANIAS.totalPestanias.length;y++){
			if (PESTANIAS.totalPestanias[y].className!=PESTANIAS.classePestaniaOculta)
				PESTANIAS.totalPestanias[y].className="";
		};
		// 
		
		if(PESTANIAS.destino==""){
		    this.parentNode.className=PESTANIAS.classePestaniaActiva;
	  }else{
	  	  document.getElementById(PESTANIAS.destino).parentNode.className=PESTANIAS.classePestaniaActiva;
	  }	
		return false; 
	}
}
