/*--------------------------------------------------------*/
/* DEFINICIÓN DE OBJETOS, CONSTANTES Y VARIABLES GLOBALES */
/*--------------------------------------------------------*/

/* VARIABLES GLOBALES */
var peticion_http = null;
var respuesta = null;
var confirmarLogin = false;

/* CONTANTES */
var numeros = "0123456789";
var numeros_punto = "0123456789.";
var caracteres = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZáéíóúÁÉÍÓÚäëïöüÄËÏÖÜ-_()#@$%&!¡¿?=/+.,:;+* ";
var numeros_caracteres = numeros + caracteres;
var teclas_especiales = [8, 9, 35, 36, 37, 38, 39, 40, 46];
var net = new Object();
net.READY_STATE_UNINITIALIZED = 0;
net.READY_STATE_LOADING = 1;
net.READY_STATE_LOADED = 2;
net.READY_STATE_INTERACTIVE = 3;
net.READY_STATE_COMPLETE = 4;

/*-------------------------*/
/* DEFINICIÓN DE FUNCIONES */
/*-------------------------*/

/* FUNCIÓN CONTROLADORA DE LOS TEXT PARA EVITAR INGRESOS INDEVIDOS */
function permite(elEvento, permitidos, Submit){
	switch(permitidos){
		case "num":
			permitidos = numeros;
			break;
		case "num_pun":
			permitidos = numeros_punto;
			break;
		case "car":
			permitidos = caracteres;
			break;
		case "num_car":
			permitidos = numeros_caracteres;
			break;
	}
	var evento = elEvento || window.event;
	if(evento.keyCode == 13){
		Submit.click();
		return false;
	}
	var caracter = 0;
	var tecla_especial = false;
	if(navigator.appName == "Microsoft Internet Explorer"){
		caracter = String.fromCharCode(evento.keyCode);
	}else if(navigator.appName == "Opera"){
		caracter = String.fromCharCode(evento.keyCode);
		if(evento.keyCode != 39 && teclas_especiales.indexOf(evento.keyCode) != -1){tecla_especial = true;}
	}else{
		if(evento.charCode == 0){
			if(teclas_especiales.indexOf(evento.keyCode) != -1){tecla_especial = true;}
		}else{
			caracter = String.fromCharCode(evento.charCode);
		}
	}
	return permitidos.indexOf(caracter) != -1 || tecla_especial;
}

/* FUNCIÓN DE VALIDACIÓN DE CARACTERES INGRESADOS EN LOS FOMULARIOS */
function validarTecla(form, campos){
	var text = [];
	var tecla_especial = false;
	var error = false;
	var parametros = eval("("+campos+")");
	var permitidos = "";
	for(var i = 0; i < parametros.Campos.length; i++){
		text[i] = document.getElementById(parametros.Campos[i]);
	}
	for(var i = 0; i < text.length; i++){
		if(text[i].value.length == 0){
			text[i].focus()
			return false;
		}
		switch(parametros.Valores[i]){
			case "num":
				var permitidos = numeros;
				break;
			case "num_pun":
				var permitidos = numeros_punto;
				break;
			case "car":
				var permitidos = caracteres;
				break;
			case "num_car":
				var permitidos = numeros_caracteres;
				break;
		}
		for(var z = 0; z < text[i].value.length; z++){
			if(permitidos.indexOf(text[i].value.charAt(z)) == -1){
				error = true;
				text[i].value = ""
			}
		}
	}
	if(error == true){
		alert("Ha ingresado caracteres no válidos para este fomulario.")
		return false;
	}else{
		if(form == "loguearse"){
			if(confirmarLogin == false){
				valida();
				return false;
			}else{
				return true;
			}
		}else if(form == "buscarArticulos"){
			return true;
		}else if(form == "consultaReparacion"){
			return true;
		}
	}
}

