document.write("<script type='text/javascript' src='libjs/doc/context-menu.js'></"+"script>");
document.write("<script type='text/javascript' src='libjs/doc/drag-drop-folder-tree.js'></"+"script>");

function format_number(p,d) 
{
  var r;
  if(p<0){p=-p;r=format_number2(p,d);r="-"+r;}
  else   {r=format_number2(p,d);}
  return r;
}
function format_number2(pnumber,decimals) 
{
  var strNumber = new String(pnumber);
  var arrParts = strNumber.split('.');
  var intWholePart = parseInt(arrParts[0],10);
  var strResult = '';
  if (isNaN(intWholePart))
    intWholePart = '0';
  if(arrParts.length > 1)
  {
    var decDecimalPart = new String(arrParts[1]);
    var i = 0;
    var intZeroCount = 0;
     while ( i < String(arrParts[1]).length ) {
       if( parseInt(String(arrParts[1]).charAt(i),10) == 0 ) {
         intZeroCount += 1;
         i += 1;
       }
       else
         break;
    }
    decDecimalPart = parseInt(decDecimalPart,10)/Math.pow(10,parseInt(decDecimalPart.length-decimals-1)); 
    Math.round(decDecimalPart); 
    decDecimalPart = parseInt(decDecimalPart)/10; 
    decDecimalPart = Math.round(decDecimalPart); 

    //If the number was rounded up from 9 to 10, and it was for 1 'decimal' 
    //then we need to add 1 to the 'intWholePart' and set the decDecimalPart to 0. 

    if(decDecimalPart==Math.pow(10, parseInt(decimals)))  { 
      intWholePart+=1; 
      decDecimalPart="0"; 
    } 
    var stringOfZeros = new String('');
    i=0;
    if( decDecimalPart > 0 ) {
      while( i < intZeroCount) {
        stringOfZeros += '0';
        i += 1;
      }
    }
    decDecimalPart = String(intWholePart) + "." + stringOfZeros + String(decDecimalPart); 
    var dot = decDecimalPart.indexOf('.');
    if(dot == -1) {
      decDecimalPart += '.'; 
      dot = decDecimalPart.indexOf('.'); 
    }
    var l=parseInt(dot)+parseInt(decimals); 
    while(decDecimalPart.length <= l) 
    {
      decDecimalPart += '0'; 
    }
    strResult = decDecimalPart;
  }
  else
  {
    var dot; 
    var decDecimalPart = new String(intWholePart); 

    decDecimalPart += '.'; 
    dot = decDecimalPart.indexOf('.'); 
    var l=parseInt(dot)+parseInt(decimals); 
    while(decDecimalPart.length <= l) 
    {
      decDecimalPart += '0'; 
    }
    strResult = decDecimalPart;
  }

	var n = strResult.split(".");
	var num = n[0];

	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));

	if (parseInt(n[1])>0) {
		strResult = num+"."+n[1];
	} else {
		strResult = num;
	}
  return strResult;
}

/******************************************** RELOJ ONLINE ***************************/

function startTime()
{
	var today=new Date();
	var h=today.getHours();
	var m=today.getMinutes();
	var s=today.getSeconds();
	var d= checkTime(today.getDate());
	var me= checkTime(today.getMonth());
	var y= today.getFullYear();
	
	// add a zero in front of numbers<10
	m=checkTime(m);
	s=checkTime(s);
	document.getElementById('online_clock').innerHTML = d+"-"+me+"-"+y+" "+h+":"+m+":"+s;
	t=setTimeout('startTime()',500);
}

function checkTime(i)
{
	if (i<10) 
	  {i="0" + i;}
	  return i;
}

/******************************************** EVITAR QUE SE HABRA EN UNA FRAME ***************************/

if (top.location != self.location)top.location = self.location;

/********************************************LIMPIEZA INICIAL PARA EVITAR QUE SE VEA LINK ***************************/
function hidestatus()
{
	window.status=''
	return true
}
if (document.layers)
	document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT );
document.onmouseover=hidestatus;
document.onmouseout=hidestatus;
/******************************************************************************************************************************/
function invString(message1)
{
	var message2="";

	for (count = message1.length; count >= 0; count--)
		message2 += message1.substring(count,count-1);
  
  return message2;
}
/****************************************INVERTIR FORMATO FECHA*****************************************/
function invDate(dateInfo)
{
	var formato = 1;
	return invFecha(formato,dateInfo);
}

