// JavaScript Document

function trim (inputString) {

	if (typeof inputString != "string") { 
		return inputString; 
	}
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	
	while (ch == " ") {
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	
	ch = retValue.substring(retValue.length-1, retValue.length);
	
	while (ch == " ") {
		retValue = retValue.substring(0, retValue.length - 1);
		ch = retValue.substring(retValue.length - 1, retValue.length);
	}
	
	while (retValue.indexOf(" ") != -1) {
		retValue = retValue.substring(0, retValue.indexOf(" ")) + retValue.substring(retValue.indexOf(" ") + 1, retValue.length);
	}
	
	return retValue;
}

function validatelogin (thevalue, thename){
	
	var nowcont = true;
	if (thename == "uname_txt") {
		if (trim (thevalue) == "") {
			window.open('ingreso.php', '_self');
			nowcont = false;
		}
	}
	if (nowcont == true){
		if (thename == "pword_txt") {
			if (trim (thevalue) == "") {
				window.open('ingreso.php', '_self');
				nowcont = false;
			}
		}
	}
	return nowcont;
}

var aok;

function getformvalues (fobj, valfunc) {

	var str = "";
	aok = true;
	var val;
	for(var i = 0; i < fobj.elements.length; i++) {
		if(valfunc) {
			if (aok == true) {
				val = valfunc (fobj.elements[i].value, fobj.elements[i].name);
				if (val == false) {
				aok = false;
				}
			}
		}
		if(fobj.elements[i].type != "button")
		{
			if(fobj.elements[i].name == "pword_txt")
				str += fobj.elements[i].name + "=" + hex_sha1(hex_md5(fobj.elements[i].value)) + "&"; // hex_sha1(hex_md5(escape(fobj.elements[i].value))) + "&";
			else
				str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
		}
	}
	return str;
}

function submitform (theform, serverPage, valfunc, caller) {

	var file = serverPage;		
	var str = getformvalues(theform,valfunc);
	
	if (aok == true) {			
		
		new Ajax.Request(file,
		{
			method:'post',
			parameters: str,
				onSuccess: function(response){
					var resultado = response.responseText;
					if(resultado.substring(0, 5) == "false")
					{
						if(caller == 'cart.php')
							window.open("ingreso.php?do=wlogin&url=cart.php", "_self");
						else
							window.open("ingreso.php?do=wlogin", "_self");
					}
					else // if(resultado.substring(0, 4) == "true")
					{
						if(resultado.substring(0, 4) == "flag")
						{
							rsts = resultado.split("|");
							var idusuario = rsts[1];
							
							window.open('ingreso.php?c=bd4e6f82n&u=' + idusuario, '_self');
						}
						else
						{
							if(caller == 'registro.php' || caller == 'ingreso.php')
								window.open('perfil.php', '_self');
							else if(caller == 'cart.php')
								window.open('cart.php', '_self');
								
							document.getElementById('uname_txt').value = "";
							document.getElementById('pword_txt').value = "";
							
							var o = document.getElementById('uname_txt');
							o.parentNode.removeChild(o);
							
							var o = document.getElementById('pword_txt');
							o.parentNode.removeChild(o);
							
							document.getElementById('response_space').innerHTML = resultado;
							//window.open('perfil.php', '_self');
						}
					}
				},
			onFailure: function(){ }
		});
	}
}

function submitformingreso (theform, valfunc, caller) {

	var file = '_prototype/loginIngresoPrototype.php';
	var str = getformvalues(theform,valfunc);
		
	if (aok == true) {			
		
		new Ajax.Request(file,
		{
			method:'post',
			parameters: str,
				onSuccess: function(response){
					var resultado = response.responseText;
					if(resultado.substring(0, 5) == "false")
					{
						if(caller == 'cart.php')
							window.open("ingreso.php?do=wlogin&url=cart.php", "_self");
						else
							window.open("ingreso.php?do=wlogin", "_self");
					}
					else // if(resultado.substring(0, 4) == "true")
					{
						if(resultado.substring(0, 4) == "flag")
						{
							rsts = resultado.split("|");
							var idusuario = rsts[1];
							
							window.open('ingreso.php?c=bd4e6f82n&u=' + idusuario, '_self');
						}
						else if(resultado == 'loginok')
						{
							if(caller == 'cart.php')
								window.open("cart.php", "_self");
							else
								window.open('perfil.php', '_self');
						}
					}
				},
			onFailure: function(){ }
		});
	}
}

function logoutUser()
{						
	new Ajax.Request('_prototype/logoutPrototype.php', { method: 'post', parameters: '',
		onSuccess: function(response){
			var resultado = response.responseText;
			window.open('index.php', '_self');
		}				 
	});
}

/*
if(correcto)
{
	var usuario = document.usuario_nuevo.username_txt.value;
	var url = 'includes/AJAXUsuario.php';
	
	new Ajax.Request(url,
	  {
		method:'post',
		parameters: {vle:'nmlc', username: usuario, accion: 'agregar'},
		onSuccess: function(response){
		  var resultado = response.responseText;

		  if(resultado == "Pz8qa")
		  {
				document.usuario_nuevo.submit();
		  }
		  else
		  {
				alert("Ese nombre de usuario ya existe");
		  }
		},
		onFailure: function(){ }
	  });
}
*/

function escondeMensaje()
{
	document.getElementById('muestra_mensaje').innerHTML = "";
}


function enviaInformacionContacto()
{	
	var nombre_val = document.nuevo_comentario.nombre_contacto_txt.value;
	var correo_val = document.nuevo_comentario.correo_contacto_txt.value;
	var region_val = document.nuevo_comentario.region_contacto_txt.value;
	var comentario_val = document.nuevo_comentario.comentario_contacto_txt.value;
	
	var url = '_prototype/contactoPrototype.php';
	/*
	new Ajax.Updater('muestra_mensaje', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', nombre_txt: nombre_val, correo_txt: correo_val,region_txt: region_val, comentario_txt: comentario_val}
	  });
	*/
	
	new Ajax.Request(url,
	{
		method:'post',
		parameters: {vle:'nmlc', nombre_txt: nombre_val, correo_txt: correo_val,region_txt: region_val, comentario_txt: comentario_val},
			onSuccess: function(response){
				var resultado = response.responseText;
				if(resultado == "correct")
				{
					document.getElementById('muestra_mensaje').innerHTML = "Gracias, hemos recibido tu mensaje";
					document.nuevo_comentario.reset();
				}
			},
		onFailure: function(){ }
	});
}

function validaNuevoComentario()
{
	var correcto = true;
	var correo = document.nuevo_comentario.correo_contacto_txt.value;

	if(document.nuevo_comentario.nombre_contacto_txt.value == "")
	{
		//alert("Por favor introduce tu nombre");
		document.getElementById('muestra_mensaje').innerHTML = "Por favor introduce tu nombre";
		setTimeout("escondeMensaje()", 5000);
		document.nuevo_comentario.nombre_contacto_txt.focus();
		correcto = false;
	}
	else if(correo == "" || !validaMail(correo))
	{
		//alert("El formato del correo electrónico no es válido");
		document.getElementById('muestra_mensaje').innerHTML = "El formato del correo electrónico no es válido y no puede tener caracteres especiales";
		setTimeout("escondeMensaje()", 5000);
		document.nuevo_comentario.correo_contacto_txt.focus();
		correcto = false;
	}
	else if(document.nuevo_comentario.region_contacto_txt.value == "")
	{
		//alert("Por favor escribe la región en la que te encuentras");
		document.getElementById('muestra_mensaje').innerHTML = "Por favor escribe la región en la que te encuentras";
		setTimeout("escondeMensaje()", 5000);
		document.nuevo_comentario.region_contacto_txt.focus();
		correcto = false;
	}
	else if(document.nuevo_comentario.comentario_contacto_txt.value == "")
	{
		//alert("Por favor escribe tus comentarios");
		document.getElementById('muestra_mensaje').innerHTML = "Por favor escribe tus comentarios";
		setTimeout("escondeMensaje()", 5000);
		document.nuevo_comentario.comentario_contacto_txt.focus();
		correcto = false;
	}
	
	if(correcto)
	{
		enviaInformacionContacto();		
	}
}

function validaMail(email)
{
	var res = true;
	
	var iChars = "! #$%^&*()+=[]\\\';,/{}|\":<>?'";
	
	for (var i = 0; i < email.length; i++) {
		if (iChars.indexOf(email.charAt(i)) != -1) {
//			alert("charAt: " + email.charAt(i));
			res = false;
		}
	}
	
	if(res == true)
	{
		res = false;
		if(email.indexOf("@")>0 && email.indexOf("@") == email.lastIndexOf("@"))
		{
			if(email.lastIndexOf(".")>email.indexOf("@") && email.lastIndexOf(".")<email.length-1)
			{
				res = true;
			}
		}	
	}

	return res;
}

function actualizaInformacionTiendas(idpais, strlugar, id)
{	
	contadorLigas(id);
	
	var url = '_prototype/tiendasPrototype.php';
	
	new Ajax.Updater('tiendas_informacion', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', idpais: escape(idpais), lugar: strlugar }
	  });
}

