//Funciones para mostrar 'cargando'

function MostrarCargando() {
    if (DivCuerpo) { DivCuerpo.style.display='none'; }
    if (DivCargando) { DivCargando.style.display=''; }
}

function QuitarCargando() {
    if (DivCuerpo) { DivCuerpo.style.display=''; }
    if (DivCargando) { DivCargando.style.display='none'; }
}

//funciones para la ruta de la cabecera
function AnadirRuta(psCad) {
    if (parent.frmCabecera)
    {
        if (parent.frmCabecera.document.all.TxtRuta) {     
            var cValor = parent.frmCabecera.document.all.TxtRuta.innerText;        
            if (cValor=='') {
                parent.frmCabecera.document.all.TxtRuta.innerText = psCad;
            }
            else {
                if (cValor.lastIndexOf(psCad)>=0) {
                    if (cValor.lastIndexOf(psCad)==cValor.length- psCad.length) {
                        return;
                    }
                }
                parent.frmCabecera.document.all.TxtRuta.innerText = cValor + '\\' + psCad;
            }    
        }   
    }
}

function QuitarUltimaRuta() {
    if (parent.frmCabecera)
    {
        if (parent.frmCabecera.document.all.TxtRuta) {     
            var cValor = parent.frmCabecera.document.all.TxtRuta.innerText;
            var i = cValor.lastIndexOf('\\');
            parent.frmCabecera.document.all.TxtRuta.innerText = cValor.substring(0,i);
        }
    }
}

function BorrarRuta() {
    if (parent.frmCabecera.document.all.TxtRuta) { 
        parent.frmCabecera.document.all.TxtRuta.innerText = '';
    }
}

// función para deshabilitar el backspace y que no puedan hacer atrás
function escBackSpace()  {
	if(event.keyCode == 8)
	   {
		  if  ( (document.activeElement.getAttribute("type") == "text") || (document.activeElement.getAttribute("type") == "textarea") || (document.activeElement.getAttribute("type") == "password") )
		   {
		   if (!document.activeElement.getAttribute("readonly")) {
			   return true;
			   }
		   }
			 event.cancelBubble=true;
			 event.returnValue=false;
	   }    
 }	
 

// función que controla el menú contextual del botón derecho del mouse
// cambiar el valor de la variable 'DeshabilitarMenuContextual' para permitir o no el menú contextual
function EscContextMenu()  {
	
	var DeshabilitarMenuContextual = false;
	
	event.cancelBubble=DeshabilitarMenuContextual;
	event.returnValue=!DeshabilitarMenuContextual;
	return !DeshabilitarMenuContextual;
}


function EscribirFechaActual() {
	
	var now = new Date();
	var dia = now.getDay();
	var mes = now.getMonth();
	var fecha;
	
	//el día de la semana
	if(dia==0){
	fecha="Domingo, ";
	}else if(dia==1){
	fecha="Lunes, ";
	}else if(dia==2){
	fecha="Martes, ";
	}else if(dia==3){
	fecha="Miércoles, ";
	}else if(dia==4){
	fecha="Jueves, ";
	}else if(dia==5){
	fecha="Viernes, ";
	}else{
	fecha="Sábado, ";
	}
	
	fecha = fecha + now.getDate() + ' de ';
	
	//El nombre del mes
	if(mes==0){
	fecha=fecha + "Enero"
	}else if(mes==1){
	fecha=fecha + "Febrero"
	}else if(mes==2){
	fecha=fecha + "Marzo"
	}else if(mes==3){
	fecha=fecha + "Abril"
	}else if(mes==4){
	fecha=fecha + "Mayo"
	}else if(mes==5){
	fecha=fecha + "Junio"
	}else if(mes==6){
	fecha=fecha + "Julio"
	}else if(mes==7){
	fecha=fecha + "Agosto"
	}else if(mes==8){
	fecha=fecha + "Septiembre"
	}else if(mes==9){
	fecha=fecha + "Octubre"
	}else if(mes==10){
	fecha=fecha + "Noviembre"
	}else{
	fecha=fecha + "Diciembre"
	}
	
	fecha = fecha + " del " + now.getYear();
	document.write(fecha);

}

