var isFormUpdated = false;
var isCreate=false;
var isUpdate=false;
var isDelete=false;
var isImprimir=false;

var direccion=1;
var maximo=100;
var cuantos=maximo;

var numeroClick=0;

var isNS4 = (navigator.appName=="Netscape")?1:0;

// Evita el funcionamiento de la tecla backspace para regresar una página
window.history.forward(1);

/* Funciones para que se convierta a mayúsculas en mozilla*/


document.onkeydown = alertkey;
if (isNS4==1){
HTMLElement.prototype.click = function() {
	var evt = this.ownerDocument.createEvent('MouseEvents');
	evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
	this.dispatchEvent(evt);
	} 
}

function alertkey(e) {

  if (navigator.appName.indexOf("Microsoft")>=0)
    return;
    if( !e ) {
      //if the browser did not pass the event information to the
      //function, we will have to obtain it from the event register
      if( window.event ) {
        //Internet Explorer
        e = window.event;
      } else {
        //total failure, we have no way of referencing the event
        return;
      }
    }
    event=e;

    if( typeof( e.keyCode ) == 'number'  ) {
      //DOM
      e = e.keyCode;
    } else if( typeof( e.which ) == 'number' ) {
      //NS 4 compatible
      e = e.which;
    } else if( typeof( e.charCode ) == 'number'  ) {
      //also NS 6+, Mozilla 0.9+
      e = e.charCode;
    } else {
      //total failure, we have no way of obtaining the key code
      return;
    }
  //  window.alert('The key pressed has keycode ' + e + ' and is key ' + String.fromCharCode( e ) );
    event=e;
  }

///////////


/* función para desactivar ctrl+u, ctrl+t, ctrl+n, tecla del menú contextual y F11*/
function desactivar() {
  if (typeof event != 'undefined'){
    var pressedKey = String.fromCharCode(event.keyCode).toLowerCase();
//    if (event.altKey)
//    alert(event.keyCode);
    // 93 tecla menu contextual
    // 122 F11

    if (event.altKey && event.keyCode==115){
      location.href="cerrarsession";
      alert("Ha forzado la salida del sistema!!!");
      event.keyCode=0;
      event.returnValue = false;
    }


    if (((event.ctrlKey && (pressedKey == "u" || pressedKey == "t" || pressedKey == "n"))) || (event.keyCode == 122 || event.keyCode == 93) || (event.altKey && event.keyCode==115) ) {
      alert("Operación inválida");
      event.keyCode=0;
      event.returnValue = false;
    }
  }
}



function my_onkeydown_handler(){
  if (typeof event != 'undefined'){
    switch (event.keyCode){
      case 0 :
        alert("Tecla control desactivada");
        event.returnValue = false;
        break;
    }
  }
}



function right(e) {
	if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2))
		return false;
	else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 || event.button == 3)) {

		alert("El click derecho se encuentra deshabilitado.");
		return false;

	}
	return true;
}


function lanzar(){
  numeroClick=0;
  document.onmousedown=right;
  document.onmouseup=right;
  if (document.layers)
    window.captureEvents(Event.MOUSEDOWN);
  if (document.layers)
    window.captureEvents(Event.MOUSEUP);
  window.onmousedown=right;
  window.onmouseup=right;

/*alert(document.images.length);
    elementos=document.images;
    for(j=0;j<elementos.length;j++){
      campo=elementos[j];
      alert(campo.src);
}*/

    //alert('tipo: '+campo.type+'  valor: '+campo.value);
//    if(campo.type=='text' || campo.type=='textarea'){
//      campo.value=campo.value.Trim();
      //alert('valor sin esp: '+campo.value);

}




<!--  Este código es creado para reemplazar las funciones insertAdjacentHTML, insertAdjacentElement, -->
<!--  creadas por Microsoft y funcionales solo para Internet Explorer. -->

if(navigator.appName != "Microsoft Internet Explorer"){
 if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
  HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode){
    switch (where){
      case 'beforeBegin':
        this.parentNode.insertBefore(parsedNode,this)
        break;
      case 'afterBegin':
        this.insertBefore(parsedNode,this.firstChild);
        break;
      case 'beforeEnd':
        this.appendChild(parsedNode);
        break;
      case 'afterEnd':
        if (this.nextSibling)
          this.parentNode.insertBefore(parsedNode,this.nextSibling);
        else
          this.parentNode.appendChild(parsedNode);
        break;
    }
  }

  HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr){
    var r = this.ownerDocument.createRange();
    r.setStartBefore(this);
    var parsedHTML = r.createContextualFragment(htmlStr);
    this.insertAdjacentElement(where,parsedHTML)
  }

  HTMLElement.prototype.insertAdjacentText = function (where,txtStr){
    var parsedText = document.createTextNode(txtStr)
    this.insertAdjacentElement(where,parsedText)
  }
 }
}