var idLigaActual = null;

function contadorLigas(id)
{
	if(idLigaActual != null)
	{
		document.getElementById(idLigaActual).className = 'menu_izquierda_class';		
	}
	
	idLigaActual = id;
	
	document.getElementById(id).className = 'menu_izquierda_selected';
}

/* Sección: Noticias y Eventos */

var idLigaActualEvento = null;

function cambiaEstiloLigaEvento(idLiga)
{
	if(idLigaActualEvento == -1)
	{
		var leng = document.links.length;	
		for(var i = 0; i < leng; i++)
		{
			  if(document.links[i].className == 'menu_eventos_selected')
			  {
				document.links[i].className = 'menu_eventos_class';
				break;
			  }				
		}
	}
	else
	{
		if(document.getElementById(idLigaActualEvento))
		{
			if(document.getElementById(idLigaActualEvento))
				document.getElementById(idLigaActualEvento).className = 'menu_eventos_class';		
		}
	}
	
	idLigaActualEvento = idLiga;
	
	if(document.getElementById(idLiga))
		document.getElementById(idLiga).className = 'menu_eventos_selected';
}

function muestraEventoSeleccionado(idEvento, idLiga, seccion)
{
	var url = '_prototype/eventosPrototype.php';
	
	new Ajax.Updater('contenidoeventos', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', idevento: escape(idEvento), seccion: escape(seccion) },
		onComplete: function(){
			cambiaEstiloLigaEvento(idLiga);
		}
	  });	
	
	/* Esta sección solamente cambia el div contenidoeventos (área principal) */
}

var offset = 0;

function muestraListaEventosOffset(offs, direccion, seccion, idLiga)
{
	offset = offs;
	
	var url = '_prototype/listaEventosPrototype.php';
	
	new Ajax.Updater('menu_eventos', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offset), seccion: escape(seccion) },
		onComplete: function(){
			cambiaEstiloLigaEvento(idLiga);
		}
	  });
}

