<?php

$cartao_num = '';
$cartao_mes = '';
$cartao_ano = '';
$cartao_cvv = '';
$cartao_nome = '';

$cartao_teste = 0;

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;
}

?>

<?php /* ?><link rel="stylesheet" href="<?php echo $stylesheet; ?>"><?php */ ?>

<div class="row">

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

	<!-- Total do pedido -->
	<input type="hidden" name="totalValue" id="totalValue" value="<?php echo $total; ?>">
	<input type="hidden" name="creditCardToken" id="creditCardToken">
	<input type="hidden" name="creditCardBrand" id="creditCardBrand">
	<input type="hidden" name="installmentValue" id="installmentValue">

	<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: <span id="cardBrand"></span></label>
			<div class="col-xs-12">
				<input type="tel" name="cardNumber" id="cardNumber" size="19" maxlength="16" 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: 40%;">
					<input type="tel" id="cardExpirationYear" name="expirationYear" placeholder="AAAA" size="4" value="<?php echo $cartao_ano; ?>" class="form-control" style="width: 60%; 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 id="installmentsWrapper" class="col-xs-12">
		<div class="row">

			<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>
	</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 $telefone; ?>" class="form-control">
			</div>
		</div>
	</div>

	<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
		<div class="row form-group">
			<label class="col-xs-12" for="shippingAddressStreet">Endereço da fatura do cartão:</label>
			<div class="col-xs-12">
				<input type="text" name="shippingAddressStreet" id="shippingAddressStreet" size="20" value="<?php echo $endereco; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-2 col-md-2 col-lg-2">
		<div class="row form-group">
			<label class="col-xs-12" for="shippingAddressNumber">N&ordm;:</label>
			<div class="col-xs-12">
				<input type="tel" name="shippingAddressNumber" id="shippingAddressNumber" size="4" value="<?php echo $numero; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
		<div class="row form-group">
			<label class="col-xs-12" for="shippingAddressComplement">Complemento:</label>
			<div class="col-xs-12">
				<input type="text" name="shippingAddressComplement" id="shippingAddressComplement" size="10" value="<?php echo $complemento; ?>" class="form-control">
			</div>
		</div>
	</div>

	<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
		<div class="row form-group">
			<label class="col-xs-12" for="shippingAddressDistrict">Bairro:</label>
			<div class="col-xs-12">
				<input type="text" name="shippingAddressDistrict" id="shippingAddressDistrict" size="10" value="<?php echo $bairro; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
		<div class="row form-group">
			<label class="col-xs-12" for="shippingAddressCity">Cidade:</label>
			<div class="col-xs-12">
				<input type="text" name="shippingAddressCity" id="shippingAddressCity" size="20" value="<?php echo $cidade; ?>" class="form-control">
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-3 col-md-2 col-lg-2">
		<div class="row form-group">
			<label class="col-xs-12" for="shippingAddressState">UF:</label>
			<div class="col-xs-12">
				<select name="shippingAddressState" id="shippingAddressState" class="form-control">
					<option value="440" <?php echo $estado == '440' ? 'selected' : ''; ?>>AC</option>
					<option value="441" <?php echo $estado == '441' ? 'selected' : ''; ?>>AL</option>
					<option value="442" <?php echo $estado == '442' ? 'selected' : ''; ?>>AP</option>
					<option value="443" <?php echo $estado == '443' ? 'selected' : ''; ?>>AM</option>
					<option value="444" <?php echo $estado == '444' ? 'selected' : ''; ?>>BA</option>
					<option value="445" <?php echo $estado == '445' ? 'selected' : ''; ?>>CE</option>
					<option value="446" <?php echo $estado == '446' ? 'selected' : ''; ?>>DF</option>
					<option value="447" <?php echo $estado == '447' ? 'selected' : ''; ?>>ES</option>
					<option value="448" <?php echo $estado == '448' ? 'selected' : ''; ?>>GO</option>
					<option value="449" <?php echo $estado == '449' ? 'selected' : ''; ?>>MA</option>
					<option value="450" <?php echo $estado == '450' ? 'selected' : ''; ?>>MT</option>
					<option value="451" <?php echo $estado == '451' ? 'selected' : ''; ?>>MS</option>
					<option value="452" <?php echo $estado == '452' ? 'selected' : ''; ?>>MG</option>
					<option value="453" <?php echo $estado == '453' ? 'selected' : ''; ?>>PA</option>
					<option value="454" <?php echo $estado == '454' ? 'selected' : ''; ?>>PB</option>
					<option value="455" <?php echo $estado == '455' ? 'selected' : ''; ?>>PR</option>
					<option value="456" <?php echo $estado == '456' ? 'selected' : ''; ?>>PE</option>
					<option value="457" <?php echo $estado == '457' ? 'selected' : ''; ?>>PI</option>
					<option value="458" <?php echo $estado == '458' ? 'selected' : ''; ?>>RJ</option>
					<option value="459" <?php echo $estado == '459' ? 'selected' : ''; ?>>RN</option>
					<option value="460" <?php echo $estado == '460' ? 'selected' : ''; ?>>RS</option>
					<option value="461" <?php echo $estado == '461' ? 'selected' : ''; ?>>RO</option>
					<option value="462" <?php echo $estado == '462' ? 'selected' : ''; ?>>RR</option>
					<option value="463" <?php echo $estado == '463' ? 'selected' : ''; ?>>SC</option>
					<option value="464" <?php echo $estado == '464' ? 'selected' : ''; ?>>SP</option>
					<option value="465" <?php echo $estado == '465' ? 'selected' : ''; ?>>SE</option>
					<option value="466" <?php echo $estado == '466' ? 'selected' : ''; ?>>TO</option>
				</select>
			</div>
		</div>
	</div>
	<div class="col-xs-12 col-sm-4 col-md-2 col-lg-2">
		<div class="row form-group">
			<label class="col-xs-12" for="shippingAddressPostalCode">CEP:</label>
			<div class="col-xs-12">
				<input type="tel" name="shippingAddressPostalCode" id="shippingAddressPostalCode" size="8" value="<?php echo $cep; ?>" class="form-control">
			</div>
		</div>
	</div>