<!--Funciones creadas por Fredy Wilches-->

function validarNumero(Objeto, nombre)
{
	var NumeroValido = '0123456789.:';
	var string = Objeto.value;

	if (string != "")
	{
		for (var i=0; i< string.length; i++) {
			if (NumeroValido.indexOf(string.charAt(i)) == -1) {
				alert(nombre + " no es un valor numérico.\n ");
				Objeto.focus();
				return false;
			}
		}
	}
  return true;
}

function cambiarTildes(forma){
  var i;
  for(i=0;i<forma.elements.length;i++){
    campo = forma.elements[i];
    var texto=campo.value;
    if(texto != null){
      texto=texto.replace('Ã¡','a');
      texto=texto.replace('Ã©','e');
      texto=texto.replace('Ã­','i');
      texto=texto.replace('Ã³','o');
      texto=texto.replace('Ãº','u');
      texto=texto.replace('ï¿½\uFFFD','A');
      texto=texto.replace('Ã‰','E');
      texto=texto.replace('ï¿½\uFFFD','I');
      texto=texto.replace('Ã“','O');
      texto=texto.replace('Ãš','U');
    }
    campo.value = texto;
  }
}


function enabledButtonsGif(form){
  if(isUpdate && document.getElementById("btnEditar")!=null){
    document.getElementById("btnEditar").disabled=false;
    document.getElementById("btnEditar").src="../images/actualizar.gif";
  }
  if(isDelete && document.getElementById("btnEliminar")!=null){
    document.getElementById("btnEliminar").disabled=false;
    document.getElementById("btnEliminar").src="../images/eliminar.gif";
  }
  if(isImprimir && document.getElementById("btnImprimir")!=null){
    document.getElementById("btnImprimir").disabled=false;
    document.getElementById("btnImprimir").src="../images/imprimir.gif";
  }

}

function enabledButtonEditar(codigo, nombre){
  if(isUpdate){
    document.getElementById("anclaEditar").href="javascript:actualizarRegistro(" + codigo + ", '" + nombre + "')";
  }
}



function finalizar(forma,accion){
   if ( isFormUpdated == true ){
    var guardar = confirm ("Desea guadar los cambios ?");
       if( guardar == true ){
         var valido = validateForm(forma);
         if(valido){
            return true;
         }
         else {
          return false;
        }
       }
       else{
          forma.action=accion;
          forma.submit();
          return false;
       }
	 }
   else{
      forma.action=accion;
      forma.submit();
      return false;
   }
}


function openHelp(){
      window.open('/asocars/help/index.htm','Ayuda');
}


function cancelar(forma,accion){
     //alert("Actualizado =" + isFormUpdated);
	 if ( isFormUpdated == true ){
    var guardar = confirm ("Desea guardar los cambios ?");
       if( guardar == true ){
         var valido = validateForm(forma);
         if(valido){
            forma.submit();
         }
         else {
          return false;
        }
       }
       else{
          forma.action=accion;
          forma.submit();
       }
	 }
   else{
      forma.action=accion;
      forma.submit();
   }
}


function forward( form ) {
	 if( isFormUpdated == true ) {
			 valido = validateForm(forma);
			 return valido;
	 }
   return true;
}

function isEmailAddr(email){
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0) {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
        result = true;
  }
  return result;
}

function validRequired(formField, fieldLabel){
  var result = true;
  formField.value = trimWhitespace(formField.value);
  if (formField.value == ""){
    alert('El campo ' + fieldLabel +' es requerido.');
    formField.focus();
    return false;
  }
  return result;
}

function validEmail(formField,fieldLabel,required){
  var result = true;

  if (required && !validRequired(formField,fieldLabel))
    result = false;

  if (result && ((formField.value.length < 3) || !isEmailAddr(formField.value)) && (formField.value != "") ){
    alert("Favor ingrese una dirección de email completa de la forma: username@dominio.com");
    formField.focus();
    result = false;
  }
  return result;
}

/**
* Valida si un select ha sido seleccionado en un valor valido. El select debe
* contener el valor -1 para poder validar.
* @param formSelect, select que se quiere validar.
* @param fieldLabel, nombre descriptivo del select.
*/
function validSelect( formSelect, fieldLabel ){

   var index = formSelect.selectedIndex;
   var valor = formSelect.options[index].value;
   if( valor == -1 )
   {
     alert('Por favor seleccione un valor para el campo "' + fieldLabel +'"');
     formSelect.focus();
     return false;
   }

   return true;
}

