/*****************************************************************
-util.js
-General purpose functions
-Author: Mariano Szklanny
-Company: Epidata Consulting S.R.L.
-Last Modified: 06/10/2005
*****************************************************************/



// CONSTANTS *****************************************************/

var APP_NAME = "VONDERHEIDE.jobs";
var APP_PATH = "/vdh";
//var IMG_ICON_PATH = APP_PATH + "/img/icons";
var IMG_PATH = APP_PATH + "/img";
var MENU_TIMEOUT = 500;


// All of this can be called from many forms
var ADS_NEW = "agregarAviso.do?accion=executePreparar&origen=menu";
var APPLICANTS_NEW = "postulantes/nuevoPostulante.do?llamada=menu";
var PROCESSES_NEW = APP_PATH + "/nuevoProceso.do?accion=executePreparar&origen=menu";
var FILES_TEMPLATE = "buscarTemplates.do";
var SECURITY_USERS_NEW = "nuevoUsuario.do";
var SECURITY_HISTORIAL = "buscarHistorialSeguridad.do";
var PANELDECONTROL_CUENTA = "agregarInformacionCuenta.do?accion=executePreparar";

// GLOBAL SENTENCES **********************************************/
//document.oncontextmenu = new Function("return false"); //Disable right click

//Set all windows to have the same title
document.title = APP_NAME;


// PUBLIC FUNCTIONS **********************************************/



//** NAVIGATION, WINDOWS ****************************************/


/*****************************************************************
InitializeWindow
----------------
Initializes windows properties. Useful for popups.
Inputs:
	int width
	int height
	string title
*****************************************************************/
function InitializeWindow(width, height, title)
{
	if (title != null)
		document.title = title;
	else
		document.title = APP_NAME;
	window.resizeTo(width,height);
}

/*****************************************************************
CloseWindow
-----------
Closes a window
*****************************************************************/
function CloseWindow()
{
	window.close();
}


/*****************************************************************
Redirect
--------
Redirects to the specified URL
Inputs:
	string form: Target URL
*****************************************************************/
function Redirect(form)
{
	document.location = form;
}

/*****************************************************************
PopUpScrolleable
-----
Opens a PopUp window with scroll bars
Inputs:
	string form: PopUp URL
*****************************************************************/
function PopUpScrolleable(form)
{
	return window.open(form,"","location = 0, resizable = 1, toolbar = 0, status = 0, menubar = 0, directories = 0, scrollbars = yes, width = 200, height = 200");
}

/*****************************************************************
PopUpConTamanio
-----
Opens a PopUp window with parametrized size
Inputs:
	string form: PopUp URL
*****************************************************************/
function PopUpConTamanio(form, x, y)
{
	return window.open(form,"","location = 0, resizable = 1, toolbar = 0, status = 0, menubar = 0, directories = 0, scrollbars = 0, width = " + x + ", height = " + y);
}

/*****************************************************************
PopUp
-----
Opens a PopUp window.
Inputs:
	string form: PopUp URL
*****************************************************************/
function PopUp(form)
{
	return window.open(form,"","location = 0, resizable = 1, toolbar = 0, status = 0, menubar = 0, directories = 0, scrollbars = 0, width = 200, height = 200");
}

/*****************************************************************
ModalDialog
-----------
Opens a ModalDialog.
Inputs:
	string form: Dialog URL
	int width
	int height
*****************************************************************/
function ModalDialog(form, width, height)
{
	return window.showModalDialog(form,self,"status: No; resizable: No; scroll: No; dialogWidth: " + width + "px; dialogHeight: " + height + "px;");
}


/*****************************************************************
ShowError
-----------
Shows an error window
Inputs:
	string error: Description of the error
*****************************************************************/
function ShowError(error)
{
	alert(error);
}




//** DYNAMIC STYLES**********************************************/




/*****************************************************************
SetBackground
-------------
Sets the background of the sender to 'background'
Inputs:
	obj sender
	string background
*****************************************************************/
function SetBackground (sender,background)
{
	sender.style.background = "url(" + background + ")";
}


