 
// Peticiones AJAX..............................................................
//.............................................................................. 

	function ajaxobj() {
		try {
			_ajaxobj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				_ajaxobj = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				_ajaxobj = false;
			}
		}
	   
		if (!_ajaxobj && typeof XMLHttpRequest!='undefined') {
			_ajaxobj = new XMLHttpRequest();
		}
		
		return _ajaxobj;
	} 
 
 function makeRequest(url,pars,funcion,tipo,debug,funerror) {
	var http_request = ajaxobj();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
      // Ver nota sobre esta linea al final
    } 

    //Si la ventana existe y no es una url restringida, la enseñamos en cada peticion a bbdd
    if ((typeof(cargando2) != "undefined")&&
        (url.indexOf('xsesion.info_sesion.xml') == -1)&&
        (url.indexOf('xweb_servicios_sup.lista.xml') == -1)
       ){
      cargando2.visible('on');
    }
     
    if (!http_request) {
        alert('Abandonando :( No se puede crear una instancia XMLHTTP');
        return false;
    }
    http_request.onreadystatechange = function () {
      if (http_request.readyState == 4) {
          if ((http_request.status == 200)||(http_request.status == 0)) {
             switch(tipo){
               case 'TEXT': {
                  funcion(http_request.responseText);
                  break;
               }
               case 'JSON':{
                  ControlErrores(funcion,xml2json.parser(http_request.responseText),http_request.responseText,funerror);
                  break;
               }
               case 'XML':{
                  ControlErroresXML(funcion,xml2json.parser(http_request.responseText),http_request.responseXML);
                  break;
               }
             }
          } else {
            if ((http_request.status != '12152' && http_request.status != '12030')|| 1==1) {    
                if (typeof(cargando2) != "undefined"){
                  cargando2.display({descripcion:"Error: "+http_request.status+" de comunicación con el servidor",
                                     boton_visible:true,
                                     gif_visible:true,
                                     img:'error'});
                }else{
                  alert("Error: "+http_request.status+" de comunicación con el servidor");
                }
            } else {
                makeRequest(url,pars,funcion,tipo,debug,funerror);
            }  
          }
      }
  }
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http_request.send(pars);
    
    if(debug){
      window.open(url+'?'+pars);
      alert(url+'?'+pars);
    } 
}

// Control Errores en JSON
function ControlErrores(funcion,data,dataText,funerror){
  if(data.error){
  
   switch (data.error.code){
     case 'ACCNOE':{
        if (typeof(cargando2) != "undefined"){
           cargando2.visible('off');
         }
        alert("La petición no está declarada en la tabla de acciones");
        break;
      }
      case 'SESCAD':{
		if (typeof(cargando2) != "undefined") {
			cargando2.display({
				descripcion: 'Sesión caducada',
				boton_visible: true,
				gif_visible: true,
				img: 'error'
			});

			if (self != top) {
				// Redireccion especial para canal Halcon.com:
				cargando2.onclick({
					func: "window.location = 'http://www.pepephone.com/ppm_web/ppm_web/1/alta/xweb_sesion_operacion.lista_alta.html?p_canhal=S';"
				});
			} else {
				// Redireccion normal:
				cargando2.onclick({
					func: "window.location = 'http://www.pepephone.com/ppm_web/ppm_web/1/alta/xweb_sesion_operacion.lista_alta.html';"
				});
			}

			cargando2.visible('on');
		} else {
			alert('Sesión caducada');
			if (self != top) {
				// Redireccion especial para canal Halcon.com:
				window.location = 'http://www.pepephone.com/ppm_web/ppm_web/1/alta/xweb_sesion_operacion.lista_alta.html?p_canhal=S';
			} else {
				// Redireccion normal:
				window.location = 'http://www.pepephone.com/ppm_web/ppm_web/1/alta/xweb_sesion_operacion.lista_alta.html';
			}
		}
        return false;        
        break;
      }
      default:{
        if (typeof(cargando2) != "undefined"){
          cargando2.display({descripcion:data.error.code+' '+data.error.message,
                             boton_visible:true,
                             gif_visible:true,
                             img:'error'});
        }else{
          alert(data.error.code+' '+data.error.message);
        }
        break;
      }    
    }
    if(funerror){
      funerror(data);
    }  
  } else {
    if (data.pre){
      if (typeof(cargando2) != "undefined"){
        cargando2.visible('off');
      } 
      alert(dataText);
      if(funerror){
        funerror();
      }
    } else { 
      funcion(data);
    }
  }    
}


