<!--
/**
* NOTA SOBRE LA LICENCIA DE USO DEL SOFTWARE
* 
* El uso de este software está sujeto a las Condiciones de uso de software que
* se incluyen en el paquete en el documento "Aviso Legal.pdf". También puede
* obtener una copia en la siguiente url:
* http://www.redsys.es/wps/portal/redsys/publica/areadeserviciosweb/descargaDeDocumentacionYEjecutables
* 
* Redsys es titular de todos los derechos de propiedad intelectual e industrial
* del software.
* 
* Quedan expresamente prohibidas la reproducción, la distribución y la
* comunicación pública, incluida su modalidad de puesta a disposición con fines
* distintos a los descritos en las Condiciones de uso.
* 
* Redsys se reserva la posibilidad de ejercer las acciones legales que le
* correspondan para hacer valer sus derechos frente a cualquier infracción de
* los derechos de propiedad intelectual y/o industrial.
* 
* Redsys Servicios de Procesamiento, S.L., CIF B85955367
*/
-->
<html>

<head>
	<meta charset="UTF-8">
	<script src="<?php echo $this->getRedsysJS() ?>"></script>
	<link rel="stylesheet" type="text/css" href="<?php echo $block->getViewFileURL("Redsys_Redsys::css/estilos.css") ?>" />
	<!-- <style>
	[aria-]
	</style> -->
</head>