/* Validación de fecha mayor by Mauricio Escobar

Este script y otros muchos pueden descarse on-line de forma gratuita en El Código: www.elcodigo.com

Formato de la fecha
 1 = DD/MM/YYYY
 2 = MM/DD/YYYY   
 3 = YYYY/MM/DD
 4 = YYYY/DD/MM

    invierta una fecha dada retornando en formato YYYYMMDD  
	dFecIni = Fecha a invertir 
	nTipFormat = Formato en que biene la fecha
             1 = DD/MM/YYYY
             2 = MM/DD/YYYY   
             3 = YYYY/MM/DD
             4 = YYYY/DD/MM
*/
function invFecha(nTipFormat,dFecIni)
{
	var separador = "-";
   var dFecIni = dFecIni.replace(/-/g,"/");               // reemplaza el - por /   
   
   // primera division fecha
   var nPosUno = ponCero(dFecIni.substr(0,dFecIni.indexOf("/")));
   // 2º divicion fecha
   var nPosDos = ponCero(dFecIni.substr(parseInt(dFecIni.indexOf("/")) + 1,parseInt(dFecIni.lastIndexOf("/")) - parseInt(dFecIni.indexOf("/")) - 1));
   // 3º divicion fecha
   var nPosTres = ponCero(dFecIni.substr(parseInt(dFecIni.lastIndexOf("/")) + 1));

   switch(nTipFormat)
   {
      case 1 :   //   DD/MM/YYYY
         dReturnFecha = nPosTres + separador + nPosDos + separador + nPosUno;
         break;

      case 2 :   //   MM/DD/YYYY
         dReturnFecha = nPosTres + separador + nPosUno + separador +nPosDos;
         break;

      case 3 :   //   YYYY/MM/DD
         dReturnFecha = nPosUno + separador + nPosDos + separador +nPosTres;
         break;
   
      case 4 :   //   YYYY/DD/MM
         dReturnFecha = nPosUno + separador + nPosTres +separador +nPosDos;
         break;
   }
   
   return dReturnFecha;   // retorna la fecha    
}

// Agrega un cero delante del strPon cuando tenga solo un caracter
function ponCero(strPon){
   if(parseInt(strPon.length) < 2)
      strPon = "0" + strPon;
   return strPon;
}
/******************************************FUNCIONES PROPIAS DEL SISTEMA********************************************************************/
/*funciones de posicion de div dentro de la ventana */
function getWidthWindow()
{
	return getSizeWindow('width');
}

function getHeightWindow()
{
	return getSizeWindow('height');
}

function getSizeWindow(type)
{
	var winW = 0; var winH = 0;

	 if (document.all) 
	 {
		  winW = document.body.offsetWidth;
		  winH = document.body.offsetHeight;
	 }
	 else
	 {
		  winW = window.innerWidth;
		  winH = window.innerHeight;
	 }
	
	if(winH == 0)
		winH = 500;
		
	//alert(winH+' '+winW)
		

	if(type == 'width')
		return winW;
	else
		return winH;
}

function centerPositionDiv(id)
{
	var left, top; 
	var parent = window; 
	var Div = document.getElementById(id); 
	var width  = Div.getWidth();
	var height = Div.getHeight(); 

	var winW = 0;
	var winH = 0;

	if (document.all) {
		winW = document.body.offsetWidth;
		winH = document.body.offsetHeight;
	} else {
		winW = window.innerWidth;
		winH = window.innerHeight;
	}

	var left_var = Math.max(0, (winW - width)/2); 
	var top_var = Math.max(0, (winH - height)/2); 

	Div.style.left = left_var+'px';  
	Div.style.top = top_var+'px';        
}


/******************************************************************************************************************************/


/*Funciones del BUC Original*/
 function validaDia(control) {
   if (control.value!='') {
	  if (control.value < 1 || control.value > 31 || !isNumber(control.value)) {
		   alert('El dia solo puede estar entre 1 y 31');
		   control.value='';
	  }
   }
 }
 function validaMes(control) {
   if (control.value!='') {
	  if (control.value<1 || control.value>12 || !isNumber(control.value)) {
		   alert('El mes solo puede estar entre 1 y 12');
		   control.value='';
	  }
   }
 } 
  function validaAgno(control) {
   if (control.value!='') {
	  if (control.value<1 || control.value>2050 || !isNumber(control.value)) {
		   alert('El dia solo puede estar entre 1 y 2050');
		   control.value='';
	  }
   }
 } 

 function isNumber(sText) {
   var ValidChars = '0123456789';
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
	  Char = sText.charAt(i); 
	  if (ValidChars.indexOf(Char) == -1) {
		IsNumber = false;
	  }
   }
   return IsNumber;
 }
function openLink(linkFile) 
{
	window.open(linkFile); 
}
/*Funciones del BUC Original*/

/*muestra los pisos con foto*/
function showPicture(file,piso) {

	var coordenadas= document.main.coordenadas.value;
	var pisoOld=document.main.piso.value;
	var texto="showPicture.php?file="+file+"&piso="+piso+"&coordenadas="+coordenadas+"&pisoold="+pisoOld;
	
	 window.open(texto,file,"width=1100,height=520,noscroll,resizable,menubar=no,toolbar=no,status=yes,dependent=yes");
}

