/*
*	Nombre: Miscelanea.js
*	Descripci�n: Funciones genericas y basicas para la Validacion de los Formularios
*	Autor: Jhoan Alejandro Garc�a Trujillo
*	E-mail: jhoalejandro@gmail.com
*	Fecha de Creaci�n: 14-08-2006
*	Fecha de �ltima Modificaci�n: 31-08-2006
*/


/*	********************	VALIDAR NULO	************************	*/

/*
*	Utilidad:
*		Se encarga de validar si el texto ingresado por el Usuario es vac�o o nulo
*	P�rametros:
*		email -> Texto digitado por el Usuario
*	Valores de retorno:
*		true, si el texto no es vac�o o nulo
*		false, de lo contrario
*/

function trim (myString)
{
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}


function validarNulo(valor)
{
    valor = valor.trim();
	if(valor==null || valor=='' || valor=='null')
	{
		return false;
	}
	
	for(i=0; i < valor.length; i++)
	{
		val = valor.charAt(i);
		if( !(val==null || val==' ') )
		{
			return true;
		}
	}
	return false;
}	


/*	********************	VALIDAR MAIL	************************	*/

/*
*	Utilidad:
*		Se encarga de validar si el texto ingresado representa una Direcci�n de Correo Electr�nico
*	P�rametros:
*		email -> Texto que representa la Direcci�n de Correo Electr�nico digitada por el Usuario
*	Valores de retorno:
*		true, si el texto digitado por el Usuario representa una Direcci�n de Correo Electr�nico
*		false, de lo contrario
*/

function validarMail(email) 
{
    email = email.trim();
	var token = /^[a-z][a-z-_0-9\.]+@[a-z-_=>0-9\.]+\.[a-z]{2,4}$/
    return token.test(email);
}


/*	********************	VALIDAR N�MERO	************************	*/

/*
*	Utilidad:
*		Se encarga de validar si el texto ingresado representa un N�mero
*	P�rametros:
*		valor -> Texto que representa el N�mero digitado por el Usuario
*	Valores de retorno:
*		true, si el texto digitado por el Usuario representa un N�mero
*		false, de lo contrario
*/

function validarNumero(valor)
{
    valor = valor.trim();
    
	if(isNaN(valor))
	{
		return false;
	}
	else
	{
		return true;
	}
}


/*	********************	VALIDAR N�MERO ENTERO	************************	*/

/*
*	Utilidad:
*		Se encarga de validar si el texto ingresado representa un N�mero Entero
*	P�rametros:
*		valor -> Texto que representa el N�mero Entero digitado por el Usuario
*	Valores de retorno:
*		true, si el texto digitado por el Usuario representa un N�mero Entero
*		false, de lo contrario
*/

function validarNumeroEntero(valor)
{
    valor = valor.trim();
	var token = /^\d+$/;
	return token.test(valor);
}


/*	*************************	VALIDAR TAMA�O	*********************************	*/

/*
*	Utilidad:
*		Se encarga de validar que la entrada tenga cierto tama�o definido
*	P�rametros:
*		valor -> Valor de la Variable a la cual se le quiere verificar su Tama�o
*		num_caracteres_minimo -> N�mero m�nimo de caracteres que debe contener la Variable
*		num_caracteres_maximo -> N�mero m�ximo de caracteres que debe contener la Variable
*	Valores de retorno:
*		true, Si el valor de la Variable cumple con el Tama�o especificado
*		false, de lo contrario
*/

function validarTamanho(valor, num_caracteres_minimo, num_caracteres_maximo)
{
    valor = valor.trim();
	var tamanho= valor.length;
	if(tamanho>=num_caracteres_minimo && (num_caracteres_maximo==null || tamanho<=num_caracteres_maximo))
	{
		return true;
	}
	return false;
}//Fin validarTamanho()	


/*	********************	VALIDAR FECHA	************************	*/