function muestraListaEventos(offsetNuevo, direccion, seccion)  /* Usado para motrar la lista de eventos inicial, y cuando se haga click en los botones anterior y siguiente */
{
	/*  Dentro de esta función podemos tener los siguientes casos:
	 * 	 1) Que sea necesario actualizar solamente el div eventos_lista_info (menú de eventos)
	 */
	 
	 document.getElementById('menu_eventos').innerHTML = "";
	
	if(offsetNuevo != -1)
	{
		if(direccion == '+')
			offset++;
		else
			offset--;
	}
	else
		offset = offsetNuevo + 1;
	 
	var url = '_prototype/listaEventosPrototype.php';
	
	new Ajax.Updater('menu_eventos', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offset), seccion: escape(seccion) }
	  });
}

var offsetBusqueda = 0;
//var seccionEventos = 0;

function realizaBusqueda()
{
	if(document.getElementById('searchbox'))
	{
		var buscar_texto = document.getElementById('searchbox').value;
		if(buscar_texto == "")
		{
			window.open("eventos_noticias.php", "_self"); //muestraListaEventos(-1, '+', seccionEventos);
		}
		else
		{
			document.getElementById('textobusqueda').value = buscar_texto;
			var url = '_prototype/listaBusquedaEventosPrototype.php';
			
			new Ajax.Updater('menu_eventos', url,
			  {
				method:'post',
				parameters: {vle:'nmlc', offset: escape(offsetBusqueda), buscar_texto: buscar_texto, primera_vez: escape('si') },
				onComplete: function() {
					muestraEventoSeleccionadoBusqueda(0, '');
					idLigaActualEvento = -1;
				}
			  });
		}
	}
}

function muestraEventoSeleccionadoBusqueda(idEvento, idLiga)
{
	var url = '_prototype/eventosBusquedaPrototype.php';
	var buscar_texto = document.getElementById('textobusqueda').value;
		
	new Ajax.Updater('contenidoeventos', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', idevento: escape(idEvento), buscar_texto: buscar_texto },
		onComplete: function(){
			if(idLiga != '')
				cambiaEstiloLigaEvento(idLiga);
		}
	  });	
	
	/* Esta sección solamente cambia el div contenidoeventos (área principal) */
}

function muestraListaEventosBusquedaOffset(offs, idLiga)
{
	offsetBusqueda = offs;
	
	var buscar_texto = document.getElementById('textobusqueda').value;
	var url = '_prototype/listaBusquedaEventosPrototype.php';
	
	new Ajax.Updater('menu_eventos', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offsetBusqueda), buscar_texto: buscar_texto },
		onComplete: function(){
			cambiaEstiloLigaEvento(idLiga);
		}
	  });
}

function muestraListaEventosBusqueda(offsetNuevo, direccion)  /* Usado para motrar la lista de eventos inicial, y cuando se haga click en los botones anterior y siguiente */
{
	/*  Dentro de esta función podemos tener los siguientes casos:
	 * 	 1) Que sea necesario actualizar solamente el div eventos_lista_info (menú de eventos)
	 */
	 
	document.getElementById('menu_eventos').innerHTML = "";
	
	var buscar_texto = document.getElementById('textobusqueda').value;
	
	if(offsetNuevo != -1)
	{
		if(direccion == '+')
			offsetBusqueda++;
		else
			offsetBusqueda--;
	}
	else
		offsetBusqueda = offsetNuevo + 1;
	 
	var url = '_prototype/listaBusquedaEventosPrototype.php';
	
	new Ajax.Updater('menu_eventos', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offsetBusqueda), buscar_texto: buscar_texto }
	  });
}

function actualizaDescargasCategoria(idtipo, idliga)
{	
//	contadorLigas(id);
	
//	alert("actualizaDescargasCategoria");
	
	cambiaEstiloLigaDownloads(idliga);
	
	var url = '_prototype/archivosDownloadsPrototype.php';
	
	new Ajax.Updater('contenido', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', tipo: escape(idtipo) }
	  });
}

var idLigaActualDownload = null;
function cambiaEstiloLigaDownloads(id)
{
	if(idLigaActualDownload != null)
	{
		document.getElementById(idLigaActualDownload).className = 'menu_izquierda_categorias';		
	}
	
	idLigaActualDownload = id;
	
	document.getElementById(id).className = 'menu_izquierda_categorias_selected';
}

function muestraListaPosts(offsetNuevo, direccion, seccion)  /* Usado para motrar la lista de posts inicial, y cuando se haga click en los botones anterior y siguiente */
{
	/*  Dentro de esta función podemos tener los siguientes casos:
	 * 	 1) Que sea necesario actualizar solamente el div menu_comunidad (menú de posts)
	 */
	 
	 document.getElementById('menu_comunidad').innerHTML = "";
	
	if(offsetNuevo != -1)
	{
		if(direccion == '+')
			offset++;
		else
			offset--;
	}
	else
		offset = offsetNuevo + 1;
	 
	var url = '_prototype/listaComunidadPrototype.php';
	
	if(seccion == 2)
	{
		document.getElementById('searchbox').value = "";
		document.getElementById('textobusqueda').value = "";
		offsetBusquedaPosts = 0;
	}
	
	new Ajax.Updater('menu_comunidad', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offset), seccion: escape(seccion) }
	  });
}

function muestraListaPostsOffset(offs, direccion, seccion, idLiga)
{
	offset = offs;
	
	var url = '_prototype/listaComunidadPrototype.php';
	
	new Ajax.Updater('menu_comunidad', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offset), seccion: escape(seccion) },
		onComplete: function(){
			cambiaEstiloLigaComunidad(idLiga);
		}
	  });
}