/**
* Valida si un checkbox o grupo de checkbox ha sido seleccionado.
* @param formCheckBox, checkbox que se quiere validar.
* @param fieldLabel, nombre descriptivo del checkbox.
*/
function validCheckBox( formCheckBox, fieldLabel ) {

  var length = formCheckBox.length? formCheckBox : 0;
  if( length ) {
    for( i = 0; i < length; i++ ) {
      if( formCheckBox[i].checked ) return true;
    }
  }
  else {
    if( formCheckBox.checked ) return true;
  }

  alert('Por favor seleccione por lo menos un valor para el campo "' + fieldLabel +'"');
  formCheckBox.focus();
  return false;

}


function validNum(formField,fieldLabel,required){
  var result = true;

  if (required && !validRequired(formField,fieldLabel))
    result = false;

   if (result && formField.value != ""){
     var num = parseInt(formField.value,10);
     if (isNaN(num)){
       alert('Por favor digite un número para el campo "' + fieldLabel +'"');
      formField.focus();
      result = false;
    }
	formField.value = num;
  }
  return result;
}

function validIntegerPositive(formField,fieldLabel,required){
  var result = true;

  if (required && !validRequired(formField,fieldLabel))
    result = false;

   if (result){
     if (isInteger(formField.value) == false){
       alert('Por favor digite un valor entero positivo para el campo "' + fieldLabel +'"');
       formField.focus();
       result = false;
    }

  }
  return result;
}

function validAlphaNumeric(formField,fieldLabel,required){
  var result = true;

  if (required && !validRequired(formField,fieldLabel))
    result = false;

   if (result){
     if (isAlphanumeric(formField.value,true) == false){
       alert('Por favor digite caracteres alfanuméricos para el campo "' + fieldLabel +'"');
       formField.focus();
       result = false;
    }

  }
  return result;
}

function validAlphabetic(formField,fieldLabel,required){
  var result = true;

  if (required && !validRequired(formField,fieldLabel))
    result = false;

   if (result){
     if (isAlphabetic(formField.value,true) == false){
       alert('Por favor digite caracteres alfabéticos para el campo "' + fieldLabel +'"');
       formField.focus();
       result = false;
    }

  }
  return result;
}

// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}

function isInteger(val){
	var isInt = true;
	inputStr = val.toString()
	for (var i = 0; i < val.length && isInt == true; i++){
		var oneChar = inputStr.charAt(i)
		if ( oneChar < "0" || oneChar > "9" ) {
			isInt = false
		}
	}
	return (isInt)
}

function validateSize(formField,fieldLabel,required,maxSize){
	var result = true;
    if (required && !validRequired(formField,fieldLabel)){
      result = false;
	}
	if( result ) {
		var text = formField.value;
		if(text.length > maxSize){
			alert('Texto demasiado largo para campo "' + fieldLabel+'". Máximo '+maxSize+' caracteres');
            formField.focus();
			result = false;
		}
	}
	return result;
}

function validDate(formField,fieldLabel,required){
  var result = true;
  if (required && !validRequired(formField,fieldLabel))
    result = false;

   if (result){
     var elems = formField.value.split("/");

     result = (elems.length == 3); // should be three components

     if (result){
       var month = parseInt(elems[0],10);
       var day = parseInt(elems[1],10);
       var year = parseInt(elems[2],10);
       result = !isNaN(month) && (month > 0) && (month < 13) &&
            !isNaN(day) && (day > 0) && (day < 32) &&
            !isNaN(year) && (elems[2].length == 4);
     }

      if (!result){
       alert('Por favor digitar una fecha en formado MM/DD/YYYY para el campo "' + fieldLabel+'"');
       formField.focus();
    }
  }

  return result;
}

function openWindowFinder(accion){
        var propiedadesVentana = "toolbar=no,scrollbars=yes,resizable=no";
        propiedadesVentana = armarPropiedadesVentana(400,600,propiedadesVentana);
	window.open(accion,"NewWin",propiedadesVentana);
}

// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;

	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {

		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {

			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}

		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}