/* FUNCIÓN VERIFICADORA DE TIPO DE CONEXIÓN */
function inicializaXHR(){
	var xmlhttp = null;
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){xmlhttp = false;}
	}
	if(!xmlhttp && typeof XMLHttpRequest != "undefined"){
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp
}

/* FUNCIÓN VALIDADORA DE CONCULTAS */
function valida(){
	peticion_http = inicializaXHR();
	if(peticion_http){
		peticion_http.onreadystatechange = procesaRespuesta;
		peticion_http.open("POST", "./Codigos/ASP-Login.ASP", true);
		peticion_http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		consulta = "Email=" + escape(document.getElementById("nombreUsuario").value) + "&Password=" + escape(document.getElementById("passwordUsuario").value) + ((document.getElementById("recordarUsuario").checked == true) ? "&Recordar=Si" : "&Recordar=No") + "&nocache=" + Math.random();
		peticion_http.send(consulta);
//alert(consulta);
	}
}

/* FUNCIÓN PROCESADORA DE RESPUESTAS DE CONSULTAS */
function procesaRespuesta(){
	if(peticion_http.readyState == net.READY_STATE_COMPLETE){
		if(peticion_http.status == 200){
//alert(peticion_http.responseText)
			respuesta = eval("("+peticion_http.responseText+")");
			if(respuesta.Ingreso == "Valido"){
				confirmarLogin = true;
				document.getElementById("loguearse").submit();
			}else{
				alert("La contraseña no concuerda o el nombre de usuario no existe. Verifique haber ingresado correctamente los datos e inténtelo nuevamente.");
				document.getElementById("nombreUsuario").focus();
			}
		}
	}
}

/* FUNCIÓN QUE MUESTRA LOS ARTÍCULOS CORRESPONDIENTES A LA PÁGINA ACTUAL */
function CambiarPagina(Indice){
	if(menuContenidos.Objetos.RespuestaArticulos.CantidadArticulos < menuContenidos.Objetos.RespuestaArticulos.ArticulosPorPagina || menuContenidos.Propiedades.PaginaActual == menuContenidos.Propiedades.CantidadPaginas - 1 && Indice >= menuContenidos.Propiedades.PaginaActual || menuContenidos.Propiedades.PaginaActual == 0 && Indice < 0){return}
	menuContenidos.Propiedades.PaginaActual = Indice;
	menuContenidos.Propiedades.IndiceArticulos = menuContenidos.Objetos.RespuestaArticulos.ArticulosPorPagina * menuContenidos.Propiedades.PaginaActual;
	document.getElementById("ActualSuperior").selectedIndex = Indice;
	document.getElementById("ActualInferior").selectedIndex = Indice;
	MostrarArticulos();
}

/* FUNCIÓN QUE MODIFICA EL COLOR DE FONDO DE LA COLUMNA EN LA QUE ESTA POSICIONADO EL CURSOR */
function CambiarFondo(Accion, PosicionV, PosicionH, Fila, Columna){
	if(PosicionV == "Titulo"){
		Columna.parentNode.parentNode.getElementsByTagName("tr")[Fila].getElementsByTagName("td")[PosicionH].style.backgroundColor = ((Accion == "Entrar") ? "#DCDCDC" : "#E6E6E6");
		Columna.getElementsByTagName("p")[0].getElementsByTagName("a")[0].style.color = ((Accion == "Entrar") ? "#DC1414" : "#7D7D7D");
	}else{
		Columna.parentNode.parentNode.getElementsByTagName("tr")[Fila].getElementsByTagName("td")[PosicionH].style.backgroundColor = ((Accion == "Entrar") ? "#DCDCDC" : "#E6E6E6");
		Columna.parentNode.parentNode.getElementsByTagName("tr")[Fila].getElementsByTagName("td")[PosicionH].getElementsByTagName("p")[0].getElementsByTagName("a")[0].style.color = ((Accion == "Entrar") ? "#DC1414" : "#7D7D7D");
	}
	Columna.style.backgroundColor = ((Accion == "Entrar") ? "#DCDCDC" : "#E6E6E6");
}