/*
*	Utilidad:
*		Se encarga de validar si el texto ingresado representa una Fecha en el formato YYYY-MM-DD
*	P�rametros:
*		fecha -> Texto que representa la Fecha digitada por el Usuario
*	Valores de retorno:
*		true, si el texto digitado por el Usuario representa una Fecha en el formato YYYY-MM-DD
*		false, de lo contrario
*/

function validarFecha(fecha)
{
	var token = /^\d{4}(-\d{1,2}){1,2}$/;
	return token.test(fecha);
}

/*	*****************************	VALIDAR FECHA ACTUAL	***********************************	*/
/*
*	Utilidad:
*		Se encarga de validar si la fecha ingresada (aaaa-dd-mm)
*	P�rametros:
*		fecha -> string con la fecha a validar
*	Valores de retorno:
*		true, la fecha ingresada es mayor a la actual
*		false, de lo contrario
*/

function validarFechaActual(fecha)
{
	var fecha_actual = new Date();
	var fecha_actual_conversion =fecha_actual.getFullYear()+"-"+fecha_actual.getDate()+"-"+(fecha_actual.getMonth() + 1);
	return validarRangoFechas(fecha, fecha_actual_conversion);
	
}//!validarFechaActual(fecha)

/*	********************	VALIDAR TIPO ARCHIVO	************************	*/

/*
*	Utilidad:
*		Se encarga de validar si el Archivo seleccionado es del Tipo de Archivo esperado
*	P�rametros:
*		archivo -> Texto que representa la ruta del Archivo seleccionado
*		tipo_archivo -> Extensi�n del Tipo de Archivo esperado
*	Valores de retorno:
*		true, si el Archivo seleccionado es del Tipo de Archivo esperado
*		false, de lo contrario
*/

function validarTipoArchivo(archivo, tipo_archivo)
{
	var partes_nombre_archivo = archivo.split(".");
	var extension_archivo = partes_nombre_archivo[partes_nombre_archivo.length-1].toLowerCase();
	if(extension_archivo == tipo_archivo)
	{
		return true;
	}
	else
	{
		return false;
	}
}


/*	********************	VALIDAR IMAGEN	************************	*/

/*
*	Utilidad:
*		Se encarga de validar si el Archivo seleccionado es una Imagen GIF, PNG, JPG o JPEG
*	P�rametros:
*		archivo -> Texto que representa la ruta del Archivo seleccionado
*	Valores de retorno:
*		true, si el Archivo seleccionado es una Imagen GIF, PNG, JPG o JPEG
*		false, de lo contrario
*/

function validarImagen(archivo)
{
	if(validarTipoArchivo(archivo, "gif") || validarTipoArchivo(archivo, "png") || validarTipoArchivo(archivo, "jpg") || validarTipoArchivo(archivo, "jpeg"))
	{
		return true;
	}
	else
	{
		return false;
	}
}



/*	********************	VALIDAR RANGO FECHAS	************************	*/

/*
*	Utilidad:
*		Se encarga de validar el rango entre dos Fechas dadas
*	P�rametros:
*		fecha_inicial -> L�mite Inferior del Rango
*		fecha_final -> L�mite Superior del Rango
*	Valores de retorno:
*		true, si el L�mite Superior del Rango es mayor o igual al L�mite Inferior
*		false, de lo contrario
*/

