
// -- HACER XMLHTTPREQUEST --
function crearRequestObject() {
	var xmlhttp = null;
	
	if(window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
	} else {
		alert ("Su navegador no soporta xmlhttprequest");
	}
	return xmlhttp;
}


// -- IDENTIFICACION DE CLIENTE --
function identificarCliente(nombre,password) {
	var cadena = "submit=1&cliente_email=" + escape(nombre) + "&cliente_pass=" + escape(password);
	xmlhttp.open("POST","js/identificarCliente.php",true);
	xmlhttp.setRequestHeader("Man","POST js/identificarCliente.php HTTP/1.1");
	xmlhttp.setRequestHeader("MessageType","CALL");
	xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if( xmlhttp.readyState == 4 ) {
			window.location = './index.php?go=index';
		}
		/*if( xmlhttp.readyState == 4 ) {
			var listaXML = xmlhttp.responseXML;
			var lista = listaXML.getElementsByTagName('cliente');

			for (cont=0; cont<lista.length; cont++) {
				id = lista[cont].getAttribute('id');
				item = lista[cont].getElementsByTagName('email')[0];
				if (item.hasChildNodes()) { email = item.firstChild.nodeValue; } else { email = ""; }
				item = lista[cont].getElementsByTagName('contacto')[0];
				if (item.hasChildNodes()) { contacto = item.firstChild.nodeValue; } else { contacto = ""; }
				item = lista[cont].getElementsByTagName('estado')[0];
				if (item.hasChildNodes()) { estado = item.firstChild.nodeValue; } else { estado = ""; }
	
				if (es_nulo(estado)) {
					document.getElementById('bloqueuser_estado').innerHTML = '';
					document.getElementById('contacto').innerHTML = contacto;
					document.getElementById('email').innerHTML = email;
					document.getElementById('login').className = "off";
					document.getElementById('logout').className = "on";
					document.getElementById('comprasi').className = "on";
					document.getElementById('comprano').className = "off";					
				} else {
					if (nombre == -1 && password == -1) estado = "desconectado";
					document.getElementById('bloqueuser_estado').innerHTML = '<span class="resaltar">'+estado+'</span>';
					document.getElementById('contacto').innerHTML = "";
					document.getElementById('email').innerHTML = "";
					document.getElementById('logout').className = "off";
					document.getElementById('login').className = "on";
					document.getElementById('comprasi').className = "off";
					document.getElementById('comprano').className = "on";					
				}
				document.getElementById('cliente_email').value = "";
				document.getElementById('cliente_pass').value = "";
			}
		} else {
			document.getElementById('bloqueuser_estado').innerHTML = '<span class="resaltar">Comprobando los datos ...</span>';
		}*/
	}
	xmlhttp.send(cadena);
}


// -- ACTUALIZACION DE LA CESTA --
function modCantidadArt(actual,id,cant,mod) {
	// -- definir variables --
	var cadena = "js/modcesta.php?id=" + escape(id) + "&cant=" + escape(cant) + "&mod=" + escape(mod);
	var salida = "";
	if(mod == 0) {
		alert ('Seleccione una opción del desplegable');	
		exit;
	}

	// -- hacer get y ejecutar funcion --
	xmlhttp.open("GET",cadena,true);
	xmlhttp.onreadystatechange = function() {
		window.location = actual;
		/*if(xmlhttp.readyState == 4) {
			var listaXML = xmlhttp.responseXML;
			var lista = listaXML.getElementsByTagName('articulo');

			// -- sacar elementos de la lista xml --
			for (cont=0; cont<lista.length; cont++) {
				id = lista[cont].getAttribute('id');
				item = lista[cont].getElementsByTagName('nombre')[0];
				if (item.hasChildNodes()) { nombre = item.firstChild.nodeValue; } else { nombre = ""; }
				item = lista[cont].getElementsByTagName('modelo')[0];
				if (item.hasChildNodes()) { modelo = item.firstChild.nodeValue; } else { modelo = ""; }
				item = lista[cont].getElementsByTagName('cantidad')[0];
				if (item.hasChildNodes()) { cantidad = item.firstChild.nodeValue; } else { cantidad = ""; }
				item = lista[cont].getElementsByTagName('importe')[0];
				if (item.hasChildNodes()) { importe = item.firstChild.nodeValue; } else { importe = ""; }
				salida = salida + "<p>"+nombre+" (<i>"+modelo+"</i>) [<strong>Cantidad: "+cantidad+"</strong>]</p>";
			}

			// -- calcular y poner totales --
			var lista = listaXML.getElementsByTagName('total');
			for (cont=0; cont<lista.length; cont++) {
				item = lista[cont].getElementsByTagName('cantidad')[0];
				if (item.hasChildNodes()) { cantidad = item.firstChild.nodeValue; } else { contacto = ""; }
				item = lista[cont].getElementsByTagName('importe')[0];
				if (item.hasChildNodes()) { importe = item.firstChild.nodeValue; } else { estado = ""; }
				salida = salida + "<p><strong>Productos en total:</strong> "+cantidad+"</p>";
				salida = salida + "<p><strong>Importe total:</strong> "+importe+"</p>";
				salida = salida + "<p align=center>";
				salida = salida + "<span class=\"boton\" onClick=\"window.location='index.php?go=cesta';\">Ver carrito</span>";
				salida = salida + "</p>";
			}
			document.getElementById('contenidocesta').innerHTML = salida;
		} else {
			document.getElementById('contenidocesta').innerHTML = '<span class="resaltar">Actualizando...</span>';
		}*/
	}
	xmlhttp.send(null);	
}