function muestraPostSeleccionado(idPost, idLiga, seccion)
{
	var url = '_prototype/comunidadPrototype.php';
	
	new Ajax.Updater('contenidocomunidad', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', idpost: escape(idPost), seccion: escape(seccion) },
		onComplete: function(){
			cambiaEstiloLigaComunidad(idLiga);
		}
	  });	
	
	/* Esta sección solamente cambia el div contenidoeventos (área principal) */
}

var idLigaActualPost = null;

function cambiaEstiloLigaComunidad(idLiga)
{
//	alert("cambiaEstiloLigaComunidad");
	if(idLigaActualPost == -1) // || idLigaActualPost == null)
	{
		var leng = document.links.length;	
		for(var i = 0; i < leng; i++)
		{
			  if(document.links[i].className == 'menu_comunidad_selected')
			  {
				document.links[i].className = 'menu_comunidad_class';
				break;
			  }				
		}
	}
	else
	{
		if(document.getElementById(idLigaActualPost))
		{
			if(document.getElementById(idLigaActualPost))
				document.getElementById(idLigaActualPost).className = 'menu_comunidad_class';		
		}
	}
	
	idLigaActualPost = idLiga;
	
	if(document.getElementById(idLiga))
		document.getElementById(idLiga).className = 'menu_comunidad_selected';
}

var offsetBusquedaPosts = 0;
function muestraListaPostsBusquedaOffset(offs, idLiga)
{
	offsetBusquedaPosts = offs;
	
	var buscar_texto = document.getElementById('textobusqueda').value;
	var url = '_prototype/listaBusquedaPostsPrototype.php';
	
	new Ajax.Updater('menu_comunidad', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offsetBusquedaPosts), buscar_texto: buscar_texto },
		onComplete: function(){
			cambiaEstiloLigaComunidad(idLiga);
		}
	  });
}

function muestraPostSeleccionadoBusqueda(idPost, idLiga)
{
//	alert("idLiga: " + idLiga);
	var url = '_prototype/postsBusquedaPrototype.php';
	var buscar_texto = document.getElementById('textobusqueda').value;
		
	new Ajax.Updater('contenidocomunidad', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', idpost: escape(idPost), buscar_texto: buscar_texto },
		onComplete: function(){
			if(idLiga != '')
				cambiaEstiloLigaComunidad(idLiga);
		}
	  });	
	
	/* Esta sección solamente cambia el div contenidoeventos (área principal) */
}

function realizaBusquedaComunidad()
{
	if(document.getElementById('searchbox'))
	{
		var buscar_texto = document.getElementById('searchbox').value;
		if(buscar_texto == "")
		{
			window.open("comunidad.php", "_self"); //muestraListaEventos(-1, '+', seccionEventos);
		}
		else
		{
			document.getElementById('textobusqueda').value = buscar_texto;
			var url = '_prototype/listaBusquedaPostsPrototype.php';
			
			new Ajax.Updater('menu_comunidad', url,
			  {
				method:'post',
				parameters: {vle:'nmlc', offset: escape(offsetBusquedaPosts), buscar_texto: buscar_texto, primera_vez: escape('si') },
				onComplete: function() {
					muestraPostSeleccionadoBusqueda(0, '');
					idLigaActualPost = -1;
				}
			  });
		}
	}
}

function muestraListaPostsBusqueda(offsetNuevo, direccion)  /* Usado para motrar la lista de eventos inicial, y cuando se haga click en los botones anterior y siguiente */
{
	/*  Dentro de esta función podemos tener los siguientes casos:
	 * 	 1) Que sea necesario actualizar solamente el div eventos_lista_info (menú de eventos)
	 */
	 
	document.getElementById('menu_comunidad').innerHTML = "";
	
	var buscar_texto = document.getElementById('textobusqueda').value;
	
	if(offsetNuevo != -1)
	{
		if(direccion == '+')
			offsetBusquedaPosts++;
		else
			offsetBusquedaPosts--;
	}
	else
		offsetBusquedaPosts = offsetNuevo + 1;
	 
	var url = '_prototype/listaBusquedaPostsPrototype.php';
	
	new Ajax.Updater('menu_comunidad', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offsetBusquedaPosts), buscar_texto: buscar_texto }
	  });
}

function cambiaEstiloCampo(elemento)
{
	if(elemento.id == "lada_txt")
	{
		if(elemento.value == 'Lada')
		{
			elemento.className = 'TextField_Lada';
			elemento.value = '';
		}
	}
	else
	{
		if(elemento.value == 'Teléfono')
		{
			elemento.className = 'TextField_Telefono';
			elemento.value = '';
		}
	}
}

function compruebaInformacion(elemento)
{
	if(elemento.id == "lada_txt")
	{
		if(elemento.value == '')
		{
			elemento.className = 'TextField_Lada_Info';
			elemento.value = 'Lada';
		}
	}
	else
	{
		if(elemento.value == '')
		{
			elemento.className = 'TextField_Telefono_Info';
			elemento.value = 'Teléfono';
		}
	}
}

var nav4 = window.Event ? true : false;

function soloNumeros(evt)
{
	var key;
	if(evt.which) key = evt.which;
	else key = evt.keyCode;
		
	return (key <= 13 || (key >= 48 && key <= 57) || (key == 37) || (key == 39) || (key == 46));
}