/*****************************************************************
ChangeClass
-----------
Changes the class of the 'sender' to 'className'
Inputs:
	obj sender
	string className
*****************************************************************/
function ChangeClass(sender,className)
{
	sender.className = className;
}

/*****************************************************************
AppendClass
-----------
Append the class 'className' to the 'sender'
Inputs:
	obj sender
	string className
*****************************************************************/
function AppendClass(sender, className)
{
	// Remove the class if it already exists.
	RemoveClass(sender, className);
	
	// Append the new class
	sender.className = sender.className + " " + className;
}

/*****************************************************************
RemoveClass
-----------
Remove the class 'className' from the 'sender'
Inputs:
	obj sender
	string className
*****************************************************************/
function RemoveClass(sender, className)
{
	var originalLength, newLength ;
	
	//Get original length
	originalLength = sender.className.length;
	
	//Remove the class
	sender.className = sender.className.replace(className,"");
	
	//Get new length
	newLength = sender.className.length;
	
	//If length changed, then something was removed.
	return !(newLength == originalLength);
}

/*****************************************************************
ToggleAvailable
---------------
Makes an element (HTML Node) available or unavailable to the user.
Inputs:
	obj element
	bool enable
	bool hide
Remarks:
	If 'enable' is true, it will make the 'element' available. Else, it will make it unavailable.
	If 'hide' is true, the 'element' will be hidden. Else, all of its child elements will be disabled.
*****************************************************************/
function ToggleAvailable(element, enable, hide)
{
	
	if (hide)
	{
		//THIS WILL HIDE THE ELEMENT
		element.style.display = (enable) ? "block" : "none";
		
	}
	else	
	{
		//THIS WILL DISABLE ALL THE CHILD NODES OF ELEMENT
		var elements;
		
		if (elements = element.childNodes) 
		{     
			
			
			for (var i = 0; i < elements.length ; i++)
			{ 
				var field = elements.item(i);
				
				if (field.nodeType == 1)
					field.disabled = !enable;
				
				//If the field is an input, make it readOnly (or not) and change its background.
				if (field.nodeName == "INPUT")
				{
					field.readOnly = !enable;
					if (enable)
						field.style.background =  "#fff"
					else
						field.style.background =  "#eee"
				}
				
				//Maybe some elements have child elements. Apply this function to them.
				if (field.nodeName == "LABEL" || field.nodeName == "DIV") ToggleAvailable(field, enable, false);
			}
		}
	} 

}

/*****************************************************************
AddAttributes
-------------
Set an attribute and its value to the child elements of 'element'.
Use e.g.: check all checkboxes.
Inputs:
	obj		element
	string	nodeName
	string	attribute
	string	value
*****************************************************************/
function AddAttributes(element, nodeName, attribute, value)
{
	var nodes = element.childNodes;
	
	for (var i = 0 ; i < nodes.length ; i++)
	{
		if (nodes[i].nodeName == nodeName)
		{
			nodes[i].removeAttribute(attribute);	
			nodes[i].setAttribute(attribute, value);
		}
		AddAttributes(nodes[i], nodeName, attribute, value);
	}
}

/*****************************************************************
RemoveAttributes
----------------
Remove an attribute from the child elements of 'element'.
Use e.g.: uncheck all checkboxes.
Inputs:
	obj element
	string nodeName
	string attribute
*****************************************************************/
function RemoveAttributes(element, nodeName, attribute)
{
	var nodes = element.childNodes;
	
	for (var i = 0 ; i < nodes.length ; i++)
	{
		if (nodes[i].nodeName == nodeName)
			{
				//Actually we 'clean' instead of removing, because IE doesn't seem to like removing attributes...
				nodes[i].setAttribute(attribute,"");
			}
		RemoveAttributes(nodes[i], nodeName, attribute);
	}
}





// PROTOTYPE LOGIC ***********************************************



