/*
	WCh Doc Rep
	Programado por Ronny Abarca
	Implementado por Enmanuel Ulloa
	Febrero 2003
	www.novaedit.com
	Modulo de javascript para WCHcons.com 
*/

// ======================================================================
function CrearNuevaPreg()
{

		document.frmMain.dfAction.value=-1;
		document.frmMain.dfID.value="";
		document.frmMain.submit();
		
}

// ======================================================================

function BorrarPregunta(intQ)
{
	if (confirm('Está seguro que desea borrar la pregunta seleccionada?\nPresione OK para Sí, CANCEL para No.') )
	{
		document.frmMain.dfAction.value = 14;
		document.frmMain.dfParam1.value =intQ;
		document.frmMain.submit();
	}	
}


// ======================================================================
function BorrarCategoria(intCategID)
{
	if (confirm('Está seguro que desea borrar el tipo de subscripción seleccionado?\nPresione OK para Sí, CANCEL para No.'))
	{
		document.frmMain.dfID.value = intCategID;
		document.frmMain.dfAction.value = 13;
		document.frmMain.submit();
		
	}
}


// ======================================================================
function emailCheck (emailStr) 
{
		
		/* V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com)
			 Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com) */
		
		/* The following variable tells the rest of the function whether or not
		to verify that the address ends in a two-letter country or well-known
		TLD.  1 means check it, 0 means don't. */
		
		var checkTLD=1;
		
		/* The following is the list of known TLDs that an e-mail address must end with. */
		
		var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
		
		/* The following pattern is used to check if the entered e-mail address
		fits the user@domain format.  It also is used to separate the username
		from the domain. */
		
		var emailPat=/^(.+)@(.+)$/;
		
		/* The following string represents the pattern for matching all special
		characters.  We don't want to allow special characters in the address. 
		These characters include ( ) < > @ , ; : \ " . [ ] */
		
		var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
		
		/* The following string represents the range of characters allowed in a 
		username or domainname.  It really states which chars aren't allowed.*/
		
		var validChars="\[^\\s" + specialChars + "\]";
		
		/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. */
		
		var quotedUser="(\"[^\"]*\")";
		
		/* The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */
		
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
		
		/* The following string represents an atom (basically a series of non-special characters.) */
		
		var atom=validChars + '+';
		
		/* The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.
		Basically, a word is either an atom or quoted string. */
		
		var word="(" + atom + "|" + quotedUser + ")";
		
		// The following pattern describes the structure of the user
		
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
		
		/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */
		
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
		
		/* Finally, let's start trying to figure out if the supplied address is valid. */
		
		/* Begin with the coarse pattern to simply break up user@domain into
		different pieces that are easy to analyze. */
		
		var matchArray=emailStr.match(emailPat);
		
		if (matchArray==null) {
		
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		
		alert("La direccion de correo parece incorrecta (revise @ y puntos)");
		return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("El nombre de usuario de correo tiene caracteres invalidos.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("El nombre de dominio del correo tiene caracteres invalidos.");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

alert("El nombre de usuario no parece valido.");
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("El IP destino es invalido.");
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("El nombre de dominio del correo no parece valido.");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("La direccion de correo debe ser en un formato conocido de pais o dominio. ");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
alert("Le falta el nombre del servidor a la direccion de correo.");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

// ======================================================================


function ValidarCampos(strNombre,strApellido,strEmail,strTelefono,intStatus,strFechaFinal,strSecQ,strSecA)
{
	var blRetorno = false; 
	dtHoy = new Date();
	dtFechaFinal = new Date();	

	if (emailCheck (strEmail) )
	{
		if ( strNombre != '')
		{			
			if (strApellido == '')
			{
				alert('El apellido no puede ser vacio');
			}
			else
			{
				if ( strTelefono == '')
				{
					alert('Por favor digite un numero en el campo telefonico requerido.');
				}
				else
				{
					if (strTelefono.length < 6)
					{
						alert('El largo del numero de telefono debe ser al menos de 6 caracteres. ');
					}
					else
					{
						if  (intStatus > -1)
						{
								strDias = strFechaFinal.slice(0,2);
								strMes = strFechaFinal.slice(3,5);
								strAno = strFechaFinal.slice(6,10);
							
								dtFechaFinal.setDate(strDias);	
								dtFechaFinal.setMonth(strMes-1);
								dtFechaFinal.setYear(strAno);		
								
								if ( ( dtFechaFinal >= dtHoy) && (intStatus==4) )
								{
										if (confirm('La fecha de expiración es mayor a la actual pero el status es EXPIRADO,\ndesea actualizar el status tambien?\n\nPresione OK para SI o CANCEL para NO'))
										{
											document.frmMain.dfParam2.value = 1;
										}
								}
						}					
						blRetorno = true; 
					}
				}
			}
		}
		else
		{
			alert('El nombre no puede ser vacio');
		}
	}
	
	
	if (strSecQ == '')
	{
		blRetorno = false;
		alert('La pregunta de seguridad no puede ser vacia');
	}

	if (strSecA == '')
	{
		blRetorno = false;
		alert('La respuesta de seguridad no puede ser vacia');		
	}

	return blRetorno;
	
}

// ======================================================================



function NewWindow(strPathToSource,intAncho,intAlto)
{
	var NewWin = null;
	var strTitle = 'Novaedit';
	var boolScroll = 'yes';
	var intTop = (screen.height) ? (screen.height- intAlto)/2 : 0;
	var intLeft = (screen.width) ? (screen.width- intAncho)/2 : 0;
	winAttribs = 'height='+intAlto+',width='+intAncho+',top='+intTop+',left='+intLeft+',resizable=no,scrollbars=yes';
	return  window.open(strPathToSource,strTitle,winAttribs)
}


// ======================================================================

function OpenFile(strSource, ancho, alto)
{
	NewWin =NewWindow(strSource, ancho, alto)
	if(NewWin.window.focus)
		{
			NewWin.window.focus()
		};
}


// ======================================================================


function FechaSuma(dtFecha,dtSumarDias)
{
	// Suma la fecha en dias de dtSumarDias a dtFecha
	dtHoy = new Date();
	dtFechaASumar = new Date();
	dtSiguienteDia = new Date();
	dtDia = dtHoy.getDate();	
	dtMes = dtHoy.getMonth();		// 0 = Ene
	dtAno = dtHoy.getYear();			
	// The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

	
	if (dtFecha == "")
	{
	   dtFecha = (dtHoy.getDate() < 10 ? '0' : '') + dtHoy.getDate() + "/"
			+ (dtHoy.getMonth() < 9 ? '0' : '') + (dtHoy.getMonth() + 1) + "/"
			+ dtHoy.getFullYear()
	}
	
	strDias = dtFecha.slice(0,2);
	strMes = dtFecha.slice(3,5);
	strAno = dtFecha.slice(6,10);

	
	dtFechaASumar.setDate(strDias);	
	dtFechaASumar.setMonth(strMes-1);
	dtFechaASumar.setYear(strAno);
	
    // Convert both dates to milliseconds
    dtFecha = dtFechaASumar.getTime();

	var dtFechaFinal = Math.abs(dtFecha + (dtSumarDias*ONE_DAY));
	
	dtSiguienteDia.setTime(dtFechaFinal);
	
	strRetorno= (
		(dtSiguienteDia.getDate() < 10 ? '0' : '') + dtSiguienteDia.getDate() + "/"
		+ (dtSiguienteDia.getMonth() < 9 ? '0' : '') + (dtSiguienteDia.getMonth() + 1) + "/"
		+ dtSiguienteDia.getFullYear()
	);
	
	return strRetorno;
	
}


// ======================================================================

function CheckStartDate(strStartDate)
{
 	if (strStartDate!= '') 
	{
		document.frmMain.dfFechaFinal.value=FechaSuma(document.frmMain.dfFechaInicio.value,document.frmMain.slSubs[document.frmMain.slSubs.selectedIndex].id);
	}
}

// ======================================================================

function ValidarClave(strClave1,strClave2)
{
	var blRetorno = true;
	
	if (strClave1 != strClave2)
	{
		 blRetorno = false;
		alert('La confirmación de la clave es incorrecta');
	}
	else
	{
		if (strClave1.length < 8)
		{
			 blRetorno = false;
			 alert('La clave debe tener al menos 8 caracteres');
		}
		else
		{
			document.frmMain.dfParam2.value = strClave1;
		}
	
	}
	
	return blRetorno;

}

// ======================================================================

function EstaVacio(objObjeto)
{

	if (objObjeto.value == '')
	{
		alert('Por favor verifique que la información no esté vacía.');
		return true;
	}
	else
	{
		return false;
	}

}

function DoDelete(blExec,intWho)
{
	// Si blExec es true, hace submit al form
	var intObjetos = document.frmMain.elements.length;
	var intCheckedItems = 0;
	document.frmMain.dfParam1.value = '';
	strComma = "";	

	for (var i = 0; i < intObjetos; i++) 
		{
	    	var objCheckbox = document.frmMain.elements[i];
		    if (objCheckbox.name == "cbMsj") 
			{
				if (objCheckbox.checked == true)
				{
					// Incluirlo en la lista para borrar
					if (document.frmMain.dfParam1.value != "")
					{
						strComma = ",";
					}
					document.frmMain.dfParam1.value =	document.frmMain.dfParam1.value + strComma +  objCheckbox.value ;
					intCheckedItems++;
				}
	    	}
		}

		if (intWho == 1)
		{
			blConfirm = confirm("Seguro que desea borrar los documentos seleccionados?");
		}
		else
		{
			blConfirm = confirm("Seguro que desea borrar los usuarios seleccionados?");
		}
		
		if (blExec && intCheckedItems > 0 && blConfirm == true)
		{
					document.frmMain.submit();		
		}

}


// ======================================================================

function AllChecked()
{
	var intObjetos = document.frmMain.elements.length;
	for(var i = 0 ; i < intObjetos ; i++) 
	{
	    if (document.frmMain.elements[i].name == "cbMsj" && !document.frmMain.elements[i].checked)
		 {
			return false;
	    }
	 }
	return true;
}


// ======================================================================

function ClickCheckBox(objQuien)
 {
	if (objQuien.checked) 
	{
	    document.frmMain.cbCheckAll.checked = AllChecked();
	}
	else 
	{
	    document.frmMain.cbCheckAll.checked = false;
	}
 }

// ======================================================================


function DoCheckAll(objQuien)
{
	var intObjetos = document.frmMain.elements.length;
	if (objQuien.checked)
	{
		/* Mandar a seleccionar todos*/
		for (var i = 0; i < intObjetos; i++) 
		{
	    	var objCheckbox = document.frmMain.elements[i];
		    if (objCheckbox .name == "cbMsj") 
			{
				objCheckbox.checked = true;
	    	}
		}
	}
	else
	{
		/* Limpiar todos */
		for (var i = 0; i < intObjetos; i++) 
		{
	    	var objCheckbox = document.frmMain.elements[i];
		    if (objCheckbox .name == "cbMsj") 
			{
				objCheckbox.checked = false;
	    	}
		}

	}
	
}

// ======================================================================

function Ordenar(strBy)
{

	document.frmOrdenar.dfOrden.value = strBy;
	document.frmOrdenar.submit();

}


// ======================================================================

function DoProcess(intWhatToDo,intUsrID,intTipoSubs)
{

	document.frmMain.dfUsrID.value = intUsrID;
	document.frmMain.dfAction.value = intWhatToDo;
	document.frmMain.dfParam2.value = intTipoSubs;
	
	if (intWhatToDo == 1) // Aceptar
	{
			strMsg = 'Está seguro que desea aceptar esta solicitud?';
	}
	else							// Rechazar
	{
			strMsg = 'Está seguro que desea denegar esta solicitud?';
	}

	if (confirm(strMsg))
	{
		if (intWhatToDo == 1)
		{
				document.frmMain.submit();
		}
		else
		{
				strRazon = prompt("Por favor detalle brevemente la razon", "");
				if (strRazon != null)
				{
					if (strRazon == "")
					{
						alert("Por favor detalle una razon");	
					}
					else
					{
						document.frmMain.dfParam1.value = strRazon;
						document.frmMain.submit();
					}
				}
		}
	}
	
}



// ======================================================================


function LoadValues(intIndex)
{
	
	document.frmMain.dfDuracion_dias.value=arrayDiasSubs[intIndex];	
	document.frmMain.dfDescripcion.value=arrayNombreSubs[intIndex];
	document.frmMain.dfID.value=intIndex;	


	if  (document.frmMain.cbMostrar.checked) 
	{
		if (arrayMostrar[intIndex] == 0)
		{
			document.frmMain.cbMostrar.click();
		}
	}
	else
	{
		if (arrayMostrar[intIndex] == 1)
		{
			document.frmMain.cbMostrar.click();
		}

	}
	
}

// ======================================================================


function LoadCateg(intIndex)
{
	

	document.frmMain.dfDescripcion.value=arrayNombreSubs[intIndex];
	document.frmMain.dfID.value=arrayID[intIndex];	


		if (arrayEsPadre[intIndex] == 1)
		{
			document.frmMain.rbPadre[0].click();
		}
		else
		{
			document.frmMain.rbPadre[1].click();
		}
	
}


// ======================================================================
function DeleteCateg(intIndex)
{
	if (confirm('Advertencia: Borrar una categoria imposibilita la busqueda\nde documentos asociados a esta. \n\nEsta seguro que desea borrar la categoria seleccionada?'))
	{
		document.frmMain.dfAction.value='7';
		document.frmMain.dfParam1.value=arrayID[intIndex];	
		if (arrayEsPadre[intIndex] == 1)
		{
			if (confirm('Las categorias hijas de esta, seran convertidas\na categorias padre. \n\nEsta seguro que desea continuar?'))
			{
				LoadCateg(intIndex);
				document.frmMain.submit();
			}
		}
		else
		{
				LoadCateg(intIndex);
				document.frmMain.submit();
		}
	}
}


// ======================================================================
function CheckIfFather(intIndex)
{
	if (arrayEsPadre[intIndex] == 1 && document.frmMain.dfDescripcion.value != '')
	{
		alert('Antes de aceptar, por favor seleccione de la lista superior\ncual sera la nueva categoria padre de la actual y de sus hijas.');
		
	}

	
}

// ======================================================================

function CheckSubType(objDesc,objDuracion)
{

	var	blRetorno = false;

	if (objDesc.value == '')
	{
		alert('La descripción no puede ser vacia');		
	}
	else
	{
		if (objDuracion.value=='')
		{
			alert('La duracion no puede ser vacia');					
		}
		else
		{
			if (isNaN(parseInt(objDuracion.value)))
			{

				alert('La duración debe ser un número');												
			}
			else
			{
				if (objDuracion.value<1)
				{
					alert('La duracion debe ser mayor a 1 dia');								
				}
				else
				{
					blRetorno = true;
					document.frmMain.dfID.disabled = false;
				}
			}
		}
	}
	
	return blRetorno;	
	
}

// ======================================================================
function CheckCateg(objDescripcion,objRBPadre)
{
	var	blRetorno = false;

	if (objDescripcion.value == '')
	{
		alert('La descripción no puede ser vacia');		
	}
	else
	{
		if ((objRBPadre[0].checked==false) &&  (objRBPadre[1].checked==false))
		{
			alert('Por favor seleccione si es categoria padre o no.');
		}
		else
		{
			blRetorno = true;
			document.frmMain.dfID.disabled = false;
		}
	}
	
	return blRetorno;	
}
// ======================================================================
function CheckQType(objPregunta,objRespuesta)
{
	var	blRetorno = false;

	if (objPregunta.value == '')
	{
		alert('Por favor verifique el contenido de la pregunta');		
	}
	else
	{
		if (objRespuesta.value == '')			
		{	
			alert('Por favor verifique el contenido de la respuesta');			
		}
		else
		{
			blRetorno = true;			
			document.frmMain.dfID.disabled = false;
		}
	} 

	return blRetorno;	
	
}
// ======================================================================
function EditQ()
{

	document.frmMain.dfAction.value=10;
	document.frmMain.dfID.disabled = false;
	document.frmMain.submit();
}

// ======================================================================

// Menu Button Functions //
// ======================================================================
function btnUp(obj)   
{ 
	obj.className = "NavUp"; 
}
// ======================================================================
function btnHide(obj) 
{ 
	obj.className ="'NavOff"; 
}
// ======================================================================
function btnDown(obj) 
{ 
	obj.className = "NavDown"; 
}

// ======================================================================