function validaRegistroUsuario()
{
	cambiaClassNameRegistro();
	
	var valido = true;
	var form = document.registro_usuario;
	var indice = form.pais_txt.selectedIndex;

	var iChars = "! @#$%^&*()+=-[]\\\';,./{}|\":<>?'áéíóú¿ñ";
	var nick = trim(form.nick_txt.value);
	
	if (nick == "") {
		form.nick_txt.className = 'TextField_Registro_Requerido';
		valido = false;	
	}
	else if(nick.length < 6)
	{
		form.nick_txt.className = 'TextField_Registro_Requerido';
		valido = false;	
	}
	else
	{
		for (var i = 0; i < form.nick_txt.value.length; i++) {
			if (iChars.indexOf(form.nick_txt.value.charAt(i)) != -1) {
				form.nick_txt.className = 'TextField_Registro_Requerido';
				valido = false;
				return false;
			}
		}
	}
	if (trim (form.nombre_txt.value) == "") {
		form.nombre_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.paterno_txt.value) == "") {
		form.paterno_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.materno_txt.value) == "") {
		form.materno_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.rfc_txt.value) == "" && form.pais_txt.options[indice].value == 156) { // 156 es el valor de México
		form.rfc_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.correo_txt.value) == "") {
		form.correo_txt.className = 'TextField_Registro_Requerido';		
		valido = false;
	}
	if (trim (form.correo2_txt.value) == "") {
		form.correo2_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if(!validaMail(form.correo_txt.value))
	{
		form.correo_txt.className = 'TextField_Registro_Requerido';
		document.getElementById('msj_correo').innerHTML = "<strong>Formato de correo electrónico incorrecto</strong>";
		valido = false;
	}
	if (trim (form.correo_txt.value) != trim (form.correo2_txt.value))
	{
		form.correo_txt.className = 'TextField_Registro_Requerido';
		form.correo2_txt.className = 'TextField_Registro_Requerido';
		document.getElementById('msj_correo').innerHTML = "<strong>No coinciden los correos electrónicos</strong>";
		document.getElementById('msj_correo2').innerHTML = "<strong>No coinciden los correos electrónicos</strong>";
		valido = false;
	}
	if (trim (form.password_txt.value) == "") {
		form.password_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.password2_txt.value) == "") {
		form.password2_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim(form.password_txt.value).length < 6)
	{
		form.password_txt.className = 'TextField_Registro_Requerido';		
		document.getElementById('msj_pwd').innerHTML = "<strong>La contraseña debe tener seis caracteres mínimo</strong>";
		valido = false;
	}
	if (trim (form.password_txt.value) != trim (form.password2_txt.value))
	{
		form.password_txt.className = 'TextField_Registro_Requerido';
		form.password2_txt.className = 'TextField_Registro_Requerido';
		document.getElementById('msj_pwd').innerHTML = "<strong>No coinciden las contraseñas</strong>";
		document.getElementById('msj_pwd2').innerHTML = "<strong>No coinciden las contraseñas</strong>";
		valido = false;
	}
	if (trim (form.lada_txt.value) == "Lada") { // lada
		form.lada_txt.className = 'TextField_Lada_Requerido';
		valido = false;
	}
	if (trim (form.telefono_txt.value) == "Teléfono") { // teléfono
		form.telefono_txt.className = 'TextField_Telefono_Requerido';
		valido = false;
	}
	if(indice == 0)
	{
		form.pais_txt.className = 'ComboBox_Paises_Requerido';
		document.getElementById('msj_pais').innerHTML = "<strong>Por favor selecciona tu país</strong>";
		valido = false;
	}
	if (trim (form.calle_txt.value) == "") {
		form.calle_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.numero_txt.value) == "") {
		form.numero_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.colonia_txt.value) == "") {
		form.colonia_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.delegacion_txt.value) == "" && form.pais_txt.options[indice].value == 156) { // 156 es el valor de México
		form.delegacion_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}	
	if (trim (form.estado_txt.value) == "") {
		form.estado_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}	
	if (trim (form.cp_txt.value) == "") {
		form.cp_txt.className = 'TextField_CodigoPostal_Requerido';
		valido = false;
	}	
	
	if(valido)
	{
		var url = '_prototype/verificaCorreoRegistro.php';
	
		new Ajax.Request(url,
		{
			method:'post',
			parameters: {vle:'nmlc', correo_txt: form.correo_txt.value, nick_txt: form.nick_txt.value},
				onSuccess: function(response){
					var resultado = response.responseText;
					if(resultado == "existe-correo")
					{
						form.correo_txt.className = 'TextField_Registro_Requerido';
						document.getElementById('msj_correo').innerHTML = "<strong><span style='color:#FF0000;'>El correo electrónico ya existe, por favor escribe otro</span></strong>";
					}
					else if(resultado == "existe-nick")
					{
						form.correo_txt.className = 'TextField_Registro_Requerido';
						document.getElementById('msj_nick').innerHTML = "<strong><span style='color:#FF0000;'>Ese nick ya existe, por favor escribe otro</span></strong>";
					}
					else if(resultado == "no-existe")
					{
						var url = '_prototype/registroPrototype.php';
						//form.submit();
						var nombre = form.nombre_txt.value;
						var paterno = form.paterno_txt.value;
						var materno = form.materno_txt.value;
						var rfc = form.rfc_txt.value;
						var correo = form.correo_txt.value;
						var upass = form.password_txt.value;
						var empresa = form.empresa_txt.value;
						var lada = form.lada_txt.value;
						var telefono = form.telefono_txt.value;
						var pais = form.pais_txt.value;
						var calle = form.calle_txt.value;
						var numero = form.numero_txt.value;
						var colonia = form.colonia_txt.value;
						var delegacion = form.delegacion_txt.value;
						var estado = form.estado_txt.value;
						var cp = form.cp_txt.value;
												
						new Ajax.Request(url,
						{
							method:'post',
							parameters: {vle:'nmlc', nick_txt: nick, nombre_txt: nombre, paterno_txt: paterno, materno_txt: materno, rfc_txt: rfc, correo_txt: correo, upass_txt: upass, empresa_txt: empresa, lada_txt: lada, telefono_txt: telefono, pais_txt: pais, calle_txt: calle, numero_txt: numero, colonia_txt: colonia, delegacion_txt: delegacion, estado_txt: estado, cp_txt: cp},
								onSuccess: function(response){
									var resultado = response.responseText;
									if(resultado == "existe-correo")
									{
										form.correo_txt.className = 'TextField_Registro_Requerido';
										document.getElementById('msj_correo').innerHTML = "<strong><span style='color:#FF0000;'>El correo electrónico ya existe, por favor escribe otro</span></strong>";
									}
									else if(resultado == "existe-nick")
									{
										form.nick_txt.className = 'TextField_Registro_Requerido';
										document.getElementById('msj_nick').innerHTML = "<strong><span style='color:#FF0000;'>Ese nick ya existe, por favor escribe otro</span></strong>";
									}
									else if(resultado == "falta")
									{
										alert("Por favor llene todos los campos marcados con *");
									}
									else if(resultado == "carrito")
									{
										window.open('cart.php', '_self');
									}
									else if(resultado == "todobien")
									{
										document.getElementById('registro_informacion').innerHTML = '<div style="font:Helvetica; font-family:Helvetica; margin-top:15px;"><span style="font-size:16px;">Gracias por registrarte con <strong>Remeritas</strong></span><br /><br /><span style="font-size:14px; color:#ff0295;"><a href="catalogo.php" target="_self" class="ver_catalogo">Ver catálogo</a></span></div>';
									}
								},
							onFailure: function(){ }
						});
					}
				},
			onFailure: function(){ }
		});
	}
}

