<?php if (preg_match('/[0-9]/', $code)) { ?>
<?php

$cpf = isset($custom_field['cpf']) ? $custom_field['cpf'] : '';
$data_nascimento = isset($custom_field['nascimento']) ? $custom_field['nascimento'] : '';

if ($data_nascimento != '') {
	$data_nascimento = date('d/m/Y', strtotime($data_nascimento));
}

$cartao_num = '';
$cartao_mes = '';
$cartao_ano = '';
$cartao_cvv = '';
$cartao_nome = trim(trim($firstname) .' '. trim($lastname));

$cartao_teste = 1;

switch ($cartao_teste) {
case 1:
	// visa
	$cartao_num = '4024007180455619';
	$cartao_mes = '12';
	$cartao_ano = '2018';
	$cartao_cvv = '737';
	$cartao_nome = 'Blahh Blehhh';
	break;
case 2:
	// master
	$cartao_num = '5136502827536518';
	$cartao_mes = '10';
	$cartao_ano = '2018';
	$cartao_cvv = '193';
	$cartao_nome = 'Blahh Blehhh';
	break;
case 3:
	// amex
	$cartao_num = '341231847003158';
	$cartao_mes = '01';
	$cartao_ano = '2019';
	$cartao_cvv = '513';
	$cartao_nome = 'Blahh Blehhh';
	break;
}

?>
<style type="text/css">
#warning, #success, #form { display:none; }

#bandeiras { text-align:center; }
#bandeiras a { display:inline-block; opacity:0.5; cursor:pointer; border-radius:2px; overflow:hidden; }
#bandeiras a:hover { opacity:1; }

#tool-tip-cvc{position:relative; cursor:pointer;}
#tool-tip-cvc #tool-tip-content{display:none; position:absolute; top:-18px; left:22px; width:100px; z-index:2;}
#tool-tip-cvc #tool-tip-content:before{content:''; position:absolute; width:0; height:0; top:50%; left:-5px; margin-top:-7px; border-style:solid; border-width:5px 5px 5px 0; border-color:transparent #000 transparent transparent;}
#tool-tip-cvc #tool-tip-content img{width:100%;}
#tool-tip-cvc:focus #tool-tip-content,
#tool-tip-cvc:hover #tool-tip-content{display:block;}
</style>

<div id="warning" class="alert alert-danger"></div>
<div id="success" class="alert alert-success"></div>

<div id="bandeiras">
	<strong>Selecione a bandeira do seu cartão de crédito:</strong><br>
	<br>

	<div style="display:inline-block;">
		<a id="Visa"><img src="image/moip/cartaoCredito/5.jpg" alt="Visa" title="Visa"></a>
		<a id="Mastercard"><img src="image/moip/cartaoCredito/4.jpg" alt="Mastercard" title="Mastercard"></a>
		<a id="AmericanExpress"><img src="image/moip/cartaoCredito/1.jpg" alt="American Express" title="American Express"></a>
		<a id="Diners"><img src="image/moip/cartaoCredito/2.jpg" alt="Diners" title="Diners"></a>
		<a id="Hipercard"><img src="image/moip/cartaoCredito/3.jpg" alt="Hipercard" title="Hipercard"></a>
	</div>
</div>

<div id="form" class="row">

	<div class="col-xs-12">
		<br>
		<strong>Por favor, confirme ou preencha as informações abaixo para finalizar sua compra.</strong>
		<br>&nbsp;
	</div>

	<input class="form-control" type="hidden" id="creditCardBrand" name="creditCardBrand">

	<div class="col-xs-12 col-sm-8 col-md-3 col-lg-4">
		<div class="row form-group">
			<label class="col-xs-12" for="cardNumber">Número do cartão:</label>
			<div class="col-xs-12">
				<input type="tel" name="cardNumber" id="cardNumber" size="19" placeholder="0000000000000000" value="<?php echo $cartao_num; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-4 col-sm-4 col-md-2 col-lg-1">
		<div class="row form-group">
			<!-- aqui colocar um tooltip com uma imagem mostrando onde fica o CVV de um cartão de crédito -->
			<label class="col-xs-12" for="cvv" id="label-cvc">CVV: <span id="tool-tip-cvc"><i class="fa fa-question-circle"></i><span id="tool-tip-content"><img src="image/cartao-cvc.png"></span></span></label>
			<div class="col-xs-12">
				<input type="tel" name="cvv" id="cvv" placeholder="000" size="4" maxlength="5" value="<?php echo $cartao_cvv; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-8 col-sm-4 col-md-3 col-lg-2">
		<div class="row form-group">
			<label class="col-xs-12" for="cardExpirationMonth">Validade do cartão:</label>
			<div class="col-xs-12">
				<div class="input-group" style="width: 100%; z-index: 1;">
					<input type="tel" id="cardExpirationMonth" name="expirationMonth" placeholder="MM" size="2" value="<?php echo $cartao_mes; ?>" class="form-control" style="width: 50%;">
					<input type="tel" id="cardExpirationYear" name="expirationYear" placeholder="AA" size="2" value="<?php echo $cartao_ano; ?>" class="form-control" style="width: 50%; margin-left: -1px;">
				</div>
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-8 col-md-4 col-lg-5">
		<div class="row form-group">
			<label class="col-xs-12" for="creditCardHolderName">Nome impresso no cartão:</label>
			<div class="col-xs-12">
				<input type="text" name="creditCardHolderName" id="creditCardHolderName" size="20" maxlength="50" value="<?php echo $cartao_nome; ?>" class="form-control">
			</div>
		</div>
	</div>

	<div class="col-xs-12 col-sm-6 col-md-4">
		<div class="row form-group">
			<label class="col-xs-12" for="installmentQuantity">Parcelamento</label>
			<div class="col-xs-12">
				<select name="installmentQuantity" id="installmentQuantity" class="form-control"></select>
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-6 col-md-8">
		<div class="row form-group">
			<label class="col-xs-12" for="installmentTotal">Total</label>
			<div class="col-xs-12">
				<p id="installmentTotal" class="form-control-static" style="padding: 7px 10px; font-weight: bold;"></p>
			</div>
		</div>
	</div>

	<div class="col-xs-12">
		<strong>Informações do titular do cartão:</strong>
		<br>&nbsp;
	</div>

	<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
		<div class="row form-group">
			<label class="col-xs-12" for="creditCardHolderCPF">CPF:</label>
			<div class="col-xs-12">
				<input type="tel" name="creditCardHolderCPF" id="creditCardHolderCPF" value="<?php echo $cpf; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
		<div class="row form-group">
			<label class="col-xs-12" for="creditCardHolderBirthDate">Data de Nascimento:</label>
			<div class="col-xs-12">
				<input type="tel" name="creditCardHolderBirthDate" id="creditCardHolderBirthDate" value="<?php echo $data_nascimento; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
		<div class="row form-group">
			<label class="col-xs-12" for="creditCardHolderPhone">Telefone:</label>
			<div class="col-xs-12">
				<input type="tel" name="creditCardHolderPhone" id="creditCardHolderPhone" value="<?php echo $telephone; ?>" class="form-control">
			</div>
		</div>
	</div>

</div>

<div class="buttons">
	<div class="pull-right">
		<div id="MoipWidget" data-token="<?php echo $code; ?>" callback-method-success="funcaoSucesso" callback-method-error="funcaoFalha"></div>
		<a id="button-confirm" class="btn btn-primary" style="cursor:pointer">Confirmar pedido</a>
	</div>
</div>

<script type="text/javascript" src="catalog/view/javascript/jquery.maskedinput.min.js?v20180205"></script>

<script type="text/javascript"><!--
var $buttonConfirm = $('#button-confirm');

var $bandeiras           = $("#bandeiras");
var $cardNumber          = $("#cardNumber");
var $cvv                 = $("#cvv");
var $cardExpirationMonth = $("#cardExpirationMonth");
var $cardExpirationYear  = $("#cardExpirationYear");
var $creditCardBrand     = $("#creditCardBrand");
var $installmentQuantity = $("#installmentQuantity");
var $installmentTotal    = $("#installmentTotal");

var $creditCardHolderName      = $("#creditCardHolderName");
var $creditCardHolderCPF       = $("#creditCardHolderCPF");
var $creditCardHolderBirthDate = $("#creditCardHolderBirthDate");
var $creditCardHolderPhone     = $("#creditCardHolderPhone");

(function($){

	// mascaras
	$cvv.unmask().mask("999");
	$cardExpirationMonth.unmask().mask("99");
	$cardExpirationYear.unmask().mask("99");
	$creditCardHolderCPF.unmask().mask("999.999.999-99");
	$creditCardHolderBirthDate.unmask().mask("99/99/9999");

	$creditCardHolderPhone.unmask().mask("(99) 9999-9999?9").bind('keyup', function(e){
		if (e.type == 'keyup' && $.inArray(parseInt(e.which), [9, 16, 17, 18, 35, 36, 37, 38, 39, 40]) > -1){ return true; }
		var length = this.value.replace(/[^0-9]/g, '').length;
		if (e.type == 'keyup' && length < 10) { return true; }
		$(this).unmask().mask(length > 10 ? '(99) 99999-999?9' : '(99) 9999-9999?9');
	}).trigger('keyup');

	// auto focus
	$cvv.bind('keyup', function(e){
		if (e.type == 'keyup' && $.inArray(parseInt(e.which), [8, 9, 16, 17, 18, 35, 36, 37, 38, 39, 40, 46]) > -1){ return true; }
		// soma 1 para não dar problema na máscara em dispositivos android
		if (this.value.replace(/\D/g, '').length+1 == +this.getAttribute('maxlength')) {
			$cardExpirationMonth.focus();
		}
	});
	$cardExpirationMonth.bind('keyup', function(e){
		if (e.type == 'keyup' && $.inArray(parseInt(e.which), [8, 9, 16, 17, 18, 35, 36, 37, 38, 39, 40, 46]) > -1){ return true; }
		if (this.value.replace(/\D/g, '').length == 2) {
			$cardExpirationYear.focus();
		}
	});
	$cardExpirationYear.bind('keyup', function(e){
		if (e.type == 'keyup' && $.inArray(parseInt(e.which), [8, 9, 16, 17, 18, 35, 36, 37, 38, 39, 40, 46]) > -1){ return true; }
		if (this.value.replace(/\D/g, '').length == 2) {
			$creditCardHolderName.focus();
		}
	});


	$buttonConfirm.on('click', function() {
		$('#warning').hide().html('');

		var data = {
			"Forma"       : "CartaoCredito",
			"Instituicao" : $creditCardBrand.val(),
			"Parcelas"    : $installmentQuantity.val(),
			"CartaoCredito": {
				"Numero"          : $cardNumber.val(),
				"Expiracao"       : $cardExpirationMonth.val() +'/'+ $cardExpirationYear.val(),
				"CodigoSeguranca" : $cvv.val(),
				"Portador": {
					"Nome"           : $creditCardHolderName.val(),
					"DataNascimento" : $creditCardHolderBirthDate.val(),
					"Telefone"       : $creditCardHolderPhone.val(),
					"Identidade"     : $creditCardHolderCPF.val()
				}
			}
		}

		MoipWidget(data);
	});

	// Atualiza valor do parcelamento
	$installmentQuantity.on('change keyup', function () {
		var option = this.options[this.selectedIndex];
		if (option) {
			$installmentTotal.html(formatMoney(option.getAttribute('data-total')));
		}
	});

	$bandeiras.find('a').click(function(){
		var cardBrand = this.getAttribute('id');

		var settings = {cofre: "", instituicao: cardBrand, callback: "retornoCalculoParcelamento"};
		MoipUtil.calcularParcela(settings);

		$bandeiras.find('a').css('opacity', '0.5');
		$(this).css('opacity', '1');

		$('#form').stop(true,true).slideUp();

		if (cardBrand == 'AmericanExpress') {
			$cvv.attr('maxlength', '5');
			$cvv.attr('placeholder', '0000');
			$cvv.unmask().mask('999?9');
		} else {
			$cvv.attr('maxlength', '4');
			$cvv.attr('placeholder', '000');
			$cvv.unmask().mask('999');
		}

		$creditCardBrand.val(cardBrand);
		// $cardNumber.val('');
		// $cardExpirationMonth.val('');
		// $cardExpirationYear.val('');
		// $cvv.val('');

		$('#form').slideDown();
	});

})(jQuery);
//-->
</script>
<script type="text/javascript"><!--
var funcaoSucesso = function(data){
	$.ajax({
		type: 'GET',
		url: 'index.php?route=payment/moip_cartao/confirm',
		cache: false,
		success: function() {
			location.href = '<?php echo $continue; ?>';
		}
	});
};

var funcaoFalha = function(data) {
	if (data.Codigo) {
		$('#warning').html(data.Mensagem).show();
	} else {
		var html = '';

		html += '<ul>';
		for (var i=0; i<data.length; i++) {
			html += '<li>' + data[i].Mensagem + '</li>';
		}
		html += '</ul>';

		$('#warning').html(html).show();
	}
};

var retornoCalculoParcelamento = function(data) {
	if (data.codigoErro) {
		$('#warning').html(data.message).show();
	} else {
		$installmentQuantity.html('');

		for (var i=0; i<data.parcelas.length; i++) {
			var p = data.parcelas[i];

			var qtd = p.quantidade;
			var valor = (+p.valor).toMoney(2, '.', '');
			var total = (+p.valor_total).toMoney(2, '.', '');

			var label = (qtd == 1) ? formatMoney(valor)+' à vista' : qtd+'x de '+formatMoney(valor);

			$installmentQuantity.append('<option value="' + qtd + '" data-total="' + total + '">' + label + '</option>');
		}

		$installmentQuantity.trigger('change');
	}
};

var formatMoney = function (valor) {
	var valorAsNumber = Number(valor);
	return 'R$ ' + valorAsNumber.toMoney(2, ',', '.');
};

Number.prototype.toMoney = function (decimals, decimal_sep, thousands_sep) {
	var n = this,
		c = isNaN(decimals) ? 2 : Math.abs(decimals),
		d = decimal_sep || '.',
		t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
		sign = (n < 0) ? '-' : '',
		i = parseInt(n = Math.abs(n).toFixed(c)) + '',
		j = ((j = i.length) > 3) ? j % 3 : 0;
	return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
};
//-->
</script>

<?php } else { ?>
	<div class="alert alert-danger"><?php echo $code ?></div>
<?php } ?>
