﻿// JScript File
var strCtrl;
var items;
var httpReq = null;
var Content;


function getJSON(url,cont)
{
}


function getXML(url,cont)
{     



    if (cont == null)
    {
        Content=0;
    }
    //AjaxExec(url);
	//Si es Mozilla, Opera o safari (entre otros que lo soportan como objeto nativo del navegador)			

    if (window.XMLHttpRequest)
    {	        
	    httpReq = new XMLHttpRequest();
    }
    else	//Internet Explorer lo expone como control Active X
    {
	    httpReq = new ActiveXObject('Microsoft.XMLHTTP');
	    //httpReq = new ActiveXObject("MSXML2.XMLHTTP.3.0");

    }
    //Ya debería tener una referencia al objeto
        
    if (httpReq != null)
    {        
	    httpReq.onreadystatechange = finCarga;
	    //httpReq.open('GET', url, true);	//El true del final es para que lo solicite de forma asíncrona 
	    // Nota: Se ha cambiado a false ya que no procesa correctamante dos peticiones seguidas como es el caso de rellenar el
	    // Combo de Marcas y Modelos. No Cambiar.
	    httpReq.open('GET', url, true);	//El true del final es para que lo solicite de forma asíncrona
	    httpReq.send(null);	//al ser una petición GET no va nada en el cuerpo de la petición, de ahí el null
    }    	
}


