/**
 * Versión:        1.0
 * Autor:          Agustín Rodríguez Reina
 * E-mail:         agustin@jfactory.es
 * Ult. Actualiz:  08/02/2006
 * Utilidad:       Funciones genéricas
 */

/* Selecciona el elemento */
function sel(componente)
{
  componente.focus();
  // Los "select" (listas) no tienen el método "select" (paradojas de la vida)
  if (componente.type != 'select-one') componente.select();

  return (false); // Impide que se procese la etiqueta <a href="xxx">
}  

/* Abre en la ventana indicada el elemento referenciado (en su defecto en la actual)
   Valores estándar: top, self, parent
   La ventana tiene que existir y haber sido abierta con "window.open()" para que 
   funcione "nomVentana" (o ser un iframe por ejemplo)
*/
function toPage(url, nomVentana) {
	if (nomVentana == null)
	   window.location.assign(url);
	else
	   eval(nomVentana+".location.href ='"+ url +"'");	
}  

/* Obtiene la posición actual del cursor en el campo de texto */
function getCursorPos(componente) 
{
	var cursorPos = 0;	// IE Support
	if (document.selection) 
	{
	    componente.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -componente.value.length);
		cursorPos = Sel.text.length;
	}
	// Firefox support
	else if (componente.selectionStart || componente.selectionStart == '0')
		cursorPos = componente.selectionStart;
	return (cursorPos);
}