// Petición bd
function PeticionBD(url,pars,funcion,funerror){
      this.url = "/ppm_web/ppm_web/1/"+url;
      this.pars = pars;
      this.funcion = funcion;
      this.funerror= funerror;    
    
      this.Iniciar=function(valor,debug){
        var vPars="";
        if (this.pars!="null"){
          for(k=0; this.pars.length-1>k; k++){
            vPars+=this.pars[k]+"="+valor[k]+"&";
          }
          vPars+=this.pars[k]+"="+valor[k];
        }
        makeRequest(this.url,vPars,this.funcion,"JSON",debug,this.funerror);
      }
      this.IniciarCopiaForms=function(forms,debug){
        var vPars="";
        for(k=0; forms.length>k;k++){
          if(document.getElementById(forms[k])){
            var formulario = document.getElementById(forms[k]).elements;
          } else {
            alert("No existe un formulario con ID="+forms[k]);
            return false;
          }
          for (kk=0;this.pars.length>kk;kk++){
            if (formulario[pars[kk]]){
              if (formulario[pars[kk]].type == "checkbox"){
                if (formulario[pars[kk]].checked){
						      vPars+=this.pars[kk]+"=S&";
					      }else{
						      vPars+=this.pars[kk]+"=N&";					  
					      }
              } else {
                vPars+=this.pars[kk]+"="+formulario[pars[kk]].value+"&";
              }
            }
          }
        }
        if(vPars.substring(vPars.length-1)=="&"){
          vPars= vPars.substring(0,vPars.length-1)
        }
        makeRequest(this.url,vPars,this.funcion,"JSON",debug,this.funerror);
      }
      this.EventoError=function (funerror){
      this.funerror=funerror;
      }
}

//Combos Dinamicos..............................................................
//..............................................................................
//var rellenaIdCombo,rellenaTodos;
function rellena_combo(pIdCombo,pSeq,pFiltros,pTodos,pTipo,pDefault,pdebuger){
  var rellenaIdCombo = document.getElementById(pIdCombo);
  var rellenaTodos = pTodos;
  var rellenaTipo = pTipo;
  var valorDefault = pDefault;
  
  if(!rellenaIdCombo){
    ventana.alert("No existe ningún combo con el id="+pIdCombo);
    return false;
  }
  if(rellenaIdCombo.type!="select-one"){
    ventana.alert("el "+ pIdCombo+" No es un select");
    return false;
  }
  
  for (j=rellenaIdCombo.options.length;j>=0;j--){
	  rellenaIdCombo.remove(j); 
	}
  rellenaIdCombo.options[0]=new Option("Cargando....","");
   
  var rellena_combo_datos=function(datos){
    var hijos = NumeroHijos(datos.lov.item);
    var i=0;
    
    if (hijos==0){
      rellenaIdCombo.options[i]=new Option("No existen valores","");
      return false;
    }
    if (rellenaTodos){
      rellenaIdCombo.options[i]=new Option("","");
      i++;
    }
    if(hijos==1){
      if(rellenaTipo=="Tipo2"){
        rellenaIdCombo.options[i]=new Option("("+datos.lov.item.cod+") "+datos.lov.item.des,datos.lov.item.cod);
      } else {
        rellenaIdCombo.options[i]=new Option(datos.lov.item.des,datos.lov.item.cod);
      }  
    } else {
      if(rellenaTipo=="Tipo2"){
         for(rc=0;hijos>rc;rc++){
          rellenaIdCombo.options[rc+i]=new Option("("+datos.lov.item[rc].cod+") "+datos.lov.item[rc].des,datos.lov.item[rc].cod);
        }         
      } else {
        for(rc=0;hijos>rc;rc++){
          rellenaIdCombo.options[rc+i]=new Option(datos.lov.item[rc].des,datos.lov.item[rc].cod);
        }
      }
    }
    if (valorDefault != ''){
      rellenaIdCombo.value = valorDefault;
    }  
  }
  
  var Combo = new PeticionBD("xlov.lista.xml",["p_codent","p_desbus","p_filtro","p_numpag","p_numreg"],rellena_combo_datos);
  Combo.Iniciar([pSeq,rellenaIdCombo.name,pFiltros,1,100],pdebuger);
}

