//var urlDir='http://localhost/ap_sigespro/';
var urlDir='http://localhost/enfer/';
//var urlDir='http://usfx.info/sigespro/';
//var urlDir='http://10.0.11.14/ap_sigespro/';
/*
	ñ -> Ã±
	á -> Ã¡
	é -> Ã©
	í -> Ã­
	ó -> Ã³
	ú -> Ãº
*/
//alert(document.URL);
function ajax()
{
	var o_ajax; 
	try 
	{
		o_ajax = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e) 
	{
		try 
		{
			o_ajax = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) 
		{
			o_ajax= false;
		}
	}
	if (!o_ajax && typeof XMLHttpRequest!='undefined') 
	{
		o_ajax = new XMLHttpRequest();
	}
	return o_ajax;
}


function animar_cargador()
{
	showLightbox();
/*	var contenedor = document.getElementById('cargando');
	contenedor.style.display = '';
	contenedor.style.visibility = '';
	*/
}
function ocultar_cargador() {
	hideLightbox();
/*	var contenedor = document.getElementById('cargando');
	contenedor.style.display='none';
	contenedor.style.visibility='hidden';*/
}


/*
Función que carga contenido en un contenedor
dirURL:		Dirección de la que se cargará el contenido
contenedor:	Contenedor en el cual se mostrará el contenido
msj:		Anula el mensaje de información anterior en caso de ser vacio, 
			muestra el msj enviado en caso de tener valor '',
			caso contrario no hace nada
*/
function cargar_div(id_div, dir_url, metodo, parametros, transferencia, cargador)
{
	if(transferencia == '')
		transferencia = true;
	if(parametros == '')
		parametros = false;
	if(cargador)
		animar_cargador();
	
	var o_ajax 	= ajax();
	var id_div  = document.getElementById(id_div);

	o_ajax.open(metodo, dir_url, transferencia);
	o_ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
	o_ajax.onreadystatechange = function()
	{
		switch(o_ajax.readyState)
		{
			case 1:
				if(cargador)
					animar_cargador();
			break;
			case 2:
				if(cargador)		
					animar_cargador();
			break;
			case 4:
				if(o_ajax.status==200)
				{
					id_div.innerHTML = o_ajax.responseText;
					if(cargador)
						ocultar_cargador();
				}
				else
				{
					if(cargador){
						ocultar_cargador();							
						alert('Error: ' + o_ajax.status);
					}
						
				}
			break;
		}
	}
	if(metodo == 'GET')
		o_ajax.send(null);
	if(metodo == 'POST')
		o_ajax.send(parametros);
}


var numero = 0;
var cantidad = 0;
// Funciones comunes
c= function (tag) { // Crea un elemento
   return document.createElement(tag);
}
d = function (id) { // Retorna un elemento en base al id
   return document.getElementById(id);
}
e = function (evt) { // Retorna el evento
   return (!evt) ? event : evt;
}
f = function (evt) { // Retorna el objeto que genera el evento
   return evt.srcElement ?  evt.srcElement : evt.target;
}
	addField = function () {
	if(cantidad<=2){	
	cantidad++;
   container = d('files');
   
   span = c('SPAN');
   span.className = 'file';
   span.id = 'file' + (++numero);

   field = c('INPUT');   
   field.name = 'archivos[]';
   field.type = 'file';
   
   a = c('A');
   a.name = span.id;
   a.href = '#';
   a.onclick = removeField;
   a.innerHTML = 'Quitar';

   span.appendChild(field);
   span.appendChild(a);
   container.appendChild(span);
	}
}
removeField = function (evt) {
	cantidad--;
   lnk = f(e(evt));
   span = d(lnk.name);
   span.parentNode.removeChild(span);
}

var win = null;
function ventana(pagina,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h-55)/2 : 0;
	estilo ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',menubar=yes,scrollbars=yes,toolbar=no,location=no,directories=no,resizable=no';
	win = window.open(pagina,'ventana',estilo)
}

