// JavaScript Document
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n)
        /***
                IN: str - the string we are RIGHTing
                    n - the number of characters we want to return

                RETVAL: n characters from the right side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                   return "";
                else if (n > String(str).length)   // Invalid bound, return
                   return str;                     // entire string
                else { // Valid bound, return appropriate substring
                   var iLen = String(str).length;
                   return String(str).substring(iLen, iLen - n);
                }
        }

//---Funciones relacionadas con capas:----------------------------------------
function QueNav()
{

	if(navigator.appName=='Microsoft Internet Explorer')
	{	
	   return "E";
	} 
	else
	{
           return "N";
	}
}

var Nav=QueNav();

var VisNom=(Nav == "E")?"visible":"visible";
var OcuNom=(Nav == "E")?"hidden":"hidden";

var DisBloque=(Nav == "E")?"block":"block";
var DisBorde  =(Nav == "E")?"inline":"inline";
var DisNone   =(Nav == "E")?"none":"none";

function GetXCenter(WidthObjeto)
{
	var x= Math.floor(document.body.clientWidth / 2) - ((WidthObjeto>0)?WidthObjeto/2:0); 
	if(x<0){x=0;} 
	return x;
}

function GetYCenter(HeightObjeto)
{
	var y= Math.floor(document.body.clientHeight / 2) - ((HeightObjeto>0)?HeightObjeto/2:0); 
	if(y<0){y=0;} 
	return y;
}

function GetTagId(NomTag)
{
	return document.getElementById(NomTag);
}


function GetLayer(Nom)
{
 if(Nav=="E")
 {
	return eval('document.all.' + Nom + '.style');
 }
 else //Netscape
 {
	return document.getElementById(Nom).style;
 }

}

function GetId(Nom)

{
 if(Nav=="E")
 {
	return eval('document.all.' + Nom );
 }
 else //Netscape
 {
	return document.layers[Nom];
 }
}

//Oculta o muestra
function HideLayer(Nom)
/*Registered Joaquín Forcada.09/2002*/
{
	GetLayer(Nom).visibility=OcuNom;
	GetLayer(Nom).display=DisNone;
}

function ShowLayer(Nom)
{
	GetLayer(Nom).visibility=VisNom;
	GetLayer(Nom).display=DisBloque;
}

function ShowHideLayer(Nom, f_Show)
{	
	if(f_Show=="1")
	{
		ShowLayer(Nom);
	}
	else if( GetLayer(Nom).visibility == VisNom || f_Show=="0")
	{
		HideLayer(Nom);	
	}
	else
	{
		ShowLayer(Nom);
	}
}

function CollapseLayer(Nom,Tamanyo)
{
	var obj = GetLayer(Nom);

if(Tamanyo=='' || Tamanyo=='undefined'){ Tamanyo = '180px';}
		
	obj.height = Tamanyo;
	obj.overflow='auto';	
}

function ExpandLayer(Nom)
{
	var obj = GetLayer(Nom);
	
	obj.height='100%';
	obj.overflow='auto';
}
function ExpandCollapseLayer(Nom, f_Expand, Tamanyo)
{
	var obj = GetLayer(Nom);
	
	if(Tamanyo=='' || Tamanyo=='undefined'){ Tamanyo = '180px';}
	
	if(f_Expand=="1")
	{
		ExpandLayer(Nom);
	}
	else if( obj.height!=Tamanyo || f_Expand=="0")
	{
		CollapseLayer(Nom,Tamanyo);	
	}
	else
	{
		ExpandLayer(Nom);
	}
}

//--Funciones relacionadas con imágenes:------------------------------------------------------------------------------

function CambiarImagen(NameImg, NewImg)
{
	var objimg = new Image();
	objimg.src = NewImg;
	var img = eval("document." + NameImg);	
	img.src = objimg.src;
}


function ImgEfectoPulsado(NameImg,b_Pulsado)
{
	try{
		var img = GetLayer(NameImg);
		if(b_Pulsado)
		{
			img.borderColor = "#FFFFDD";
			img.borderStyle = "inset";	
			img.borderWidth = 1;		
		}
		else if(!b_Pulsado)
		{
			img.borderColor = "transparent";
			img.borderStyle = "outset";	
			img.borderWidth = 1;				
		}
		else
		{
			//NADA DE NADA;
		}
	
	}
	catch(err){ 	return true; }
}

function OpenNewWindow(pathPage, alto, ancho, params, strwinName) 
{
		
	var	strwinURL = pathPage;
	
	if (!params == "") 
		{
		strwinURL = strwinURL +"?"+ params
		}
	
	var winOpts ='toolbar=no,location=no,directories=no,status=no,menubar=no, height='+alto+',width='+ancho+', resizable=yes, scrollbars=auto';
		
	var newWindow = window.open( strwinURL, "",winOpts);
	
	return newWindow;
}
/*******************************/
function CancelarFormGenerico()
{
	document.formulario.ACCION.value='CANCELAR';	
	document.formulario.submit();
}