function validaActualizaUsuario() /* AQUÍ ESTOY, AQUÍ ESTOY, AQUÍ ESTOY */
{	
	cambiaClassNamePerfil();
	
	var valido = true;
	var form = document.registro_usuario;
	var idusuario = form.idusuario.value;
	var indice = form.pais_txt.selectedIndex;
	
	if (trim (form.rfc_txt.value) == "" && form.pais_txt.options[indice].value == 156) { // 156 es el valor de México
		form.rfc_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.correo_txt.value) == "") {
		form.correo_txt.className = 'TextField_Registro_Requerido';		
		valido = false;
	}
	if (trim (form.correo2_txt.value) == "") {
		form.correo2_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if(!validaMail(form.correo_txt.value))
	{
		form.correo_txt.className = 'TextField_Registro_Requerido';
		document.getElementById('msj_correo').innerHTML = "<strong>Formato de correo electrónico incorrecto</strong>";
		valido = false;
	}
	if (trim (form.correo_txt.value) != trim (form.correo2_txt.value))
	{
		form.correo_txt.className = 'TextField_Registro_Requerido';
		form.correo2_txt.className = 'TextField_Registro_Requerido';
		document.getElementById('msj_correo').innerHTML = "<strong>No coinciden los correos electrónicos</strong>";
		document.getElementById('msj_correo2').innerHTML = "<strong>No coinciden los correos electrónicos</strong>";
		valido = false;
	}
	if (trim (form.lada_txt.value) == "Lada") { // lada
		form.lada_txt.className = 'TextField_Lada_Requerido';
		valido = false;
	}
	if (trim (form.telefono_txt.value) == "Teléfono") { // teléfono
		form.telefono_txt.className = 'TextField_Telefono_Requerido';
		valido = false;
	}
	if (trim (form.calle_txt.value) == "") {
		form.calle_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.numero_txt.value) == "") {
		form.numero_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.colonia_txt.value) == "") {
		form.colonia_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.delegacion_txt.value) == "" && form.pais_txt.options[indice].value == 156) { // 156 es el valor de México
		form.delegacion_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}	
	if (trim (form.estado_txt.value) == "") {
		form.estado_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}	
	if (trim (form.cp_txt.value) == "") {
		form.cp_txt.className = 'TextField_CodigoPostal_Requerido';
		valido = false;
	}	
	
	if(valido)
	{
		var url = '_prototype/verificaCorreoPerfil.php';
	
		new Ajax.Request(url,
		{
			method:'post',
			parameters: {vle:'nmlc', correo_txt: form.correo_txt.value, usuario_txt: idusuario},
				onSuccess: function(response){
					var resultado = response.responseText;
					if(resultado == "existe-correo")
					{
						form.correo_txt.className = 'TextField_Registro_Requerido';
						document.getElementById('msj_correo').innerHTML = "<strong><span style='color:#FF0000;'>El correo electrónico ya existe, por favor escribe otro</span></strong>";
					}
					else if(resultado == "no-existe")
					{
						var url = '_prototype/perfilPrototype.php';
						//form.submit();
						var rfc = form.rfc_txt.value;
						var correo = form.correo_txt.value;
						var empresa = form.empresa_txt.value;
						var lada = form.lada_txt.value;
						var telefono = form.telefono_txt.value;
						var pais = form.pais_txt.value;
						var calle = form.calle_txt.value;
						var numero = form.numero_txt.value;
						var colonia = form.colonia_txt.value;
						var delegacion = form.delegacion_txt.value;
						var estado = form.estado_txt.value;
						var cp = form.cp_txt.value;
												
						new Ajax.Request(url,
						{
							method:'post',
							parameters: {vle:'nmlc', usuario_txt: idusuario, rfc_txt: rfc, correo_txt: correo, empresa_txt: empresa, lada_txt: lada, telefono_txt: telefono, pais_txt: pais, calle_txt: calle, numero_txt: numero, colonia_txt: colonia, delegacion_txt: delegacion, estado_txt: estado, cp_txt: cp},
								onSuccess: function(response){
									var resultado = response.responseText;
									
									if(resultado == "existe-correo")
									{
										form.correo_txt.className = 'TextField_Registro_Requerido';
										document.getElementById('msj_correo').innerHTML = "<strong><span style='color:#FF0000;'>El correo electrónico ya existe, por favor escribe otro</span></strong>";
									}
									else if(resultado == "falta")
									{
										alert("Por favor llene todos los campos marcados con *");
									}
									else if(resultado == "todobien")
									{
										document.getElementById('registro_informacion').innerHTML = '<div style="font:Helvetica; font-family:Helvetica; margin-top:15px;"><span style="font-size:16px;">Tu perfil ha sido actualizado</span><br /><br /><span style="font-size:14px; color:#ff0295;"><a href="catalogo.php" target="_self" class="ver_catalogo"><strong>Ver catálogo</strong></a></span></div>';
									}
								},
							onFailure: function(){ }
						});
					}
				},
			onFailure: function(){ }
		});
	}
}

