// JavaScript Document

// Abreviacion de "document.getElementById(id)" 
function GEBI(id){
	return document.getElementById(id);
}

//Validacion para los checkboxes
function getCheckBoxes(checkbox_name,aux_name){
GEBI(aux_name).checked = false;
	for(i=0;i<document.getElementsByTagName("input").length;i++){
		if(document.getElementsByTagName("input")[i].name == checkbox_name && document.getElementsByTagName("input")[i].checked == true){
		GEBI(aux_name).checked = true;
		break;
		}
	}
}
	
//Validacion para el tiny cone LiveValidator
function Pass_Values(tiny_field,aux_field){
	if(trim(tinyMCE.get(tiny_field).getContent())=='' || trim(tinyMCE.get(tiny_field).getContent())=='<p></p>' || trim(tinyMCE.get(tiny_field).getContent())=='<p>&nbsp;</p>'
	|| trim(tinyMCE.get(tiny_field).getContent())=='&nbsp;' || trim(tinyMCE.get(tiny_field).getContent())=='&nbsp;&nbsp;' || trim(tinyMCE.get(tiny_field).getContent())=='&nbsp;&nbsp;&nbsp;')
		GEBI(aux_field).value = '';
	else
		GEBI(aux_field).value = '1';		
}

// Muestra u Oculta la flecha del ordenamiento para SortTable campos date
function switchArrowDate(down, up, type){
	if (type == 1){
		if (GEBI(down).style.display == 'none' && GEBI(up).style.display == 'none'){
			GEBI(up).style.display = '';
		}else if (GEBI(down).style.display == 'none'){
			GEBI(down).style.display = '';
			GEBI(up).style.display = 'none';	
		}else if (GEBI(up).style.display == 'none'){
			GEBI(up).style.display = '';
			GEBI(down).style.display = 'none';
		}else{}						
	}else{
		GEBI(down).style.display = 'none';
		GEBI(up).style.display = 'none';
	}
}

// muestra un componente cuando se hace "click" en el componente invocante
function clickShowData(id){
	if (GEBI(id).style.display == "none" ){
		GEBI(id).style.display = "";
	}else{
		GEBI(id).style.display = "none";
	}
}

// muestra un componente cuando se "checked" al componente invocante
function checkedShowData(check, id){
	if (check.checked){
		GEBI(id).style.display = "";
	}
	else{
		GEBI(id).style.display = "none";
	}
}

// Mensaje de Alerta al intentar borrar algun registro.
function delete_this(type, name, url) {
	if (confirm(">>> Are you sure you want to delete " + type +  " " + name + "?\n\n <WARNING> \nThis action can't be undo!!!")) {
		window.location=url;
	} else {
		return false;
	}
}

// Redirecciona para Ordenamiento por URL
function reloadSorter(url, criteria, asc){
	window.location = "" + url + "?sortby=" + criteria + "&asc_desc=" + asc;
}

// Solo permite numero en caja de texto
function numberValidate(e) { 
	if (e.keyCode == 9 || e.keyCode == 8 || e.keyCode == 39 || e.keyCode == 37 || e.keyCode == 46 || e.keyCode == 13) return true;
	if (e.which == 9 || e.which == 8 || e.which == 39 || e.keyCode == 37 || e.which == 46 || e.which == 13) return true;	
	tecla = (document.all) ? e.keyCode : e.which; 	
	patron =/[0-9]/;  
	te = String.fromCharCode(tecla); 
	return patron.test(te); 
};

// Solo permite valor para USD en caja de texto
function dollarValidate(e) { 
	if (e.keyCode == 9 || e.keyCode == 8 || e.keyCode == 39 || e.keyCode == 37 || e.keyCode == 46 || e.keyCode == 13) return true;
	if (e.which == 9 || e.which == 8 || e.which == 39 || e.keyCode == 37 || e.which == 46 || e.which == 13) return true;	
	tecla = (document.all) ? e.keyCode : e.which; 	 
	patron =/[0-9,.]/;  
	te = String.fromCharCode(tecla); 
	return patron.test(te); 
};

// Redondea un valor a nDec decimales y retorna valor
function redondea(sVal, nDec){
	var n = parseFloat(sVal);
	var s = "0.00";
	if (!isNaN(n)){
	 n = Math.round(n * Math.pow(10, nDec)) / Math.pow(10, nDec);
	 s = String(n);
	 s += (s.indexOf(".") == -1? ".": "") + String(Math.pow(10, nDec)).substr(1);
	 s = s.substr(0, s.indexOf(".") + nDec + 1);
	}
	return s;
} 

// Redondea un valor de un campo de texto a nDec decimales
function redondea_field(sVal, nDec){
	var n = parseFloat(sVal.value);
	var s = "0.00";
	if (!isNaN(n)){
	 n = Math.round(n * Math.pow(10, nDec)) / Math.pow(10, nDec);
	 s = String(n);
	 s += (s.indexOf(".") == -1? ".": "") + String(Math.pow(10, nDec)).substr(1);
	 s = s.substr(0, s.indexOf(".") + nDec + 1);
	}
	sVal.value = s;
} 

// quta espacios antes y despues de una cadena
function trim(cadena){
	for(i=0; i<cadena.length; )	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	
	return cadena;
}

/**
 * Compara Fechas, fecha inicial no puede ser mayor a fecha final
 * @param fini: fecha inicial
 * @param ffin: fecha final
 */