</div>

<div class="buttons">
	<div class="pull-right">
		<input type="button" value="Confirmar compra" id="button-confirm" class="btn btn-primary" data-loading-text="Por favor aguarde...">
	</div>
</div>

<style>
#installmentsWrapper{display:none;}
#cardBrand{display:inline-block; vertical-align:middle;}
#cardBrand img{height:17px;}
#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>

<script type="text/javascript" src="<?php echo $pagseguro_js; ?>"></script>
<script type="text/javascript" src="catalog/view/javascript/jquery.maskedinput.min.js?v20180205"></script>
<script type="text/javascript"><!--
(function($){

	var initInterval = setInterval(function(){
		if (typeof PagSeguroDirectPayment !== 'undefined') {
			init();
		}
	}, 100);

	function init() {
		clearInterval(initInterval);

		PagSeguroDirectPayment.setSessionId('<?php echo $pagseguro_session; ?>');

		<?php if ($cartao_teste > 0) { ?>
			$cardNumber.triggerHandler('blur');
		<?php } ?>
	}

	var $buttonConfirm = $('#button-confirm');

	var $cardNumber          = $("#cardNumber");
	var $cvv                 = $("#cvv");
	var $cardExpirationMonth = $("#cardExpirationMonth");
	var $cardExpirationYear  = $("#cardExpirationYear");
	var $cardBrand           = $("#cardBrand");
	var $creditCardBrand     = $("#creditCardBrand");
	var $creditCardToken     = $("#creditCardToken");
	var $installmentsWrapper = $("#installmentsWrapper");
	var $installmentQuantity = $("#installmentQuantity");
	var $installmentValue    = $("#installmentValue");
	var $installmentTotal    = $("#installmentTotal");

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

	var $shippingAddressStreet     = $("#shippingAddressStreet");
	var $shippingAddressNumber     = $("#shippingAddressNumber");
	var $shippingAddressComplement = $("#shippingAddressComplement");
	var $shippingAddressDistrict   = $("#shippingAddressDistrict");
	var $shippingAddressPostalCode = $("#shippingAddressPostalCode");
	var $shippingAddressCity       = $("#shippingAddressCity");
	var $shippingAddressState      = $("#shippingAddressState");

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

	$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 == 4) {
			$creditCardHolderName.focus();
		}
	});

	function PagseguroValidate() {
		var cardNumber                = $cardNumber.val();
		var cvv                       = $cvv.val();
		var cardExpirationMonth       = $cardExpirationMonth.val();
		var cardExpirationYear        = $cardExpirationYear.val();
		var creditCardBrand           = $creditCardBrand.val();
		var creditCardToken           = $creditCardToken.val();
		var creditCardHolderName      = $creditCardHolderName.val();
		var creditCardHolderCPF       = $creditCardHolderCPF.val();
		var creditCardHolderPhone     = $creditCardHolderPhone.val();
		var creditCardHolderBirthDate = $creditCardHolderBirthDate.val();
		var shippingAddressStreet     = $shippingAddressStreet.val();
		var shippingAddressNumber     = $shippingAddressNumber.val();
		var shippingAddressDistrict   = $shippingAddressDistrict.val();
		var shippingAddressCity       = $shippingAddressCity.val();
		var shippingAddressPostalCode = $shippingAddressPostalCode.val();

		cardNumber = cardNumber.replace(/[^0-9]g/, '');
		$cardNumber.val(cardNumber);
		if (cardNumber.length < 13 || cardNumber.length > 19) {
			alert('Por favor informe um número de cartão de crédito válido.');
			$cardNumber.focus();
			return false;
		}

		cvv = cvv.replace(/[^0-9]g/, '');
		$cvv.val(cvv);
		if (cvv.length < 3 || cvv.length > 4) {
			alert('Por favor informe um CVV válido, contendo 3 ou 4 dígitos.');
			$cvv.focus();
			return false;
		}

		cardExpirationMonth = +cardExpirationMonth;
		$cardExpirationMonth.val(('00' + cardExpirationMonth).slice(-2));
		if (cardExpirationMonth < 1 || cardExpirationMonth > 12) {
			alert('Por favor informe um mês de vencimento válido, de 01 a 12.');
			$cardExpirationMonth.focus();
			return false;
		}

		var anoAtual = <?php echo date('Y'); ?>;
		var mesAtual = <?php echo date('n'); ?>;

		cardExpirationYear = +cardExpirationYear;
		$cardExpirationYear.val(('0000' + cardExpirationYear).slice(-4));
		if (cardExpirationYear < anoAtual) {
			alert('Por favor informe um ano de vencimento válido.');
			$cardExpirationYear.val('').focus();
			return false;
		}

		if (cardExpirationYear == anoAtual && cardExpirationMonth < mesAtual) {
			alert('Por favor informe uma data de vencimento válida.');
			$cardExpirationYear.val('');
			$cardExpirationMonth.val('').focus();
			return false;
		}

		if (creditCardBrand == '') {
			alert('Não foi possível identificar a bandeira do seu cartão. Por gentileza, digite novamente o número do cartão.');
			$cardNumber.val('').focus();
			return false;
		}

		if (creditCardToken == '') {
			alert('Não foi possível iniciar o pagamento. Alguma informação do cartão está incorreta. Por gentileza, digite novamente as informações do seu cartão.');
			$cardExpirationMonth.val('');
			$cardExpirationYear.val('');
			$creditCardHolderName.val('');
			$cvv.val('');
			$cardNumber.val('').focus();
			return false;
		}

		creditCardHolderName = $.trim(creditCardHolderName);
		$creditCardHolderName.val(creditCardHolderName);
		if (creditCardHolderName.split(' ').length <= 1) {
			alert('Por favor informe o nome e sobrenome do titular do cartão.');
			$creditCardHolderName.focus();
			return false;
		}

		if (!(/^[0-9]{3}\.[0-9]{3}\.[0-9]{3}-[0-9]{2}$/).test(creditCardHolderCPF)) {
			alert('Por favor informe corretamente o CPF do titular do cartão.');
			$creditCardHolderCPF.focus();
			return false;
		}

		if (!(/^\([0-9]{2}\) [0-9]{4,5}-[0-9]{4}$/).test(creditCardHolderPhone)) {
			alert('Por favor informe corretamente o telefone do titular do cartão.');
			$creditCardHolderPhone.focus();
			return false;
		}

		if (!(/^((0[1-9]|[12][0-9]|3[01])\/(0[13578]|1[02])\/[12][0-9]{3})|((0[1-9]|[12][0-9]|30)\/(0[469]|11)\/[12][0-9]{3})|((0[1-9]|1[0-9]|2[0-8])\/02\/[12][0-9]([02468][1235679]|[13579][01345789]))|((0[1-9]|[12][0-9])\/02\/[12][0-9]([02468][048]|[13579][26]))$/).test(creditCardHolderBirthDate)) {
			alert('Por favor informe corretamente a data de nascimento do titular do cartão.');
			$creditCardHolderBirthDate.focus();
			return false;
		}

		if (shippingAddressStreet == '') {
			alert('Por favor informe corretamente o endereço de fatura do cartão.');
			$shippingAddressStreet.focus();
			return false;
		}

		if (shippingAddressNumber == '') {
			alert('Por favor informe corretamente o número do endereço de fatura do cartão.');
			$shippingAddressNumber.focus();
			return false;
		}

		if (shippingAddressDistrict == '') {
			alert('Por favor informe corretamente o bairro do endereço de fatura do cartão.');
			$shippingAddressDistrict.focus();
			return false;
		}

		if (shippingAddressCity == '') {
			alert('Por favor informe corretamente a cidade do endereço de fatura do cartão.');
			$shippingAddressCity.focus();
			return false;
		}

		if (!(/^[0-9]{5}-[0-9]{3}$/).test(shippingAddressPostalCode)) {
			alert('Por favor informe corretamente o CEP do endereço de fatura do cartão.');
			$shippingAddressPostalCode.focus();
			return false;
		}

		return true;
	}

	$buttonConfirm.bind('click', function (e) {
		e.preventDefault();

		if (PagseguroValidate()) {
			var params = '';
			params += 'creditCardToken='            + $creditCardToken.val();
			params += '&installmentQuantity='       + $installmentQuantity.val();
			params += '&installmentValue='          + $installmentValue.val();
			params += '&creditCardHolderName='      + $creditCardHolderName.val();
			params += '&creditCardHolderCPF='       + $creditCardHolderCPF.val();
			params += '&creditCardHolderBirthDate=' + $creditCardHolderBirthDate.val();
			params += '&creditCardHolderPhone='     + $creditCardHolderPhone.val();
			params += '&shippingAddressStreet='     + $shippingAddressStreet.val();
			params += '&shippingAddressNumber='     + $shippingAddressNumber.val();
			params += '&shippingAddressComplement=' + $shippingAddressComplement.val();
			params += '&shippingAddressDistrict='   + $shippingAddressDistrict.val();
			params += '&shippingAddressPostalCode=' + $shippingAddressPostalCode.val();
			params += '&shippingAddressCity='       + $shippingAddressCity.val();
			params += '&shippingAddressState='      + $shippingAddressState.val();
			params += '&senderHash='                + PagSeguroDirectPayment.getSenderHash();

			$buttonConfirm.button('loading');

			$.ajax({
				type: 'POST',
				url: 'index.php?route=payment/pagseguro_credit_card/payment',
				dataType: 'json',
				data: encodeURI(params),
				success: function (response) {
					// console.log('success');
					// console.log(response);
					if (response['success']) {
						location.href = '<?php echo HTTP_SERVER; ?>index.php?route=payment/pagseguro_boleto/confirm';
						return true;
					}

					alert('Ops, ocorreu um erro. Por favor atualize seu cadastro incluindo seu nome completo, CPF, telefone com DDD e endereço completo. Depois tente finalizar o pedido novamente.');
					location.href = '<?php echo HTTP_SERVER; ?>index.php?route=account/edit';
				},
				error: function (response) {
					// console.log('error');
					alert('Ops, ocorreu um erro. Por favor tente novamente. Caso este erro continue aparecendo entre em contato conosco.');
					location.reload(true);
				},
				complete: function (response) {
					// console.log('complete');
					$buttonConfirm.button('reset');
				}
			});
		}
	});

	// Pega bandeira e parcelamento
	var last_cardnumber = '';
	$cardNumber.bind('blur keyup', function(){
		var cardnumber = ('' + this.value).replace(/ /gi, '');
		if (cardnumber == last_cardnumber) { return; }
		last_cardnumber = cardnumber;

		// Obtendo apenas os 6 primeiros dígitos (bin)
		var bin = cardnumber.substring(0, 6);

		// Atualizar Brand
		updateCardBrand(bin);
	});

	var updateCardBrand = function (bin) {
		$cardBrand.html('');
		$creditCardBrand.val('');

		// Atualizar Brand apenas se tiver 6 ou mais dígitos preenchidos
		if (String(bin).length >= 6) {
			PagSeguroDirectPayment.getBrand({
				cardBin: bin,
				success: function (response) {
					// console.log('success');
					// console.log(response);
					var brand = response.brand.name;
					var cvvSize = response.brand.cvvSize;

					$cardBrand.html("<img src='https://stc.pagseguro.uol.com.br/public/img/payment-methods-flags/68x30/" + brand + ".png'>");
					$creditCardBrand.val(brand);

					// soma 1 para não dar problema na máscara em dispositivos android
					$cvv.attr("maxlength", cvvSize+1).unmask().mask((cvvSize == '3') ? '999' : '999?9');

					updateInstallments(brand);
				},
				error: function (response) {
					console.log(response);
					alert('Ops, não foi possível detectar a bandeira do seu cartão. Por favor, confira e digite novamente o número do seu cartão.');
					$cardNumber.val('').focus();
					last_cardnumber = '';
				},
				complete: function (response) {
					// console.log('complete');
				}
			});
		}
	};

	// Atualiza dados de parcelamento atráves da bandeira do cartão
	var updateInstallments = function (brand) {
		$installmentsWrapper.hide();

		if (brand != '') {
			PagSeguroDirectPayment.getInstallments({
				amount: <?php echo number_format($total, 2, '.', ''); ?>,
				brand: brand,
				success: function (response) {
					// console.log('success');
					// console.log(response);
					// Para obter o array de parcelamento use a bandeira como "chave" da lista "installments"
					var installments = response.installments[brand];

					var options = '';
					for (var i in installments) {
						var p = installments[i];

						var quantity = p.quantity;
						var parcela  = (+p.installmentAmount).toMoney(2, '.', '');
						var total    = (+p.totalAmount).toMoney(2, '.', '');
						var semJuros = p.interestFree ? 1 : 0;

						var label = quantity + 'x ' + formatMoney(parcela);
						if (quantity > 1) {
							label += (semJuros ? ' sem ' : ' com ') + 'juros';
						}

						options += ('<option value="' + quantity + '" data-parcela="' + parcela + '" data-total="' + total + '" data-sem-juros="' + semJuros + '">' + label + '</option>');
					}

					// Atualizando dados do select de parcelamento
					$installmentQuantity.html(options).trigger('change');

					// Exibindo select do parcelamento
					$installmentsWrapper.show();

					<?php if ($cartao_teste > 0) { ?>
						$cardNumber.triggerHandler('change');
					<?php } ?>
				},
				error: function (response) {
					// console.log('error');
					alert('Ops, não foi possível obter os valores de parcelamento. Por favor, confira e digite novamente o número do seu cartão.');
					$cardNumber.val('').focus();
					last_cardnumber = '';
				},
				complete: function (response) {
					// console.log('complete');
				}
			});
		}
	};

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

	// Gera o token do cartão
	$('#cardNumber, #cvv, #cardExpirationMonth, #cardExpirationYear').bind('change', function(){
		var cardNumber          = ($cardNumber.val() + '').replace(/[^0-9]g/, '');
		var cvv                 = ($cvv.val() + '').replace(/[^0-9]g/, '');
		var cardExpirationMonth = ($cardExpirationMonth.val() + '').replace(/[^0-9]g/, '');
		var cardExpirationYear  = ($cardExpirationYear.val() + '').replace(/[^0-9]g/, '');
		var creditCardBrand     = $.trim($creditCardBrand.val() + '');

		if (cardNumber.length > 6 && cvv.length >= 3 && cardExpirationMonth.length == 2 && cardExpirationYear.length == 4 && creditCardBrand != '') {
			PagSeguroDirectPayment.createCardToken({
				cardNumber      : cardNumber,
				cvv             : cvv,
				expirationMonth : cardExpirationMonth,
				expirationYear  : cardExpirationYear,
				brand           : creditCardBrand,
				success: function (response) {
					// console.log('success');
					// console.log(response);
					$creditCardToken.val(response.card.token);
				},
				error: function (response) {
					// console.log('error');
					// console.log(response);
					alert('Ops, houve algum erro nas informações do cartão. Por favor, digite cuidadosamente os dados do seu cartão.');
					$cardNumber.val('').focus();
					$cvv.val('');
					$cardExpirationMonth.val('');
					$cardExpirationYear.val('');
					$creditCardBrand.val('');
					$installmentsWrapper.hide();
					last_cardnumber = '';
				},
				complete: function (response) {
					// console.log('complete');
				}
			});
		}
	});

	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) : '');
	};

})(jQuery);
//--></script>
