window.addEvent('domready', function() {
 	var nS5 = new noobSlide({
		mode: 'vertical',
		box: $('box5'),
		items: $$('#box5 span'),
		size: 160,
		autoPlay: true,
		interval: 10000
	});
});


window.addEvent('domready', function() {
 	modificar_input_selector();
	datosCarrito();
});

 

var ancho_minimo = "30px"; // Del input type="text"

// Navegadores
var _IE_ = navigator.appName.toLowerCase().indexOf("microsoft") > -1;
var _MOZILLA_ = navigator.appName.toLowerCase().indexOf("netscape") > -1;

// Selecciona todos los input:text y les añade
// un control para modificar el valor numérico
// que consiste en flechas arriba/abajo y 
// una barra

function guardarBuscarPrecio(id, cantidad,operacion,precio) {
	var req = new Request({  
		method: 'get',  
		url: 'includes/buscarPrecio.php',  
		data: 'info='+id+'/'+cantidad,  
		onComplete: function(response) {
			var subTotalProducto = document.getElementById('subTotal'+id);
			if (subTotalProducto != null){
				precioSubTotal=response.replace("[","");
				precioSubTotal=precioSubTotal.replace("]","");
				subTotalProducto.innerHTML=precioSubTotal;
			}  
			if(operacion == '+'){
				guardarProductoCarrito(id, cantidad,precio);
			}else{
				if(parseInt(cantidad) >= 0){
					modificarCantidadProductoCarrito(id, cantidad);
				}
			}
		}  
	}).send(); 
 }

