function not_null(pctl, pmsg){
   if (pctl.value == "") { alert(pmsg); pctl.focus(); return false; }
   return true;
}

function check_longitud_maxima(pctl, plen, pmsg) {
   if (pctl.value.length > plen) {
     alert(pmsg);
     pctl.focus();
     return false;
   }
     return true;
}

function check_extension(pctl, pext, pmsg) {
   var Despues = 0;
   var PointPos = pctl.value.indexOf(".");

   // Si no hay punto no hay extenxion
   if (PointPos == -1) {
     alert(pmsg);
     pctl.focus();
     return false;
   }
   //buscamos una extension htm o html
   else {  
     Despues = pctl.value.length - (PointPos+1);
     var cadena = pctl.value;
     if (Despues == 3) {
       if (
            ( cadena.substr(PointPos+1,1).toUpperCase() == pext.substr(0,1) ) &&
            ( cadena.substr(PointPos+2,1).toUpperCase() == pext.substr(1,1) ) &&
            ( cadena.substr(PointPos+3,1).toUpperCase() == pext.substr(2,1) )
          ) {
         return true;
       }
       else {
         alert(pmsg);
         pctl.focus();
         return false;
       }
     }

     if ((Despues == 4) && (pext.length == 4)) {
       if (
            ( cadena.substr(PointPos+1,1).toUpperCase() == pext.substr(0,1) ) &&
            ( cadena.substr(PointPos+2,1).toUpperCase() == pext.substr(1,1) ) &&
            ( cadena.substr(PointPos+3,1).toUpperCase() == pext.substr(2,1) ) &&
            ( cadena.substr(PointPos+4,1).toUpperCase() == pext.substr(3,1) )
          ) {
         return true;
       }
       else {
         alert(pmsg);
         pctl.focus();
         return false;
       }
     }
     else {
	   alert(pmsg);
       pctl.focus();
       return false;
     }
   }
}

function modificar_accion(newFormAction,disableAction,newAction,frm) {
	var oldFAction= frm.action;
	var oldNameActionCode= frm.actionCode.name;
	var oldValueActionCode= frm.actionCode.value;
	
	frm.action=newFormAction;
	if ( disableAction == 'true' ) {
		frm.actionCode.name = null;
		frm.actionCode.value = null;
	}
	else {
		frm.actionCode.value = newAction;
	}
	frm.submit();	

	frm.action=oldFAction;
	if (oldNameActionCode!=null){
		frm.actionCode.name = oldNameActionCode;
		frm.actionCode.value = oldValueActionCode;
	}
	//return true;
}

//modifica la visibilidad de una capa
function changeVisibility(name){
	var elm = document.getElementById(name);
    if(!elm) return;
	if (elm.style.visibility == "hidden" || elm.style.display == "none") {
		elm.style.visibility = "visible";
		elm.style.display='block';
	}
	else{
		elm.style.visibility = "hidden";
		elm.style.display='none';
	}
}

//pone la visibilidad a 'visible'
function setVisible(name){
	var elm = document.getElementById(name);
    if(elm) {
	elm.style.visibility = "visible";
	elm.style.display='block';
    }
}

//pone la visibilidad a 'hidden'
function setHidden(name){
	var elm = document.getElementById(name);
    if(elm) {
	elm.style.visibility = "hidden";
	elm.style.display='none';
    }
}

var layers = new Array();

function addLayer(nameLayer){
	layers[layers.length] = nameLayer;
}

function hideAllLayers(){
	for(i=0;i<layers.length; i++){
		setHidden(layers[i]);
	}
}


//inserta un meta tag correspondiente a un recurso
function insertResource(text,position,resource) {
	//recuperamos los diferentes elementos de la pagina
	var elmText = document.getElementById(text);
	var elmPos = document.getElementById(position);
	var elmRes = document.getElementById(resource);
	
	if (elmRes.length==0) {
		//si el recurso es nulo damos un alert
		alert("No hay recursos disponibles");
	}
	else {
		//insertamos en la posición correpondiente
		insertAtCaret(elmText, '[RES_' + elmRes.value + '_' + elmPos.value + ']');
	}	
}