<body>
	<input type="radio" name="redsys_payment" value="ref" style="<?php echo $this->getDisplayRadios() ?>" checked>
	<h4 style="display: inline; <?php echo $this->getDisplayRadios() ?>"><?php echo $this->getReferenceTitle() ?></h4> <?php echo ($this->getShowCardBrandLogo() ?  '<img src="' . $block->getViewFileURL("Redsys_Redsys::images/brands/" . $this->getCardBrandLogo()) . '" style="display: inline;"/>' : "") ?>
	<button id="redsysRefButton" onclick="redsysReferencePayment()" style="font-size: 18px;padding: 9px 20px;border: none;box-shadow: 0px 2px 7px #CCC;margin: 0 auto;width: 220px;text-align: center;border-radius: 8px;height: 39px;padding-top: 9px;padding-bottom: 9px;color: white; <?php echo $this->getBtnStyle() ?>; display: none;"><?php echo $this->getBtnText() ?></button>
	<br>
	<input type="radio" name="redsys_payment" value="new" style="<?php echo $this->getDisplayRadios() ?>">
	<h4 style="display: inline; <?php echo $this->getDisplayRadios() ?>">Usar otra tarjeta</h4><br>
	<div class="col-md-8" id="redsysForm" style="display: none;">
		<div id="insite-form-container" class="form-container">
		</div>
		<div style="width: auto; max-width: 350px; margin: 0 auto;<?php echo $this->getAllowReference() ? '' : ' display: none; '; ?>">
			<input type="checkbox" id="check-guardar" name="check-guardar" />
			<label for="check-guardar">Guardar tarjeta para futuras compras</label>
		</div>
	</div>

	<input type="hidden" id="token"></input>
	<input type="hidden" id="errorCode"></input>
	<script>
		<!-- Petición de carga de iframes con estilos para el input-->
		getInSiteForm(
			'insite-form-container',
			'<?php echo $this->getBtnStyle() ?>',
			'<?php echo $this->getBodyStlye() ?>',
			'<?php echo $this->getFormStyle() ?>',
			'<?php echo $this->getFormTextStyle() ?>',
			'<?php echo $this->getBtnText() ?>',
			'<?php echo $this->getMerchantCode() ?>',
			'<?php echo $this->getMerchantTerminal() ?>',
			'<?php echo $this->getNumPed() ?>'
		);

		function cargaValoresBrowser3DS() {

			var valores3DS = new Object();

			//browserJavaEnabled
			valores3DS.browserJavaEnabled = navigator.javaEnabled();

			//browserJavascriptEnabled
			valores3DS.browserJavascriptEnabled = true;

			//browserLanguage
			var userLang = navigator.language || navigator.userLanguage;
			valores3DS.browserLanguage = userLang;

			//browserColorDepth
			valores3DS.browserColorDepth = screen.colorDepth;

			//browserScreenHeight
			//browserScreenWidth
			var myWidth = 0,
				myHeight = 0;
			if (typeof window.innerWidth == "number") {
				//Non-IE
				myWidth = window.innerWidth;
				myHeight = window.innerHeight;
			} else if (
				document.documentElement &&
				(document.documentElement.clientWidth ||
				document.documentElement.clientHeight)
			) {
				//IE 6+ in 'standards compliant mode'
				myWidth = document.documentElement.clientWidth;
				myHeight = document.documentElement.clientHeight;
			} else if (
				document.body &&
				(document.body.clientWidth || document.body.clientHeight)
			) {
				//IE 4 compatible
				myWidth = document.body.clientWidth;
				myHeight = document.body.clientHeight;
			}
			valores3DS.browserScreenHeight = myHeight;
			valores3DS.browserScreenWidth = myWidth;

			//browserTZ
			var d = new Date();
			valores3DS.browserTZ = d.getTimezoneOffset();

			//browserUserAgent
			valores3DS.browserUserAgent = navigator.userAgent;

			var valores3DSstring = JSON.stringify(valores3DS);

			return valores3DSstring;
		}

        function idOperOK() {
			$('input[type=radio][name=redsys_payment]').attr('disabled', true);
			
			var dataToSend = {
				"save": <?php echo $this->getAllowReference() ?> ? document.getElementById("check-guardar").checked : false,
				"operID": event.data.idOper,
				"numPed": "<?php echo $this->getNumPed() ?>",
				"idCart": "<?php echo $this->getIdCart() ?>",
				"valores3DS":cargaValoresBrowser3DS(),
			};

			$.ajax({
				url: "<?php echo $this->getProcURL() ?>",
				type: "POST",
				data: dataToSend,
				dataType: 'json',
				success: function(data) {
					if (data.redir == true)
						window.location.href = data.url;
					else {
						$('<iframe id="redsysModalDialog" src="' + data.url + '"  />').dialog({
							title: "Autenticacion de titular",
							autoOpen: true,
							minWidth: 900,
							minHeight: 600,
							modal: true,
							draggable: false,
							resizable: false,
							close: function(event, ui) {
								$(this).remove();
							},
							overlay: {
								opacity: 0.6,
								background: "black"
							}
						}).width(860).height(580);
						$("[aria-describedby='redsysModalDialog']").css("z-index", "999");
						$("[aria-describedby='redsysModalDialog']").css("display", "flex");
						$("[aria-describedby='redsysModalDialog']").css("flex-direction", "column");
						$("[aria-describedby='redsysModalDialog']").css("justify-content", "center");
						$("[aria-describedby='redsysModalDialog']").css("align-items", "center");
						$("[aria-describedby='redsysModalDialog']").css("text-align", "center");
						$("[aria-describedby='redsysModalDialog']").css("min-height", "100vh");
					}
					
					$('#redsysModalDialog').css("background", "white");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("text-align", "center");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("background-image", "none");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("background", "none");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("border", "none");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').children("button").remove();
				},
				error: function(request, status, error) {
					window.location.href = "<?php echo $this->getURLKo() ?>";
				}
			});
        }

        function idOperKO() {
            document.getElementById("redsys-err-val").style["display"] = "block";
        }

		function merchantValidation() {
			//Insertar validaciones si fuera necesario.
			return true;
		}

		window.addEventListener("message", function receiveMessage(event) {
			if(event.origin.includes("redsys.es")){
				storeIdOper(event, "token", "errorCode", merchantValidation);
				if (document.getElementById("token").value != "") {
					idOperOK();
				}
			}
		});

		function redsysReferencePayment() {
			document.getElementById("redsysRefButton").style["display"] = "none";
			$('input[type=radio][name=redsys_payment]').attr('disabled', true);

			var dataToSend = {
				"idCart": "<?php echo $this->getIdCart() ?>",
				"numPed": "<?php echo $this->getNumPed() ?>",
				"valores3DS":cargaValoresBrowser3DS()
			};

			$.ajax({
				url: "<?php echo $this->getProcURLRef() ?>",
				type: "POST",
				data: dataToSend,
				dataType: 'json',
				success: function(data) {
					if (data.redir == true)
						window.location.href = data.url;
					else {
						$('<iframe id="redsysModalDialog" src="' + data.url + '" frameborder="no" />').dialog({
							title: "Autenticacion de titular",
							autoOpen: true,
							minWidth: 900,
							minHeight: 600,
							modal: true,
							draggable: false,
							resizable: false,
							close: function(event, ui) {
								$(this).remove();
							},
							overlay: {
								opacity: 0.6,
								background: "black"
							}
						}).width(860).height(580);
								$("[aria-describedby='redsysModalDialog']").css("z-index", "999");
								$("[aria-describedby='redsysModalDialog']").css("display", "flex");
								$("[aria-describedby='redsysModalDialog']").css("flex-direction", "column");
								$("[aria-describedby='redsysModalDialog']").css("justify-content", "center");
								$("[aria-describedby='redsysModalDialog']").css("align-items", "center");
								$("[aria-describedby='redsysModalDialog']").css("text-align", "center");
								$("[aria-describedby='redsysModalDialog']").css("min-height", "100vh");
					}

					$('#redsysModalDialog').css("background", "white");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("text-align", "center");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("background-image", "none");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("background", "none");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').css("border", "none");
					$('#redsysModalDialog').siblings('div.ui-dialog-titlebar').children("button").remove();
				},
				error: function(request, status, error) {
					window.location.href = "<?php echo $this->getURLKo() ?>";
				}
			});
		};

		function sleep(delay) {
			var start = new Date().getTime();
			while (new Date().getTime() < start + delay);
		}

		function configInputs(){
			$('input[type=radio][name=redsys_payment]').attr('disabled', true);
			document.getElementById("redsysRefButton").style["display"] = "inline";
			$("#redsysForm").parent().parent().parent().parent().css("margin", "0 auto");
			$("#tdb5").hide();

			$("#redsys-hosted-pay-button").css("height", "auto");
			$("#redsys-hosted-pay-button").css("min-height", "275px");

			if ("<?php echo $this->getDisplayRadios() ?>" != "") {
				$("#redsysRefButton").hide();
				$("#redsysForm").show();
			}
			$('input[type=radio][name=redsys_payment]').attr('disabled', false);

			$('input[type=radio][name=redsys_payment]').change(function() {
				if (this.value == 'new') {
					$("#redsysForm").show();
					$("#redsysRefButton").hide();
				} else {
					$("#redsysForm").hide();
					$("#redsysRefButton").show();
				}
			});

			var but_ref = $("#redsysRefButton");
			if (but_ref != null && but_ref != undefined) {
				but_ref.click(function(event) {
					event.preventDefault();
				});
			}
		}

		window.onload = function() {
			//Cargo jQuery aqui, porque sino entra en conflicto con la version que provee Magento
			var scrJquery = document.createElement( "script" );
			scrJquery.type = "text/javascript";
			scrJquery.src = "<?php echo $block->getViewFileURL("Redsys_Redsys::js/jquery-1.7.min.js") ?>";

			var scrJqueryUI = document.createElement( "script" );
			scrJqueryUI.type = "text/javascript";
			scrJqueryUI.src = "<?php echo $block->getViewFileURL("Redsys_Redsys::js/jquery-ui.min.js") ?>";

			document.getElementsByTagName("head")[0].appendChild(scrJquery);
			document.getElementsByTagName("head")[0].appendChild(scrJqueryUI);

			scrJquery.addEventListener('load', function() {
				loadRedsysForm();
				configInputs();
			});
		}
	</script>
</body>

</html>