function MaximizarVentana () {   
    window.moveTo(0,0);
    if (document.all) {
        top.window.resizeTo(screen.availWidth,screen.availHeight);
    }
    else if (document.layers||document.getElementById) {
        if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){
            top.window.outerHeight = screen.availHeight;
            top.window.outerWidth = screen.availWidth;
        }
    }
}

function BloquearCampos()
{
    var f = document.getElementsByTagName('input');
    for(var i=0;i<f.length;i++)
    {
        if(f[i].getAttribute('type')=='text' || f[i].getAttribute('type')=='checkbox' ||
           f[i].getAttribute('type')=='password' || f[i].getAttribute('type')=='radio' ||
           f[i].getAttribute('type')=='file' )
        {
            f[i].setAttribute('disabled',true)
        }
    }
    
    f = document.getElementsByTagName('select');
    for(var i=0;i<f.length;i++)
    {
        f[i].setAttribute('disabled',true);
    }
}

function PosicionarEnPrimerElemento()
{
    f=document.forms[0]; 
    for (var i=0;i<f.length ;i++) 
    { 
        try { 
            if (f[i].disabled!=true && f[i].readonly!=true && f[i].style.visibility!='hidden' && 
                f[i].style.display!='none' && f[i].type.toLowerCase()!='hidden') 
            {
                f[i].focus(); 
                return;
            } 
        } 
        catch(e) 
        { 
            continue; 
        } 
    }
}

function PonerMensajePorDefectoStatus() {
    window.defaultStatus = "Espinaler backoffice";
}

function abreVentana (pagURL, pagTarget, w, h) {
    var winLeft = (screen.width-w)/2;
    var winTop = (screen.height-h)/2;
    var propiedades = 'width='+ w;
    propiedades = propiedades +',height='+ h;
    propiedades = propiedades +',left='+ winLeft;
    propiedades = propiedades +',top='+ winTop;
    propiedades = propiedades +',fullscreen=no';
    propiedades = propiedades +',directories =no';
    propiedades = propiedades +',toolbar=no';
    propiedades = propiedades +',status=yes';
    propiedades = propiedades +',menubar=no';
    propiedades = propiedades +',scrollbars=yes';
    propiedades = propiedades +',resizable=yes';
    window.open(pagURL, pagTarget ,propiedades);
}

function abreVentanaMaximizada (pagURL, pagTarget) {
    var propiedades = 'width='+ (screen.availWidth - 10); 
    propiedades = propiedades +',height='+ (screen.availHeight - 56);
    propiedades = propiedades +',left=0'; 
    propiedades = propiedades +',top=0'; 
    propiedades = propiedades +',fullscreen=no';
    propiedades = propiedades +',directories =no';
    propiedades = propiedades +',toolbar=no';
    propiedades = propiedades +',status=yes';
    propiedades = propiedades +',menubar=no';
    propiedades = propiedades +',scrollbars=yes';
    propiedades = propiedades +',resizable=yes'; 
    window.open(pagURL, pagTarget ,propiedades);
}

function cerrar() 
{
    window.close();
    return false;
}

function volver() 
{
    history.back();
    return false;
}

function ConfigurarBotonVolverCerrar(boton) 
{
    
    if (history.length >0) 
    {
        if (boton) {
            boton.value = Texto('Volver');
            boton.onclick = volver;
        }
    }
    else 
    {
        if (boton) {
            boton.value = Texto('Cerrar');
            boton.onclick = cerrar;
        }
    }
}

function mostrar(nombreCapa){ 
    document.getElementById(nombreCapa).style.visibility="visible"; 
} 
function ocultar(nombreCapa){ 
    document.getElementById(nombreCapa).style.visibility="hidden"; 
} 

function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

function trim( value ) {
	return LTrim(RTrim(value));
}


//// no funciona
//function getRutaServidor()
//{