function NumeroHijos(pJson){
  if(!pJson){
    return 0;
  }
  if(!pJson.length){
   return 1;
  }else{
   return pJson.length;
  } 
}

//...............LOADING........................................................
//..............................................................................

function Cargando_O(){
  this.estado = 'off';
  this.divlng = document.createElement('div');
  
  
  this.divlng.style.visibility="hidden";
  this.divlng.id="div_cargando";
  this.divlng.appendChild(document.createTextNode('Cargando '));
  
  var imagen = document.createElement("img");
  imagen.src="/img/loading2.gif";
  this.divlng.appendChild(imagen);
  
  var bodylng = document.getElementsByTagName('body')[0];
  bodylng.appendChild(this.divlng);
  
  this.visible= function (estado){
    if (estado == 'off') {
      this.divlng.style.visibility="hidden";
    } else {
      this.divlng.style.visibility="visible";
    }
  }
}


// CONSTRUCTOR DE LA VENTANA CARGANDO
//
//  Ejemplo de llamada:
//
// Loading = new VentanaCargando({descripcion:"Cargando..."});
//   "descripcion" es solo la descripcion de inicio
// para cambiar el contenido usar el metodo display

function VentanaCargando(objPar){
  
  //Paths a imagenes 
  var pathImg = "/img/cargando/pepephone_imagen.gif";
  var pathGif = "/img/cargando/ajax-loader.gif";
  var pathBtn = "/img/cargando/continuar.gif";
  var pathBtnC = "/img/volver.gif";
  var pathErr = "/img/cargando/error.gif";
  var pathOk  = "/img/cargando/button_ok.gif";
  var pathcConf  = "/img/confirm.gif";
  
  //Recogemos de parametro el texto inicial de la caja cargando
  var desc = objPar.descripcion;
  
  this.estado = 'off';
  
  //Estado inicial: con el gif cargando, 
  //                con el texto de entrada de la creacion del objeto, 
  //                y sin boton
  //  GUARDAMOS TEXTO INICIAL
  this.msginicial = objPar.descripcion;
  
  //Compatibilidad IE6
  /*if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			document.getElementsByTagName('html')[0].style.height="100%";
			document.getElementsByTagName('html')[0].style.width="100%";
			document.body.style.height="200%";
			document.body.style.width="100%";
			document.body.style.overflow="hidden";
			
			
  }*/
  
  //DIV de fondo transparente
  this.divOverlay = document.createElement('div');
  
  

  this.divOverlay.style.display="none";

  this.divOverlay.id="TB_overlay";
  if(tb_detectMacXFF()){
			this.divOverlay.className="TB_overlayMacFFBGHack";
		}else{
			this.divOverlay.className="TB_overlayBG";
		}
  
  //DIV root de la ventana cargando
  this.divWindow = document.createElement('div');
  
  

  //this.divWindow.style.visibility="hidden";

  this.divWindow.style.display="none";

  this.divWindow.id="TB_window";
  this.divWindow.style.marginLeft = "-240px";
  this.divWindow.style.marginTop = "-155px";
  this.divWindow.style.width = "480px";

  //this.divWindow.style.display = "block";

  
  
    //IMAGEN
    var imagen = document.createElement("img");
    imagen.id="TB_image";
    imagen.alt="Tu petición se está procesando, por favor espera...";
    imagen.style.marginLeft="15px";
    imagen.style.marginTop="15px";
    imagen.src=pathImg;
    this.divWindow.appendChild(imagen);
    
    //Span que contiene el GIF CARGANDO
    var load = document.createElement("span");
    load.style.position = 'relative';
    load.style.top = "-190px";
    load.style.left = "123px"; 
    //load.style.visibility = "visible";
    
      var gif_cargando = document.createElement("img");
      gif_cargando.id = "IdGif_Cargando";
      gif_cargando.border="0";
      gif_cargando.alt="cargando";
      gif_cargando.src=pathGif;
      load.appendChild(gif_cargando);
        
      
    this.divWindow.appendChild(load);
  
    //DIV Inferior
    var divCaption = document.createElement('div');
    //divCaption.style.height = "75px"; //altura forzada para que quepan descripciones largas
    divCaption.id="TB_caption";
    
    
      //DIV que contiene la descripcion
      var texto_des = document.createElement("div");
      texto_des.id = 'TB_desc'
      texto_des.style.width = '450px';
      //texto_des.style.height = '50px';
      texto_des.style.overflow = 'auto';
      texto_des.appendChild(document.createTextNode(desc));
      divCaption.appendChild(texto_des);
      
      //DIV secondline
      var divSecondLine = document.createElement('div');
      divSecondLine.id="TB_secondLine";
      divCaption.appendChild(divSecondLine);
  
      
      //DIV BOTON
      var divCloseWindow = document.createElement('div');
      divCloseWindow.id="TB_closeWindow";

      divCloseWindow.style.display = 'none'; //Oculto de primeras

      
      
        //elemto enlace
        var enlace_cont = document.createElement('a');
        //el boton continuar devuelve el texto inicial a la ventana
        //aparte de ocultar las dos capas que forman la ventana

        enlace_cont['onclick'] = new Function("document.getElementById('TB_window').style.display ='none';document.getElementById('TB_overlay').style.display  ='none';document.getElementById('TB_desc').innerHTML='"+this.msginicial+"';document.getElementById('TB_closeWindow').style.display = 'none';document.getElementById('IdGif_Cargando').style.display = 'inline';document.getElementById('IdGif_Cargando').src='" +pathGif + "';");

        enlace_cont.id = 'TB_closeWindowButton';
        enlace_cont.href="#";
        enlace_cont.title = 'Close';
        
          
          //elemento imagen
          var btn_continuar = document.createElement('img');
          btn_continuar.src = pathBtn;
          btn_continuar.border = "0";
          enlace_cont.appendChild(btn_continuar);
        
        divCloseWindow.appendChild(enlace_cont);  
//
      var divCloseWindow2 = document.createElement('div');
      divCloseWindow2.id="TB_closeWindowC";

      divCloseWindow2.style.display = 'none'; //Oculto de primeras

      
      
        //elemto enlace
        var enlace_cont2 = document.createElement('a');
        //el boton continuar devuelve el texto inicial a la ventana
        //aparte de ocultar las dos capas que forman la ventana

        enlace_cont2['onclick'] = new Function("document.getElementById('TB_window').style.display ='none';document.getElementById('TB_overlay').style.display  ='none';document.getElementById('TB_desc').innerHTML='"+this.msginicial+"';document.getElementById('TB_closeWindow').style.display = 'none';document.getElementById('IdGif_Cargando').style.display = 'inline';document.getElementById('IdGif_Cargando').src='" +pathGif + "';document.getElementById('TB_closeWindowC').style.display = 'none';cargando2.onclickReinit();");

        enlace_cont2.id = 'TB_closeWindowButtonC';
        enlace_cont2.href="#";
        enlace_cont2.title = 'Close';
        
          
          //elemento imagen
          var btn_continuar = document.createElement('img');
          btn_continuar.src = pathBtnC;
          btn_continuar.border = "0";
          enlace_cont2.appendChild(btn_continuar);
        
        divCloseWindow2.appendChild(enlace_cont2); 
      divCaption.appendChild(divCloseWindow2);
//		
		 
          
      divCaption.appendChild(divCloseWindow);
      
    this.divWindow.appendChild(divCaption);
  
  
  var bodylng = document.getElementsByTagName('body')[0];
  bodylng.appendChild(this.divOverlay);
  bodylng.appendChild(this.divWindow);
  
  //funcion para ocultar
  this.visible= function (estado){
    if (estado == 'off') {

      this.divOverlay.style.display ="none";

      this.divWindow.style.display  ="none";

    } else {
    
    

      this.divOverlay.style.display ="inline";

      this.divWindow.style.display  ="inline";

    }
  }
  
  //funcion para mostrar boton
  //
  // params entrada: 
  // objeto tipo {descripcion: texto nuevo, 
  //              boton_visible: booleano por si queremos boton de cerrar,
  //              gif_visible: booleano por si queremos ocultar el gif animado,
  //              img: imagen }
  this.display = function(objParHecho) {
    
    //descripcion
    document.getElementById('TB_desc').innerHTML=objParHecho.descripcion;
    
    //Boton continuar
    if (objParHecho.boton_visible){

      document.getElementById('TB_closeWindow').style.display = "inline";

    }else {

      document.getElementById('TB_closeWindow').style.display = "none";

    }
    
    //Gif visible
    if (objParHecho.gif_visible){

      document.getElementById('IdGif_Cargando').style.display = "inline";

    }else {

      document.getElementById('IdGif_Cargando').style.display = "none";

    }
    
    //imagen  (los paths estan definidos en la cabecera de la definicion del objeto)
    switch (objParHecho.img){
        case 'cargando':  
                          document.getElementById('IdGif_Cargando').src = pathGif;
                          break;
        case 'error':  
                      document.getElementById('IdGif_Cargando').src = pathErr;
                      break;
        case 'ok':  
                      document.getElementById('IdGif_Cargando').src = pathOk;
                      break;
		case 'aviso': 					   
					  document.getElementById('IdGif_Cargando').src = pathcConf;
					  break;  					                        
        default: document.getElementById('IdGif_Cargando').src = pathGif;
                 break;
    }
  }
  
  //metodo que cambia el evento onclick del boton continuar, 
  //por si necesitamos hacer un control de la ventana cargando
  this.onclick = function (objParonclick){

     document.getElementById("TB_closeWindowButton")['onclick'] = new Function("document.getElementById('TB_window').style.display ='none';document.getElementById('TB_overlay').style.display  ='none';document.getElementById('TB_desc').innerHTML='"+this.msginicial+"';document.getElementById('TB_closeWindow').style.display = 'none';document.getElementById('IdGif_Cargando').style.display = 'inline';document.getElementById('IdGif_Cargando').src='" +pathGif + "';" + objParonclick.func + "document.getElementById('TB_closeWindowC').style.display = 'none';cargando2.onclickReinit();");

  }
  
  //reinicio del evento onclick
  this.onclickReinit = function (){

     document.getElementById("TB_closeWindowButton")['onclick'] = new Function("document.getElementById('TB_window').style.display ='none';document.getElementById('TB_overlay').style.display  ='none';document.getElementById('TB_desc').innerHTML='"+this.msginicial+"';document.getElementById('TB_closeWindow').style.display = 'none';document.getElementById('IdGif_Cargando').style.display = 'inline';document.getElementById('IdGif_Cargando').src='" +pathGif + "';");

  }    
  
  // params entrada: 
  // objeto tipo {descripcion: texto nuevo, 
  //              func: booleano por si queremos boton de cerrar}  
  this.confirm = function(objParHecho) {
	    
    //descripcion
    document.getElementById('IdGif_Cargando').src = pathcConf;
    document.getElementById('TB_desc').innerHTML=objParHecho.descripcion;
    document.getElementById('TB_closeWindow').style.display = "inline";
    document.getElementById('TB_closeWindowC').style.display = "inline";
    document.getElementById('IdGif_Cargando').style.display = "inline";
    cargando2.onclick({func:objParHecho.func});

  }  
}



//compatibilidad estilos mac
function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


//Definicion de objeto auxiliar falso para contener el funcionamiento del cargando
function VentanaCargandoProv(objPar){

this.visible= function (estado){ return false;}
this.display = function(objParHecho) {return false;}
this.onclick = function (objParonclick) {return false;}
}