// -- (parece que sirve para sacar los datos de envio) --
function datosEnvio(datos) {
	// -- crear parametros de URL --
	var cadena = "submit=1&nif=" + escape(datos[1]) + "&contacto=" + escape(datos[2]) + "&empresa=" + escape(datos[3]);
	cadena += "&direccion=" + escape(datos[4]) + "&cp=" + escape(datos[5]) + "&poblacion=" + escape(datos[6]);
	cadena += "&provincia=" + escape(datos[7]) + "&pais=" + escape(datos[8]) + "&telefono=" + escape(datos[9]);
	cadena +=  "&movil=" + escape(datos[10]) + "&fax=" + escape(datos[11]);

	// -- hacer post, comprobar estado y ejecutar funcion --
	xmlhttp.open("POST","js/datosEnvio.php",true);
	xmlhttp.setRequestHeader("Man","POST js/datosEnvio.php HTTP/1.1");
	xmlhttp.setRequestHeader("MessageType","CALL");
	xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4) {
			var listaXML = xmlhttp.responseXML;
			var lista = listaXML.getElementsByTagName('operacion');

			for (cont=0; cont<lista.length; cont++) {
				estado = lista[cont].getAttribute('estado');
				item = lista[cont].getElementsByTagName('mensaje')[0];
				if (item.hasChildNodes()) { mensaje = item.firstChild.nodeValue; } else { mensaje = ""; }

				if (estado == 1) {
					document.getElementById('estadooperacion').innerHTML = '<span class="resaltar">'+mensaje+'</span>';
					document.getElementById('botonpaso23').className = 'boton on';
				} else {
					document.getElementById('estadooperacion').innerHTML = '<span class="resaltar error">Se ha producido un error al enviar los datos, int&eacute;ntelo de nuevo en unos segundos</span>';
				}
			}
		} else {
			document.getElementById('estadooperacion').innerHTML = '<span class="resaltar">Guardando los datos ...</span>';
		}
	}
	// -- enviar URL --
	xmlhttp.send(cadena);
}


// -- actualiza los desplegables de forma de pago y forma de envio ir pasando entre desplegables en el final de la compra --
function actualiza(que,d,p,e) {
	// -- crear variables --
	var cadena = "js/actualizaEnvio.php?q=" + escape(que) + "&d=" + escape(d) + "&p=" + escape(p) + "&e=" + escape(e);
	//var salida = "";
	var salida = new Array();

	// -- hacer get y ejecutar funcion --
	xmlhttp.open("GET",cadena,true);
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4) {
			var listaXML = xmlhttp.responseXML;
			var lista = listaXML.getElementsByTagName('select');
			for (cont=0; cont<lista.length; cont++) {
				id = lista[cont].getAttribute('id');
				opciones = lista[cont].getElementsByTagName('opt');
				for (aux=0; aux<opciones.length; aux++) {
					indice = opciones[aux].getAttribute('id');
					item = opciones[aux];
					if (item.hasChildNodes()) { valor = item.firstChild.nodeValue; } else { valor = ""; }
					salida[indice] = valor;
				}
				if (que == 'destino') {
					obj = document.getElementById('selpago');
					document.getElementById('selenvio').length = 0;
					document.getElementById('estadogastosenvio').innerHTML = 'Seleccione la forma de pago';
					document.getElementById('botonpaso12').className = 'off';
				}
				if (que == 'pago') {
					obj = document.getElementById('selenvio');
					document.getElementById('estadogastosenvio').innerHTML = 'Seleccione el modo de envio';
					document.getElementById('botonpaso12').className = 'off';
				}
				if ((que == 'destino') || (que == 'pago')) {
					obj.length = 0;
					i = 0;
					for (x in salida) {
						var newOpt = new Option(salida[x], x);
					    	obj.options[i] = newOpt;
						i++;
					}
				}
			}
			if(que == 'envio') {
				var gastos = listaXML.getElementsByTagName('gastos');
				for (cont=0; cont<gastos.length; cont++) {
					item = gastos[cont].getElementsByTagName('envio')[0];
					if (item.hasChildNodes()) { valor = item.firstChild.nodeValue; } else { valor = ""; }
					item = gastos[cont].getElementsByTagName('total')[0];
					if (item.hasChildNodes()) { valor2 = item.firstChild.nodeValue; } else { valor2 = ""; }
				}
				var estado = 'Gastos de env&iacute;o: '+valor+' &euro;';
				document.getElementById('estadogastosenvio').innerHTML = estado;
				document.getElementById('labgastosenvio').innerHTML = valor+' &euro;';
				document.getElementById('labgastosfinal').innerHTML = valor2+' &euro;';				
				document.getElementById('botonpaso12').className = 'on';
			}
		}
	}
	xmlhttp.send(null);
}

var xmlhttp = crearRequestObject(); // CREAMOS EL OBJETO