//    var i = 0;
//    var sRuta = document.location.protocol + "//" + document.domain;
//    var arrPathParts = document.location.pathname.split("/");

//    var numParts= arrPathParts.length;
//    
//    var numBarras = numParts-1;
//    
//    var maxLoop = (numParts < 3) ? 0 : numParts - 3;

//    for (i = 0; i <= maxLoop; i++) 
//    {
//        
//        alert("arrpathparts["+i+"]:"+arrPathParts[i] );
//        if(arrPathParts[i] != "") {
//            sRuta+= "/" + arrPathParts[i];
//        }
//    }

//    alert(sRuta);
//    return sRuta;
//}

function Mensaje(pMensaje, pParametros) {
	

	var oXmlHttp = CrearXMLHTTP();

// original:

	oXmlHttp.open(
		"POST",
		"webservices/wsidioma.asmx",
		false
	);
	
	
//    var sWebServicePath = getRutaServidor();

//	oXmlHttp.open(
//		"POST",
//		sWebServicePath + "/webservices/wsidioma.asmx",
//		false
//	);


	oXmlHttp.setRequestHeader("Content-Type", "text/xml");
    oXmlHttp.setRequestHeader("SOAPAction", "http://www.webservices.com/Mensaje");
    
    var sIdioma = ParamQueryString('lan');
    if (sIdioma=='') sIdioma='es';    

	var sLlamada = "<?xml version='1.0' encoding='utf-8'?> \
		<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \
			xmlns:xsd='http://www.w3.org/2001/XMLSchema' \
			xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
			<soap:Body> \
				<Mensaje xmlns='http://www.webservices.com/'> \
				    <pIdioma>" + sIdioma + "</pIdioma> \
					<pMensaje>" + pMensaje + "</pMensaje> ";
    
    if (pParametros!=null) {
        sLlamada = sLlamada +  " <pParametros> ";        
        for(i=0;i<pParametros.length;i++) {
            sLlamada = sLlamada +  " <string>";
            sLlamada = sLlamada +  pParametros[i];
            sLlamada = sLlamada +  "</string> ";
        }        
        sLlamada = sLlamada +  " </pParametros> ";
    }                  
    sLlamada = sLlamada +  " \
				</Mensaje> \
			</soap:Body> \
		</soap:Envelope> \
	";
    
    //alert(sLlamada);
    oXmlHttp.send(sLlamada);
    
    //alert(oXmlHttp.responseText);    
    //alert(oXmlHttp.responseXML.xml);
    
	return oXmlHttp.responseXML.selectSingleNode("//MensajeResponse").text;
}

function Texto(pMensaje) {

	var oXmlHttp = CrearXMLHTTP();

// original:

    oXmlHttp.open(
		"POST",
		"webservices/wsidioma.asmx",
		false
	);

//    var sWebServicePath = getRutaServidor();    

//    oXmlHttp.open(
//		"POST",
//		sWebServicePath + "/webservices/wsidioma.asmx",
//		false
//	);

	oXmlHttp.setRequestHeader("Content-Type", "text/xml");
    oXmlHttp.setRequestHeader("SOAPAction", "http://www.webservices.com/Texto");
    
    var sIdioma = ParamQueryString('lan');
    if (!sIdioma || sIdioma=='') sIdioma='es';

	var sLlamada = "<?xml version='1.0' encoding='utf-8'?> \
		<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \
			xmlns:xsd='http://www.w3.org/2001/XMLSchema' \
			xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
			<soap:Body> \
				<Texto xmlns='http://www.webservices.com/'> \
				    <pIdioma>" + sIdioma + "</pIdioma> \
					<pTexto>" + pMensaje + "</pTexto> \
				</Texto> \
			</soap:Body> \
		</soap:Envelope> \
	";
    
    //alert(sLlamada);
    
    oXmlHttp.send(sLlamada);
    
    //alert(oXmlHttp.responseText);    
    //alert(oXmlHttp.responseXML.xml);
    
	return oXmlHttp.responseXML.selectSingleNode("//TextoResponse").text;
}