function armarPropiedadesVentana(aHEIGHT, aWIDTH, aFeatures){
       if (aHEIGHT == "*"){ aHEIGHT = (screen.availHeight - 80) };
       if (aWIDTH == "*"){ aWIDTH = (screen.availWidth - 30) };
       var newFeatures = "height=" + aHEIGHT + ",innerHeight=" + aHEIGHT;
       newFeatures += ",width=" + aWIDTH + ",innerWidth=" + aWIDTH;
       if (window.screen){
	      var ah = (screen.availHeight - 30);
          var aw = (screen.availWidth - 10);
          var xc = (( aw - aWIDTH ) / 2);
          var yc = (( ah - aHEIGHT ) / 2);
          newFeatures += ",left=" + xc + ",screenX=" + xc;
          newFeatures += ",top=" + yc + ",screenY=" + yc;
          newFeatures += "," + aFeatures
	   }
       return newFeatures;
}

function enabledButtons(form){
    form.btnEliminar.disabled = form.btnEditar.disabled=false;
}


function enableButton( lista, boton ){

   if( lista.selectedIndex != -1 )
    	boton.disabled=false;
}


/**
* Mueve hacia arriba o abajo el elemento seleccionado de un select
* @param lista, select donde se encuentra elemento
* @param direccion, cadena que indica si se mueve hacia arriba o hacia
*                   abajo (valores: 'arriba', 'abajo')
*/
function mover( lista, direccion )
{
   var index = lista.selectedIndex;
   var mover;
   if( direccion == "arriba" )
   {
     mover = index - 1;
	 if( mover < 0 )
	 	return;
   }
   else
   {
     mover = index + 1;
	 if( mover >= lista.length )
	    return;
   }

   var beforeValue = lista.options[mover].value;
   var beforeText = lista.options[mover].text;

   // Reemplazar anterior
   lista.options[mover].value = lista.options[index].value;
   lista.options[mover].text  = lista.options[index].text;

   // Reemplazar siguiente
   lista.options[index].value = beforeValue;
   lista.options[index].text  = beforeText;

   // Seleccionar el nuevo campo
   lista.selectedIndex = mover;
}

/**
* Coloca nombre y valor seleccinados en los campos apropiados de la venta
* padre
* @param tableName, id de la tabla donde se encuentra el listado
* @param radioButton, control de seleccion radio button
* @param textSel, campo oculto donde se encuentra el texto corresponditente
*                 al valor seleccionado en radioButton
* @param sourceValue, elemento donde se coloca el id
* @param sourceText, campo oculto donde se coloca el texto correspondiente
					 al valor seleccionado
*/
function setDataToParent( tableName,
                          radioButton,
                          textSel,
                          sourceValue,
                          sourceText )
{
   // Encontrar la tabla
   var list = (document.all) ? document.all.tableName : document.getElementById( tableName );
   //var list = document.getElementById( tableName );

   // Encontrar el nombre del elemento B seleccionado
   var length = radioButton.length? radioButton.length : 0;
   var index = 0;
   var value = -1;
   var text;
   if( length != 0 )
   {
      for( index = 0; index < list.rows.length - 1; index++ )
      {
        var check = radioButton[index].checked;
        value = radioButton[index].value;
        text = textSel[index].value;
        if( check == true )
          break;
      }
   }
   else
   {
      value = radioButton.value;
      text = textSel.value;
   }

   // Encontrar el texto del valor seleccionado
   sourceText.value = text;
   // Encontrar el valor seleccionado
   sourceValue.value = value;

   window.close( );

}

function filerNumbers( textField )
{
  var num = parseInt( textField.value, 10 );
  if( isNaN( num ) )
    textField.value = "";
  else
    textField.value = num;
}



function TableRowMaker( tableId ) {
  this.tableId  = tableId;
}

function switchMenu(obj){
  if(document.getElementById){
    var el = document.getElementById(obj);
    var ar = document.getElementById("masterdiv").getElementsByTagName("div");
    for (var i=0; i<ar.length; i++){
      if (ar[i].className=="submenu2"){
        ar[i].style.visibility = "hidden";
      }
    }
    el.style.visibility = "visible";
  }
}

function closeMenu(obj){
  var el = document.getElementById(obj);
  el.style.visibility = "hidden";
}

function setClass(obj, clase){
	obj.className=clase;
}

TableRowMaker.prototype.setContent=function( request, numCell ) {
  if( this.numCells < numCell )
    return;

  this.cells[numCell].innerHTML = request;
}

TableRowMaker.prototype.newRow=function( numCells, numRow ) {
  this.numCells = numCells;
  this.cells = new Array( numCells );
  //var newRow = document.getElementById( this.tableId ).insertRow( -1 );
  var newRow = this.tableId.insertRow( numRow );
  //newRow.bgColor   = "#f7f7e7";
  newRow.className = "x26";
  for( i = 0; i < numCells; i++ ) {
    this.cells[i]  = newRow.insertCell( i );
  }
}