function cambiaClassNameRegistro()
{
	var form = document.registro_usuario;
	form.nick_txt.className = 'TextField_Registro';
	form.nombre_txt.className = 'TextField_Registro';
	form.paterno_txt.className = 'TextField_Registro';
	form.materno_txt.className = 'TextField_Registro';
	form.rfc_txt.className = 'TextField_Registro';
	form.correo_txt.className = 'TextField_Registro';
	form.correo2_txt.className = 'TextField_Registro';
	form.password_txt.className = 'TextField_Registro';
	form.password2_txt.className = 'TextField_Registro';

	if(form.lada_txt.value != "Lada")
		form.lada_txt.className = 'TextField_Lada';
	if(form.telefono_txt.value != "Teléfono")
		form.telefono_txt.className = 'TextField_Telefono';
	
	form.calle_txt.className = 'TextField_Registro';
	form.numero_txt.className = 'TextField_Registro';
	form.colonia_txt.className = 'TextField_Registro';
	form.delegacion_txt.className = 'TextField_Registro';
	form.estado_txt.className = 'TextField_Registro';
	form.cp_txt.className = 'TextField_CodigoPostal';
	form.pais_txt.className = 'ComboBox_Paises';
	
	var msjcorreo = document.getElementById('msj_correo').innerHTML;
	var msjcorreo2 = document.getElementById('msj_correo2').innerHTML;
	var msjpassword = document.getElementById('msj_pwd').innerHTML;
	var msjpassword2 = document.getElementById('msj_pwd2').innerHTML;
	var msjpais = document.getElementById('msj_pais').innerHTML;
	
	if(msjcorreo.substr(0, 1) == "<")
		document.getElementById('msj_correo').innerHTML = "";
	if(msjcorreo2.substr(0, 1) == "<")
		document.getElementById('msj_correo2').innerHTML = "";
	if(msjpassword.substr(0, 1) == "<")
		document.getElementById('msj_pwd').innerHTML = "";
	if(msjpassword2.substr(0, 1) == "<")
		document.getElementById('msj_pwd2').innerHTML = "";
	if(msjpais.substr(0, 1) == "<")
		document.getElementById('msj_pais').innerHTML = "";
}

function cambiaClassNamePerfil()
{
	var form = document.registro_usuario;
	form.correo_txt.className = 'TextField_Registro';
	form.correo2_txt.className = 'TextField_Registro';

	if(form.lada_txt.value != "Lada")
		form.lada_txt.className = 'TextField_Lada';
	if(form.telefono_txt.value != "Teléfono")
		form.telefono_txt.className = 'TextField_Telefono';
	
	form.calle_txt.className = 'TextField_Registro';
	form.numero_txt.className = 'TextField_Registro';
	form.colonia_txt.className = 'TextField_Registro';
	form.delegacion_txt.className = 'TextField_Registro';
	form.estado_txt.className = 'TextField_Registro';
	form.cp_txt.className = 'TextField_CodigoPostal';
	
	var msjcorreo = document.getElementById('msj_correo').innerHTML;
	var msjcorreo2 = document.getElementById('msj_correo2').innerHTML;
	
	if(msjcorreo.substr(0, 1) == "<")
		document.getElementById('msj_correo').innerHTML = "";
	if(msjcorreo2.substr(0, 1) == "<")
		document.getElementById('msj_correo2').innerHTML = "";	
}

function generaNuevaContrasena()
{
	var form = document.recupera_contrasena;
	var valido = true;
	
	document.getElementById('msj_recuperacion').innerHTML = "";
	
	if (trim (form.correo_txt.value) == "") {
		form.correo_txt.className = 'TextField_Registro_Requerido';		
		valido = false;
	}
	if(!validaMail(form.correo_txt.value))
	{
		form.correo_txt.className = 'TextField_Registro_Requerido';
		document.getElementById('msj_recuperacion').innerHTML = "<strong>Formato de correo electrónico incorrecto</strong>";
		valido = false;
	}
	
	if(valido)
	{
		var correo_txt = document.recupera_contrasena.correo_txt.value; //  , comentario_txt: comentario_val	
		var url = '_prototype/recuperaContrasenaPrototype.php';
				
		new Ajax.Request(url,
		{
			method:'post',
			parameters: {vle:'nmlc', correo_txt: correo_txt},
				onSuccess: function(response){
					var resultado = response.responseText;
										
					if(resultado == "no-existe-correo")
					{
						document.getElementById('msj_recuperacion').innerHTML = "No existe ese correo electrónico";					
					}
					else if(resultado == "todobien")
					{
						document.getElementById('msj_recuperacion').innerHTML = "Tu nueva contraseña ha sido enviada a tu correo electrónico";
						document.recupera_contrasena.reset();
					}
				},
			onFailure: function(){ }
		});
	}
}