function cleanSelect(inputSelect)
{		
	var r = inputSelect;
		
	for(i=0; i < r.length ; i++)
	{
		if( r[i].selected )
				r[i].selected = false;			
	}
	
}

function checkSelect(name)
{		
	var r = searchElement(name);
		
	for(var i=0; i < r.length ; i++)
	{
		if( r[i].selected )
		{
			return true;			
		}
	}
	return false;
}

function checkInputCheck(nameInput)
{
	var x = document.main.elements;	
	var hayCheck = false;
	for (var i=0 ; i < x.length ; i++)
	{				
		if(x[i].name == nameInput)
		{
			if(x[i].checked)
				hayCheck = true;	
		}		
	}
	return hayCheck;
}



function cleanCheck(inputCheck)
{
	var r = inputCheck;
	if( r.checked )
		r.checked = false;
		
	if(r.defaultChecked)
		r.defaultChecked=false;
}

function idVisibility(id)
{  
	if( document.getElementById(id).style.visibility == "hidden" ) 
		document.getElementById(id).style.visibility = "visible";
	else 
		document.getElementById(id).style.visibility = "hidden";
}


function mensajeErrorForm(msg) {
	
	var id = 'mensaje_form_error';
	document.getElementById(id).innerHTML =  msg;
	mostrarError(id);
}

function mostrarError(id)
{
	document.getElementById(id).style.visibility = "visible";
	document.getElementById(id).style.height = '';	
	document.getElementById(id).style.padding = "";
}

function eliminarError(id)
{
	document.getElementById(id).style.visibility = "hidden";
	document.getElementById(id).style.height = '0px';
	document.getElementById(id).style.padding = "0px";
}

function searchElement(name)
{
	var x = document.main.elements;	
	for (var i=0 ; i < x.length ; i++)
	{			
		if(x[i].name == name ) {
			//alert(x[i].name);
			return x[i];		
		}
	}
	return false;
}


function selectOption(input,optionValue)
{
	var optiones =searchElement(input);
	var total = optiones.length;
	for(var i=1; i < total ; i++)
	{
		if(optiones.options[i] == optionValue)
			optiones.options[i].selected = true;
	}	
}


/*muestra y esconde las filas*/
function hidetr(id) 
{
	document.getElementById(id).style.display = 'none';
}

function showtr(id)
{			
	if (document.getElementById(id)) 
	{
		if (document.all)
			document.getElementById(id).style.display= 'block';
		else
			document.getElementById(id).style.display = 'table-row';
	}
}



function guardarContenidoMenu(prefijo,idmenu)
{
	if(document.main.editarMenu.value == '')
	{
		alert("El menú deber tener contenido");
	}
	else
	{		
		var opciones = 'idmenu='+idmenu+'&contenido='+document.main.editarMenu.value;		
		var url = prefijo+'externoLT_editarMenu.php';
		var ajax=objetoAjax();	
		ajax.open("POST", url,true);	
		ajax.onreadystatechange=function() 
		{
			if (ajax.readyState==4) 
			{
				var salida = ajax.responseText;	
				if(salida == 1 )
					alert("El contenido se guardo exitosamente");
				else
					
					alert("Ocurrio un problema al intentar guardar el contenido, por favor intentelo de nuevo");
			}
		}
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send(opciones);	
	}
}

function activarOriginal(prefijo)
{
	if(document.main._limpiarSeleccionCheck.checked) 
	{
		document.main._limpiarSeleccion.value = 1;
		var casoCheck = "noOriginal";
	}
	else
	{
		document.main._limpiarSeleccion.value = 0;
		var casoCheck = "conOriginal";
	}	
	limpiarSeleccion(prefijo,casoCheck);
}


function mostrarVentanaDatos(titulo,texto)
{
	return overlib(texto, STICKY, CAPTION,titulo, WIDTH, 350); //, CENTER, FIXY, -1,FIXX, 250);
}


/****************************************************************************************************************
			FUNCIONES EXCLUSIVAS DE MODULO DE CONFIGURACIÓN IP-USUARIOS
****************************************************************************************************************/

function GuardarIPUsuarios(option,action)
{
	if(document.main.ip.value == '' || document.main.nombre.value == '')
		alert('Debe ingresar el nombre y la IP');
	else
	{
		var origen=searchElement('reemplazo_Sel[]');
		origenlen = origen.length ;	
		
		if(origenlen > 0 )
			selectInputAll('reemplazo_Sel');
		else
			alert('No habilito ningún usuario para esta IP, por lo cuál se mantendrá inactiva en el sistema hasta que habilite usuarios');
		process(option,action);
	}
		

}