TableRowMaker.prototype.deleteRow=function( numRow ) {
  if( numRow <= this.tableId.rows.length )
    this.tableId.deleteRow( numRow );
}

function ampliarImagen(imagen){
  var ventana = window.open("../html/imagen.html", "imagen", "toolbar = no, scrollbar='auto'");
  ventana.document.writeln("<img src='" + imagen + "'>");
  ventana.document.writeln("<br><center><a href='javascript:window.close();'>Salir</a>");
}

function ca(){
	return '&';
}

	function popUp(URL, ventana, ancho, alto) {
		//day = new Date();
		//id = day.getTime();
        var left=(screen.width-ancho)/2;
        var top=(screen.height-alto)/2;
		eval("page = window.open(URL, '"+ventana+"', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+ancho+",height="+alto+",left = "+left+",top = "+top+"');");
		//location.href='http://localhost:8282'+URL;
//		window.open(URL, ventana, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width="+ancho+",height="+alto+",left = "+left+",top = "+top+"');
        }



function mostrar(){
  cuantos-=direccion;
  if (cuantos==-1){
    direccion*=-1;
  }
  if (cuantos==maximo+1){
    direccion*=-1;
  }
  var texto2="";
  for (i=0; i<cuantos; i++)
  	texto2+=" ";
  window.status=texto2+texto;
  setTimeout("mostrar()", 100);
}
function restablecerTexto(){
  texto=textoOriginal;
}
function cambiarTexto(textoNuevo){

}

function insertarElemento(type, parent) {
	var el = null;
	if (document.createElementNS) {
		// use the XHTML namespace; IE won't normally get here unless
		// _they_ "fix" the DOM2 implementation.
		el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
	} else {
		el = document.createElement(type);
	}
	if (typeof parent != "undefined") {
		parent.appendChild(el);
	}
	return el;
}

 function checkTime(str,campo)
 {
   hora=str.value;
   if(!validarNumero(str,campo)){
     return false;
     }
   if (hora=="") {
     alert("El campo "+campo+" es requerido");
     return false;
    }
   if (hora.length != 5) {
     alert("El formato de "+campo+" no es válido");
     return false;
    }
   a=hora.charAt(0); //<=2
   b=hora.charAt(1); //<4
   c=hora.charAt(2); //:
   d=hora.charAt(3); //<=5

   if ((a==2 && b>3) || (a>2)) {
     alert("El valor que introdujo en la Hora no corresponde, introduzca un digito entre 00 y 23");
     return false;
    }
   if (d>5) {
     alert("El valor que introdujo en los minutos no corresponde, introduzca un digito entre 00 y 59");
     return false;
    }
    return true;
 }

var flag = true;
function seleccionar(){
  var forma = document.forms[0];
  var elementos = forma.elements;
  for(var i=0; i<elementos.length; i++){
    if(elementos[i].type == "checkbox"){
      elementos[i].checked = flag;
    }
  }
  flag = !flag;
}

var flag2 = true;
function seleccionarConForm(forma){
   var elementos = forma.elements;
  for(var i=0; i<elementos.length; i++){
    if(elementos[i].type == "checkbox"){
      elementos[i].checked = flag2;
    }
  }
  flag2 = !flag2;
}

function mayusculas(obj){
  if (typeof event != 'undefined'){
  // 37 flecha a la izq
  // 39 flecha a la der
  // 38 flecha arriba
  // 40 flecha abajo
  // 8 backspace
  // 9 tab
  // 46 suprimir
  // 36 inicio
  // 35 fin
  // 16 shift

    if (event.keyCode!=8 && event.keyCode!=36 && event.keyCode!=37 && event.keyCode!=39 && event.keyCode!=46 && event.keyCode!=38 && event.keyCode!=40 && event.keyCode!=9 && event.keyCode!=35 && event.keyCode!=16 )
      obj.value=obj.value.toUpperCase();
  }else{
    //obj.value=obj.value.toUpperCase();
  }
}

function mayusculasSinEspacios(obj){
  if (typeof event != 'undefined'){
  // 37 flecha a la izq
  // 39 flecha a la der
  // 38 flecha arriba
  // 40 flecha abajo
  // 8 backspace
  // 9 tab
  // 46 suprimir
  // 36 inicio
  // 35 fin
  // 16 shift

    if (event.keyCode!=8 && event.keyCode!=36 && event.keyCode!=37 && event.keyCode!=39 && event.keyCode!=46 && event.keyCode!=38 && event.keyCode!=40 && event.keyCode!=9 && event.keyCode!=35 && event.keyCode!=16){

      var valor=obj.value.toUpperCase();
      var nuevo='';

      for (i=0; valor!=null && i<valor.length; i++)
        if (valor.substring(i, i+1)!=' ')
          nuevo+=valor.substring(i, i+1);
      obj.value=nuevo;
    }
  }else{
    //obj.value=obj.value.toUpperCase();
  }
}

function tratandoCerrar(){
  /*alert('x: '+window.event.clientX);
  alert('y: '+window.event.clientY);*/
  var pagina=location.href;
  var pag='listarProcesoAsincrono';
  if(!pagina.match(pag)){
    if ((window.event.clientX<0 && window.event.clientX>-3060) || (window.event.clientY<0 && window.event.clientY>-3060))
      event.returnValue = "Si acepta, su sesión será cerrada!!!";
  }
}

function cerrando()
{
/*    alert(document.body.onbeforeunload);
    alert(window.event.clientX);
    alert(window.event.clientY);*/
  var pagina=location.href;
  var pag='listarProcesoAsincrono';
  if(!pagina.match(pag)){
    if (document.body.onbeforeunload!="" && ((window.event.clientX<0 && window.event.clientX>-3060) || (window.event.clientY<0 && window.event.clientY>-3060) || (window.event.clientX<-9000 && window.event.clientY<-9000))){
      location.href="cerrarsession";
      alert("Sesión cerrada");
    }
  }
}


/**
 * función para ejecutar un procedimiento o una lista de valores a traves de AJAX
 *
 * @param metodoHTTP  - Tipo de solicitud HTTP: GET,POST,etc.
 * @param asyn  - boolean que indica si la solicitud es asincrona (true) o no (false)
 * @param parametros  - parametros que se le envian al recurso solicitado.
 *
 *                      parámetros obligatorios generales:
 *                        tipo=1(si es procedimiento),2 si es una función oracle o
 *                             3 si es una lista de valores
 *                        sp=nombre del procedimiento, función o lista de valores
 *
 *                      parámetros obligatorios específicos:
 *                        Lista de Valores:
 *                          filtrosLista=nombreColumnaFiltro1-valorFiltro1,...,nombreColumnaFiltroN-valorFiltroN.
 *                          colsRetorno=numeroColumnaRetorno1,numeroColumnaRetorno2,...,numeroColumnaRetornoN.
 *
 *                      Parámetros opcionales específicos:
 *                        Procedimiento o Función:
 *                          serían los parametros de entrada que recibe el procedimiento
 *                          o función.  de la forma:  nombreParam1=valor1&...&nombreParamN=valorN;
 *                        Lista de Valores:
 *                          paramLista=Los parametros que recibe el select de la lista.  De la
 *                          forma:  valorParam1-tipoDatoParam1,...,valorParamN-tipoDatoParamN
 * @return Arreglo  - Arreglo con los resultados retornado por el procedimiento, función o lista de
 *                    valores.
 *                      * Si hubo una excepción al momento de ejecutar el procedimiento, función o
 *                        la lista de valores; el retorno de esta función será un arreglo de 2 posiciones,
 *                        en cuya primer posición (la cero-0), contendrá la palabra 'excepcion' y en la
 *                        segunda posición (la uno-1) contendrá el mensaje de la excepción como tal.
 *                      * Si la ejecución del procedimiento, función o la lista de valores fue satisfactoria;
 *                        El retorno de esta función será un arreglo; que en cuya primer posicion (la cero-0),
 *                        contendrá el número de valores retornados por el procedimiento, función o
 *                        lista de valores; y en las siguientes posiciones (si el valor de la primera
 *                        posición del arreglo es mayor a cero) contendrá los valores retornados por
 *                        el procedimiento, función o lista de valores.
 */

function ajaxGenerico(metodoHTTP,asyn,parametros){

  /*
  **  url - servlet que procesa la solicitud
  */
  var url = "spcontroller";

  /*
  ** Se crea el objeto request dependiendo del
  ** navegador
  */
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  req.open(metodoHTTP, url, asyn);
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  if(asyn || asyn=='true')
    req.onreadystatechange = callback;

  req.send(parametros);

  if(!asyn || asyn=='false')
    return callSync(req);

}


function callback(){
  if (req.readyState == 4) {
    if (req.status == 200) {
      retorno = new Array();
      nodoRaiz = req.responseXML.getElementsByTagName("message")[0];
      //alert('raiz='+nodoRaiz);
      nodosHijos = nodoRaiz.childNodes;
      //alert('hijos= '+nodosHijos[0].childNodes[0].nodeValue+'   '+nodosHijos[1].childNodes[0].nodeValue);
      for(i=0;i<nodosHijos.length;++i){
        nodoHijo=nodosHijos[i];
        if(nodoHijo.nodeName == 'error' || nodoHijo.nodeName == 'ERROR'){
          retorno[0]='excepcion';
          retorno[1]=nodoHijo.childNodes[0].nodeValue;
          return retorno;
        }
        retorno[i]=nodoHijo.childNodes[0].nodeValue;
      }
      return retorno;
    }
  }
}


function callSync(request){
  if (request.readyState == 4) {
    if (request.status == 200) {
      retorno = new Array();
      //alert(request.responseXML.parentNode);
      nodoRaiz = request.responseXML.getElementsByTagName("message")[0];
      //alert('raiz='+nodoRaiz.nodeName);
      nodosHijos = nodoRaiz.childNodes;
      //alert('hijos= '+nodosHijos[0].nodeName+'   '+nodosHijos[0].childNodes[0].nodeValue);
      for(i=0;i<nodosHijos.length;++i){
        nodoHijo=nodosHijos[i];
        if(nodoHijo.nodeName == 'error' || nodoHijo.nodeName == 'ERROR'){
          retorno[0]='excepcion';
          retorno[1]=nodoHijo.childNodes[0].nodeValue;
          return retorno;
        }
        retorno[i]=nodoHijo.childNodes[0].nodeValue;
      }
      return retorno;
    }
  }
}


    function cerrar(){
      document.body.onbeforeunload="";
      window.close();
      return true;
    }

    function salir(){
      if (confirm('Realmente desea salir?')){
        location.href="cerrarsession";
        return true;
      }
      return false;
    }
  function deshabilitar(){
    numeroClick++;
    if (numeroClick==1)
      return true;
    else
      return false;
  }

    function cerrarIrOpener(){
      document.body.onbeforeunload="";
      window.close();
      opener.focus();
    }

function validarFecha(fecha, sabado, domingo, festivo){
  if (fecha!=''){
    var parametros='sp=GE_FDIA_MIG&tipo=2&fecha='+fecha;
    respuesta=ajaxGenerico('POST',false,parametros);
    texto=respuesta[1];
    if (texto=="SABADO" && sabado)
      alert("La fecha seleccionada es un Sábado");
    if (texto=="DOMINGO" && domingo)
      alert("La fecha seleccionada es un Domingo");
    if (texto=="FESTIVO" && festivo)
      alert("La fecha seleccionada es un Festivo");
    if (texto=="FECHA INVALIDA")
      alert("La fecha seleccionada es inválida");
  }
}

function validarVacio(campo){
  fecha=campo.value;
  if (fecha==null || fecha=='' || fecha=='dd/mm/yyyy'){
    respuesta=ajaxGenerico('POST', false, 'tipo=4');
     campo.value=respuesta[1];
  }
}

function textCounter(field,maxlimit) {
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
    
}

function leer(formu){
	var cadena='';
	var tipo=formu['formPrincipal:tipo'].value;
	var eje=formu['formPrincipal:eje'].value;
	var corporacion=formu['formPrincipal:corporacion'].value;
	var departamento=formu['formPrincipal:departamento'].value;
	var municipio=formu['formPrincipal:municipio'].value;
	var palabra_clave=formu['formPrincipal:palabra_clave'].value;
	cadena+='tipo='+tipo;
	if (eje!="")
		cadena+="&eje="+eje;
	if (corporacion!="")
		cadena+="&corporacion="+corporacion;
	if (departamento!="")
		cadena+="&departamento="+departamento;
	if (municipio!="")
		cadena+="&municipio="+municipio;
	if (palabra_clave!="")
		cadena+="&palabra_clave="+palabra_clave;
	return cadena;
}

function leer1(formu){
	var cadena='';
	var tipo=formu['formPrincipal:tipo'].value;
	var eje=formu['formPrincipal:eje'].value;
	var departamento=formu['formPrincipal:departamento'].value;
	var municipio=formu['formPrincipal:mun'].value;
	var palabra_clave=formu['formPrincipal:palabra_clave'].value;
	cadena+='tipo='+tipo;
	if (eje!="")
		cadena+="&eje="+eje;
	if (departamento!="")
		cadena+="&departamento="+departamento;
	if (municipio!="")
		cadena+="&municipio="+municipio;
	if (palabra_clave!="")
		cadena+="&palabra_clave="+palabra_clave;
	return cadena;
}

function leer2(formu){
	var cadena='';
	var corporacion=formu['formPrincipal:corporacion'].value;
	var departamento=formu['formPrincipal:departamentoCorp'].value;
	var municipio=formu['formPrincipal:munCorp'].value;
	var palabra_clave=formu['formPrincipal:palabra_claveCorp'].value;
	cadena+='tipo=34';
	if (corporacion!="")
		cadena+="&corporacion="+corporacion;
	if (departamento!="")
		cadena+="&departamento="+departamento;
	if (municipio!="")
		cadena+="&municipio="+municipio;
	if (palabra_clave!="")
		cadena+="&palabra_clave="+palabra_clave;
	return cadena;
}

function leer3(formu){
	var cadena='';
	var tipo=formu['formPrincipal:tipoFinan'].value;
	var departamento=formu['formPrincipal:departamentoFinan'].value;
	var municipio=formu['formPrincipal:munFinan'].value;
	var palabra_clave=formu['formPrincipal:palabra_claveFinan'].value;
	cadena+='tipo=34';
	if (tipo!="")
		cadena+="&tipoFinanciacion="+tipo;
	if (departamento!="")
		cadena+="&departamento="+departamento;
	if (municipio!="")
		cadena+="&municipio="+municipio;
	if (palabra_clave!="")
		cadena+="&palabra_clave="+palabra_clave;
	return cadena;
}

function mostrarOcultar(imagen){
	if (imagen==''){
		document.getElementById('formPrincipal:foto').style.display='none';
		return;
	}else{
		document.getElementById('formPrincipal:foto').style.display='block';
		document.getElementById('formPrincipal:foto').src='/asocars/descargaDocumentos?idDocumento='+imagen;
		return;
	}
}

function abrirPopup3(URL,nombreVentana,alto,ancho,menuBar){
	
	if (false && window.showModalDialog){
	        if(menuBar || menuBar=='true'){
	        features="help:'no';status:'no';center:'yes';resizable:'no';menubar='yes';dialogWidth:"+ancho+"px;dialogHeight:"+alto+"px";
	        }
	        else{
	        features="help:no;status:no;center:yes;resizable:no;location:no;dialogWidth:"+ancho+"px;dialogHeight:"+alto+"px";
	        }

	         winpbys=window.showModalDialog(URL, self, features);
	    }else{

	        var left=(screen.width-ancho)/2;
	        var top=(screen.height-alto)/2;
	        if(menuBar || menuBar=='true'){
	          caracteristicas="height="+alto+",width="+ancho+",left="+left+",top="+top+",status=yes,toolbar=no,menubar=yes,location=no,scrollbars=yes";
	        }else{
	          caracteristicas="height="+alto+",width="+ancho+",left="+left+",top="+top+",status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes";
	        }
	        openDialog(URL,nombreVentana,caracteristicas);
	        document.onclick = processClicks;
	        document.ondblclick = processClicks;
	        document.onkeypress = processClicks;
	    }
	}

function openDialog(theURL,winName,features){
	  var IE = navigator.appName=="Microsoft Internet Explorer";
	  var NS = navigator.appName=="Netscape";
	  if(IE){
	    openWinIEDialog(theURL,winName,features)
	  }else{
	    openWinMozDialog(theURL,winName,features)
	  }
	}

	//funcion para el manejo de popup modal en Netscape
	 function openWinMozDialog(theURL,winName,features) { //v2.0
	    window.top.captureEvents (Event.CLICK|Event.FOCUS)
	    window.top.onclick=IgnoreEvents
	    window.top.onfocus=HandleFocus
	    winId =  window.open(theURL,winName,features);
	    window.opener = winId;
	    winId.focus();
	}

	//funcion para el manejo de popup modal
	// en Internet Explorer
	function openWinIEDialog(theURL, winName, features){
	    winId = window.open(theURL,winName, features); // open an empty window
	    //winId.openerFormId = formId;
	    winId.focus();
	}

	function IgnoreEvents(e){
	    return false;
	}

	function HandleFocus(){
	    if (winId){
	        if (!winId.closed){
	            winId.focus();
	        }
	        else{
	            window.top.releaseEvents (Event.CLICK|Event.FOCUS)
	            window.top.onclick = "";
	        }
	    }
	    return false
	}
	
	
	//funcion para manejo del evento clic en popup modal
	// de Intenet explorer
	function processClicks() {
	    if (winId){
	        if (!winId.closed){
	            winId.focus();
	        }
	    }
	}