/* Coloca el cursor en el lugar indicado de campo de texto */
function setCursorPos(componente, pos)
{
	if(componente.setSelectionRange)
	{
		componente.focus();
		componente.setSelectionRange(pos,pos);
	}
	else if (componente.createTextRange) {
		var range = componente.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

/** Quita los puntos iniciales y los "/" de la URL */
function quitarPpioURL(url)
{
    var i= 0;

  	for (; i < url.length; i++)
    {
		  if (! (("." == url.charAt(i)) || (url.charAt(i) == "/")))
			    break;
    }

    return url.substring(i, url.length);
}

/* Cambia una imagen por otra */
function swapImg(img, url1, url2)
{ 
     if (img != null)
     {
       // Averigua cual es la actual y pone la otra
       if (img.src.lastIndexOf(quitarPpioURL(url1)) < 0)
           img.src= url1;
       else
           img.src= url2;
     }
}

/* Cambia una imagen por otra */
function swapImgById(idImg, url1, url2)
{
     swapImg(document.getElementById(idImg), url1, url2);
}

/** Carga una nueva imagen con las dimensiones indicadas. Si no
    especificamos 'anchuraNew' y 'alturaNew' mantendrá las dimensiones
	de la actual (si se indicaron explícitamente) 
	
    NOTA: Si está en la caché del navegador la reutiliza	
*/
function cargarImg(idImg, srcNewImg, anchuraNew, alturaNew)
{
  var img= document.getElementById(idImg);
  img.src= srcNewImg;
  
  if (anchuraNew != null)
     img.width= anchuraNew;
	 
  if (alturaNew != null)
     img.height= alturaNew;
}

/** Carga una nueva imagen con las dimensiones indicadas. Si no
    especificamos 'anchuraNew' y 'alturaNew' mantendrá las dimensiones
	de la actual (si se indicaron explícitamente) 
	
    NOTA: Fuerza la recarga de la imagen	
*/
function cargarImgForce(idImg, srcNewImg, anchuraNew, alturaNew)
{
  var img= document.getElementById(idImg);
  var tmp = new Date();
  tmp = "?"+tmp.getTime();
  img.src= srcNewImg + tmp;
  
  if (anchuraNew != null)
     img.width= anchuraNew;
	 
  if (alturaNew != null)
     img.height= alturaNew;
}

function printPage()
{
	if (window.print)
	    window.print();
	else
	    alert("Tu navegador no permite imprimir esta página!");
}

/** Añade a favoritos. 
    Si no se pone 'tit' pone el de la página actual
	Si no se pone 'pag' pone la actual
	Si lo consigue dev. TRUE. Si no dev. FALSE. Se deja en manos
	del programador mostrar un mensaje de aviso en el idioma
	esperado.
	
	Ej: if (! addMyFavorites()) 
	    alert("Sorry! Your browser doesn't support this function");
*/
function addMyFavorites(pag, tit)
{
	if(pag == null)
	   pag= location.href;
	if(tit == null)
	   tit=  document.title;
	
	if (window.sidebar) // firefox
	{
		window.sidebar.addPanel(tit, pag, "");
		return true;
	}
		
	else if(window.opera && window.print) // opera
	{
		var elem = document.createElement('a');
		elem.setAttribute('href',pag);
		elem.setAttribute('title',tit);
		elem.setAttribute('rel','sidebar');
		elem.click();
		return true;
	} 
	
	else if(document.all) // ie
	{
		window.external.AddFavorite(pag, tit);
		return true;
    } 
	
	else { 
      return false;
	}
}

/* Cuando se presiona sobre un botón "atrás", "volver",...
NS: La primera página que se visita es 'history.length= 1'
IE: La primera página que se visita es 'history.length= 0'*/
function atras()
{
	// No es la primera página que visitamos
	if (((document.layers) && (history.length > 1))   //NS
		|| ((document.all) && (history.length > 0)))  //IE
	{
		history.back();
		return (false); // Impide que se procese la etiqueta "<a href="
	}
	else return (true); // Como si no tuvieramos "javascript"
}

/* Copia el contenido textual del componente al portapapeles.
   Ej: copia_portapapeles(document.form1.txtCopiar) */
function copia_portapapeles(obj)
{
  var textRange= document.body.createTextRange();
  textRange.moveToElementText(obj);
  textRange.execCommand("Copy");
}


/* Abre una ventana nueva centrada */
function abrirWin_Centrada(pagina, anchura, altura)
{
    if (anchura == null)
        anchura= screen.width - 100;
    if (altura == null)
        altura= screen.height - 80;

    var top= Math.floor((screen.height - altura) / 2);
    var left= Math.floor((screen.width - anchura) / 2);

    ventana= window.open(pagina, '',
      ('toolbar=no,location=no,resizable=yes,scrollbars=yes,height='+altura+',width=' 
        + anchura + ',top=' + top + ',left=' + left));
    ventana.focus();
    return ventana;
}        
 
/* Abre la imagen en una ventana adaptada a su tamaño (sin botones de navegación, ...) */
function abrirWinImg(imageName,imageWidth,imageHeight,alt,bgcolor,hugger,hugMargin)
// by E Michael Brandt of ValleyWebDesigns.com - Please leave these comments intact.
// version 3.0.4  
{
	if (bgcolor=="") {
		bgcolor="#FFFFFF";
	}
	var adj=10
	var w = screen.width;
	var h = screen.height;
	var byFactor=1;

	if(w<740){
	  var lift=0.90;
	}
	if(w>=740 & w<835){
	  var lift=0.91;
	}
	if(w>=835){
	  var lift=0.93;
	}
	if (imageWidth>w){	
	  byFactor = w / imageWidth;			
	  imageWidth = w;
	  imageHeight = imageHeight * byFactor;
	}
	if (imageHeight>h-adj){
	  byFactor = h / imageHeight;
	  imageWidth = (imageWidth * byFactor);
	  imageHeight = h; 
	}
	   
	var scrWidth = w-adj;
	var scrHeight = (h*lift)-adj;

	if (imageHeight>scrHeight){
  	  imageHeight=imageHeight*lift;
	  imageWidth=imageWidth*lift;
	}

	var posLeft=0;
	var posTop=0;

	if (hugger == "hug image"){
	  if (hugMargin == ""){
	    hugMargin = 0;
	  }
	  var scrHeightTemp = imageHeight - 0 + 2*hugMargin;
	  if (scrHeightTemp < scrHeight) {
		scrHeight = scrHeightTemp;
	  } 
	  var scrWidthTemp = imageWidth - 0 + 2*hugMargin;
	  if (scrWidthTemp < scrWidth) {
		scrWidth = scrWidthTemp;
	  }
	  
	  if (scrHeight<100){scrHeight=100;}
	  if (scrWidth<100){scrWidth=100;}

	  posTop =  ((h-(scrHeight/lift)-adj)/2);
	  posLeft = ((w-(scrWidth)-adj)/2);
 	}

	if (imageHeight > (h*lift)-adj || imageWidth > w-adj){
		imageHeight=imageHeight-adj;
		imageWidth=imageWidth-adj;
	}
	posTop = parseInt(posTop);
	posLeft = parseInt(posLeft);		
	scrWidth = parseInt(scrWidth); 
	scrHeight = parseInt(scrHeight);
	
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1){
	  var args= new Array();
	  args[0]='parent';
	  args[1]=imageName;
	  var i ; document.MM_returnValue = false;
	  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
	} else {
	newWindow = window.open("","newWindow","width="+scrWidth+",height="+scrHeight+",left="+posLeft+",top="+posTop+",scrollbars=no");
	newWindow.document.open();
	newWindow.document.write('<html><title>'+alt+'</title><body leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" bgcolor='+bgcolor+' onBlur="self.close()" onClick="self.close()">');  
	newWindow.document.write('<table width='+imageWidth+' border="0" cellspacing="0" cellpadding="0" align="center" height='+scrHeight+' ><tr><td>');
	newWindow.document.write('<img src="'+imageName+'" width='+imageWidth+' height='+imageHeight+' alt="Click screen to close" >'); 
	newWindow.document.write('</td></tr></table></body></html>');
	newWindow.document.close();
	newWindow.focus();
	}
}

function cerrarWin()
{
    window.close();
}


function getRandom(inferior, superior)	
{
     var numPosibilidades = (superior + 1) - inferior; 
     var aleat = Math.random() * numPosibilidades; 
     aleat = Math.floor(aleat); 
     aleat = (inferior + aleat); 
     if((aleat < inferior) || (aleat > superior)) 
	 {
	   alert("gnral.aleatorio.- Rango recibido erroneo (" + inferior + ", " + superior + "). "
           + "Continuamos con el valor: " + inferior); 
	   return (inferior);
	 }
	 
	 return (aleat);
}


// Si el iframe no tiene indicada su página destino pone la 'urlWeb' recibida
function setIframeSrcSiNoIni(idIframe, urlWeb) 
{
     if ((document.getElementById(idIframe).src == null) || (document.getElementById(idIframe).src == ""))
          document.getElementById(idIframe).src= urlWeb;
}


/* Reemplaza la cadena "sOld" por "sNew" todas las veces que aparezca
   dentro de "sOrig" */
function replace(sOrig, sOld, sNew)
{
  temp= "" + sOrig;

  while (temp.indexOf(sOld) > -1)
  {
    pos= temp.indexOf(sOld);
    temp= "" + (temp.substring(0, pos) + sNew +
          temp.substring((pos + sOld.length), temp.length));
  }
	
  if (temp == null) temp="";
  return temp;
}


/* Permite ejecutar un código "body onload=" sin tocar este atributo en el documento HTML, JSP,...
   USO:  En el HEAD añadir:
   
      function execOnLoadAgs() 
      {
      }
   
   Al final de la zona editable del BODY añadir:
   
    <script type="text/javascript">
	<!-- //
	    prepareExecOnLoadAgs();
	// -->
	</script>
   
   NOTA: Muy útil en DW donde este atributo esté en el Template.
         Si ya existe el "body onload=" lo ejecuta antes de "execOnLoadAgs"
*/
var oldFunctionOnLoad = null;
function execOnLoadOldAndNew()
{ 
	if(oldFunctionOnLoad){ oldFunctionOnLoad(); }
	execOnLoadAgs();
}
function prepareExecOnLoadAgs()
{
	oldFunctionOnLoad = window.onload;
	window.onload = execOnLoadOldAndNew;
}