//inserta un meta tag correspondiente a un salto de pagina
function insertSP(text,type) {
	//recuperamos los diferentes elementos de la pagina
	var elmText = document.getElementById(text);
	var elmType = document.getElementById(type);

	//insertamos en la posición correpondiente
	insertAtCaret(elmText, '[SP type="' + elmType.value + '"]');
	
}

//inserta un meta tag correspondiente a una letra mayuscula
function insertCapitalLetter(text,letter) {
	//recuperamos los diferentes elementos de la pagina
	var elmText = document.getElementById(text);
	var elmLetter = document.getElementById(letter);

	//insertamos en la posición correpondiente
	insertAtCaret(elmText, '[CAPITAL_' + elmLetter.value + ']');
	
}

//inserta un meta retorno de carro
function insertBR(text) {
	//recuperamos los diferentes elementos de la pagina
	var elmText = document.getElementById(text);

	//insertamos en la posición correpondiente
	insertAtCaret(elmText, '<br>');
	
}

function insertUrl(text,content){
	//recuperamos los diferentes elementos de la pagina
	var elmContent = document.getElementById(content);

	// recuperamos el idContent y el alias
	var index = elmContent.value.indexOf('@');
	var idContent = elmContent.value.substr(0,index);
	var alias = elmContent.value.substr(index+1);

	//recuperamos los diferentes elementos de la pagina
	var elmText = document.getElementById(text);

	if (elmText.createTextRange){
		var caretPos;
		if (elmText.caretPos) {
			caretPos = elmText.caretPos;
		} else {
			caretPos = elmText.createRange().duplicate();
		}
		if(caretPos) {
			caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? '[URL alias="'+alias+'" id="'+idContent+'"]' + caretPos.text + '[/URL] ' : '[URL alias="'+alias+'" id="'+idContent+'"]' + caretPos.text + '[/URL]';
		} else { 
			alert("Fallo al fijar la posici\u00F3n");
		}
	}
	else {
		alert("Posicione el cursor en aquella parte del \u00E1rea de texto\ndonde desee insertar el recurso");
    }
	
}

function insertList(text,typeList){
	//recuperamos los diferentes elementos de la pagina
	var elmType = document.getElementById(typeList);


	//recuperamos los diferentes elementos de la pagina
	var elmText = document.getElementById(text);

	if (elmText.createTextRange){
		var caretPos;
		if (elmText.caretPos) {
			caretPos = elmText.caretPos;
		} else {
			caretPos = elmText.createRange().duplicate();
		}
		if(caretPos) {
			caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? '[LIST_' + elmType.value + ']'  + caretPos.text + '[/LIST_' + elmType.value + ']' : '[LIST_' + elmType.value + ']' + caretPos.text + '[/LIST_' + elmType.value + ']';
		} else { 
			alert("Fallo al fijar la posici\u00F3n");
		}
	}
	else
		alert("Posicione el cursor en aquella parte del \u00E1rea de texto\ndonde desee insertar el recurso");
	
}

/**
 * inserta en el texto el MetaTag de CM indicado
 *
 * @param text	el TextArea donde se debe insertar
 * @param mtO	el metatag de apertura
 * @param mtC	el metatag de cierre
 */
function insertMetaTag(text,mtO,mtC) {

	//recuperamos el campo de texto
	var elmText = document.getElementById(text);

	if (elmText.createTextRange){
		var caretPos;
		if (elmText.caretPos) {
			caretPos = elmText.caretPos;
		} else {
			caretPos = elmText.createRange().duplicate();
		}
		if(caretPos) {
			caretPos.text = mtO + caretPos.text + mtC;
		} else { 
			alert("Fallo al fijar la posici\u00F3n");
		}
	}
	else
		alert(" Debe seleccionar una posici\u00F3n del texto");
}

/**
 * inserta en el texto el MetaTag de CM indicado
 *
 * @param text	el TextArea donde se debe insertar
 * @param mt	el metatag a insertar
 */