function imprSelec(opcion)
{
	switch(opcion){
		case "1":
			nombre = 'cuerpo_imprimir';
			break;	
		case "2":
			nombre = 'contenido_imprimir';
			break;
		default:
			nombre = 'cuerpo_imprimir';
			break;	
}
	
  	var ficha = document.getElementById(nombre);
 	var ventimp = window.open(' ', 'popimpr');
	ventimp.document.write( '<head><link rel="stylesheet" href="plantillas/mccv/css/clases.css" type="text/css" /></head><body style="background:none;">' );
	ventimp.document.write( ficha.innerHTML );
	ventimp.document.write( '</body>' );
	ventimp.document.close();
	ventimp.print( );
	ventimp.close();
} 
/*
PARA EL LISTADO EN JEFE_PROYECTO
*/
function set_rdn_id(frm,valor){
	var form = document.getElementById(frm);
	with (form){
		if(rdn_id.length)  //si es mas de uno
			rdn_id[valor-1].checked = true;
		else  //si solo hay uno en la lista
			rdn_id.checked = true;
	}
}
/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)

{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 1.1 Sets the mouse pointer to pointer on mouseover and back to normal otherwise.
    if (theAction == "over" || theAction == "click") {
        theRow.style.cursor='pointer';
    } else {
        theRow.style.cursor='default';
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0)
    {
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function


	var nav = window.Event ? true : false; //objeto en el que se definen los eventos window

	function validar_num(evento){
		var key = evento.keyCode ? evento.keyCode : evento.which ? evento.which : evento.charCode; 
		return (key <= 13 || key == 46 || (key >= 48 && key <= 57)); //solo permite numeros y punto
	}
	function validar_numfecha(evento){
		var key = evento.keyCode ? evento.keyCode : evento.which ? evento.which : evento.charCode; 
		return (key <= 13 || key == 45 || (key >= 48 && key <= 57)); //solo permite numeros y punto
	}
	function desplazar(id_div,op){
		var id_div = document.getElementById(id_div);	
		if(op=='si')
			id_div.style.display = 'block';
		else
			id_div.style.display='none';
	}

  // Uso: Simple... se debe pasar la cadena de la fecha y devuelve false si no es válida...  
  // El Formato es dd-mm-aaaa  
  // Ejemplo: if (Validar('14-08-1981')==false) { alert('Entrada Incorrecta') }  
  // Uso en formularios: onSubmit="return Validar(this.fecha.value)"  
  function validar_fecha(texto){  
	var texto = document.getElementById(texto);
	  Cadena = texto.value;
      var Fecha= new String(Cadena)   // Crea un string  
      var RealFecha= new Date()   // Para sacar la fecha de hoy  
    // Cadena Año  
	 if(Cadena!=''){
      var Ano= new String(Fecha.substring(Fecha.lastIndexOf("-")+1,Fecha.length))  
     // Cadena Mes  
      var Mes= new String(Fecha.substring(Fecha.indexOf("-")+1,Fecha.lastIndexOf("-")))  
      // Cadena Día  
      var Dia= new String(Fecha.substring(0,Fecha.indexOf("-")))  
    
      // Valido el año  del 2007 hasta el 2001
      if (isNaN(Ano) || Ano.length<2 || parseFloat(Ano)<7 || parseFloat(Ano)>10){  
		texto.style.background='#FFC4C4';
        return false  
      }  
      // Valido el Mes  
      if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12){  
		texto.style.background='#FFC4C4';
        return false  
      }  
      // Valido el Dia  
      if (isNaN(Dia) || parseInt(Dia, 10)<1 || parseInt(Dia, 10)>31){  
		  texto.style.background='#FFC4C4';
          return false  
      }  
      if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2) {  
          if (Mes==2 && Dia > 28 || Dia>30) {  
			texto.style.background='#FFC4C4';
            return false  
          }  
      }
    //para que envie los datos, quitar las  2 lineas siguientes 
		texto.style.background='';
		return true    
	 }
	 return false;
  } 

