// JavaScript Document

function aniadeCarrito(cod_tipo_pedido,codigo) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/aniade_carrito.php?cod_tipo_pedido=" + cod_tipo_pedido + "&codigo=" + codigo, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
			} else {
				alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function aniadeCarritoSuscripcion(cod_tipo_pedido,codigo,extra) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "../includes/ajax/aniade_carrito.php?cod_tipo_pedido=" + cod_tipo_pedido + "&codigo=" + codigo + "&extra=" + extra, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
				if (cod_tipo_pedido == 3) {
					document.location.href='../ejemplares.php?cod_revista=' + codigo;
				}
			} else {
				alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function eliminaCarrito(codigo,cod_tipo_pedido,todo) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/elimina_carrito.php?codigo=" + codigo + "&cod_tipo_pedido=" + cod_tipo_pedido + "&todo=" + todo, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
				refrescaCarrito();
				muestraCarrito(0,0);
			} else {
				//alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function refrescaCarrito() {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/mini-carrito.php?aniade=1", true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
				document.getElementById('contenedor_minicarrito').innerHTML = oXmlHttp.responseText;
			} else {
				//alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function muestraCarrito(paso,forma_pago) {
	$.ajax({
		url: "includes/ajax/muestra-carrito.php?paso=" + paso + "&forma_pago=" + forma_pago,
		type: "GET",
		cache: false,
		success: function(html) {
			$('#contenedor_carrito').html(html);
		}
	});
}

function muestraContenidoCarrito(texto){
	document.getElementById('contenedor_medio_izda_general').innerHTML = texto;
}

function compruebaElementosEnCarrito(n_elementos){
	if (n_elementos == 0){
		alert("Agregue libros a la caja antes de seguir con el proceso de compra.");
	} else {
		window.location = "https://www.revistasprofesionales.com/carrito.php?paso=0";
	}
}

function ConfirmAction(Message){
	if (confirm(Message)){
		return true;
	} else {
		return false;	
	}		
}

function sumaCantidad(caja_texto) {
	document.getElementById(caja_texto).value++;
	//modificaTotales();
}

function restaCantidad(caja_texto) {
	if (document.getElementById(caja_texto).value > 1) {
		document.getElementById(caja_texto).value--; 
	}
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/number_format    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');    }
    return s.join(dec);
}


function calcula_precio(caja,precio,cantidad,id_productos){
	var numero = precio*cantidad;
	caja.innerHTML = number_format(numero,2,',','.') + ' &euro;';
	//caja.innerHTML = numero.formato(2, true);
	var id_productos_array = new Array();
	id_productos_array = id_productos.split(',');
	var precio_acumulado = 0.00;
	for (var i=0;i<id_productos_array.length;i++){
		precio_acumulado += parseFloat(document.getElementById('contenedor_precio_total_producto_carrito_' + id_productos_array[i]).innerHTML.replace(',','.'));
	}
	var precio_total = precio_acumulado;
	var precio_sin_iva = precio_total/1.18;
	var iva = precio_total - precio_total/1.18
	//document.getElementById('total_sin_iva').innerHTML = number_format(precio_sin_iva,2,',','.') + " &euro;";
	//document.getElementById('iva').innerHTML = number_format(iva,2,',','.') + " &euro;";
	document.getElementById('total_con_iva').innerHTML = number_format(precio_total,2,',','.') + " &euro;";
}

function lanzaFormularioDireccion(tipo_direccion)	{
		//e.preventDefault();
		
		$.modal('<div><h3>Cambio de direcci&oacute;n de ' + tipo_direccion + '</h3><p>Cambie los datos de la direcci&oacute;n.</p><form action="includes/cambia-direccion-usuario.php" id="formCambioDireccion" name="formCambioDireccion" class="lightboxForm" method="post"><input type="hidden" name="cod_direccion_usuario" id="cod_direccion_usuario"><label>Direcci&oacute;n: <input type="text" id="direccion" name="direccion" /></label><label>Cod. Postal: <input type="text" id="cod_postal" name="cod_postal" /></label><label>Localidad: <input type="text" id="localidad" name="localidad" /></label><label>Pais: <span id="paises"></span></label><label>Provincia (s&oacute;lo Espa&ntilde;a): <span id="provincias"></span></label><label>Tel&eacute;fono: <input type="text" id="telefono" name="telefono" /></label><label>M&oacute;vil: <input type="text" id="movil" name="movil" /></label><input type="submit" id="enviar" name="enviar" value="Enviar" /></form></div>',
		{ 
			position: ["5%"],
			minWidth : '450',
			maxWidth : '450',
			minHeight : '380',
			overlayClose : 'true'
		});
		
		muestraPaises('paises','cod_pais');
		muestraProvincias('provincias','cod_provincia');
		setTimeout('rellenaDatosFormularioDireccion("' + tipo_direccion + '")',1500);
		
		$("#formCambioDireccion").validate({
			rules: {
				direccion: "required",
				cod_postal: {
					required: true,
					digits: true
				},
				localidad: "required",
				cod_provincia: {
				  required: function(element) {
       				 return $("#cod_pais").val() == 73;
     			  }
				},
				cod_pais: "required",
				telefono: "required"
				},
			messages: {
				direccion: "Por&nbsp;favor&nbsp;introduzca&nbsp;su&nbsp;direcci&oacute;n",
				cod_postal: {
					required: "Por&nbsp;favor&nbsp;introduzca&nbsp;su&nbsp;c&oacute;digo&nbsp;postal",
					digits: "Por&nbsp;favor&nbsp;introduzca&nbsp;un&nbsp;c&oacute;digo&nbsp;postal&nbsp;v&aacute;lido"
				},
				localidad: "Por&nbsp;favor&nbsp;introduzca&nbsp;su&nbsp;ciudad",
				cod_pais: "Por&nbsp;favor&nbsp;seleccione&nbsp;el&nbsp;pais",
				cod_provincia: "Por&nbsp;favor&nbsp;seleccione&nbsp;la&nbsp;provincia",
				telefono: "Por&nbsp;favor&nbsp;introduzca&nbsp;su&nbsp;tel&eacute;fono"
			}
		});
		
		return false;
}