function insertSimpleMetaTag(text,mt) {

	//recuperamos el campo de texto
	var elmText = document.getElementById(text);

	//insertamos en la posición correpondiente
	insertAtCaret(elmText,mt);
}

function storeCaret (text) {
	var description_ = document.getElementById(text);
	if (description_.createTextRange) 
		description_.caretPos = document.selection.createRange().duplicate();
}



function insertAtCaret (description_, text) {
	if (description_.createTextRange){
		var caretPos;
		if (description_.caretPos) {
			caretPos = description_.caretPos;
		} else {
			caretPos = description_.createRange().duplicate();
		}
		if(caretPos) {
			caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		} else { 
			alert("Fallo al fijar la posici\u00F3n");
		}
	}
	else
		alert("Posicione el cursor en aquella parte del \u00E1rea de texto\ndonde desee insertar el recurso");
}
/**
* esta funcion permite realizar una pausa en la ejecución de un tiempo mínimo
* que se indica como parámetro
*/
function sleep(ms){
  var initialDate =  (new Date()).getTime();
  var now = (new Date()).getTime();
  while (now < initialDate + ms){
      now = (new Date()).getTime();
  }
}


/**
* Funcion que permite abrir una ventana modal
*/
function openModalWindow(url, width, height){
   return openModalWindow(url, width, height,'modalWindow');
}

/**
* Funcion que permite abrir una ventana modal
*/
function openModalWindow(url, width, height,name){
/*    if (window.showModalDialog && navigator.version>5.4){
        window.showModalDialog(url,this,'resizable: no; help: no; status: no; scroll: yes; dialogWidth:'+width+'px; dialogHeight:'+height+'px ');
    }else{*/
        return window.open(url,name,'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes , resizable=no,modal=yes,dialog=yes,width='+width+',height='+height);
/*    }*/
}

/**
 * Funcion que permite cambiar el tamaño de la fuentes incrementando o decrementando,
 * en función del parámetro que reciba (inc o dec). También recibirá la proporción en 
 * la que realizar esos cambios.
 *  
 * <P> Función mantenida por compatibilidad debe usarse la función de tres argumentos.
 *
 * @param action Si estamos incrementando o decrementado (Posibles valores 'inc' o 'dec'
 * @param val    La proporción de incremento o decremento.
 */
function fontSizer(action,val) {
      fontSizer(action,val,null);
}


/**
 * Funcion que permite cambiar el tamaño de la fuentes incrementando o decrementando,
 * en función del parámetro que reciba (inc o dec). También recibirá la proporción en 
 * la que realizar esos cambios.
 * 
 * @param action Si estamos incrementando o decrementado (Posibles valores 'inc' o 'dec'
 * @param val    La proporción de incremento o decremento.
 * @param cookiePath El path de aplicación para el que se va a tener efecto este cambio,
 *                   normalmente debe ser el contextRoot de la aplicación (ej: /mostoles)
 */
function fontSizer(action,val,cookiePath) {
    
    var baseFontSize = GetCookie('FONT_SIZE')
    if(baseFontSize == null) {
        // Establecemos el valor a 0, es decir sin aumento.
        SetCookie('FONT_SIZE','0');
        baseFontSize = "0";
    }
    
    var iCookieSize = parseInt(baseFontSize);
        
    if (action == 'dec') {
        iCookieSize--;
    }  else {
        iCookieSize++;
    }
    
    // Guardamos el valor de la cookie
    DeleteCookie('FONT_SIZE')
    // alert('Estableciendo la cookie a: ' + iCookieSize);
    var expire = new Date(); // Caduca en 1 año
    expire.setTime(expire.getTime() + 3600000*24*365);            
    SetCookie('FONT_SIZE',iCookieSize,expire,cookiePath);
    window.location.reload();    
}