function editar_datos()
{
	document.frm_registro.txt_nombre.disabled=false;
	document.frm_registro.txt_apellido.disabled=false;
	document.frm_registro.txt_cargo.disabled=false;
	document.frm_registro.txt_toficina.disabled=false;
	document.frm_registro.txt_tdomicilio.disabled=false;
	document.frm_registro.txt_celular.disabled=false;
	document.frm_registro.txt_email.disabled=false;
	document.frm_registro.btn_actualizar.disabled=false;
	document.frm_registro.txt_clave.disabled=false;
	document.frm_registro.txt_clave1.disabled=false;	
}
function validar_datos()
{
	var error = 0;
	var message = 'Se encontraron los siguientes errores\n\n';
	var count = 0;

	var name = document.frm_registro.txt_nombre.value;
	var longitud = name.length;
	if (longitud<2)
	{
		count ++;
		message = message +count+'. El nombre debe tener al menos dos caracteres\n';
		if (error == 0)
		{
			document.frm_registro.txt_nombre.select();
			document.frm_registro.txt_nombre.focus();
		}

		error = 1;
	}
	var name = document.frm_registro.txt_apellido.value;
	var longitud = name.length;
	if (longitud<2)
	{
		count ++;
		message = message +count+'. El Apellido debe tener al menos dos caracteres\n';

	if (error == 0)
		{
			document.frm_registro.txt_apellido.select();
			document.frm_registro.txt_apellido.focus();
		}
		error = 1;
	}

    var dia_nac=document.frm_registro.txt_toficina;
	var telf=document.frm_registro.txt_toficina.value;
	if (telf=="")
	{
	}
	else
	{
	if (checkNumeric(dia_nac))
	{
		
	}
	else
	{
		count ++;
		message = message + count+ ". El telefono de oficina no es válido\n";
		error = 1;
		//document.customer_form.customer_dob_day.focus();
	}
	}

    var dia_nac=document.frm_registro.txt_tdomicilio;
	var telf=document.frm_registro.txt_tdomicilio.value;
	if (telf=="")
	{
	}
	else
	{
	if (checkNumeric(dia_nac))
	{
		
	}
	else
	{
		count ++;
		message = message + count+ ". El telefono de domicilio no es válido\n";
		error = 1;
		//document.customer_form.customer_dob_day.focus();
	}
	}
	
	   var dia_nac=document.frm_registro.txt_celular;
	var telf=document.frm_registro.txt_celular.value;
	if (telf=="")
	{
	}
	else
	{
	if (checkNumeric(dia_nac))
	{
		
	}
	else
	{
		count ++;
		message = message + count+ ". El celular no es válido\n";
		error = 1;
		//document.customer_form.customer_dob_day.focus();
	}
	}

	var email = document.frm_registro.txt_email.value;
	var email_reg_exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
	if (email=="")
	{
	}
	else
	{
	if (!email_reg_exp.test(email)){
		count ++;
		message = message + count+'. Dirección de email no válida\n';

		if (error == 0){
			document.frm_registro.txt_email.select();
			document.frm_registro.txt_email.focus();
		}
		error = 1;
	}
	}


	var ci = document.frm_registro.txt_clave.value;
	var longitud = ci.length;
	if (longitud==0)
	{
	}
	else
	{
	if (longitud<5){
		count ++;
		message = message +count+'. La contraseña debe tener 5 caracteres como mínimo\n';
		if (error == 0){
			document.frm_registro.txt_clave.select();
			document.frm_registro.txt_clave.focus();
		}
		error=1;
	}
	}

	var pwdconf = document.frm_registro.txt_clave1.value;
	if (ci!=pwdconf){
		count ++;
		message = message +count+'. Las contraseñas tienen que ser idénticas\n';

		if (error == 0){
			document.frm_registro.txt_clave1.select();
			document.frm_registro.txt_clave1.focus();
		}
		error=1;
	}
  if (error==1)
  {
    alert(message);
    return false;
  }
  else
  {
	xajaxRequestUri=urlDir+'index.php?sc=superusuario&op=guardar';
	xajax_editar_datos(xajax.getFormValues('frm_registro'));
  }
}


function checkNumeric(objName)
{
	var numberfield = objName;
	if (chkNumeric(objName) == false){
		return false;
	}else{
		return true;
	}
}

function chkNumeric(objName){
	var checkOK = "0123456789/.-(),+*";
	var checkStr = objName;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";

	for (i = 0;  i < checkStr.value.length;  i++){
		ch = checkStr.value.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
		break;
		if (j == checkOK.length){
			allValid = false;
			break;
		}
		if (ch != ",")
		allNum += ch;
	}
	var str = objName.value;
	var strlen = str.length;
	if (!allValid || strlen==0){
		return false;
	}else{
		return true;
	}
}
