/*!
 * Resurs Bank Payment Gateway for WooCommerce - Scripthandler
 */
var $                    = jQuery.noConflict();
var resursReloadRequired = false;

// Things below wants to be loaded first and not wait for readiness
if (null !== resurs_omni_vars) {
	var RESURSCHECKOUT_IFRAME_URL = resurs_omni_vars.RESURSCHECKOUT_IFRAME_URL;
	var ACCEPT_CHECKOUT_PREFIXES  = resurs_omni_vars.ACCEPT_CHECKOUT_PREFIXES;
}

var customerTypes       = null;
var currentCustomerType = 'NATURAL'; // Default

var rbRefUpdated = false;

$( document ).ready(
	function ($) {
		if (typeof ResursCheckout !== "undefined" && typeof resurs_omni_vars !== "undefined" && resurs_omni_vars !== null) {

			var resursCheckout = ResursCheckout( '#resurs-checkout-container' );

			resursCheckout.init();

			resursCheckout.setBookingCallback(
				function (omniJsObject) {
					var omniRef                    = resurs_omni_vars.OmniRef;
					var currentResursCheckoutFrame = document.getElementsByTagName( "iframe" )[0];
					var invoicesubmitBtn           = $( 'div#payment .place-order button#place_order' );
					var postData                   = {};

					if (typeof currentResursCheckoutFrame !== "undefined" && typeof currentResursCheckoutFrame.src !== "undefined") {

						var errorString = "";
						// Prepare order and make it annullable on errors.

						if (omniRef != "" && typeof resurs_omni_vars.OmniPreBookUrl !== "undefined") {
							var preBookUrl = resurs_omni_vars.OmniPreBookUrl;

							var rendered              = omniJsObject["customerData"];
							var billing               = rendered["address"];
							var delivery              = rendered["delivery"];
							var useShipping           = false;
							var triggerUpdateCheckout = false;
							var fillFields            = {
								"first_name": "firstname",
								"last_name": "surname",
								"address_1": "address",
								"address_2": "addressExtra",
								"city": "city",
								"country": "countryCode",
								"email": "email",
								"postcode": "postal",
								"phone": "telephone"
							};
							// Check if there is a shipping set up on screen
							if ($( '#ship-to-different-address-checkbox' ).length > 0) {
								if (typeof delivery["firstname"] !== "undefined") {
									useShipping = true;
									if ( ! $( '#ship-to-different-address-checkbox' ).is( ':checked' )) {
										$( '#ship-to-different-address-checkbox' ).attr( "checked", false );
										$( '#ship-to-different-address-checkbox' ).click();
									}
								} else {
									if ($( '#ship-to-different-address-checkbox' ).is( ':checked' )) {
										$( '#ship-to-different-address-checkbox' ).click();
									}
								}
							}
							$( "[id^=billing_]" ).each(
								function (i, f) {
									if (typeof f.type === "string" && (f.type == "text" || f.type == "email" || f.type == "tel")) {
										var b_name = f.id.substr( f.id.indexOf( "_" ) + 1 );
										if (typeof fillFields[b_name] !== "undefined") {
											var useField = fillFields[b_name];
											if (typeof billing[useField] !== "undefined") {
												triggerUpdateCheckout = true;
												f.value               = billing[useField];
											}
										}
									}
								}
							);
							if (useShipping) {
								triggerUpdateCheckout = false;
								$( "[id^=shipping_]" ).each(
									function (i, f) {
										if (typeof f.type === "string" && (f.type == "text" || f.type == "email" || f.type == "tel")) {
											var b_name = f.id.substr( f.id.indexOf( "_" ) + 1 );
											if (typeof fillFields[b_name] !== "undefined") {
												var useField = fillFields[b_name];
												if (typeof delivery[useField] !== "undefined") {
													if (useField == "postal" && delivery[useField] != "") {
														triggerUpdateCheckout = true;
													}
													f.value = delivery[useField];
												}
											}
										}
									}
								);
							}
							if (triggerUpdateCheckout) {
								$( 'body form.woocommerce-checkout .place-order' ).trigger( 'click' );
							}
							$.ajax(
								{
									url: preBookUrl,
									type: "POST",
									data: jQuery( ".woocommerce-checkout" ).serialize(),
									beforeSend: function ( ) {
										mfRBShowLoading( true );
									}
								}
							).success(
								function (successData) {
									if (successData.result == 'success') {
										resursCheckout.confirmOrder( true );
										mfRBShowLoading( true );
									} else {
										mfRBShowLoading( false );
										resursCheckout.confirmOrder( false );

										// Remove notices from all sources
										$( '.woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message' ).remove();

										// Add new errors returned by this event
										if ( successData.messages ) {
											$( 'form.checkout' ).prepend( '<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">' + successData.messages + '</div>' );

											var scrollElement = $( '.woocommerce-NoticeGroup-updateOrderReview, .woocommerce-NoticeGroup-checkout' );
											if ( ! scrollElement.length ) {
												scrollElement = $( '.form.checkout' );
											}
											$.scroll_to_notices( scrollElement );
										}
									}
									return false;
								}
							).fail(
								function (x) {
									mfRBShowLoading( false );
									alert( resurs_translations.payError );
									resursCheckout.confirmOrder( false );
								}
							);

						}
					}
				}
			);
			resursCheckout.setPurchaseFailCallback(
				function () {
					if (resurs_fallback.url != "") {
						$.ajax(
							{
								url: resurs_fallback.url,
								type: "get",
							}
						)
							.success(
								function (successData) {
									handleResursCheckoutError( successData.errorString );
									if (successData.newIframe) {
										newIframe( successData.newIframe );
									}
									mfRBShowLoading( false );
								}
							)
							.fail(
								function (x) {
								}
							);
					}
				}
			);
			resursCheckout.setPurchaseDeniedCallback(
				function () {
					mfRBShowLoading( false );
				}
			);
		}

	}
);

function newIframe(Iframe) {
	$( '#resurs-checkout-container' ).html( Iframe );
}
function handleResursCheckoutError(resursErrorMessage) {
	var checkoutForm = $( 'form.checkout' );
	if (checkoutForm.length > 0) {
		$( '.woocommerce-error, .woocommerce-message' ).remove();
		checkoutForm.prepend( '<div class="woocommerce-error">' + resursErrorMessage + '</div>' );
		$( 'html, body' ).animate(
			{
				scrollTop: ($( 'form.checkout' ).offset().top - 100)
			},
			1000
		);
	} else {
		/*
		 * Fall back on an alert if something went wrong with the page
		 */
		alert( resursErrorMessage );
	}
}

function mfRBShowLoading(state) {
	if (state) {
		$( '#order_review, #customer_details' ).block(
			{
				message: null,
				overlayCSS: {
					background: '#fff',
					opacity: 0.6
				}
			}
		);
	} else {
		$( '#order_review, #customer_details' ).unblock();
		$( '#resurs-checkout-container' ).unblock();
	}
}