function guardarProductoCarrito(id, cantidad,precio) {
	var req = new Request({  
		method: 'get',  
		url: 'includes/guardarProductoCarrito.php',  
		data: 'info='+id+'/'+cantidad+'/'+precio,  
		onComplete: function(response) {			
			modificarDatosCarrito(response);
		}  
	}).send(); 
}
function modificarCantidadProductoCarrito(id, cantidad) {
	var req = new Request({  
		method: 'get',  
		url: 'includes/modificarCantidadProductoCarrito.php',  
		data: 'info='+id+'/'+cantidad,  
		onComplete: function(response) {
			modificarDatosCarrito(response);
		} 
	}).send(); 
}
function modificarDatosCarrito(datos) {	
	var datosCompraArealizar = datos.split("/");

	var totalProductosAgregados = document.getElementById('totalProductosAgregados');
	if (totalProductosAgregados != null){
		totalProductosAgregados.innerHTML= datosCompraArealizar[0];
	}
	var precioProductosAgregados = document.getElementById('precioProductosAgregados');
	if (precioProductosAgregados != null){
		precioProductosAgregados.innerHTML= datosCompraArealizar[1];
	}
}
function datosCarrito() {
	var req = new Request({  
		method: 'get',  
		url: 'includes/datosCarrito.php',  
 		onComplete: function(response) {
			modificarDatosCarrito(response);
		} 
	}).send(); 
}

 function modificar_input_selector(evt) {
	if (document.getElementsByTagName) {
		// Obtengo los elementos INPUT
		var objs = document.getElementsByTagName("INPUT");
		
		// Los modifico para incluir el selector a los que tenga el atributo rel = "selector"
		for (var i=0; i<objs.length; i++) {
			if (objs[i].getAttribute("rel") != null && 
				objs[i].getAttribute("rel").toLowerCase().match(/^selector(\[\-?\s*\d+\s*,\s*\-?\s*\d+\])?$/) &&
			    objs[i].type.toLowerCase() == "text") {
				// Creamos id si no lo tiene
				if (!objs[i].id) {
					objs[i].id = Math.random();
				}
				// Si no hay ancho lo ponemos
				if (!objs[i].style.width) {
					objs[i].style.width = ancho_minimo;
				}
				// Hayamos el máximo y el mínimo
				var params = objs[i].getAttribute("rel").replace(/(^selector\[)|(\]$)/g, "").split(",");
				var min = parseInt(params[0]);
				var max = parseInt(params[1]);
				if (max<min) {
					max = min;
				}
				objs[i].max = max;
				objs[i].min = min;
				// Le añadimos al objeto input el evento onchange
				objs[i].onchange = function() {
					
					if (!isNaN(parseInt(this.value))) {
						// Si es numérico
						if (parseInt(this.value) < this.min) {
							// Si es más pequeño que el mínimo toma este valor
							this.value = this.min;
						} else if (parseInt(this.value) > this.max) {
							this.value = this.max;
						}
					} else {
						// Si no es un número se devuelve el valor mínimo
						this.value = min;
					}
					
				
 					
					//this.barra.firstChild.style.width = this.barra.incremento*(parseInt(this.value)-min)+"px";
				};
				
				// Empezamos con la barra
				// Lo incluimos dentro de una capa
				var contenedor = document.createElement("SPAN");
				contenedor.className = "contenedor-controles-input-selector";

				
				// Se añade el contenedor antes de la barra
				objs[i].parentNode.insertBefore(contenedor, objs[i]);

				// Aumentar
				// Se crea el enlace
				var a = document.createElement("A");
				a.id = objs[i].id+"_AUMENTAR";
				a.href="#";
				// Se le añaden atributos para luego poder hacer referencia
				a.cajaTexto = objs[i];
				a.max = max;
				a.min = min;
				
				// No se usa click por si se quiere que vaya 
				// cambiando mientras se tiene pulsado el boton del raton
				a.onclick = function() {
					// Si es numero
					if (!isNaN(parseInt(this.cajaTexto.value))) {
						// Si es mas pequeño que el valor máximo
						if (parseInt(this.cajaTexto.value) < this.max) {
							// Si es menor que el valor minimo se pone este
							if (parseInt(this.cajaTexto.value) < this.min) {
								this.cajaTexto.value = this.min;
							} else {
								// Se incrementa el valor en 1
								this.cajaTexto.value = parseInt(this.cajaTexto.value)+1;
								//Se guarda y muestra en la pagina la cant de productos y el total de de la compra
								var idPrecioProducto = this.cajaTexto.title.split("-");
								guardarBuscarPrecio(idPrecioProducto[0],this.cajaTexto.value,'+',idPrecioProducto[1]);
							}
						} else {
							// Se pone el valor máximo si es mayor que este
							this.cajaTexto.value = this.max;
						}
					} else {
						// Si no es numerico se pone el valor minimo
						this.cajaTexto.value = this.min;
					}
					
					return false;
					
					// Se repite el evento mientras se tenga pulsado el raton
					//this.idEvento = setTimeout('document.getElementById("'+this.id+'").onmousedown()', 200);
				};
				// Se deja de repetir el evento al soltar el boton del raton
			 
				// Las flechas usan una imagen transparente para 
				// poder usar un background y hacer el efecto hover 
				// usando una única imágen
				a.innerHTML = '<img src="imagenes/sp.gif" alt=""/>';
				a.className="aumentar-input-selector";
				// Incluyo la imagen despues de la caja de texto
				objs[i].parentNode.insertBefore(a, objs[i].nextSibling);
				
				// Me quedo con este objeto para luego
				// incluir a continuación de este la otra flecha
				var a_aumentar = a;
				
				// Disminuir
				// Se crea el enlace
				a = document.createElement("A");
				a.id = objs[i].id+"_DISMINUIR";
				a.href="#";
				// Se le añaden atributos para luego poder hacer referencia
				a.cajaTexto = objs[i];
				a.max = max;
				a.min = min;
				
				// No se usa click por si se quiere que vaya 
				// cambiando mientras se tiene pulsado el boton del raton
				a.onclick = function(evt) {
					// Si es numero
					if (!isNaN(parseInt(this.cajaTexto.value))) {
						// Si es mas pequeño que el valor máximo
						if (parseInt(this.cajaTexto.value) > this.min) {
							// Si es menor que el valor minimo se pone este
							if (parseInt(this.cajaTexto.value) > this.max) {
								this.cajaTexto.value = this.max;
							} else {
								// Se incrementa el valor en 1
								this.cajaTexto.value = parseInt(this.cajaTexto.value)-1;
								var idPrecioProducto = this.cajaTexto.title.split("-");
								guardarBuscarPrecio(idPrecioProducto[0],this.cajaTexto.value,'-',idPrecioProducto[1]);
							}
						} else {
							// Se pone el valor máximo si es mayor que este
							this.cajaTexto.value = this.min;
						}
					} else {
						// Si no es numerico se pone el valor minimo
						this.cajaTexto.value = this.min;
					}
					
					return false;
					// Modificamos el progreso
					
					// Se repite el evento mientras se tenga pulsado el raton
					//this.idEvento = setTimeout('document.getElementById("'+this.id+'").onmousedown()', 200);
				};
				// Se deja de repetir el evento al soltar el boton del raton
				 
				// Las flechas usan una imagen transparente para 
				// poder usar un background y hacer el efecto hover 
				// usando una única imágen
				a.innerHTML = '<img src="imagenes/sp.gif" alt=""/>';
				a.className="disminuir-input-selector";
				// Incluyo la imagen despues de la primera flecha
				objs[i].parentNode.insertBefore(a, a_aumentar.nextSibling);

			}
		}
	}
}