function EliminarIPUsuarios()
{
	if(confirm('Esta acción eliminará la IP seleccionada y deshabilitando a los usuarios habilitados para ingresar al sistema por medio de esta dirección. ¿Está seguro de elimiarla?'))
		process('eliminar',1);
}	

/*
FUNCIONES DE SELECT MULTIPLE

function moverOrigenADestino: exige recibir el nombre de 2 select multiple del form, y mueve lo que esta seleccionado del select origen al de destino
	origen => el nombre del selet de origen
	destino => nombre del select de destino

*/
function moverOrigenADestino(origen,destino){
	
	var m1=searchElement(origen);
	var m2=searchElement(destino);
	
	m1len = m1.length ; 
    for ( i=0; i< m1len ; i++)
	{
        if (m1.options[i].selected == true ) 
		{
            m2len = m2.length;
            m2.options[m2len]= new Option(m1.options[i].text,m1.options[i].value);
        }
    }

    for ( i = (m1len -1); i>=0; i--)
	{
        if (m1.options[i].selected == true ) 
		{
            m1.options[i] = null;
        }
    }
}


function selectInputAll(inputSelect)
{
	var origen=searchElement(inputSelect+'[]');
	origenlen = origen.length ; 
	var hayElem = false;
    for ( i=0; i< origenlen ; i++)
	{
	   origen.options[i].selected = true;	   
	   hayElem = true;	   
    }

	return hayElem ;
}

function enviarMultipleSelect(option,action,inputSelect)
{
	selectInputAll(inputSelect);
	process(option,action);
}


/*********************imprimir sector***********************/
function imprSelec(nombre)
{
  var ficha = document.getElementById(nombre);
  var ventimp = window.open(' ', 'popimpr');
  ventimp.document.write( ficha.innerHTML );
  ventimp.document.close();
  ventimp.print( );
  ventimp.close();
} 


/**********************FUNCIONES ADMINISTRACION DOCUMENTOS CNE**********************/


function borrarArchivo()
{
	if(confirm('¿Esta seguro de eliminar este documento?'))
		process('delete_file',2);		
}

function cerrarArchivo() {
	if(confirm('¿Esta seguro de cerrar este documento?'))
		process('close_area',2);		
}

function view_area(id) { 
	view_area_doc(id,0);
}

function view_area_doc(id,id_doc) { 
	document.main.id_area.value   = id;
	document.main.id_doc.value    = id_doc;
	document.main.id_coment.value = 0;
	process('view_area',1);
}

function edit_area(id) { 
	document.main.id_area.value   = id;
	process('add_area|edit',1)
}


function edit_doc(id) { 
	document.main.id_doc.value   = id;
	process('add_doc|edit',1)
}

function del_doc(id) { 
	if(confirm(' Esta seguro de eliminar este documento?'))
	{
		document.main.id_elem.value   = id;
		process('view_area|del_elem',1);
	}
}

function del_area(id) { 
	if(confirm(' Esta seguro de eliminar esta área temática?'))
	{
		document.main.id_elem.value   = id;
		process('view_area|del_elem',1);
	}
}

function del_elem(id) {
	if(confirm(' Esta seguro de eliminar el elemento seleccionado?'))
	{
		document.main.id_elem.value = id;
		process('del_elem',2);
	}
}

function status_elem(id,status,parent) { 
	document.main.id_area.value       = parent;
	document.main.id_elem.value       = id;
	process('view_area|status_elem|'+status,1);
}


function view_doc(id) { 
	document.main.id_doc.value = id;
	document.main.id_coment.value = 0;
	process('view_area',1);
}

function viewHome(id,opcionValor) {
	document.main.id_menu.value = 0;
	document.main.id_elem.value = id;
	process(opcionValor,0);
}

function revisionFormEmpty(input,mensaje)
{
	var inputObj = searchElement(input);
	var mensajeObj = mensaje+'_error';
	var tiempo = 5000;
	if(inputObj.value == '')
	{
		mostrarError(mensajeObj,25);
		setTimeout("eliminarError('"+mensajeObj+"')",tiempo);				
		return false;
	}
	return true;
}

function save_com()
{
	if(revisionFormEmpty('comment','comment'))
		process('save_comment',2);
}

function add_com(id) {
	document.main.id_coment.value = id;	
	document.main.comment.focus();
  /*  document.getElementById('content_comment_sel').innerHtml =  document.getElementById('coment_content_'+id).innerHtml;*/	
	href_inside("add_com");	
}

function cancel_add_com(id)
{
	var id = document.main.id_coment.value;
	document.main.id_coment.value = 0;
    document.main.comment.value   = '';	
	href_inside("add_com_"+id);
}

function href_inside(name) {
	
	var url = location;
	var fragmentid1 = "#"+name;
	var url1 = url.fragmentid1;
	window.location.href = fragmentid1;
}


/**********************FUNCIONES ADMINISTRACION DOCUMENTOS CNE**********************/