/*****************************************************************
SelectInCombo
-------------
Selects an option in a combo.
Remarks: 
	Selection is based on the option's text.
	If option is not found, the selectIndex of the combo is set to -1.
	
Inputs:
	string comboId: Id of the combo to select.
	string optionText: Text of the option to select.
	obj window: Window where the combo exists.
*****************************************************************/
function SelectInCombo(comboId, optionText, window)
{
	var cbo = GetElement(comboId, window);
	for (var i = 0; i < cbo.options.length ; i++)
		if (cbo.options[i].text == optionText)
		{
			cbo.options.selectedIndex = i;
			return;
		}
	// If no matches found, unselect the combo
	cbo.options.selectIndex = -1;
}

/*****************************************************************
GetTextFromLookUpReturn
-----------------------
Returns the text value of a string that was returned by a "Look Up Record" window.
Eg.:
	Input string: <img src="icons/icon.gif" alt="Entity"/><a>Entity</a>
	Output string: Entity

Inputs:
	string str
Return:
	Text value of the input string
*****************************************************************/
function GetTextFromLookUpReturn(str)
{

	var start = str.indexOf("<a>");
	if (start == -1)
		start = str.indexOf("<A>");
	start += 3;
		
	var end = str.indexOf("</a>");
	if (end == -1)
		end = str.indexOf("</A>");
		
	return str.substring(start, end);
}



/*****************************************************************
RemoveSpaces
----------
Removes spaces from a string
Inputs:
	string str: Input String
Returns:
	string: String without spaces
*****************************************************************/
function RemoveSpaces(str)
{
	return str.replace(/ /g,"");
}


/** OTHER UTILITIES **********************************************/


/*****************************************************************
GetElement
----------
Gets an element from the document
Inputs:
	string elementID: ID of the desired element
	obj win: window where the element exists.
Returns:
	obj: Element.
*****************************************************************/
function GetElement(elementID, win)
{
	var time = 0;
	var timeOut = 1000;
	/*
	This loop has been implemented in order to support windows that
	may not have the entire document loaded yet (E.g.: Popups opened just before calling
	this function). timeOut is used to avoid entering in an infinite loop 
	if the element is not found in the document.
	*/
	do
	{
		if (win == null)
			element = document.getElementById(elementID);
		else
		{
			element = win.document.getElementById(elementID);
		}
		time++;
	}
	while (element == null && time < timeOut)
	return element;
}

/***************** XML *******************************************


/*****************************************************************
CreateXMLObject
---------------
Return: an XMLObject compatible with the browser
*****************************************************************/
function CreateXMLObject()
{

	if (window.ActiveXObject) 
		return new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");  //IE
	else 
		return document.implementation.createDocument("","",null);

}

/*****************************************************************
CreateXSLProcessor
---------------
Return: an XSLT Processor compatible with the browser
Inputs:
	XMLDom styleS				Stylesheet
*****************************************************************/
function CreateXSLProcessor(styleS)
{
	var proc = null;
	
	if (window.ActiveXObject) 
	{
		var xslt = new ActiveXObject("Msxml2.XSLTemplate.3.0");
		var xslStyleSheet = CreateXMLObject();		
		xslt.stylesheet = styleS;		
		proc = xslt.createProcessor();
	}
	else
	{
		proc = new XSLTProcessor();
		proc.importStylesheet(styleS);
	}

	return proc;
}



/*****************************************************************
GetXSLTransformationString
--------------------------
Transforms 'xml' with the 'processor' and returns the output as
a string
Inputs:
	IXMLDocument xml			XMLDom source to be transformed
	IXSLTProcessor processor 	XSLT Processor
Return:
	string 						Processor output
*****************************************************************/
function GetXSLTransformationString(xml, processor)
{
	var strOut = "";
	if (window.ActiveXObject)
	{
		processor.input = xmlData;
		processor.transform();
		strOut = processor.output;
	}
	else{
		strOut = new XMLSerializer().serializeToString(
						processor.transformToDocument(xmlData));
	}
	return strOut;
}