/**
 * Estable el valor por defecto de las fuentes.
 *
 * <P> Utiliza el valor de la cookie FONT_SIZE para establecer el
 * tamaño de las fuentes. El valor de 1 significa el tamaño por 
 * defecto del navegador, valores positivos significan aumentos
 * valores negativos significan decrementos, el valor cero no 
 * esta definido y sse considerará igual a 1.
 *
 * @param ratio  La proporcion de aumento de cada aumento de fuente,
 *   debe ser el mismo con el que se invoca a fontSizer
 * @param cookiePath El path de la cookie a utilizar TODO
 */
function setBaseFontSize(ratio,cookiePath) {
    // alert('Entrando en setBaseFontSize(ratio:' + ratio + ')');
    var baseFontSize = GetCookie('FONT_SIZE')
    // alert('Valor de la cookie FONT_SIZE: ' + baseFontSize);
    if(baseFontSize == null) {
        // Establecemos el valor a 1 y no hacemos nada.
        // alert('No hay cookie estableciendo el valor a 1');
        SetCookie('FONT_SIZE','1',null,cookiePath);
    } else {
        var newSize = parseInt(baseFontSize);
        // Como voy a invocar al fontSizer debo tener en cuenta
        // que se va a hacer un decremento o incremento
        var newSize2 = 1;
        if ( newSize <  0 ) {
            newSize2 = newSize+1;   
        } else if ( newSize > 0 ) {
            newSize2 = newSize-1;
        } else {
            // La cookie no debería tener nunca el valor de cero   
        }
        if ( newSize2 == 0 ) {
            // Pues no hay que hacer nada
               
        }
        // alert('newSize: ' + newSize + '/newSize2: ' + newSize2);
        if ( newSize2 < 0 ) {
            // Decrementamos   
            var actuallySize = Math.pow(ratio,Math.abs(newSize2));
            // alert('Decrementando a: ' + actuallySize);
            DeleteCookie('FONT_SIZE')
            SetCookie('FONT_SIZE',newSize2,null,cookiePath);                    
            fontSizer('dec',actuallySize,cookiePath);
        } else if ( newSize2 > 0 ) {
            var actuallySize = Math.pow(ratio,newSize2);
            // alert('Incrementando a: ' + actuallySize);
            DeleteCookie('FONT_SIZE')
            SetCookie('FONT_SIZE',newSize2,null,cookiePath);                    
            fontSizer('inc',actuallySize,cookiePath);
        } else {
            // Podemos llegar a la situación de que newSize2 sea cero
            // en dos casos: la cookie valia -1 o valia 1, en este caso
            // no actualizamos el valor de la cookie ni redimensionamos
        }
    }
    document.getElementById('mainContainer').style.visibility='visible';
    document.getElementById('mainContainer').style.display='block';
}        



/* Función que imprime un iframe cargado con un 
* contenido sin ningún formato */

function printIframeContent(url) {
/* cargamos el iframe con el contenido */

	/* si es explorer */
	if(printIframe.location) {
		printIframe.location.href = url;
	} else {
		/* si es firefox */
		printIframe.src= url;
	}
	printIframe.focus();

}

/**
 * Obtiene el valor de una cookie.
 *
 * <P> Solo obtiene el valor, nada del path, domain, etc..
 *
 * @param name El nombre de la cookie a obtener 
 * @return El valor de la cookie correspondiente o null si no se ha 
 *  encontrado
 */
function GetCookie (name) {                                              
  var arg = name + "=";                                                  
  var alen = arg.length;                                                 
  var clen = document.cookie.length;                                     
  var i = 0;                                                             
  while (i < clen) {                                                     
    var j = i + alen;                                                    
    if (document.cookie.substring(i, j) == arg)                          
    return getCookieVal (j);                                             
    i = document.cookie.indexOf(" ", i) + 1;                             
    if (i == 0) break;                                                   
  }                                                                      
  return null;                                                           
}                                                                        

/**
 * Establece una cookie
 *
 * <P> Esta función es de número de parametros variables, solo
 * son requeridos los dos primeros.
 *
 * @param name     El nombre que queremos darle a la cookie.
 * @param value    El valor que se le va a dar a la cookie
 * @param expires  (Optativo) Cuando expira la cookie.
 * @param path     (Optativo) El valor del path de la cookie.
 * @param domain   (Optativo) El dominio de validez de la cookie.
 * @param secure   (Optativo) Si estamos en un entorno seguro, por defecto no.
 */                                                                         
