function bindCheckState() {
  var url = window.location.href;
  
  //Getting parameters from the URL
  
  var userId;

  var userIdMatch = url.match(/[?|&]userId=([0-9]+?)/);
  if (userIdMatch && userIdMatch.length > 1) {
    userId = userIdMatch[1];
  }

  var token;
  var tokenMatch = url.match(/[?|&]checkStateToken=(.*?)(&|$)/);
  if (tokenMatch && tokenMatch.length > 1) {
    token = tokenMatch[1];
  }

  var culture;
  var cultureMatch = url.match(/[?|&]culture=(.*?)(&|$)/);
  if (cultureMatch && cultureMatch.length > 1) {
    culture = cultureMatch[1];
  }
  
  var amount;
  var amountMatch = url.match(/[?|&]amount=(([0-9]*[.])?[0-9]+)/);
  if (amountMatch && amountMatch.length > 1) {
    amount = +amountMatch[1];
  }

  console.log("bindCheckState:");
  console.log("- userId:" + userId);
  console.log("- checkStateToken:" + token);
  console.log("- culture:" + culture);
  console.log("- amount:" + amount);

  var bukzaCheckState = new BukzaCheckState({
    userId: userId,
    token: token,
    handler: function (result) {
      console.log(result); //{isFinished:true, isValid:true, amount:99.99}

      if (result) {
        if (result.isFinished) {
          if (result.isValid) {
            //order is completed succesfully
            window.location.href =
              "https://app.bukza.com/result.html?result=success&culture=ru";
          } else {
            //order is completed but for some reason it is not valid
            window.location.href =
              "https://app.bukza.com/result.html?result=warning&culture=ru";
          }
        } else {
          if (result.isValid) {
            if (result.amount != amount) {
              debugger;
              //amount to pay has changed, going to the previous page
              window.history.go(-1);
            } else {
              //everything is ok, waiting for payment
            }
          } else {
            //order became invalid, going to the previous page
            window.history.go(-1);
          }
        }
      } else {
        window.location.href =
          "https://app.bukza.com/result.html?result=error&culture=ru";
      }
    },
  });
  bukzaCheckState.bind();
}

if (
  document.readyState === "interactive" ||
  document.readyState === "complete"
) {
  bindCheckState();
} else {
  document.addEventListener("DOMContentLoaded", bindCheckState);
}