/*****************************************************************
XSLAddParameter
---------------
Adds the parameter 'name' with the value 'value' to the 
XSLT Processor 'processor'

Inputs:
	IXSLTProcessor processor 	XSLT Processor
	string name					Parameter name
	string value				Parameter value
*****************************************************************/
function XSLAddParameter(processor, name, value)
{
	if (window.ActiveXObject)
		processor.addParameter(name, value);
	else
		processor.setParameter("", name, value);
}

/********************* DATES ************************************/


/*****************************************************************
GetShortDate
------------
Returns a string in format DD/MM/YYYY
Inputs:
	Date dat: date to convert
Returns:
	string
*****************************************************************/
function GetShortDate(dat)
{
	return dat.getDate() + "/" + dat.getMonth() + "/" + dat.getFullYear();
}

/*****************************************************************
GetShortCurrentDate
-------------------
Returns current date string in format DD/MM/YYYY
Returns:
	string
*****************************************************************/
function GetShortCurrentDate()
{
	return GetShortDate(new Date());
}

/*****************************************************************
validarFecha
-----------
Validaci?n fecha ingresada con los combos
*****************************************************************/
        function validarFecha(dia, mes, anio){
			var dteDate = new Date(anio,mes-1,dia);
			return ((dia==dteDate.getDate()) && ((mes-1)==dteDate.getMonth()) && (anio==dteDate.getFullYear()));
		}
		function validarFechaConMensaje(dia, mes, anio, mensaje){
			if(!(validarFecha(dia, mes, anio))){
				alert(mensaje);
				return false;
			}
			return true;
		}
		function isFechaNotEmpty(dia,mes,anio){
			return ((dia != 0) || (mes != 0) || (anio != 0));
		}

/*****************************************************************
validarFechaHoy
-----------
Validacion fecha ingresada con los combos. 
Devuelve TRUE si la fecha ingresada es mayor a la actual, FALSE si es menor.
Autor: Mario Romero
*****************************************************************/
        function validarFechaHoy(dia, mes, anio){
			var dteDate = new Date(anio,mes-1,dia);		
			var today = new Date();
			var hoy;
			var hoyDia;
			var hoyMes;
			var hoyAno;
						
			hoyDia = today.getDate();
			hoyMes = today.getMonth()+1;
			hoyAno = today.getYear();
			
			hoy = new Date(hoyAno, hoyMes-1, hoyDia);
			
			if (dteDate>=hoy)
			{
			return true;
			}
			else
			{
			return false;
			}
		}



/*****************************************************************
compararFechas
-----------
Comparacion entre fechas
*****************************************************************/
        function compararFechas(inicio, fin){
			return (Date.parse(inicio) <= Date.parse(fin));
		}

/****************************************************************
Cargar Combo
Carga el combo cuyo id es pasado como parametro, desde ini a fin
*****************************************************************/
function CargarCombo(id,ini,fin)
{
	var combo=GetElement(id);
	if (ini<fin)
	{
		for (var i = ini ; i <= fin ; i++)
		{
		    var op = document.createElement("option");
		    combo.options.add(op);
		    op.innerText = i;
        	}
        }
        else
        {
		for (var i = ini ; i >= fin ; i--)
		{
		    var op = document.createElement("option");
		    combo.options.add(op);
		    op.innerText = i;
        	}

        }
}
/****************************************************************
Cargar D?as

*****************************************************************/
/****************************************************************
Cancela y cierra un popUp

*****************************************************************/
		function Cerrar(){
			self.opener.refresh();
			CloseWindow();
		}
		function Cancelar()
		{
			Cerrar();
			return false;
		}


/*****************************************************************
matchValidationVariable
-----------
Necesario para que funcione el patch de compatibilidad con 
prototype de commons-validator 
*****************************************************************/
		  function matchValidationVariable(variable, value)
		  {
		  		var theRegexp = new RegExp('^a[0-9]*$');
		  		return ((typeof value[0] !== undefined) &&
		  			(theRegexp.exec(variable) !== null));
		  }
	