function SetCookie (name, value) {                                       
  var argv = SetCookie.arguments;                                        
  var argc = SetCookie.arguments.length;                                 
  var expires = (argc > 2) ? argv[2] : null;                             
  var path = (argc > 3) ? argv[3] : null;                                
  var domain = (argc > 4) ? argv[4] : null;                              
  var secure = (argc > 5) ? argv[5] : false;                             
  document.cookie = name + "=" + escape (value) +                        
  ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +    
  ((path == null) ? "" : ("; path=" + path)) +                           
  ((domain == null) ? "" : ("; domain=" + domain)) +                     
  ((secure == true) ? "; secure" : "");                                  
}                                                                        

/**
 * Borra una cookie.
 *
 * @param name El nombre de la cookie a borrar.
 */                                                                         
function DeleteCookie (name) {                                           
  var exp = new Date();                                                  
  exp.setTime (exp.getTime() - 1);                                       
  var cval = GetCookie (name);                                           
  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}                                                                        
                                                                         

/**
 * Obtiene información de una cookie.
 *
 * <P> Permite obtener otros campos como pueden ser la fecha de expiración
 *  el path, el dominio etc.
 *
 * @param offset El campo a obtener.
 */                                                                         
function getCookieVal(offset) {                                          
  var endstr = document.cookie.indexOf (";", offset);                    
  if (endstr == -1)                                                      
  endstr = document.cookie.length;                                       
  return unescape(document.cookie.substring(offset, endstr));            
}

function hideSelects(currentElementId){

    var currentelement = document.getElementById(currentElementId);
    var _select = document.getElementsByTagName('SELECT');
    for(j=0;j<_select.length;j++) {
        if (!isElementInside(_select[j], currentelement)){
            if(!_select[j].style.oldVisibility) {
                _select[j].style.oldVisibility = _select[j].currentStyle.visibility;
                _select[j].style.visibility = 'hidden';
            }
        }
    }

    var _iframes = document.getElementsByTagName('IFRAME');
    for(j=0;j<_iframes.length;j++) {
        if (!isElementInside(_iframes[j], currentelement)){
            if(!_iframes[j].style.oldVisibility) {
                _iframes[j].style.oldVisibility = _iframes[j].currentStyle.visibility;
                _iframes[j].style.visibility = 'hidden';
            }
        }
    }
}

function showSelects(currentElementId){

    var currentElement = document.getElementById(currentElementId);

    var _select = document.getElementsByTagName('SELECT');
    for(j=0;j<_select.length;j++) {
        if (!isElementInside(_select[j], currentElement)){
            _select[j].style.visibility = _select[j].style.oldVisibility;
            _select[j].style.oldVisibility = false;
        }
    }

    var _iframes = document.getElementsByTagName('IFRAME');
    for(j=0;j<_iframes.length;j++) {
        if (!isElementInside(_iframes[j], currentElement)){
            _iframes[j].style.visibility = _iframes[j].style.oldVisibility;
            _iframes[j].style.oldVisibility = false;
        }
    }
}

function isElementInside(element, container){


    if (!element){
        return false;
    }

    if (!element.parentNode){
        return false;
    }

    var parent = element.parentNode;
    if (!parent.id){
        return isElementInside(parent, container);
    }

    if (parent.id != container.id){
        return isElementInside(parent, container);
    }
    return true
}


/* función utilizada para aplicar un filtro en los png24 y 
* se vean correctamente en internet explorer */

function imagePNG(url){
    _blank= url +"/imagenes/blank.gif";
	if(navigator.appName.indexOf("Microsoft")!=-1 && navigator.version < 7){
		var imgs = document.getElementsByTagName("img");
		for(var i=0,t=imgs.length;i<t;i++){
			var img = imgs[i];
			if(img){
				img_vell=img.src;
				img.src=_blank;
				img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+img_vell+", sizingMethod=scale)";
			}
		}
	}
}