function compareDate(fini, ffin){
	// Format day for fini and ffin mm/dd/yyyy
	a = new Date(fini.value.substring(6),parseInt(fini.value.substring(0,2))-1,fini.value.substring(3,5));
	b = new Date(ffin.value.substring(6),parseInt(ffin.value.substring(0,2))-1,ffin.value.substring(3,5));
	if (a.getTime()<b.getTime()){										
		return 1;
	} 
	if (a.getTime()>b.getTime()){ 
		alert(ffin.alt + " must be after or equal than " + fini.alt)
		ffin.value = fini.value;
		return -1;
	}
	if (a.getTime()==b.getTime()){ 
		return 0;
	}
}		

/**
 * Pone valor por defecto, si al quitar foco de componente valor es vacio, entonces pone valor defecto
 * @param obj: El campo
 * @param value: valor por defecto.
 */
function setDefaultValue(obj, value){	
	if (trim(obj.value) == ""){
		obj.value = value;
	}
}


/***********************************************************************************
 *  EL SIGUIENTE CODIGO ES PARA CLONACION DE FILAS UTILIZADO EN RUTINAS ADD MORE
 ***********************************************************************************/
 /*
 BOTON QUE AGREGA FILA
 <input type="button" value="Add a new row in table 2" onclick="cloneRow('test_table'); addRow('test_table')">
 -- test_table = id de tabla en la cual se va a aplicar add more --
 
 UTILIZAR ESTO AL FINAL
 <script type="text/javascript">	
	// arreglo de elementos a renombrar (PREFIX_ + row_counter)
	replaces_ = new Array ("input", "select", "button");
	// arreglo de tablas que implementaran add row
	tables_ = new Array ("test_table", "test_table2");
	for (k=0; k<tables_.length; k++){
		row_counter += document.getElementById(tables_[k]).getElementsByTagName('tr').length;
	}
</script>
*/

 
/*
 * REPLACE REFERENCE.
 * http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace
 */
  
// Variable que contendra el elemento clonado
var clone;
var row_counter=1;
// arreglo de elementos a renombrar (PREFIX_ + row_counter)
var replaces_;
// arreglo de tablas que implementaran add row
var tables_;

/**
 * Clonar fila
 * @param table_id: id de tabla a clonar
 */
function cloneRow(table_id){
	// Recupera las filas
	var rows=document.getElementById(table_id).getElementsByTagName('tr');
	// recupera el numero de filas
	var index=rows.length;
	// Clonar ultima fila
	clone=rows[index-1].cloneNode(true);
	
	for (k=0; k<replaces_.length; k++){
	
		// recupero todos los componentes segun etiquetas establecidas en replaces
		var inputs=clone.getElementsByTagName(replaces_[k]), 
			inp, 
			i=0 ;
		// recorro todos los elementos
		while(inp=inputs[i++]){
			// Seteo nombres y id's a componentes como ultimo + 1
			inp.name=inp.name.replace(/\d/g,'')+(row_counter+1);
			inp.id=inp.id.replace(/\d/g,'')+(row_counter+1);
			if (inp.type == "file" || inp.type == "text"){	
				inp.value="";
			}
			
		}
	}	
}

/**
 * Agregar fila
 * @param table_id: id de tabla a la cual se agregara fila
 */
function addRow(table_id){
	// Recupero el cuerpo de la tabla
	tbl_ = document.getElementById(table_id);
	var tbo=tbl_.getElementsByTagName('tbody')[0];
	if (parseInt(tbl_.title) > tbl_.getElementsByTagName('tr').length ){
		// Agrego referencia a elemento clonado.
		tbo.appendChild(clone);
		row_counter ++;
	}
}

/**
 * Eliminar fila
 * @param obj: Objeto que ejecuta evento de eliminacion 
 * 
 * DEBE ESTAR UBICADO ASI 
 	<TR>
		...
		..*
		<TD>
			<INPUT TYPE="BUTTON"... ONCLICK='deleteCurrentRow(THIS)'>
		</TD>
	</TR>
 */
function deleteCurrentRow(obj){
	var delRow = obj.parentNode.parentNode;
	var tbl = delRow.parentNode.parentNode;
	var rIndex = delRow.sectionRowIndex;
	var rowArray = new Array(delRow);
	if (tbl.getElementsByTagName('tr').length > 1){
		deleteRows(rowArray);
	}
	//reorderRows();  // Pendiente
}
	
/**
 * Eliminar filas
 * @param rowObjArray: Filas a eliminar
 */
function deleteRows(rowObjArray){
	for (var i=0; i<rowObjArray.length; i++) {
		var rIndex = rowObjArray[i].sectionRowIndex;
		rowObjArray[i].parentNode.deleteRow(rIndex);
	}
}

/**
 * Recupera el indice de un objeto
 * ejm: id='obj_5' return 5
 * para utilizar en eventos y construccion dinamica de filas.
 * @param rowObjArray: Filas a eliminar
 */
function getIndex(str){					
	return str.substring(str.lastIndexOf('_')+1, str.length)
}

/**
 * Cuenta las filas actuales segun las tablas que implementan clonacion de filas. 
 * @return numero total
 */
 function countTotalRows(){
	 temp_couter = 0
	 for (k=0; k<tables_.length; k++){
		temp_couter += document.getElementById(tables_[k]).getElementsByTagName('tr').length;
	 }
	 return temp_couter;
 }
/***********************************************************************************
 *  FIN CODIGO ES PARA CLONACION DE FILAS UTILIZADO EN RUTINAS ADD MORE
 ***********************************************************************************/