function getXMLSincrona(url)
{     

    //AjaxExec(url);
	//Si es Mozilla, Opera o safari (entre otros que lo soportan como objeto nativo del navegador)			
    if (window.XMLHttpRequest)
    {	        
	    httpReq = new XMLHttpRequest();
    }
    else	//Internet Explorer lo expone como control Active X
    {
	    httpReq = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //Ya debería tener una referencia al objeto
        
    if (httpReq != null)
    {        	    
	    httpReq.open('GET', url, false);	//El true del final es para que lo solicite de forma asíncrona
	    httpReq.send(null);	//al ser una petición GET no va nada en el cuerpo de la petición, de ahí el null
	    return httpReq.responseXML;
    }    	
}

//Función que se ejecuta cuando cambia el estado de la carga del objeto httpReq
function finCarga()
{
 
    var oItem;
    if (httpReq.readyState == 4)	//4: completado, 3: en curso, 1:cargado, 0: no iniciado
    {
	    if (httpReq.status == 200)	//200: OK (código HTTP, podría haber sido 404 (no encontrado), 500 (error), etc...)
	    {		
	        items = httpReq.responseXML.getElementsByTagName('item');	//Coge sólo los elementos "item"            	                
	        if (Content == 0)
	        {
	        ProcesaItems();	        
	        }
	        else
	        {
	         AddFavorites();
	        }
	    }
	    else	//Se produjo un error
	    {
		    alert("No se pudo recuperar la información de la lista secundaria: " + httpReq.statusText);
	    }
    }	
}

function ProcesaItems()
{
 
    listaSec = document.getElementById(strCtrl);	    	    
	if (listaSec != null)
	{	    
	    listaSec.options.length = 0;	//Vacía la lista de opciones
		//Cargamos las nuevas opciones
		for(i=0; i<items.length; i++)
		{		    
		    var opc = document.createElement('OPTION');		    
		    opc.text = items[i].getAttribute('text');
			opc.value = items[i].getAttribute('value');						
			listaSec.options.add(opc);			
		}	
		listaSec.selectedindex=0;
	 }	
}

function AddFavorites()
{

  lnumfav= document.getElementById(lblNumFav);  // label con favoritos del usuario
    
  if (items[0].getAttribute('value') == 0)
  {
        lnumfav.innerText = NumFav + 1;  // incrementamos en 1 el numero de favoritos
        Resp = 0 ;         // añadido a favoritos
  }
  else if (items[0].getAttribute('value') == 1)
  {
     Resp = 1;  // ya era uno de tus favoritos
  }
  else
  {
     Resp = 2;  // error al insertar
  }

}


function AjaxCreate(){ 
    var vers = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"]; // all available IE ActiveXes 

    if(typeof XMLHttpRequest=='undefined'){ // check if its not FIREFOX                                         
        for(var a=0; a<vers.length; a++){
            try { 
                    var XMLHttp = new ActiveXObject(vers[a]); // found good activeX, so return new! 
                    return XMLHttp; 
            }catch(dummy){ 
            } 
    } 
    }
    else{ 
        return new XMLHttpRequest; //firefox, return new XMLHttpRequest 
    } 
    return false; 
} 

function AjaxExec(url){ 
        var handler = AjaxCreate(); 
        if(!handler){ 
            alert("Ajax could not be created!"); 
            return false; 
        }         
        handler.onreadystatechange = function() { // executes this whenever the ajax's stage changes 
                var state = handler.readyState; // connection state, 0-uninitialized,1-loading,2-loaded,3-interactive,4-complete 
                alert(state);                
                if(state==4){ // We have response from server 
                    alert(handler.responseText); //alert for now, this is the last thing that is executed! 
                }
        };                
        handler.open("GET", url, true); //send request                                  
        //handler.setRequestHeader('Accept','message/x-jl-formresult')
        handler.send(); 
} 


// Function create popup
//location=0|1  Specifies whether to display the address line in the new window.  
//directories=0|1  Specifies whether to display the Netscape directory buttons.  
//status=0|1  Specifies whether to display the browser status bar.  
//menubar=0|1  Specifies whether to display the browser menu bar.  
//scrollbars=0|1  Specifies whether the new window should have scrollbars.  
//resizable=0|1  Specifies whether the new window is resizable. 
//width=pixels  Specifies the width of the new window.  
//height=pixels  Specifies the height of the new window.  
//top=pixels  Specifies the Y coordinate of the top left corner of the new window
//left=pixels  Specifies the X coordinate of the top left corner of the new window
function popUpName(URL, nom, auxWidth, auxHeight, auxLeft, auxTop, scBars, rsize, mbar, status, dtories, loction) 
{
    try{
        features ="left="+auxLeft;
        features+=",top="+auxTop;
        features+=",width="+auxWidth;
        features+=",height="+auxHeight;
        features+=",scrollbars="+scBars;
        features+=",resizable="+rsize;
        features+=",menubar="+mbar;  
        features+=",status="+status;
        features+=",directories="+dtories;
        features+=",location="+loction;      
          
          
        popup = window.open(URL, nom ,features);
        if (popup != null){
            popup.focus();
        }    
     }catch(e){}   
 }



/**
* Function Crea el ObjetoXMLHttpRequest
* @auhtor maldan
* @date 18-09-2007
* @see sin referencias
* @return XMLHttpRequest
*/
function XMLHttpRequestCreate(){ 
    var XMLHttp
    // Si es Mozilla, Opera o safari (entre otros que lo soportan como objeto nativo del navegador)			
    if (window.XMLHttpRequest)
    {	        
	    XMLHttp = new XMLHttpRequest();
    }
    else	//Internet Explorer lo expone como control Active X
    {
	    XMLHttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
	return  XMLHttp;   
}

/**
* Function getDataXML
* @auhtor maldan
* @date 18-09-2007
* @Param url 
* @Param cont
* @Param funtionName 
* @see sin referencias
* @return XMLHttpRequest
*/
function getDataXML(url,cont, functionName){
	var Content;
	var httpReq;
  if (cont == null){
        Content = 0;
    }
		httpReq =XMLHttpRequestCreate();
    // Ya debería tener una referencia al objeto
    if (httpReq != null){        
			httpReq.onreadystatechange = function() { // executes this whenever the ajax's stage changes 
					// connection state, 0-uninitialized,1-loading,2-loaded,3-interactive,4-complete 
					if( httpReq.readyState == 4){ // We have response from server 
						if ( httpReq.status == 200)	//200: OK (código HTTP, podría haber sido 404 (no encontrado), 500 (error), etc...)
						{		
							//alert( httpReq.responseText); //alert for now, this is the last thing that is executed! 
							eval(functionName);
						 } 
					}
        };
	    //httpReq.open('GET', url, true);	//El true del final es para que lo solicite de forma asíncrona 
	    // Nota: Se ha cambiado a false ya que no procesa correctamante dos peticiones seguidas como es el caso de rellenar el
	    // Combo de Marcas y Modelos. No Cambiar.
	    httpReq.open('GET', url, true);	//El true del final es para que lo solicite de forma asíncrona
	    httpReq.send(null);	//al ser una petición GET no va nada en el cuerpo de la petición, de ahí el null
    }    	
}

function checkServerError(Items, blnMustHaveItems) {
    var blnOk = true;
    
    if (Items.length==0) {
        if (blnMustHaveItems) {
            blnOk = false;
        }
    } else {
        if (Items[0].getAttribute("value") == "-999;") {
            var text = Items[0].getAttribute("text");
            if (text) window.alert (text);
            blnOk = false;
        }
    }
    
    return blnOk;
}

function getResponseItems(oXMLRespuesta, blnMustHaveItems) {
    if (oXMLRespuesta) {
        Items = oXMLRespuesta.getElementsByTagName('item');
        if (checkServerError(Items, blnMustHaveItems)) return Items;
    }
}

function callExternalAJAX(url){
    var lib=document.createElement('script'); 
    lib.src=url; 
    lib.type="text/javascript"; 
    document.getElementsByTagName("HTML")[0].getElementsByTagName("HEAD")[0].appendChild(lib); 
}