// Funciones javascript varias


// ******************
// * Reloj dinámico *
// ******************
// Variables globales para el reloj
var lang = 'es'; 			// Default: 'es'
var divId= 'dinamic_clock';	// Default: 'dinamic_clock'

function dinamic_clock() {
	var thetime=new Date();
	//var mins=new Date();
	//var secn=new Date();
	var nhours=thetime.getHours();
	var nmins=thetime.getMinutes();
	var nsecn=thetime.getSeconds();
	var nday=thetime.getDay();
	var nmonth=thetime.getMonth();
	var ntoday=thetime.getDate();
	var nyear=thetime.getYear();
	var AorP=" ";
	if (nhours>=12)    AorP="PM";
	else    AorP="AM";
	if (nhours>=13)    nhours-=12;
	if (nhours==0)   nhours=12;
	if (nsecn<10) nsecn="0"+nsecn;
	if (nmins<10) nmins="0"+nmins;
	// Selector de idioma
	if (lang == 'es') {
		if (nday==0)  nday="Domingo";
		if (nday==1)  nday="Lunes";
		if (nday==2)  nday="Martes";
		if (nday==3)  nday="Miercoles";
		if (nday==4)  nday="Jueves";
		if (nday==5)  nday="Viernes";
		if (nday==6)  nday="Sabado";
	}

	if (lang == 'en') {
		if (nday==0)  nday="Sunday";
		if (nday==1)  nday="Monday";
		if (nday==2)  nday="Tuesday";
		if (nday==3)  nday="Wednesday";
		if (nday==4)  nday="Thursday";
		if (nday==5)  nday="Friday";
		if (nday==6)  nday="Saturday";	
		}
		
	nmonth+=1;
	if (nyear<=99)  nyear= "19"+nyear;
	if ((nyear>99) && (nyear<2000)) nyear+=1900;
	//document.getElementById("reloj").innerHTML = nhours+": "+nmins+": "+nsecn+" "+AorP+" "+nday+", "+nmonth+"/"+ntoday+"/"+nyear;
	//document.getElementById(divId).innerHTML = nhours+": "+nmins+": "+nsecn+" "+AorP+" "+nday+", "+ntoday+"/"+nmonth+"/"+nyear;
	document.getElementById(divId).innerHTML = ntoday+"/"+nmonth+"/"+nyear +", "+ nhours+":"+nmins+":"+nsecn+" "+AorP+", "+nday;
	setTimeout("dinamic_clock()",1000);
	} 


// **************************************************************************	
// * toMySql																*
// * Convierte la fecha dada de formato "dd/mm/aaaa" a MySql ("yyyy-mm-dd") *
// * la carga en el 'nombre_campo_destino'									*
// **************************************************************************
function toMySql(nombre_campo,nombre_campo_destino) 
	{
	var elem = document.getElementById(nombre_campo);
	fecha = elem.value;
	//alert(fecha);
	fecha_mysql = fecha.split("/");
	document.getElementById(nombre_campo_destino).value = fecha_mysql[2]+"-"+fecha_mysql[1]+"-"+fecha_mysql[0];
	}
	
// Lo mismo que la anterir pero devuelve el valor para manejarlo dentro de un script	
function toMySqlDate(fecha) 
	{
	fecha_mysql = fecha.split("/");
	var fecha_out = fecha_mysql[2]+"-"+fecha_mysql[1]+"-"+fecha_mysql[0];
	return fecha_out;
	}
	
	
// **************************************************************************	
// * toLayoutDate															*
// **************************************************************************
function toLayoutDate(nombre_campo,nombre_campo_destino) 
	{
	var elem = document.getElementById(nombre_campo);
	fecha = elem.value;
	//alert(fecha);
	fecha_mysql = fecha.split("-");
	document.getElementById(nombre_campo_destino).value = fecha_mysql[0]+"/"+fecha_mysql[1]+"/"+fecha_mysql[2];
	}
	
	
// **************************************************************	
// * CompletarFechaActual										*
// * Rellena el campo pasado como parámetro con la fecha actual *
// **************************************************************
function completarFechaActual(field)
		{
		var elem = document.getElementById(field);
		elem.value = global_fecha_actual;
		}
