/*******************************************************************
FUNCION:			alcargar
ENTRADAS:
	Ninguna
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Carga las funciones necesarias cuando temina de cargar la página
*******************************************************************/
function alcargar(banner){
	if(!banner){banner = '';}
	cargar_banners(banner);
	nav_hover();
	carga_estilos_formularios();
	cloca_sombra();
}

/*******************************************************************
FUNCION:			cloca_sombra
ENTRADAS:
	Ninguna
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Coloca la sombre al fondo del sitio
*******************************************************************/
function cloca_sombra(){
	var incremento = 20;
	var principal_ancho	= document.getElementById('div_contenedor').offsetWidth;
	var principal_alto 	= document.getElementById('div_contenedor').offsetHeight;
	var principal_izq 	= posicion_x('div_contenedor');
	var principal_der 	= posicion_y('div_contenedor');
	if(document.all){
		document.getElementById('div_sombra_l').style.filter = 'alpha(opacity=0)';
		document.getElementById('div_sombra_r').style.filter = 'alpha(opacity=0)';
		document.getElementById('div_footer').style.filter = 'alpha(opacity=40)';
	}
	else{
		document.getElementById('div_sombra_l').style.MozOpacity = 0;
		document.getElementById('div_sombra_r').style.MozOpacity = 0;
		document.getElementById('div_footer').style.MozOpacity = .4;
	}
	document.getElementById('div_sombra_l').style.width 	= (principal_ancho + 1)+'px';
	document.getElementById('div_sombra_l').style.height 	= incremento+'px';
	document.getElementById('div_sombra_l').style.display	= 'block';
	document.getElementById('div_sombra_r').style.width 	= incremento+'px';
	document.getElementById('div_sombra_r').style.height 	= (principal_alto - incremento)+'px';
	document.getElementById('div_sombra_r').style.display	= 'block';
	animacion_simbra(0);
}

function recarga_sombra(){
	principal_alto 	= document.getElementById('div_contenedor').offsetHeight;
	document.getElementById('div_sombra_r').style.height 	= (principal_alto - 20)+'px';
}

/*******************************************************************
FUNCION:			posicion_x
ENTRADAS:
	element	->	elemento del cual se obtendra la posicion absoluta
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Devuelve la posicion absoluta del elemento dado en el eje x
*******************************************************************/
function posicion_x(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  var x = 0;
  while (element.offsetParent) {
    x += element.offsetLeft;
    element = element.offsetParent;
  }
  return x;
}
/*******************************************************************
TERMINA LA FUNCIÓN
*******************************************************************/