function GuardarFormGenerico(Elemento)
{
	if ( rellenados_campos_obligatorios() ) 
	{
		document.formulario.ACCION.value='GUARDAR';
		document.formulario.submit();
	}
	else 
	{
		return false;
	}
}

function GuardarFormGenericoSinCerrar(Elemento)
{
	if ( rellenados_campos_obligatorios() ) 
	{
		document.formulario.ACCION.value='GUARDAR';
		document.formulario.GuardaryCerrar.value='0';
		document.formulario.submit();
	}
	else 
	{
		return false;
	}
}

function EliminarFormGenerico(Elemento)
{
	if(confirm('¿Desea eliminar este '+Elemento+' y todos los documentos asociados a éste?')) 
	{
		document.formulario.ACCION.value='ELIMINAR';
		document.formulario.submit();
	}
	else
	{ 
		return false;
	}
}

function todayStr() 
{
	var today=new Date()
	return today.getMonth()+1+"/"+today.getDate()+"/"+(today.getYear() + 1900)
}




var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function isNumeric(value) {
return typeof value != "boolean" && value !== null && !isNaN(+ value);
}


/******************************/
// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

function isAlphaNumeric(textObj) 
{ 
	var newValue = textObj ;
	var newLength = newValue.length ;
	var extraChars="_,-" ;
	var search ;
	
	for(var i = 0; i != newLength; i++) 
	{ 
		 aChar = newValue.substring(i,i+1) 
		 aChar = aChar.toUpperCase() 
		 search = extraChars.indexOf(aChar) 
		 if(search == -1 && (aChar < "A" || aChar > "Z") ) 
		 { 	return false; }
	 } 

	return true;
} 



function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	if (dtStr=="") {return true}
	arrdt=dtStr.split(" ");
	dtStr=arrdt[0];
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("La fecha es incorrecta")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
	//	alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
	//	alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
	//	alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
	//	alert("Please enter a valid date")
		return false
	}
return true
}

function DiferenciaFechas (CadenaFecha1,CadenaFecha2) {   
  if (CadenaFecha1=="" || CadenaFecha2=="") return 0;
     arrFecha1=CadenaFecha1.split(" "); 
   arrFecha2=CadenaFecha2.split(" "); 

   var fecha1 = new fecha( arrFecha1[0] )  ;    
   var fecha2 = new fecha( arrFecha2[0] )   ;
      

   var miFecha1 = new Date( fecha1.anio, fecha1.mes, fecha1.dia )   ;
   var miFecha2 = new Date( fecha2.anio, fecha2.mes, fecha2.dia ) ;  
  

   var diferencia = miFecha1.getTime() - miFecha2.getTime() ;
   var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24)) ;  
   var segundos = Math.floor(diferencia / 1000) ;  
  // alert ('La diferencia es de ' + dias + ' dias,\no ' + segundos + ' segundos.')   ;
      
   return dias   
}   
  
function fecha( cadena ) {   
  

   var separador = "/"  ;
  

   if ( cadena.indexOf( separador ) != -1 ) {   
        var posi1 = 0   ;
        var posi2 = cadena.indexOf( separador, posi1 + 1 ) ;
        var posi3 = cadena.indexOf( separador, posi2 + 1 )  ; 
        this.dia = cadena.substring( posi1, posi2 )   ;
        this.mes = cadena.substring( posi2 + 1, posi3 );   
        this.anio = cadena.substring( posi3 + 1, cadena.length )   ;
   } else {   
        this.dia = 0   ;
        this.mes = 0   ;
        this.anio = 0   ;   
   }   
}   
  
function nuevoAjax(){
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
} 

/**
 * Expande/Contrae una tabla contenedora de formulario
 * 
 * @param sId String: Id de la tabla
 * @param oLink Object: Referencia al enlace que llama a esta función
 *
 */
function toggleVisibility(sId, oLink)
{
	var sDisplay = GetLayer(sId).display;
	if( sDisplay == '' || sDisplay == 'block')
	{
		GetLayer(sId).visibility = 'hidden';
		GetLayer(sId).display = 'none';
		oLink.style.backgroundPosition = 'bottom';
		oLink.title = 'Expandir';
	}
	else
	{
		GetLayer(sId).visibility = '';
		GetLayer(sId).display = '';
		oLink.style.backgroundPosition = 'top';
		oLink.title = 'Contraer';
	}
	
}

/**
 * Como toggleVisibilitySession pero en vez de Expande/Contrae guarda el estado en session
 * a traves de ajax
 *
 * @param Id String: Id de la tabla
 *
 */
function toggleVisibilitySession(Id){

	var sDisplay = GetLayer(Id).display;
	var ajax = nuevoAjax();
	
	if( sDisplay == '' || sDisplay == 'block')
		ajax.open("GET", "../lib/ajax.php?ACCION=SAVE_IN_SESSION&Variable="+Id+"&Valor=hidden" ,true);
	else
		ajax.open("GET", "../lib/ajax.php?ACCION=SAVE_IN_SESSION&Variable="+Id+"&Valor=" ,true);
	
	ajax.send(null);
}

/**/