function estadoInicialPwds()
{
	var form = document.cambia_contrasena;
	form.password_txt.className = 'TextField_Registro';
	form.password2_txt.className = 'TextField_Registro';
	document.getElementById('msj_recuperacion').innerHTML = "&nbsp;";
}

function validaNuevaContrasena()
{	
	estadoInicialPwds();
	
	var valido = true;
	var form = document.cambia_contrasena;
	var idUsuario = form.user_dt.value;
	
	if (trim (form.password_txt.value) == "") {
		form.password_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim (form.password2_txt.value) == "") {
		form.password2_txt.className = 'TextField_Registro_Requerido';
		valido = false;
	}
	if (trim(form.password_txt.value).length < 6)
	{
		form.password_txt.className = 'TextField_Registro_Requerido';		
		document.getElementById('msj_recuperacion').innerHTML = "<strong>La contraseña debe tener seis caracteres mínimo</strong>";
		valido = false;
	}
	if (trim (form.password_txt.value) != trim (form.password2_txt.value))
	{
		form.password_txt.className = 'TextField_Registro_Requerido';
		form.password2_txt.className = 'TextField_Registro_Requerido';
		document.getElementById('msj_recuperacion').innerHTML = "<strong>No coinciden las contraseñas</strong>";
		valido = false;
	}
	
	if(valido)
	{
		var url = '_prototype/actualizaContrasenaPrototype.php';
		var upass = hex_md5(form.password_txt.value);
		
		new Ajax.Request(url,
		{
			method:'post',
			parameters: {uid_txt: idUsuario, pword_txt: upass },
				onSuccess: function(response){
					var resultado = response.responseText;
					if(resultado == 'ok')
					{
						document.getElementById('msj_recuperacion').innerHTML = "Tu contraseña ha sido actualizada, por favor <a href='ingreso.php' target='_self'>ingresa</a> con ella";
						form.password_txt.value = "";
						form.password2_txt.value = "";
					}
					else if(resultado == 'no')
					{
						document.getElementById('msj_recuperacion').innerHTML = "Hubo un error en la actualización de la contraseña, por favor intenta más tarde.";
					}
				},
			onFailure: function(){ }
		});
	}
}

function muestraImagenColeccion(offset)
{
	var url = '_prototype/coleccionCatalogo.php';
	
	new Ajax.Updater('contenido', url,
	  {
		method:'post',
	    parameters: {vle:'nmlc', offset: escape(offset) }
	  });
}

function muestraCart(clp, pid)
{
	var url = 'orderform_additem.php?clp=' + clp + '&pid=' + pid;

	var comboTalla = document.getElementById("talla_select");
	if(comboTalla != null)
	{
		var indice = document.info_prod.talla_select.selectedIndex;
		url += '&idt=' + document.info_prod.talla_select[indice].value;		
	}
	else
		url += '&idt=0';
	
	var comboColor = document.getElementById("color_select");
	if(comboColor != null)
	{
		var indice = document.info_prod.color_select.selectedIndex;
		url += '&icol=' + document.info_prod.color_select[indice].value;
	}
	else
		url += '&icol=0';
	
	window.open(url, '_self');
}

function confirmaPedidoDeposito()
{
	var respuesta = confirm('¿Estás seguro de que tu forma de pago sería por Depósito Bancario?\n De estar seguro da click en ACEPTAR, si tienes dudas sobre el proceso da click en CANCELAR y ve a  ¿Cómo hacer tu pago por Depósito Bancario?');
	if(respuesta)
	{
		aceptarTerminosLegales(1);
		//generaPedido();
	}
}

function generaPedido()
{		
	var url = '_prototype/pedidoDepositoPrototype.php';
	
	new Ajax.Request(url,
	{
		method:'post',
		parameters: {vle:'nmlc'},
		onSuccess: function(response){
			var resultado = response.responseText;
			if(resultado == "sk8owtsd")
				window.open('perfil.php?d=54d5f4e65', '_self');
			else
				alert("No se pudo generar el pedido, por favor revise que esté registrado y logeado.");
		},
		onFailure: function(){ }
	});
}

function confirmaCompraPaypal()
{
	aceptarTerminosLegales(2);
}

function aceptarTerminosLegales()
{
	myLightWindow.activateWindow({href: 'terminos_legales.html', title: '', width:440, height:480});
}

function cierraVentana()
{
	myLightWindow.deactivate();
}
function revisaForma()
{
	return tmc;
}
function aceptarTerminosLegales(t)
{
	type = t;
	myLightWindow.activateWindow({href: 'terminos_legales.html', title: '', width:440, height:480});
}

function cierraVentana()
{
	myLightWindow.deactivate();
}

function respuestaTL(v)
{
	if(v == 'D6553tr')
	{
		tmc = true;
		cierraVentana();
		if(type == 1)
			generaPedido();
		else if(type == 2)
			document.paypal_check.submit();
	}
	else
		cierraVentana();
}