// Vacia el campo pasado como parámetro		
function vaciarCampo(field)
		{
		var elem = document.getElementById(field);
		elem.value = '';
		}		

// **********************************************
// * confirmarBaja								*
// * Función especifica para confirmar bajas	*
// **********************************************
function confirmarBaja(theLink)
	{
	if ( confirm("¿Esta seguro que desea dar de baja el registro?") ) { document.location = theLink; }
	}

// ******************************************************
// * confirmarReactivar									*
// * Función especifica para confirmar reactivaciones	*
// ******************************************************
function confirmarReactivar(theLink)
	{
	if ( confirm("¿Esta seguro que desea reactivar el registro?") ) { document.location = theLink; }
	}
	
// **********************************************************************
// * confirmLink														*
// * Función especifica para confirmar links con mensaje personalizable	*
// **********************************************************************
function confirmLink(theLink,msj)	
	{
	if ( confirm(msj) ) { document.location = theLink; } 
	}

//***********************
//* checkNavigator		*
//* Detecta navegador 	*
//***********************
function checkNavigator(string)
	{
	var detect = navigator.userAgent.toLowerCase();
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
	}


// Formatea una serie de numeros al formato de fecha dd/mm/aaaa
function formatDate(elem)
	{
	var value = elem.value;
	var tmp_value = "";
	value = value.replace(/[\/]/g,"");
	
	for (i=0; i<8; i++)
		{
		sChar = value.charAt(i);
		tmp_value = tmp_value + sChar;
		if (i == 1) { tmp_value = tmp_value + "/"; }
		if (i == 3) { tmp_value = tmp_value + "/"; }
		}
		elem.value = tmp_value;
	}


function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}


// Arma los parametros para los ajax en base a un array de datos
function setParams(data,first) {
	
	if (first == null) first = false;
	var params = "";
	
	if (data != null) {		
		for (i in data) 
			{
			
			// Objeto
			if (typeof(data[i]) == "object" ) {
				for (x in data[i])
				 	{
					if (typeof(data[i][x]) != "function" ) 
						{
						if (first) { params = params + "?"; first = false; }
						else { params = params + "&"; }
						params = params +i+"["+x+"]="+data[i][x];
						}
					}
				}
			// Item común
			else {
				if (typeof(data[i]) != "function" ) {
					if (first) { params = params + "?"; first = false; }
					else { params = params + "&"; }
					 params = params + i + "=" + data[i];
					}
				}
			}
		
		return params;
		}
	else{
		return false;
		}
}

/*
var data = { 
id:8,
texto: "porota"
};
*/
/*DEBUG*/ // alert(params(data,true));


// Obtiene todos los elementos de un formulario en base a su id
function getElementsByGroup(group) {

	var form = document.getElementById('abm_form');
	var elements = new Array();
	
	if (typeof(group)!= "undefined" && group != null) 
		{
		for (i=0; i <= form.elements.length-1; i++)
			{
			nombre_campo = form.elements[i].id;			
			if (nombre_campo.indexOf(group) != -1 ) { 
				elements[nombre_campo] = form.elements[i];
				}
			}		
		return elements;
		}
	else
		{
		return false;
		}
}

