$(function () {
	$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) { event.preventDefault(); $(this).ekkoLightbox(); });
	$('.cpc').TouchSpin({
		min: 1,
		max: 100000
	});
	$('.cpm').TouchSpin({
		min: 1,
		max: 100000,
		postfix: ' x 1000'
	});

	$( ".qty" ).change(function() {
		var id = $(this).data('id');
		var price = $(this).data('price');
		var qty = $(this).val();
		if (!isNumber(qty)) return;
		$("#price_" + id).html((qty * price).toFixed(2));
	});


	$( ".buy_now" ).click(function() {
		var id = $(this).data('id');
		var qty = 1;
		if ($('#qty_' + id).length){
			qty = $('#qty_' + id).val();
		}
		var method = $('#payment_method_' + id).val();
		var t = $(this);
		$.post ("index.php?spots&buy&" + id + "&" + qty + "&" + method, function( data ) {
			t.prop("disabled",true).addClass("disabled");

			if (method == 'paypal'){
				if (data.lastIndexOf('http', 0) === 0) {
					window.location.replace(data);
				} else {
					$('#alert').toggleClass('hide').html(data);
				}
			} else if (method == 'stripe'){
				var jData = $.parseJSON(data);

				if (jData.error != ''){
					$('#alert').toggleClass('hide').html(jData.error);
					return;
				}

				var handler = StripeCheckout.configure({
					key: jData.publishable_key,
					//image: jData.image,
					token: function(token) {

						if (token != null){
							if (token.id != ''){
								window.location.replace("index.php?spots&return&buy&" + id + "&" + qty + "&" + token.id + "&" + encodeURI(token.email) + "&" + "stripe");
							}
						}

					}
				});
				handler.open({
					name: jData.sitename,
					description: jData.description,
					amount: jData.amount
				});

			} else {
				var d = new Date();
				var token = d.getTime();
				window.location.replace("index.php?spots&return&buy&" + id + "&" + qty + "&" + token + "&" + "0" + "&" + "nopayment");
			}

		});
		return false;
	});

	function isNumber(n) {
		return !isNaN(parseFloat(n)) && isFinite(n);
	}
});