/*****************************************************************
hayElementosSeleccionados
-----------
Utilizada para validar si hay campos seleccionados en un listado ajax
*****************************************************************/
function hayElementosSeleccionados(){
	var elementos=document.getElementsByTagName("input");
	for (var i = 0; i<elementos.length; i++){
		if (elementos[i].type=="checkbox" && elementos[i].checked && elementos[i].filtrar == null && elementos[i].value != "on"){
			return true;
		}
	}
	return false;
}

/*****************************************************************
getCantidadElementosSeleccionados
-----------
Utilizada para obtener la cantidad de campos seleccionados en un listado ajax
*****************************************************************/
function getCantidadElementosSeleccionados(){
	//veo la cantidad de elementos seleccionados
	var elementos=document.getElementsByTagName("input");
	var cant=0; 
	for (var i = 0; i<elementos.length; i++){
		if (elementos[i].type=="checkbox" && elementos[i].checked && elementos[i].filtrar == null && elementos[i].value != "on"){
			cant++;
		}
	}
	return cant;
}

/*****************************************************************
hayElementosSeleccionados
-----------
Utilizada para validar si hay campos seleccionados en un listado ajax
*****************************************************************/
function hayElementosEnListado(){
	var elementos=document.getElementsByTagName("input");
	for (var i = 0; i<elementos.length; i++){
		if (elementos[i].type=="checkbox" && elementos[i].filtrar == null && elementos[i].value != "on"){
			return true;
		}
	}
	return false;
}

/*****************************************************************
isNotMsie
-----------
Utilizada para detectar el browser
*****************************************************************/
function isNotMsie() {
	
	var navegador = navigator.appName;
	return (navegador!="Microsoft Internet Explorer");
	
//	var gko = navigator.userAgent.toLowerCase();
//	return (gko.indexOf('gecko')!=-1);
}

/*****************************************************************
get_lastchild
-----------
Utilizada para obtener el ?ltimo hijo v?lido de un nodo
*****************************************************************/
//check if the last node is an element node
function get_lastchild(n)
{
	var x=n.lastChild;
	while (x.nodeType!=1)
	{
	x=x.previousSibling;
	}
	return x;
}

/*****************************************************************
get_childs
-----------
Utilizada para filtrar los hijos de un nodo y obtener los que son v?lidos
*****************************************************************/
function get_childs(n)
{
	var hijos = n.childNodes;
	var i = 0;

	while (i < hijos.length)
	{
		var hijo = hijos.item(i);
		if (hijo.nodeType != 1){
			n.removeChild(hijo);
		}
		i++;
	}

	return hijos;
}

var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

function addOption(theSel, theText, theValue)
{
  var newOpt = new Option(theText, theValue);
  var selLength = theSel.length;
  theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex)
{ 
  var selLength = theSel.length;
  if(selLength>0)
  {
    theSel.options[theIndex] = null;
  }
}

/*****************************************************************
moverOpciones
-----------
Utilizada para enviar datos al origen/destino de los combos de seleccion multiple
*****************************************************************/
function moverOpciones(from, to)
{
  
  var theSelFrom = document.getElementById(from);
  var theSelTo = document.getElementById(to);
  var selLength = theSelFrom.length;
  var selectedText = new Array();
  var selectedValues = new Array();
  var selectedCount = 0;
  
  var i;
  // Find the selected Options in reverse order
  // and delete them from the 'from' Select.
  for(i=selLength-1; i>=0; i--)
  {
    if(theSelFrom.options[i].selected)
    {
      selectedText[selectedCount] = theSelFrom.options[i].text;
      selectedValues[selectedCount] = theSelFrom.options[i].value;
      deleteOption(theSelFrom, i);
      selectedCount++;
    }
  }
  
  // Add the selected text/values in reverse order.
  // This will add the Options to the 'to' Select
  // in the same order as they were in the 'from' Select.
  for(i=selectedCount-1; i>=0; i--)
  {
    addOption(theSelTo, selectedText[i], selectedValues[i]);
  }
  
  if(NS4) history.go(0);
}