function completeForm(form_fields) {
	
	// Recorro el array de campos y busco elementos en el DOM con el mismo id
	for (x in form_fields)
		{
		if( typeof(form_fields[x]) != "function" && typeof(form_fields[x]) != "undefined" )
			{ 
		
			nombre_campo = x;
			//alert(x+" -> "+form_fields[x])
			// Parche para problema de arrays (Si no es un array lo transforma para que pueda ser tratado con la misma funcion)
			if (nombre_campo.indexOf('[0]') != -1 && form_fields[nombre_campo] == "undefined" && form_fields[nombre_campo.substr(0,nombre_campo.indexOf('['))] != "undefined")
				{
				form_fields[nombre_campo] = form_fields[nombre_campo.substr(0,nombre_campo.indexOf('['))];
				}
			
			if (nombre_campo.indexOf('[') != -1 && form_fields[nombre_campo] == "undefined")
				{
				fin = nombre_campo.indexOf('[');
				tmp = nombre_campo.substr(0,fin);
				form_fields[nombre_campo] = form_fields[nombre_campo];
				}		
			
			// Completa datos según el tipo de campo
			if ( nombre_campo != '' && form_fields[nombre_campo] != '' && form_fields[nombre_campo] != 'undefined' && typeof(nombre_campo) != 'undefined') 
				{
				elem = document.getElementById(nombre_campo);
				
				// Distingo entre tipos de datos
				if (typeof(elem) != "undefined") 
					{

					// Checkbox 
					if (elem.type == 'checkbox') 
						{  
						if ( form_fields[nombre_campo] != 0 && form_fields[nombre_campo] != '' && typeof(form_fields[nombre_campo]) != 'undefined' ) { elem.checked = true; }
						} // Fin tipo checkbox
						
					
					// Selects
					if (elem.type == 'select-one' )
							{	
														
								for (j=0;j < elem.options.length ; j++)
									{
									if (elem.options[j].value == form_fields[nombre_campo] )
										{										
										elem.options[j].selected = true;
										}
									}								
								
								
								// Llama a la funcion q rellena los select dependientes	
								if ( typeof(mostrar_provincias) != 'undefined' && typeof(mostrar_localidades) != 'undefined') 
									{
									switch (elem.name) 
										{
										case 'id_pais':
											mostrar_provincias(form_fields[elem.name],'id_provincia');
											break;
										case 'id_pais_crp':
											mostrar_provincias(form_fields[elem.name],'id_provincia_crp');
											break;
										case 'id_provincia':
											mostrar_localidades(form_fields[elem.name],'id_localidad');
											break;
										case 'id_provincia_crp':
											mostrar_localidades(form_fields[elem.name],'id_localidad_crp');
											break;
										}//switch
									}//if
									
							}
					
					
					// Radiobuttons
					if (elem.type == 'radio')
						{
						elem_rb = document.getElementsByName(nombre_campo);
			
						if (elem_rb.length) 
							{
							for (j=0;j< elem_rb.length ; j++)
								{ 
								if (elem_rb[j].value == form_fields[nombre_campo]) { elem_rb[j].checked = true; }
								} 
							}
						}
					
					
					// Textboxes
					if (elem.type == 'textarea' || elem.type == 'text' || elem.type == 'hidden' ) { elem.value = form_fields[nombre_campo]; }
					}
				}
			}
		}// fir for

} // Fin completeForm()