function validarRangoFechas(fecha_inicial, fecha_final)
{    
	var datos_fecha_inicial = fecha_inicial.split("-"); // Datos de la Fecha Inicial
	var datos_fecha_final = fecha_final.split("-"); // Datos de la Fecha Final

	var anho_fecha_inicial = parseInt(datos_fecha_inicial[2]); // A�o de la Fecha Inicial
	var mes_fecha_inicial = parseFloat(datos_fecha_inicial[1]); // Mes de la Fecha Inicial
	var dia_fecha_inicial = parseFloat(datos_fecha_inicial[0]); // D�a de la Fecha Inicial
	
	
	var anho_fecha_final = parseInt(datos_fecha_final[2]); // A�o de la Fecha Final
	var mes_fecha_final = parseFloat(datos_fecha_final[1]); // Mes de la Fecha Final
	var dia_fecha_final = parseFloat(datos_fecha_final[0]); // D�a de la Fecha Final
	    		
	if(anho_fecha_final == anho_fecha_inicial)
	{
		if(mes_fecha_final == mes_fecha_inicial)
		{
			if(dia_fecha_final >= dia_fecha_inicial)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		if(mes_fecha_final > mes_fecha_inicial)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (anho_fecha_final > anho_fecha_inicial)
	{
		return true;
	}
	else
	{
		return false;
	}
}


/*	*******************	DESPLEGAR RESULTADO VALIDACI�N	************************	*/

/*
*	Utilidad:
*		Se encarga de desplegar un alert al usuario con el valor del string error
*	P�rametros:
*		error -> Texto con el mensaje construido con los errores que se presentaron en un Formulario determinado
*	Valores de retorno:
*		true, si no se present� ning�n error
*		false, de lo contrario. Adem�s presentar� en pantalla los errores que se presentaron
*/


function desplegarResultadoValidacion(error)
{
	if (error != "")
	{
		alert(error);
		return false;
	}
	else
	{
		return true;
	}
}


/*	******************************	CONFIRMAR ELIMINAR	*********************************	*/

/*
*	Utilidad:
*		Despliega una ventana de confirmaci�n para una acci�n de eliminaci�n
*	P�rametros:
*	Valores de retorno:
*		true, si el Usuario elige la opci�n SI o YES
*		false, si el Usuario elige la opci�n NO
*/

function confirmarEliminar()
{
	respuesta = confirm ("Desea eliminar el registro seleccionado ?");
	if (respuesta)
	{
		return true;
	}
	else
	{
		return false;
	}
}


function abrirPopUp (url, nombre, ancho, alto, x, y)
{
	var caracteristicas_ventana = "";
	caracteristicas_ventana += "dependent";
	caracteristicas_ventana += ",directories=no";
	caracteristicas_ventana += ",height="+alto;
	caracteristicas_ventana += ",hotkeys=no";
	//caracteristicas_ventana += ",innerHeight";
	//caracteristicas_ventana += ",innerWidth";
	caracteristicas_ventana += ",location=no";
	caracteristicas_ventana += ",menubar=no";
	//caracteristicas_ventana += ",outerHeight";
	caracteristicas_ventana += ",personalbar=no";
	caracteristicas_ventana += ",resizable=yes";
	caracteristicas_ventana += ",screenX=0";
	caracteristicas_ventana += ",screenY=0";
	caracteristicas_ventana += ",scrollbars=yes";
	caracteristicas_ventana += ",status=no";
	caracteristicas_ventana += ",titlebar=no";
	caracteristicas_ventana += ",toolbar=no";
	caracteristicas_ventana += ",width="+ancho;
	caracteristicas_ventana += ",z-lock=yes";
	caracteristicas_ventana += ",left="+x;
	caracteristicas_ventana += ",top="+y;
	var ventana=window.open(url,nombre,caracteristicas_ventana);
	
	// return ventana;
}//Fin abrirPopUp()


function transformarFecha($fecha)
{
	$arreglo_fecha=fecha.split('-');
	/*if($arreglo_fecha[1].length==1)
	{
		$arreglo_fecha[1]='0'+$arreglo_fecha[1];
	}
	if($arreglo_fecha[2].length==1)
	{
		$arreglo_fecha[2]='0'+$arreglo_fecha[2];
	}*/
	return new Date($arreglo_fecha[0],$arreglo_fecha[2]-1,$arreglo_fecha[1]);

}//Fin transformarFecha()

function campoColor(campo,estado)
{
	var color = "#FFFFFF";
	if( estado == 1 )
	{
		color = "#FFFF66";
	}
	campo.style.background =color;
}

function checkAll(nodo, all, nombre_campo, valores){

    var varCheck = all.checked;
        
    if(nombre_campo != undefined )
    {
        var elementos = document.forms[0].elements;
        for(var i=0; i < elementos.length; i++)
        {   
            if( elementos[i].name==nombre_campo )
            {
                if(valores == undefined )
                {
                	if(!elementos[i].disabled) //MAOH - 16 Ene 2012 - No debe seleccionar un checkbox si esta deshabilitado
                    	elementos[i].checked = varCheck;
                }
                else
                {
                    if( valores.indexOf(","+nodo[i].value+",") > 0 )
                    {          
                		if(!nodo[i].disabled) //MAOH - 16 Ene 2012 - No debe seleccionar un checkbox si esta deshabilitado
                       		nodo[i].checked = varCheck;
                    }                    
                }       
            }
        }//Fin de for(var i=0; i < elementos.lenght; i ++)
    }
    else
    {        
        for (i=0; i<nodo.length; i++)
        {
            if(valores == undefined )
            {
            	if(!nodo[i].disabled) //MAOH - 16 Ene 2012 - No debe seleccionar un checkbox si esta deshabilitado
                	nodo[i].checked = varCheck;
            }
            else
            {
                if( valores.indexOf(","+nodo[i].value+",") > 0 )
                {               
                	if(!nodo[i].disabled) //MAOH - 16 Ene 2012 - No debe seleccionar un checkbox si esta deshabilitado
                    	nodo[i].checked = varCheck;
                }
            }       
        }    
    }
}//Fin de checkAll()


/**
 * This array is used to remember mark status of rows in browse mode
 */

var marked_row = new Array;
/**
 * COLOREA DE UN FONDO CUANDO SE PASA EL MOUSE SOBRE UNA FILA 
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   integer  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{

    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }


    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
        
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0)
    {
    
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }



    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
           
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
        
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function


function cambiarColorFila(fila,nuevo_color)
{
    document.getElementById(fila).style.backgroundColor=nuevo_color;
}

function cambiarColorColumna(columna,nuevo_color)
{
   document.getElementById(columna).style.backgroundColor=nuevo_color;
}

function trim (myString)
{
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}

function obtenerCampoGrupo(forma, nombre, posicion)
{
    var campo = null;
    var size = forma.elements.length;
    var contador =0;
    for(var i=0; i < size; i++)
    {
        if( forma.elements[i].name==nombre)
        {
            if( contador==posicion)
            {
                campo = forma.elements[i];
                break; 
            }
            contador++;
            
        }//fin de if( forma.elements[i].name==nombre)
    }//Fin de for(var i=0; i < size; i++)
    
    return campo;
}//Fin de obtenerCampoGrupo


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


function clickFila(campo,clase)
{
    var clase = campo.className;
    switch(clase)
    {
        case 'listado_fila_1':
            campo.className = "listado_fila_1_click";
            break;
        case 'listado_fila_1_click':
            campo.className = "listado_fila_1";
            break;
        case 'listado_fila_2':
            campo.className = "listado_fila_2_click";
            break;
        case 'listado_fila_2_click':
            campo.className = "listado_fila_2";
            break;
        case 'listado_fila_1_rojo':
            campo.className = "listado_fila_1_rojo_click";
            break;
        case 'listado_fila_1_rojo_click':
            campo.className = "listado_fila_1_rojo";
            break;
        case 'listado_fila_2_rojo':
            campo.className = "listado_fila_2_rojo_click";
            break;
        case 'listado_fila_2_rojo_click':
            campo.className = "listado_fila_2_rojo";
            break;
    }
    
}//Fin de clickFila()

function exportarExcel(ruta)
	{
		location.href=ruta;
	}
	
function seleccionHotelDatos(valor)
{
	 var error=""; // Errores que se presentan
	 
	if( !validarNulo(valor))
	{
		error += idioma['auxiliar_seleccion_hotel'] + "\n";
	}
	
    if( desplegarResultadoValidacion(error) )
    {
        location.href="index.php?m=datoshotel&accion=fm_datoshotel&est_id="+valor;  
    }
}

function validarEstablecimientoLog()
{
	if (document.forms[0].est_id.value == '')
		{
			alert('No se ha ingresado el Identificador del establecimiento');
		}
	else if (isNaN(document.forms[0].est_id.value))
		{
			document.forms[0].est_id.value = '';
			alert('El Identificador del establecimiento debe ser numerico');
		}
	else if (document.forms[0].est_codigo.value == '')
		{
			alert('No se ha ingresado el Codigo del establecimiento');
		}
	else
		{
			document.forms[0].submit();
		}
}//Fin validarEstablecimientoLog()

function verArchivoLog(archivo)
{
	document.forms[0].archivo.value = archivo;
	document.forms[0].submit();
}//Fin de verArchivoLog(archivo)

function validarAgregarDatosDemo(accion)
{
	if (document.agregarDatos.hotelesOrigen.value == '')
		{
			alert('Se debe ingresar al menos un hotel origen');
		}
	else if (document.agregarDatos.fechaInicio.value == '')
		{
			alert('Se debe ingresar la fecha Inicial');
		}
	else if (document.agregarDatos.fechaFin.value == '')
		{
			alert('Se debe ingresar la fecha Final');
		}
	else if (document.agregarDatos.hotelesDestino.value == '')
		{
			alert('Se debe ingresar al menos un hotel destino');
		}
	else if (document.agregarDatos.sizeBloque.value == '')
		{
			alert('Se debe ingresar el tamaño del bloque de huespedes a agregar');
		}
	else if (isNaN(document.agregarDatos.sizeBloque.value))
		{
			alert('El tamaño del bloque de huespedes a agregar debe ser numerico');
		}
	else
		{
			document.agregarDatos.accion.value = accion;
			document.agregarDatos.submit();
		}
}//Fin validarPrevioAgregarDatosDemo()

function iniciarAgregarDatosHuespedes()
{
	document.agregarDatos.accion.value = 1;
	document.agregarDatos.submit();
}//Fin validarPrevioAgregarDatosDemo()

function seleccionarPreguntaOpcionesEstandar(valor,pre_id, pee_id)
{
	//Si se hace un cambio aca no olvidar hacer el cambio tambien para los dispositivos moviles y tables que no reconocen las funciones
	var nombreCampoHidden = 'hidden_activar_texto_'+pre_id+'_'+pee_id+'_'+valor;
	var campo = document.getElementsByName(nombreCampoHidden)
	var divOculta = document.getElementById('pregopcionestandar_texto_div_'+pre_id+'_'+pee_id+'_'+valor);
	
	//Ocultamos todas las diviciones de texto
	var divisionesDelDocumento = document.getElementsByTagName("div");
	for (i = 0 ; i < divisionesDelDocumento.length ; i++)
		{
			if ((divisionesDelDocumento[i].id.substring(0,25) == 'pregopcionestandar_texto_') &&
				(divisionesDelDocumento[i].id.indexOf('pregopcionestandar_texto_div_'+pre_id) == 0))
				{
					divisionesDelDocumento[i].style.display='none';
				}
		}
	
	if (campo[0].value == 1)//La opcion de select activa un campo de texto
		{
			divOculta.style.display="inline";
		}
}//Fin seleccionarPreguntaOpcionesEstandar(valor,pre_id, pee_id)

function activarCampoTexto(valor,pre_id, pee_id)
{
	//Ocultamos todas las divisiones de texto
	var divisionesDelDocumento = document.getElementsByTagName("div");
	for (i = 0 ; i < divisionesDelDocumento.length ; i++)
		{
			if ((divisionesDelDocumento[i].id.substring(0,25) == 'pregopcionestandar_texto_') &&
				(divisionesDelDocumento[i].id.indexOf('pregopcionestandar_texto_div_'+pre_id) == 0))
				{
					divisionesDelDocumento[i].style.display='none';
				}		
		}
	var nombreCampoHidden = 'hidden_activar_texto_'+pre_id+'_'+pee_id+'_'+valor;
	var campo = document.getElementsByName(nombreCampoHidden)
	var divOculta = document.getElementById('pregopcionestandar_texto_div_'+pre_id+'_'+pee_id+'_'+valor);
	if (campo[0].value == 1)//La opcion de select activa un campo de texto
		{
			divOculta.style.display="inline";
		}
} 