/*****************************************************************
seleccionarAntesDeSubmitear
-----------
Selecciona los campos antes de ser submiteados
*****************************************************************/
function seleccionarAntesDeSubmitear(destino) {
	var len = document.getElementById(destino).length;
	for (i = 0; i < len; i++) {
		document.getElementById(destino).options[i].selected = true;
	}
}

/*****************************************************************
borrarDatosOrigen
-----------
Elimina del combo multiple de origen las opciones seleccionadas en el destino
*****************************************************************/
function borrarDatosOrigen(origen, destino){
	var aBorrar= new Array();
	var indiceABorrar=0;
	for (var i=0; i<document.getElementById(destino).length; i++){
		var elementosDestino = document.getElementById(destino).options[i];
		var elementosOrigen = document.getElementById(origen);
		if (elementosDestino.value>="0"){
			aBorrar[indiceABorrar]=elementosDestino.value;
			indiceABorrar++;
			idGOrigen=null;
		}
	}
	for (var j=0;j<=aBorrar.length;j++){
		for (var i=0; i<document.getElementById(origen).length; i++){
			var elementosOrigen=document.getElementById(origen).options[i];
			if (elementosOrigen.value==aBorrar[j]){
				document.getElementById(origen).options[i]=null;
			}

		}
	}
}

/*****************************************************************
getSelectedRadioValue
-----------
Devuelve el valor seleccionado en un radio button
*****************************************************************/
function getSelectedRadioValue(radio){
	for(var i = 0; i < radio.length; i++) {
		if(radio[i].checked) {
			return radio[i].value;
		}
	}
}

function validarTexto(texto) {
	
	if (isAlfaNumerico(texto)){
		return true;
     } else {
	    alert("El texto ingresado debe ser alfanumérico");
    	return false;
    }
}

function isAlfaNumerico(texto){
	if (texto.match(/^[a-zA-Z0-9 \'@&_ãâÂàÀêÊèÈîÎìÌõôÔòÒûÛùÙáéíóúÁÉÍÓÚñÑüÜ€%\.\*\#\+\-\$\/çÇ]*$/) && !texto.match(/^[\\']/) && !texto.match(/[\\']$/)){
		return true;
     } else {
    	return false;
    }
}

/**
 * setOptionSelected()
 * ---------------------
 * 
 */
function setOptionSelected(combo,value){
	var options=combo.options;
	var founded=false;
	for(var i=0;i<options.length && !founded;i=i+1) {
		if(options[i].value==value){
			founded=true;
			options[i].selected=true;
		}
	}
}


/**
 * Utilizada para paginado en listados ajax + xslt
 * @param {Object} sentido
 */
function irA(sentido){
	var numeroPagina = parseInt(document.getElementById('pagina').value);
	var cantidadPaginas = parseInt(document.getElementById('cantidadPaginas').value);
	if ((sentido == "anterior") && (numeroPagina != 1)){
		numeroPagina = numeroPagina - 1;
	}
	if ((sentido == "siguiente") && (numeroPagina != cantidadPaginas)){
		numeroPagina = numeroPagina + 1;
	}
	document.getElementById('pagina').value=numeroPagina;
	if (numeroPagina > 0){
		mostrarData(xml,numeroPagina);
	}
}

function procesosirA(sentido){
	var numeroPagina = parseInt(document.getElementById('pagina').value);
	var cantidadPaginas = cantidadfix;
	
	if ((sentido == "anterior") && (numeroPagina != 1)){
		numeroPagina = numeroPagina - 1;
	}
	if ((sentido == "siguiente") && (numeroPagina != cantidadPaginas)){
		numeroPagina = numeroPagina + 1;
	}
	document.getElementById('pagina').value=numeroPagina;
	if (numeroPagina > 0){
		mostrarData(xml,numeroPagina);
	}
}

function cambiarPagina(numero){
	document.getElementById('pagina').value=numero;
	mostrarData(xml,numero);
}

function getMenu(nombre) {
	//registro el Request AJAX 
	ajaxEngine.registerRequest('getMenu', nombre);
	menuUPD.getData();
}