function addslashes(str) 
{
	if (typeof(str)=="string" && str!="")
	{
		str=str.replace(/\'/g,'\\\'');
		str=str.replace(/\"/g,'\\"');
		str=str.replace(/\\/g,'\\\\');
		str=str.replace(/\0/g,'\\0');
		return str;
	}
}

function stripslashes(str) 	
{
	if (typeof(str)=="string" && str!="")
	{
		str=str.replace(/\\'/g,'\'');
		str=str.replace(/\\"/g,'"');
		str=str.replace(/\\\\/g,'\\');
		str=str.replace(/\\0/g,'\0');
		return str;
	}
}


// Mostrar u ocultar el formulario de búsqueda
function showHideSearchBox(){ 
	var searchBox = document.getElementById('searchBox');
	if (searchBox.style.display != "none") { searchBox.style.display = "none"; } else { searchBox.style.display = "";  }
}

/**
	Muestra u oculta una capa
**/
function showHideObj(id,ac)
	{
	var obj = document.getElementById(id);
	if(ac == "show")
		{
		obj.style.display = "";
		}
	else if(ac == "hidden")
		{
		obj.style.display = "none";
		}
	}
	
/*
	Funcion especifica que muestra y oculta el panel de busqueda y cambia el icono de la lupa
*/
function searchPanel(tabNumber){
	var searchDivId = 'searchDiv'+tabNumber;
	searchDiv = document.getElementById(searchDivId);
	if(searchDiv.style.display == "none")
		{
		document.getElementById('ico_lupa_'+tabNumber).src = "images/ico_lupa_sel.gif";
		showHideObj(searchDivId,'show');
		}
	else
		{
		document.getElementById('ico_lupa_'+tabNumber).src = "images/ico_lupa.gif";
		showHideObj(searchDivId,'hidden');
		}
}


/*
	Copia el formulario de las listas en el documento principal main
*/
function dynSearch(searchDivNumber){
	//Extraemos el codigo del formulario del frame
	var form = '';
	form += '<table>';
	form += document.getElementById('searchBox').innerHTML;
	form += '</table>';
	//Escribimos el codigo
	window.parent.document.getElementById('searchDiv'+searchDivNumber).innerHTML = form;
}



/*
*	Parsea el string con el siguiente formato 
*
*	Recibe:
*	string 	= 	"key1=valor1;key2=valor2;key3=valor3"
*
*	Devuelve:
*	array	= 	fields['key1'] = "valor1" 
*				fields['key2'] = "valor2" 
*				fields['key3'] = "valor3" 
*
*/
function splitDataIntoArray(data){ 	
	datos_array = data.split(";");
	var campos_array 	= new Array(datos_array.length);
	for(x=0; x<datos_array.length; x++) 
		{
		if ( datos_array[x].indexOf("=") != -1 ) 
			{							
			tmp = datos_array[x].split("=");
			campos_array[tmp[0]] = tmp[1];	
			}
		} 	
	return campos_array;
}

function addEvent(elmId, evType, fn, useCapture) {
	var elm = document.getElementById(elmId);
	
	if ( elm != null ) {
	
		if (elm.addEventListener) {
			elm.addEventListener(evType, fn, useCapture);
			return true;
		}
		else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		}
		else {
			elm['on' + evType] = fn;
		}
	}
}

function removeEvent(elmId, evType, fn, useCapture) {
	var elm = document.getElementById(elmId);
	
	if ( elm != null ) {
		if (elm.removeEventListener) 
			{
			elm.removeEventListener(evType, fn, useCapture);
			return true;
			}
	}
}


function getValorCampo(campo) {
					
	var valor = "";
	
	// CheckBoxes
		if (campo.type=='checkbox')
			{
			if (campo.checked==true) 
				{
				if (campo.value!="") 
					{
					valor=campo.value;					
					}
				else
					{
					valor=1;
					}
				}
			}
	// Selects
		if (campo.type=='select-one')
			{
			for (j=0;j < campo.options.length ; j++)
				{
				if (campo.options[j].selected==true) valor = campo.options[j].value;		
				}		
			}					
	// Radiobuttons
		if (campo.type == 'radio')
			{
			valor = getValorRadioBtn(campo.name);
			}
	// Demas elementos...
		if (campo.type == 'textarea' || campo.type == 'text' || campo.type == 'hidden' ) 
			{
			if (campo.value && campo.value!="") 
				{
				// Si es un campo con nombre "fecha" y el valor coincide con un formato de fecha..
				// Formatos posibles: "21/10/2007" ; "10-21-2007" ; "10.21.2007"
				var dateformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
				if  ( campo.name.indexOf("fecha")!=-1 && dateformat.test(campo.value) )
					{
					// Cambia el formato de "21/10/2007" a "2007-10-21"
					var fecha = campo.value;
					valor = fecha.substr(6,4)+"-"+fecha.substr(3,2)+"-"+fecha.substr(0,2);
					}
				else
					{
					valor = campo.value;
					}
				}
			}
	
	return valor;
}


function getValorRadioBtn(nombre_campo) {
	var rbtn = document.getElementsByName(nombre_campo);
	var valor = "";
	for (i=0;i<rbtn.length;i++)
		{
		if (rbtn[i].checked==true) valor = rbtn[i].value;
		}
	
	return valor;
}

function poner_en_mayusculas(elemento)
	{	
	if (elemento.value) 
		{
		elemento.value = elemento.value.toUpperCase();
		}
	}



function getDiasMes(mes, anio){ 
	//regresa la cantidad de días del mes del año que pasamos como parametro 
	switch (mes){ 
	case 0: return 31; break; 
	case 1: 
	if (anio % 4 == 0){ 
	if (anio % 400 == 0){ 
	return 29; 
	} 
	else { 
	if (anio % 100 == 0){ 
	return 28; 
	} 
	else { 
	return 29; 
	} 
	} 
	} 
	else { 
	return 28; 
	}; 
	break; 
	case 2: return 31; break; 
	case 3: return 30; break; 
	case 4: return 31; break; 
	case 5: return 30; break; 
	case 6: return 31; break; 
	case 7: return 31; break; 
	case 8: return 30; break; 
	case 9: return 31; break; 
	case 10: return 30; break; 
	case 11: return 31; break; 
	
	} 
} 

// Devuelve 1 si dateA > dateB; -1 si dateA < dateB y 0 si las dos fechas son iguales
function compareDate(dateA, dateB) 
	{ 
	   timeDifference = dateA - dateB; 
	   if (timeDifference > 0) 
		  return 1; 
	   else if (timeDifference < 0) 
		  return -1; 
	   else 
		  return 0; 
	}

function completar_checkboxes(form_name) 
	{
	form = document.getElementById(form_name);
	for (i=0; i <= form.elements.length-1 ; i++)
		{
		nombre_campo = form.elements[i].name;
		elem = document.getElementById(nombre_campo);
		// Checkbox		
		if (elem.type == 'checkbox') 
			{ 			 			
			if (elem.checked == false) { elem.checked = true; elem.value=0; }
			} // Fin tipo checkbox
		}
	}

/*
*	Intercambia el valor style.display de 2 o mas elementos
*	Se activa el elemento pasado como elem_mostrar
*
*	elems 			array		Array de nombres de elementos 
*	elem_mostrar	int			indice del elemento a activar
*/
function switch_elements_display(elems,elem_mostrar,nombre_campo)
	{	
		var valor = "";		
		for (x in elems)
			{				
				valor = (x==elem_mostrar) ? "" : "none";
				if ( $(elems[x]) && (!nombre_campo || (nombre_campo && x.indexOf(nombre_campo)!=-1)) ) $(elems[x]).style.display = valor; 
			}
	}


/*
*	Intercambia el valor style.display de 2 o mas elementos
*	Se activa el elemento pasado como elem_mostrar
*
*	elems 			array		Array de nombres de elementos 
*	elem_mostrar	int			indice del elemento a activar
*/
function activar_fondo(elems,elem_mostrar,nombre_campo)
	{	
		var valor = "";
		for (x in elems)
			{
				valor = (x==elem_mostrar) ? "tdCeldaActiva" : "tdCeldaInActiva";
				if ( $(elems[x]) && (!nombre_campo || (nombre_campo && x.indexOf(nombre_campo)!=-1)) ) $(elems[x]).className = valor;
			}
	}

// Agrega una opcion a un select-one
function addOption(objSelec,value,text) {
		
	var option=document.createElement('option');
	option.text=text;
	option.value=value;

	try
		{
		objSelec.add(option,null); // standards compliant
		return true;
		}
	catch(ex)
		{
		objSelec.add(option); // IE only
		return true;
		}

		
	return false;
}

// Inserción de una opción en un select-one crossBrowser
// Resuleve el problema
function insertOption(idSelect,text,value,before) {
	
 var option=document.createElement('option');
 option.text	= text;
 option.value  	= value;
 if (before == '') { before = null; } // Solo válido para Exploradores estándar
 var x=document.getElementById(idSelect);
  try {
    x.add(option,before); // Standards compliant
    }
  catch(ex) {
    x.add(option); // IE only
    }
}

/*
*	Normaliza los campos Fecha 
*	(prepara para guardar en la base)
*/
function normalizarCamposFecha(elemento)
	{	
	var elems = getElementsByGroup("fecha");
	var valor = "";
	var elemName = "";
	for (x in elems) 
		{			
		if (elems[x].name.indexOf("_temp")!=-1)
			{
			valor = getValorCampo(elems[x]);
			if (valor!="undefined") 
				{ 
				elemName = elems[x].name.replace("_temp","");
				if ($(elemName))  { $(elemName).value = valor; }
				
				}
			}
		}
	return true;
	}