function CrearXMLHTTP()
{
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
     try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       xmlhttp = false;
      }
     }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	    try {
		    xmlhttp = new XMLHttpRequest();
	    } catch (e) {
		    xmlhttp=false;
	    }
    }
    if (!xmlhttp && window.createRequest) {
	    try {
		    xmlhttp = window.createRequest();
	    } catch (e) {
		    xmlhttp=false;
	    }
    }
    
    return xmlhttp;
}



/*  FUNCIONES PARA ACCEDER A LA QUERYSTRING */

//this is to store the key value pairs of the querystring    
function qsObject(){
    this.objects = new Array();
    this.add = _add;
    this.remove =_remove;
    this.item = _item;
    this.populateCollection =_populateCollection;
    this.setRawString = _setRawString;
    this.rawString ="";
    
    this.setRawString();
    this.populateCollection();
    
    // to add items to the array
    function _add(obj){
        this.objects[this.objects.length] = obj;
    }
    //to remove items from the array
    function _remove(index){
        this.objects.splice(index, 1);
    }
    //gets a reference to an item object
    function _item(searchKey){
        searchKey = new String(searchKey);
        searchKey = searchKey.toLowerCase();
        for(i=0;i<this.objects.length;i++){
            //the current key in the coll
            var key = this.objects[i].key;
            key = new String(key);
            key = key.toLowerCase();
            
            if(key == searchKey){
                return this.objects[i];
            }
        }
        return '';
    }
    
    function _setRawString(){
        //Create regular expression object to retrieve the qs part
        // Used regex 'cause the search property on the location object includes the bookmark stuff
        var qsReg = new RegExp("[?][^#]*","i");  
        hRef = unescape( window.location.href);
        var qsMatch = hRef.match(qsReg);  
        //removes the question mark from the url 
        qsMatch = new String(qsMatch);
        qsMatch = qsMatch.substr(1, qsMatch.length -1);        
        this.rawString = qsMatch;        
    }
    
    //takes a string and populates the array with the key/value pairs
    function _populateCollection(rawString){
        this.rawString = new String(this.rawString);
        var rootArr = this.rawString.split("&");
        for(i=0;i<rootArr.length;i++){
            var tempArr =  rootArr[i].split("=");
            if(tempArr.length ==2){
                tempArr[0] = unescape(tempArr[0]);
                tempArr[1] = unescape(tempArr[1]);
                
                this.add(new qsValue(tempArr[0], tempArr[1]));
            }
        }
    }
    
    function qsValue(key, value){
        this.key = key;
        this.value=value;    
    }     
}    
    
function ParamQueryString(pParam){
    var qs= new qsObject(); 
    return qs.item(pParam).value; 
}

function PlegarDesplegarArbol(elem)
{
    if  (document.getElementById("ctl00_ArbCatalogo_divItem_" + elem).style.display == 'none'){
        document.getElementById("ctl00_ArbCatalogo_divItem_" + elem).style.display = '';
        //document.getElementById("ctl00_ArbCatalogo_imgItem_" + elem).src = 'imagenes/menu_menos.gif';
    }else{
        document.getElementById("ctl00_ArbCatalogo_divItem_" + elem).style.display = 'none';
        //document.getElementById("ctl00_ArbCatalogo_imgItem_" + elem).src = 'imagenes/menu_mas.gif';
    }
}

function DefaultButtonKeyPress(evt, thisElementName, errorMsg) 
{

      var keyCode;
      keyCode = (window.event) ? evt.keyCode : evt.which;      
      
    if (keyCode == 13)
    {    
        var elem = (evt.srcElement)? evt.srcElement : evt.target;

        if (trim(elem.value) =='') 
        {
            alert(errorMsg);
            elem.value='';
            elem.focus();
            return false;
        }
        //alert('post back href: ' +      document.getElementById(thisElementName).href);
        location = document.getElementById(thisElementName).href;
        return false;
    }
    else
    {
        return true;
    }
}
    