function muestraPaises(elemento,nombre_select) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/muestra-paises.php?nombre_select=" + nombre_select, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
				document.getElementById(elemento).innerHTML = oXmlHttp.responseText
			} else {
				//alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function muestraProvincias(elemento,nombre_select) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/muestra-provincias.php?nombre_select=" + nombre_select, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
				document.getElementById(elemento).innerHTML = oXmlHttp.responseText
			} else {
				//alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function rellenaDatosFormularioDireccion(tipo_direccion) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/rellena-datos-formulario-direccion.php?tipo_direccion=" + tipo_direccion, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
				var datos = oXmlHttp.responseText.split('$%$');
				document.getElementById('cod_direccion_usuario').value = datos[0];
				document.getElementById('direccion').value = datos[1];
				document.getElementById('cod_postal').value = datos[2];
				document.getElementById('localidad').value = datos[3];
				document.getElementById('cod_pais').value = datos[4];
				document.getElementById('cod_provincia').value = datos[5];
				document.getElementById('telefono').value = datos[6];
				document.getElementById('movil').value = datos[7];
			} else {
				//alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function cambiaCantidadProducto(codigo,cantidad) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/cambia-cantidad-producto.php?codigo=" + codigo + "&cantidad=" + cantidad, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
			} else {
				alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function insertaComentarioPedido(cod_pedido,comentario) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/inserta-comentario-pedido.php?cod_pedido=" + cod_pedido + "&comentario=" + document.getElementById(comentario).value, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
			} else {
				alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function cambiaCondicionesGenerales(cod_pedido,condicion) {
	var acepta_condiciones_generales
	if (condicion){
		acepta_condiciones_generales = 'Si';
	} else {
		acepta_condiciones_generales = 'No';
	}
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/cambia-condiciones-generales.php?cod_pedido=" + cod_pedido + "&acepta_condiciones_generales=" + acepta_condiciones_generales, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
			} else {
				alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function cambiaGastosEnvio(cod_pedido,cod_tipo_tarifa) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/cambia-gastos-envio.php?cod_pedido=" + cod_pedido + "&cod_tipo_tarifa=" + cod_tipo_tarifa, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
			} else {
				alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function compruebaCondicionesGenerales() {
	if (document.getElementById('condiciones_generales_venta').checked) {
		return true;
	} else {
		alert("Debe aceptar las condiciones generales de compra para poder continuar");
		return false;
	}
}

function compruebaCodigoCupon(codigo_cupon,cod_pedido) {
	var oXmlHttp = zXmlHttp.createRequest();
	oXmlHttp.open("get", "includes/ajax/comprueba-codigo-cupon.php?codigo_cupon=" + codigo_cupon + "&cod_pedido=" + cod_pedido, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			if (oXmlHttp.status == 200) {
				//alert(oXmlHttp.responseText);
				if (oXmlHttp.responseText == 'no') {
					alert('Verifique el codigo introducido. No es correcto');
					document.getElementById('codigo_cupon').focus();
				}
			} else {
				alert(oXmlHttp.statusText);
			}
		}            
	};
	oXmlHttp.send(null);
}

function imprimePedido(cod_pedido,cod_forma_pago) {
	popUpWindow1('includes/imprime-pedido.php?cod_pedido=' + cod_pedido + '&cod_forma_pago=' + cod_forma_pago,0,0,500,400,0);
}

function popUpWindow1(URLStr, left, top, width, height,IsResizable)
{ 
	/*x = document.getElementById(extraParam);
		myString = x.src;
		splitString = myString.split("/");
		imagename=splitString[6];
		newsplitString = imagename.split(".");
		
		myRegExp = newsplitString[0] ;
		newmyRegExp = newsplitString[0]+"_big" ;
		newString = myString.replace(myRegExp,newmyRegExp);
		URLStr=URLStr+"&image_big_path="+newString;
		
	  	if(popUpWin)
	  	{
	    	if(!popUpWin.closed) popUpWin.close();
	  	}
	  
	 		popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');*/
		
		 /*if(popUpWin)
		 {
		    if(!popUpWin.closed) popUpWin.close();
		 }*/

			day = new Date();
			id = day.getTime();
			
			if (!width) width = 700;
			if (!height) height = 500;
	
			if (isNaN(parseInt(width))) width = 700;
			if (isNaN(parseInt(height))) height = 500;	
		
			width	 = parseInt(width);
			height = parseInt(height);
			
		
			LeftTemp = screen.width - width;
			left = (screen.width - width) / 2;
			TopTemp = screen.height - height;	
			top = (screen.height - height) / 2;
			
popUpWin =  open(URLStr, id, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable='+IsResizable+',copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'')
}