/*******************************************************************
FUNCION:			posicion_y
ENTRADAS:
	element	->	elemento del cual se obtendra la posicion absoluta
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Devuelve la posicion absoluta del elemento dado en el eje y
*******************************************************************/
function posicion_y(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  
  var y = 0;
  while (element.offsetParent) {
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return y;
}

/*******************************************************************
FUNCION:			animacion_simbra
ENTRADAS:
	contador,incremento
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Ejecuta la animación de la sombra
*******************************************************************/
function animacion_simbra(contador){
	contador = parseInt(contador) + 2;
	if(contador <= 40){
		if(document.all){
			document.getElementById('div_sombra_l').style.filter = 'alpha(opacity='+(contador)+')';
			document.getElementById('div_sombra_r').style.filter = 'alpha(opacity='+(contador)+')';
		}
		else{
			document.getElementById('div_sombra_l').style.MozOpacity = (contador)/100;
			document.getElementById('div_sombra_r').style.MozOpacity = (contador)/100;
		}
		setTimeout("animacion_simbra('"+contador+"')",100);
	}
}

/*******************************************************************
FUNCION:			formato_numero
ENTRADAS:
	numero						->	Numero a formatear
	decimales					->	Numero de decimales
	separador_decimal	->	Separador para los decimales
	separador_miles		->	Separador para los miles
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Le da formato a unumero y le agrega algun indicador
*******************************************************************/
function formato_numero(numero, decimales, separador_decimal, separador_miles){
	numero=parseFloat(numero);
	if(isNaN(numero)){
		return "";
	}
	if(decimales!==undefined){
		numero=numero.toFixed(decimales);
	}
	numero=numero.toString().replace(".", separador_decimal!==undefined ? separador_decimal : ",");
	if(separador_miles){
		var miles=new RegExp("(-?[0-9]+)([0-9]{3})");
		while(miles.test(numero)) {
			numero=numero.replace(miles, "$1" + separador_miles + "$2");
		}
	}
	return numero;
}

/*******************************************************************
FUNCION:			XHConn
ENTRADAS:
SALIDAS:
DESCRIPCIÓN:
	Funcion ajax
*******************************************************************/
function XHConn(){
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone){
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();
    try {
      if (sMethod == "GET"){
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else{
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				xmlhttp.send(sVars);
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete){
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

/*******************************************************************
FUNCION:			cargar_ciudades
ENTRADAS:
	clase		->	Clase del combo
	disable	->	Si se encuentra descativado o no
	tamanio	->	Tamañño del combo
SALIDAS:
DESCRIPCIÓN:
	Recarga
*******************************************************************/
function cargar_ciudades(numero,clase,disable,tamanio){
	var variables = 'accion=cargar_ciudades&numero='+escape(numero)+'&id='+escape(document.getElementById('txt_paises_'+numero).value)+'&clase='+escape(clase)+'&disable='+escape(disable)+'&tamanio='+escape(tamanio);
	document.getElementById('span___paises_'+numero).innerHTML = '<span class="span_gris">Cargando ciudades <img src="../imagenes/web/load_1.gif" alt="" title="" /></span>';
	var myConn = new XHConn();
	if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
	var peticion = function (oXML) {  
		document.getElementById('span___paises_'+numero).innerHTML = oXML.responseText;
		carga_estilos_formularios();
	};
	myConn.connect("../ajax/globales.php","POST", variables, peticion);
}

/*******************************************************************
FUNCION:		trim
ENTRADAS:
	cadena		->	Cadena de caracteres a evaluar
SALIDAS:
	cadena		->	Sin espacios en las orillas
DESCRIPCIÓN:
	Quita los espacios al principio y al final sde 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);
}

/*******************************************************************
FUNCION:		validarmail
ENTRADAS:
	email		->	Emal a evaluar
SALIDAS:
	False o True
DESCRIPCIÓN:
	Valida que el email tenga el formato correcto
*******************************************************************/
function validarmail(email){
	var filtro  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filtro.test(email)){
		return false;
	}
	return true;
}

/***********************************************************************************************
FUNCION:		valida_nombre
DESCRIPCION:	Verifica el correcto formato de un nombre para un contacto
PARAMETROS:		cadena: nombre de contacto obtenido del textbox correspondiente
SALIDAS:		1: si es correcto;  -1: si la longitud no es la adecuada;  -2: si no es correcto
***********************************************************************************************/
function validar_nombre(cadena)
{
	var patron = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzñÑáéíóúÁÉÍÓÚ ";
	var letra = "";
	if ( cadena.length > 3 ) {
		for ( i=0; i<cadena.length; i++ ) {
			letra = cadena.substring( i, i+1 );
			if ( patron.indexOf(letra) == -1 ) {
				return false;
			}
		}
		return true;
	}
	return false;
}

/***********************************************************************************************
FUNCION:		valida_dominio
DESCRIPCION:	Verifica el correcto formato de un nombre para un contacto
PARAMETROS:		cadena: nombre de contacto obtenido del textbox correspondiente
SALIDAS:		1: si es correcto;  -1: si la longitud no es la adecuada;  -2: si no es correcto
***********************************************************************************************/
function validar_dominio(dominio)
{
	// obtener los posibles incios
	inicio_http = dominio.substr(0,7);
	inicio_www = dominio.substr(0,4);
	inicio_httpwww = dominio.substr(0,11);
	
	// quitar los posibles inicios para quedarnos solo con el link
	if ( inicio_httpwww == 'http://www.' ) {
		dominio = dominio.replace( inicio_httpwww, '' );
	}
	if ( inicio_http == 'http://' ) {
		dominio = dominio.replace( inicio_http, '' );
	}
	
	if ( inicio_www == 'www.' ) {
		dominio = dominio.replace( inicio_www, '' );
	}
	
	// validar la sintaxis de la url sin los inicios. 
	ereg = /^[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-]+/
	if ( ereg.test(dominio) ) {
		return (true);
	}
	// si llega aqui hubo algun errror
	return (false);
}

/*******************************************************************
FUNCION:			posicion_x
ENTRADAS:
	element	->	elemento del cual se obtendra la posicion absoluta
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Devuelve la posicion absoluta del elemento dado en el eje x
*******************************************************************/
function posicion_x(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  var x = 0;
  while (element.offsetParent) {
    x += element.offsetLeft;
    element = element.offsetParent;
  }
  return x;
}

/*******************************************************************
FUNCION:			posicion_y
ENTRADAS:
	element	->	elemento del cual se obtendra la posicion absoluta
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	Devuelve la posicion absoluta del elemento dado en el eje y
*******************************************************************/
function posicion_y(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  
  var y = 0;
  while (element.offsetParent) {
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return y;
}

/*******************************************************************
FUNCION:		validarrfc
ENTRADAS:
	rfc			->	validarrfc
SALIDAS:
	Correcto o el tipo de error del RFC en texto
DESCRIPCIÓN:
	Valida que el RFC tenga el formato correcto
*******************************************************************/
function validarrfc(rfc){
	if(rfc.length<12 || rfc.length>13){
		return 'El tamaño del RFC es inválido, este debe ser de entre 12 y 13 caracteres.';
	}
	var parte1 = '';
	var parte2 = '';
	var parte3 = '';
	if(rfc.length == 12){
		parte1 = rfc.substr(0,3);
		parte2 = rfc.substr(3,6);
		parte3 = rfc.substr(9,3);
	}
	else{
		parte1 = rfc.substr(0,4);
		parte2 = rfc.substr(4,6);
		parte3 = rfc.substr(10,3);
	}
	var filtro = /[a-z]|[A-Z]/;
	if(!filtro.test(parte1)){
		return 'El primer segmento del RFC: "'+parte1+'" RFC posee un carácter inválido.';
	}
	filtro = /[1-9]/;
	if(!filtro.test(parte2)){
		return 'El segundo segmento del RFC: "'+parte2+'" RFC posee un carácter inválido.';
	}
	var filtro = /[a-z]|[A-Z]|[1-9]/;
	if(!filtro.test(parte3)){
		return 'El tercer segmento del RFC: "'+parte3+'" RFC posee un carácter inválido.';
	}
	return 'Correcto';
}


/*******************************************************************
FUNCION:		abrirVentana
ENTRADAS:
	rfc			->	validarrfc
SALIDAS:
	<< ninguna >>
DESCRIPCIÓN:
	Crea una ventana emergente
*******************************************************************/
function abrirVentana(direccion, pantallacompleta, herramientas, direcciones, estado, barramenu, barrascroll, cambiatamano, ancho, alto, izquierda, arriba, sustituir){
     var opciones = "fullscreen=" + pantallacompleta +
                 ",toolbar=" + herramientas +
                 ",location=" + direcciones +
                 ",status=" + estado +
                 ",menubar=" + barramenu +
                 ",scrollbars=" + barrascroll +
                 ",resizable=" + cambiatamano +
                 ",width=" + ancho +
                 ",height=" + alto +
                 ",left=" + izquierda +
                 ",top=" + arriba;
     var ventana = window.open(direccion,"venta",opciones,sustituir);
}

/*******************************************************************
FUNCION:		mouse__noticia
ENTRADAS:
	id			->	Id de la bullet
SALIDAS:
	Ninguna
DESCRIPCIÓN:
	COloca la bullet correspondiente
*******************************************************************/
function mouse__noticia(id){
	var total = document.getElementById('numero__noticias').value;
	for(i=0; i<= total; i++){
		if(i == id){
			document.getElementById('img__noticia_'+i).src = 'includes/noticias/imagenes/masover.gif';
		}
		else{
			document.getElementById('img__noticia_'+i).src = 'includes/noticias/imagenes/mas.gif';
		}
	}
	document.getElementById('posicion__img').value = id;
}

function mouuse_hover__noticia(id, caso){
	var seleccionado = document.getElementById('posicion__img').value;
	/*
	if(caso == '1'){
		var total = document.getElementById('numero__noticias').value;
		for(i=0; i<= total; i++){
			if(seleccionado != id){
				document.getElementById('img__noticia_'+i).src = 'includes/noticias/imagenes/mas.gif';
			}
		}
		document.getElementById('img__noticia_'+id).src = 'includes/noticias/imagenes/masover.gif';
	}
	else{
		if(seleccionado != id){
			document.getElementById('img__noticia_'+i).src = 'includes/noticias/imagenes/mas.gif';
		}
	}
	*/
}


/*****************************************************************************************
FUNCION:		cambiar_imagen
DESCRIPCIÓN:	controla los eventos onmousemove y onmouseout para un link con imagenes
ENTRADAS:		id -> de la imagen a cambiar
				accion -> define si se trata de mouseover o mouseout
SALIDAS:		<< ninguna >>
*****************************************************************************************/
function cambiar_imagen(id) {
	// si existen las imagenes, proceder
	if ( document.getElementById(id+'_off') && document.getElementById(id+'_on') ) {
		
		// si la apagada esta visible, encender
		if ( document.getElementById(id+'_off').style.display == '' ) {
			document.getElementById(id+'_off').style.display = 'none';
			document.getElementById(id+'_on').style.display = '';
		}
		// sino, apagar
		else {
			document.getElementById(id+'_off').style.display = '';
			document.getElementById(id+'_on').style.display = 'none';
		}
	}
}