<!DOCTYPE html>
<html>
<head>
  <title>OSM BTC</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.10/js/dataTables.bootstrap.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
  <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel='stylesheet' href="https://cdn.datatables.net/1.10.10/css/dataTables.bootstrap.min.css">
  <link rel='stylesheet' href="/css/site.css">
  <link rel='stylesheet' href="/css/report.css">
  <meta name="msapplication-config" content="/images/favicons/browserconfig.xml">
  <meta name="theme-color" content="#ffffff">
</head>
<body>
<div class="maincontainer">
  <div class="main">
    <div class="nav-holder">
      <ul class="navigation">
        <li class="active"><a data-toggle="tab" href="#information">Information</a></li>
        <li><a data-toggle="tab" href="#report">OSM Contributions</a></li>
        <li><a data-toggle="tab" href="#recipients">Recipients</a></li>
      </ul>
    </div>
    <div class="container">
      <div class="tab-content">
        <div class="loading"></div>
        <div id="report" class="tab-pane fade">
          <h2>OSM Contributions</h2>
          <div class="report-period-group">
            <div class="report-group period">
              <h4 class="vlabel" for="month-selection">Report period</h4>
              <div class="styled-select">
                <select class="form-control" id="month-selection"></select>
              </div>
            </div>
            <div class="report-group region">
              <h4 class="vlabel" for="region-selection">Region</h4>
              <div class="styled-select">
                <select class="form-control" id="region-selection"></select>
              </div>
            </div>
          </div>
          <div class="report-total-div">
            <div class="overview-body">
              <p class='overview-hint' ><span>Overview for</span> <span id="overview-contributors_options">
              </span><span id='overview-id' style="color:black;float:right;"></span></p>
              <div id="report-total" class="infobox"></div>
            </div>
          </div>
          <h4 class="vlabel" for="report-table" id="report-ranking"></h4>
          <table id="report-table" class="table table-bordered" cellspacing="0" width="100%"></table>
          <h4 class="vlabel" for="users-table" id="users-ranking"></h4>
          <div class="table-controls hidden">
            <div class="tc search">
              <input type="search" class="form-control" aria-control="users-table" id="users-table-search" placeholder="Search">
            </div>
            <div class="tc entries">
              <label>
              <span>Show entries</span>
              <div class="styled-select">
                <select name="users-table_length" aria-controls="users-table" class="form-control" id="users-table-select">
                  <option value="10">10</option>
                  <option value="25">25</option>
                  <option value="50" selected>50</option>
                  <option value="100">100</option>
                </select>
              </div>
              </label>
            </div>
          </div>
          <table id="users-table" class="table table-bordered" cellspacing="0" width="100%"></table>
        </div>
        
        <div id="information" class="tab-pane fade in active">
          <div id="general-info-div">
            <div id="general-info" class="infobox">
              <h2>OSM BTC fund</h2>
              <p>OSM BTC is an open Fund initiative which has a primary goal to support OpenStreetMap contributors by small donations via Bitcoin. </p>
              <div style="background:#ececec;padding:1px 25px;">
                <h3>OSM BTC stopped payouts since July 2022!</h3>
                <p>As a result of Russia invasion to Ukraine in 2022 (#StandForUkraine) main sponsor of OSM BTC fund has lost the ability to contribute. Fund will suspend payouts unless it finds another sponsor.</p>
              </div>
              <h3>How it works</h3>
              <ul>
                <li> Any OSM contributor can be registered as a recipient by providing a valid Bitcoin address in the form below.
                <li> Any individual or company can contribute to the common fund via Bitcoin payment, 3% will be hold as tx fee (see below).
                <li> All donations are exchanged for Bitcoin and distributed among OSM contributors based on their ranking. 
                <li> During the current month there is a preliminary report (with label 'Estimation'). Final report (with label 'Total payout') is calculated at the beginning of the next month. Payments could be delayed in case Bitcoin fees are very high.
              </ul>
              <h3>Details</h3>
              <ul>
                <li><b>Minimum payment threshold.</b> OSM BTC tries to leverage payout fees and payout frequencies by monitoring that payout fee doesn't exceed <b>3% of payout sum</b>. With an average bitcoin tx fee of 5 satoshi per byte - minimum payout is <b>0.5 mBTC</b> = 5000 satoshi  (fee 250 satoshi).
                <li><b>Cumulative payout report.</b> In case payout doesn't exceed Minimum payment threshold, it won't be payout immediately but accumulated for the next month. Payout sum will be present in Recipient reports and <a href="https://builder.osmand.net/reports/query_btc_balance_report">Cumulative payout report (json)</a>.
                <li><b>Bans.</b> User can be banned in case of <a class="vlabel program-rules-ref"> rule violations</a>.
                <li><b>Rankings.</b> The payouts are distributed based on the ranking which is available in OSM Contributions tab, the last ranking has weight&nbsp;=&nbsp;1, the ranking before the last has weight&nbsp;=&nbsp;2 and so on till the 1st ranking. Ranking stimulates contributors to be in the top 10% most active contributors of OSM but not necessarily the top 1 contributor.
                <li><b>OpenStreetMap password</b>. OSM BTC <b>doesn't keep</b> OpenStreetMap password and it is only needed to verify OSM identity, it is strongly advised to change the password before registration and after to avoid any possible password leak. In case you would like to contribute to OSM BTC and change it to OSM OAuth, please feel free.
              </ul>
            </div>
          </div>
          <div class="registration recipient-registration" id="recipients-register-div">
            <h4 class="vlabel" for="recipients-register-div">Register as a recipient</h4 >
            <div class="alert alert-danger" role="alert" id="osm_register_failed" style="display:none">
              <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> 
              OSM Authentication has failed.
            </div>
            <div class="alert alert-success" role="alert" id="osm_register_success" style="display:none">
              <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> 
              You have successfully registered as a recipient.
            </div>
            <form role="form" action="subscription/register_osm" method="post" id="register_osm">
              <label for="osm_usr">OpenStreetMap nick name (not email):</label>
              <div class="input-holder input-user">
                <input type="text" class="form-control" id="osm_usr" name="osm_usr">
              </div>
              <p class="input-hint">We use OpenStreetMap.org API to access user stats.</p>
              <label for="osm_pwd">OpenStreetMap password:</label>
              <div class="input-holder input-pass">
                <input type="password" class="form-control" id="osm_pwd" name="osm_pwd">
              </div>
              <p class="input-hint">We need it to verify that the account belongs to you. We do not store it on our servers.</p>
              <label for="email">Email address:</label>
              <div class="input-holder input-user">
                <input type="text" class="form-control" id="email" name="email">
              </div>
              <p class="input-hint">We can use it to confirm that account doesn't violate TOS.</p>
              <label for="bitcoin_addr">Bitcoin address:</label>
              <div class="input-holder input-bitcoin">
                <input type="text" class="form-control" id="bitcoin_addr" name="bitcoin_addr">
              </div>
              <p class="input-hint">This bitcoin address will be used to transfer funds to.</p>
              
              <div class="input-agree">
                  <input type="checkbox" id="agree_osm_btc" name="agree_osm_btc">
                  <label for="agree_osm_btc" class="agree_osm_btc_label">I Agree with OSM BTC program</label><a class="vlabel program-rules-ref"> rules.</a>
              </div>
              <button type="submit" class="btn btn-default" id="register_osm_user">Register</button>
              <p style="font-size:12px; line-height:1.3em; padding-top:20px">To update your BTC address, repeat the registration process using the new address. To delete an account, re-enter your credentials and leave the Bitcoin address field empty.</p>
            <div id="rules-modal-dialog" class="modal">
              <!-- Modal content -->
              <div class="modal-content">
                <div class="modal-header">
                  <span class="close-params">&times;</span>
                  <h2>Program Rules</h2>
                </div>
                <div class="modal-body">
                  <p style="font-size:15px; padding-top:20px">By registering, <b>you accept the following:</b>
                    <ul style="font-size:15px; line-height:1.3em;">
                      <li>- The payments made to mappers within OSM BTC project are considered donations for their contributions, not remuneration for labor;</li>
                      <li>- OSM BTC can not be called liable for any donations/payments loss;
                      <li>- OSM BTC can suspend payouts and/or remove accounts of certain users if their work is not beneficial to the project;</li>
                      <li>- The project allows only 1 payment per 1 individual at a time;</li>
                      <li>- The payments can be suspended in case of unexpected emergencies.</li>
                    </ul>
                  </p>
                </div>
              </div>
            </div>
            </form>
          </div>
          <div class="registration contributor-registration" id="contributor-register-div">
            <h4 class="vlabel" for="recipients-register-div">Register as a contributor</h4 >
            <h5 class="vlabel">Donate directly to OSM BTC fund</h5>
            <div class="btc-address">3MHyi4qtrmaxEy9A336RMwZaYqUzcbF2gr</div>
            
            <!-- 
            <h5 class="vlabel">Donate to OsmAnd</h5>
            <p>If you want to support OsmAnd team, you could purchase it on following Markets.</p>
            <div class="registration-badges">
              <a data-gatag="googleplay" href="https://play.google.com/store/apps/details?id=net.osmand.plus"><img
                  alt="Get it on Google Play" src="/images/en-play-badge.png" /></a>
              <a data-gatag="ios"
                href="https://itunes.apple.com/app/apple-store/id934850257?pt=2123532&amp;ct=WebSite&amp;mt=8"><img
                  src="/images/app-store-badge.png" /></a>
            </div>
            <p>If you want to donate to OsmAnd Team, please use the following address:</p>
            <div class="btc-address">1GRgEnKujorJJ9VBa76g8cp3sfoWtQqSs4</div>
            -->
          </div>
        </div>
        <div id="recipients" class="tab-pane fade">
          <h2>Recipients</h2>
          <!--
            <h4 class="vlabel" for="recipients-info-div">Information</h4 >
              <div class="panel panel-default" id="recipients-info-div">
                  <div class="panel-body"><p id="recipients-general-info" class="infobox"></p></div>
              </div>
            <hr>
          -->
          <div class="report-period-group">
            <div class="report-group period">
              <h4 class="vlabel" for="recipient-month-selection">Report period</h4>
              <div class="styled-select">
                <select class="form-control osm-live-month-select" id="recipient-month-selection"></select>
              </div>
            </div>
            <div class="report-group region" id="recipient-region-group" style="display:none">
              <h4 class="vlabel" for="recipient-region-selection">Region</h4>
              <div class="styled-select">
                <select class="form-control" id="recipient-region-selection"></select>
              </div>
            </div>
          </div>
          <div class="report-total-div">
            <div class="overview-body">
              <div id="recipients-data-info" class="infobox">
                  <p class='recipients-data-header overview-hint'>
                        Collected in 
                        <span id='overview-recipients_option'></span> 
                        <span id='recipients-gen-date' style=\"color:black;float:right;\"></span>
                  </p>

                  <div id="recipients-world-collected" class='overview overview-btc'>
                    <p>- mBTC</p><span>total collected (may change in the final report)</span>
                  </div>
                  <div id="recipients-region-collected" class="overview overview-btc" style="display:none">
                    <p>- mBTC</p><span>collected Worldwide</span>
                  </div>
                  <p id="recipients-payouts" class='recipients-data-header overview-hint'></p>
                  <p id="recipients-reports"></p>
              </div>
            </div>
          </div>
          <!--          <p><b>Important:</b> Registration temporarily suspended. Read <a href="https://www.osmand.net/blog?id=osmand_payouts_suspended_01_2018">this article</a> for more information.</p> -->
          <h4 class="vlabel" for="recipients-table" id="recipients-table-header">OSM Recipients</h4>
          <div class="table-controls recipients-controls hidden">
            <div class="tc search">
              <input type="search" class="form-control" aria-control="recipients-table" id="recipients-table-search" placeholder="Search">
            </div>
            <div class="tc entries">
              <label>
              <span>Show entries</span>
              <div class="styled-select">
                <select name="recipients-table_length" aria-controls="recipients-table" class="form-control" id="recipients-table-select">
                  <option value="10">10</option>
                  <option value="25">25</option>
                  <option value="50" selected>50</option>
                  <option value="100">100</option>
                </select>
              </div>
              </label>
            </div>
          </div>
          <table id="recipients-table" class="table table-bordered" cellspacing="0" width="100%"></table>
        </div>
      </div>
    </div>
  </div>
</div>
<script>


  $.urlParam = function(name){
      var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
      if (results==null){
         return null;
      }
      else{
         return results[1] || 0;
      }
  }
  var extended = $.urlParam('full') == 'yes';
  var mid = "";
  var midName = "";
  var supportMonth = "";
  var supportMonthName = "";
  var region = "";
  var regionName = "";
  var regionsmap = {};
  var regionsbydownloadname = {};
  var recipientMonth = "";
  var recipientMonthName = "";
  var recipientRegion = "";
  var recipientRegionName = "";

  var floatFormat = function (o) { 
      var fl = parseFloat(o) * 100;
      return Math.round(fl) / 100.;
  }
  
  function regionDepth(region, regionsmap) {
    if(region.parentid in regionsmap) {
      return regionDepth(regionsmap[region.parentid], regionsmap) + 1;
    } else {
      return 0;
    }
  }
  
  function updateRegions() {
    $('#region-selection').empty();
    $('#recipient-region-selection').empty();
    regionsmap = {};
    regionsbydownloadname = {};
    if(regionName.length > 0 && regionName != "Worldwide") {
      $("#region-selection").append("<option value='"+region+"'>"+regionName+"</option>"); 
    }
    if(recipientRegionName.length > 0 && recipientRegionName != "Worldwide") {
      $("#recipient-region-selection").append("<option value='"+recipientRegion+"'>"+recipientRegionName+"</option>"); 
    }
    $("#region-selection").append("<option value=''>Worldwide</option>"); 
    $("#recipient-region-selection").append("<option value=''>Worldwide</option>"); 
    $.ajax({
        url: "/reports/query_report?report=all_countries", 
        async: true
      }).done(function(res) {
        var data = jQuery.parseJSON( res );
        var namemap = {};
        for(i = 0; i < data.rows.length; i++) {
          var row = data.rows[i];
          regionsmap[data.rows[i].id] = data.rows[i];
          if(row.downloadname && row.map == "1" ) {
            var name = row.name;
            if(row.visiblename) {
                name = row.visiblename;
            } else { 
              var depth = regionDepth(row, regionsmap);
              if(depth > 2 || (depth == 2 && regionsmap[row.parentid].name == "Russia")) {
                var parent = regionsmap[row.parentid];
                var parentparent = regionsmap[parent.parentid];
                if(depth == 3) {
                  if(parentparent.name == "Russia") {
                    name = parentparent.name + " " + name;
                  } else if(parent.name != "United Kingdom"){
                    name = parent.name + " " + name;
                  }
                } else {
                  // only england
                  name = parent.name + " " + name;
                }
              }
            } 
            namemap[name] = row.downloadname;
            regionsbydownloadname[row.downloadname] = name;
          }
      }
      var sorted_keys = Object.keys(namemap).sort()
      for(i = 0; i < sorted_keys.length; i++) {
        $("#region-selection").append("<option value='"+namemap[sorted_keys[i]]+"'>"+sorted_keys[i]+"</option>"); 
        $("#recipient-region-selection").append("<option value='"+namemap[sorted_keys[i]]+"'>"+sorted_keys[i]+"</option>"); 
      }
    });
  }
  
  function updateTotalChanges() {
    $('#report-total').empty();
    if(reportUserDataTable) {
      reportUserDataTable.clear().draw();
    }
    if(reportDataTable) {
      reportDataTable.clear().draw();
    }
    $('#report-ranking').empty();
    $.ajax({
        url: "/reports/query_report?report=all_contributions_requests&month="+mid+"&region="+region, 
        async: true
      }).done(function(res) {
        // var resultArray = res.split("\n");
        var resultArray = jQuery.parseJSON(res);
        var totalChanges = resultArray[0];
        var data = totalChanges; //jQuery.parseJSON( totalChanges );
        var html = "<div class='overview overview-changes'><p>" + data.changes + "</p><span>changes</span></div>" 
          + "<div class='overview overview-users'><p>" + data.users   + "</p><span>contributors</span></div>";
        if(regionName.length > 0) {
           html = html + "<div class='overview overview-region'><p>" + regionName + "</p><span>country</span></div>";
        }
        if (data.date != null || data.date != undefined) {
          //html += "<p class=\"overview-hint\">Generation date: " + "<span id=\"overview-date\">" + data.date + "</span></p>";
          $('#overview-id').html("Generation date <span>"+ formatDate(data.date) + "</span>");
        }
        else {
           $('#overview-id').html("");
        } 
        $('#report-total').html(html);
        setContributorsOverviewHint();
        updateRankingByMonth(resultArray[1]);
        
        if (resultArray.length > 2) {
          updateUserRankingByMonth(resultArray[2]);
        }
    });
  }

  function formatDate(timestampString) {
   var currTime = parseInt(timestampString, 10);
   var currTimeString = (new Date(currTime*1000)).toString();
   return currTimeString.substring(currTimeString.indexOf(" "), currTimeString.lastIndexOf(":"));
  }
  
  
  function countryName(value) {
    if(value == '') {
      return "Worldwide";
    }
    if(value in regionsbydownloadname) {
      return regionsbydownloadname[value];
    }
    return value;
  }
  
  
  var reportRecipientsDataTable;
  var reportRecipientsDataInfo;
  function updateRecipientsByMonth() {
    if(reportRecipientsDataTable && reportRecipientsDataInfo) {
      reportRecipientsDataTable.clear().draw();
      $("#recipients-data-info").html("");
    }
    $.ajax({
          url: "/reports/query_report?report=recipients_by_month&month="+recipientMonth+"&region="+recipientRegion, 
          async: true
    }).done(function(res) {
          var data = jQuery.parseJSON( res );
          var recipients = data;
          //$("#recipients-general-info").html(intro);
          // reportRecipientsDataInfo = $("#recipients-data-info").html(data.message);
          if (recipients.date != null && recipients.date != undefined) {
            $("#recipients-gen-date").html("Generation date " + formatDate(recipients.date));
          } else {
            $("#recipients-gen-date").html("");
          }
          $("#recipients-world-collected").html(data.worldCollectedMessage);
          if (recipientMonth >= '2021-03' || recipientMonth == '') {
            $("#recipients-region-collected").hide();
          } else {
            $("#recipients-region-collected").show();
            $("#recipients-region-collected").html(data.regionCollectedMessage +
                  '<span> ' + countryName(recipientRegion)+'</span>');
          }
          $("#recipients-payouts").html(data.payouts);
          $("#recipients-reports").html(data.reports);
          var list = recipients.rows.map(function(key){
              if(recipients.regionTotalWeight > 0) {
                key.percent = key.weight + " / " + recipients.regionTotalWeight ;
              } else {
                key.percent = '';
              }
              key.mbtc = (key.btc * 1000.).toFixed(4)  + " mBTC";
              return key;
          });
          var rowPerPage = function(windowWidth) {
            if (windowWidth < 380) {
              return 10;
            } else if (windowWidth < 650) {
              return 20;
            } else if (windowWidth < 970) {
              return 30;
            } else {
              return 50;
            }
          }
          reportRecipientsDataTable = $('#recipients-table').DataTable({
              data: list,
              destroy: true,
              columns: [
                  { "data": "osmid", title: "OSM ID"},
                  ( recipientMonth >= '2021-12' || recipientMonth == '' ?
                      { "data": "objchanges", title: "Edits" } :
                      { "data": "changes", title: "Changesets"} )
                  ,
                  { "data": "rank", title: "Rank"},
                  { "data": "weight", title: "Weight"},
                  { "data": "percent", title: "Part"},
                  { "data": "mbtc", title: "Sum"},
                  { "data": "btcaddress", title: "Bitcoin Address"}
              ],
              "paging":   true,
              "iDisplayLength": rowPerPage($(window).width()),
              "info":     false,
              "bAutoWidth": false,
              "dom": "tp"
          });
          $('.table-controls.recipients-controls').removeClass('hidden');
          setRecipientOverviewHint();
    });
  }
    
  var reportUserDataTable;
  function updateUserRankingByMonth(resource) {
    $('#users-ranking').text("Select region to see user statistics ");
    if(region.length > 0 ) {
      
          var data = resource;
          $('#users-ranking').text("Ranking of contributors");
          var columns = [
                  { "data": "rank", title: "Region rank"},
                  { "data": "grank", title: "World rank"},
                  { "data": "user", title: "User name"},        
                  { "data": "changes", title: "Changesets"},
          ];
          if(mid >= '2018-09') {
              columns.push({ "data": "atomglobalchanges", title: "Edits"});
              columns.push({ "data": "globalchanges", title: "Worldwide changes"});
              columns.push({ "data": "atomchanges", title: "Worldwide Edits" });
          }
          reportUserDataTable = $('#users-table').DataTable({
              data: data.rows,
              destroy: true,
              columns: columns,
              "paging":   true,
              "ordering": true,
              "iDisplayLength": 50,
              "info":     false,
              "searching": true,
              "dom": 'tp'
          });
          $('.table-controls').removeClass('hidden');
    }
  }

  var reportDataTable;
  function updateRankingByMonth(resource) {
    var data = resource; //jQuery.parseJSON(resource);
    var c = 0;
    if (data.rows.length > 0) {
      c = data.rows[data.rows.length - 1].minChanges;
    }
    $('#report-ranking').html("Ranking of contributors by " + data.rows.length + " groups <span>(made more than " + 
      c + " changes)</span>");
      
    var columns = [
                { "data": "rank", title: "Rank"},
                { "data": "countUsers", title: "Contributors <span>in a group</span>"},
                { "data": "minChanges", title: mid >= '2021-12' ? "Minimum edits <span>in group</span>" : "Minimum changesets <span>in group</span>"},
                { "data": "maxChanges", title: mid >= '2021-12' ? "Maximum edits <span>in group</span>" : "Maximum changesets <span>in group</span>" },
    ];
    if (mid >= '2018-09') {
        columns.push({ "data": "totalChanges", title: "Total changesets <span>by group</span>"}); //, render:floatFormat
        columns.push({ "data": "atomTotalChanges", title: "Total edits <span>by group</span>"});
    }
      reportDataTable = $('#report-table').DataTable({
            data: data.rows,
            destroy: true,
            columns: columns,
            "paging":   false,
            "ordering": true,
            //"iDisplayLength": 20,
            "info":     false,
            "searching": false,
            "dom": "t",
      });
  }

  
  function formatYearMonthHuman(year, month) {
    var monthNames = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"];
    return monthNames[month - 1] + " " + year;
  }
  
  function formatYearMonth(year, month) {
    if(month < 10) {
      return year +"-0" +month;
    } else {
      return year +"-" +month;
    }
  }
  

  function isEmail(emailV) {
    if(emailV != null && emailV != undefined) {
        var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
        return pattern.test(emailV);    
    }
    else{
        return false;
    }
  }
  
  function handleRegisterOsm() {

    $("#register_osm_user").click(function( event ) {
        event.preventDefault();
          // if($("#bitcoin_addr").val() == "") {
          //   $("#osm_register_failed").html("Please specify correct bitcoin address");
          //   $("#osm_register_failed").fadeIn(100);
          //   return;
          // }
          if(!isEmail($("#email").val())) {
            $("#osm_register_failed").html("Please specify a valid email address");
            $("#osm_register_failed").fadeIn(100);
            return;
          }
          if (!$("#agree_osm_btc").is(':checked')) {
            $("#osm_register_failed").html("You must agree to the tems of use.");
            $("#osm_register_failed").fadeIn(100);
            return;
          }
  
        $.post("subscription/register_osm", $("#register_osm").serialize(), function(res) {
            if (res == "OK") {
              $("#osm_register_success").fadeIn(100);
            }
            var data = res;
            if (data.error) {
              $("#osm_register_failed").fadeIn(100);
              $("#osm_register_failed").html(data.error);
            } else {
              $("#osm_register_failed").fadeOut(0);
              $("#osm_register_success").fadeIn(100); 
            }
           
        });
    });
  }
  
  function selectProperTab() {
    var url = document.location.toString();
    if (url.match('#')) {
        $('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
    } 
  }
  $(document).ready(function(){

    // Get the button that opens the modal
    $(".program-rules-ref").click(function (event) {
      $('body').css('overflow', 'hidden');
      document.getElementById('rules-modal-dialog').style.display = "block";
    });

    // When the user clicks on <span> (x), close the modal
    $(".close-params").click(function (event) {
        $('body').css('overflow', 'auto');
        document.getElementById('rules-modal-dialog').style.display = "none";
    });

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
       let modal = document.getElementById('rules-modal-dialog');
        if (event.target == modal) {
          $('body').css('overflow', 'auto');
          modal.style.display = "none";
        }
    }

    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    mid = formatYearMonth(year, month);
    for(yi = 2016; yi <= year; yi++) {
      stmonth = yi == 2015? 8 : 1;
      endmonth = yi == year? month : 12;
      for(mi = stmonth; mi <= endmonth; mi++) {
        $("#month-selection").prepend("<option value='"+formatYearMonth(yi,mi)+"'"+((mi==endmonth&&yi==year)?' selected':'')+">"+formatYearMonthHuman(yi,mi)+"</option>");
      }
    }
    for(yi = 2016; yi <= year; yi++) {
      stmonth = yi == 2016? 1 : 1;
      endmonth = yi == year? month : 12;
      for(mi = stmonth; mi <= endmonth; mi++) {
        $(".osm-live-month-select").prepend("<option value='"+formatYearMonth(yi,mi)+"'"+((mi==endmonth&&yi==year)?' selected':'')+">"+formatYearMonthHuman(yi,mi)+"</option>");
      }
    }
    if(typeof(Storage) !== "undefined") {
        if(sessionStorage.recipientMonth) {
            recipientMonth = sessionStorage.recipientMonth;
            recipientMonthName = sessionStorage.recipientMonthName;
            $("#recipient-month-selection").val(recipientMonth);
            var currentMonth  = $("#recipient-month-selection").children("option").filter(":selected").text();
            $('#overview-recipients_option').text(currentMonth);
        }
        if(sessionStorage.recipientRegion) {
            recipientRegion = sessionStorage.recipientRegion;
            recipientRegionName = sessionStorage.recipientRegionName;
            $("#recipient-region-selection").val(recipientRegion);
        }
  
        if(sessionStorage.month) {
            mid = sessionStorage.month;
            midName = sessionStorage.monthName;
            $("#month-selection").val(mid);
        }
        if(sessionStorage.region) {
            region = sessionStorage.region;
            regionName = sessionStorage.regionName;
            $("#region-selection").val(region);
            var currentMonth  = $("#month-selection").children("option").filter(":selected").text(),
                currentRegion = $("#region-selection").children("option").filter(":selected").text();
            $('#overview-contributors_options').text(currentMonth + ', ' + currentRegion);
        }
    }
  
    
    handleRegisterOsm();
    updateRegions(); 
    updateRecipientsByMonth();
    
    updateTotalChanges();
    //updateRankingByMonth();
    //updateUserRankingByMonth();
    
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        /*var target = $(e.target).attr("href") // activated tab
        window.location.hash = target;*/
        $('.loading').removeClass("active");
        e.preventDefault();
        return false;
    });
    window.onpopstate = function(event) {
      selectProperTab();
    };
    selectProperTab();
  
    $('#donate-month-selection').on('change', function (e) {
        if (!$('#information').is(':visible')) {
          $('.loading').addClass("active");
        }
        var optionSelected = $("option:selected", this);
        supportMonth = this.value;
        supportMonthName = optionSelected.text();
        if(typeof(Storage) !== "undefined") {
          sessionStorage.supportMonth = supportMonth;
          sessionStorage.supportMonthName = supportMonthName;
        }
        setSupportersOverviewHint();
    });
    $('#recipient-month-selection').on('change', function (e) {
        if (!$('#information').is(':visible')) {
          $('.loading').addClass("active");
        }
        var optionSelected = $("option:selected", this);
        recipientMonth = this.value;
        recipientMonthName = optionSelected.text();
        if (recipientMonth < '2021-03') {
          $('#recipient-region-group').show();
        } else {
          recipientRegion = '';
          sessionStorage.recipientRegion = recipientRegion;
          $('#recipient-region-group').hide();
        }
        if(typeof(Storage) !== "undefined") {
          sessionStorage.recipientMonth = recipientMonth;
          sessionStorage.recipientMonthName = recipientMonthName;
        }
        updateRecipientsByMonth();
        setRecipientOverviewHint();
    });
    $('#recipient-region-selection').on('change', function (e) {
        if (!$('#information').is(':visible')) {
          $('.loading').addClass("active");
        }
        var optionSelected = $("option:selected", this);
        recipientRegion = this.value;
        recipientRegionName = optionSelected.text();
        if(typeof(Storage) !== "undefined") {
          sessionStorage.recipientRegion = recipientRegion;
          sessionStorage.recipientRegionName = recipientRegionName;
        }
        updateRecipientsByMonth();
      });
    
    $('#month-selection').on('change', function (e) {
        if (!$('#information').is(':visible')) {
          $('.loading').addClass("active");
        }
        var optionSelected = $("option:selected", this);
        mid = this.value;
        midName = optionSelected.text();
        if(typeof(Storage) !== "undefined") {
          sessionStorage.month = mid;
          sessionStorage.monthName = midName;
        }
        updateTotalChanges();
        //updateRankingByMonth();
        //updateUserRankingByMonth();
        setContributorsOverviewHint();
    });
  
    $('#region-selection').on('change', function (e) {
        if (!$('#information').is(':visible')) {
          $('.loading').addClass("active");
        }
        var optionSelected = $("option:selected", this);
        region = this.value;
        regionName = optionSelected.text();
        if(typeof(Storage) !== "undefined") {
          sessionStorage.region = region;
          sessionStorage.regionName = regionName;
        }
        
        updateTotalChanges();
        //updateRankingByMonth();
        //updateUserRankingByMonth();
      });  
  });

  function setContributorsOverviewHint() {
    var currentMonth  = $("#month-selection").children("option").filter(":selected").text(),
        currentRegion = $("#region-selection").children("option").filter(":selected").text()
    $('#overview-contributors_options').text(currentMonth + ', ' + currentRegion);
  }

  function setRecipientOverviewHint() {
    var currentMonth  = $("#recipient-month-selection").children("option").filter(":selected").text();
    $('#overview-recipients_option').text(currentMonth);
  }

  $('#users-table-search').on('keyup', function() {
    reportUserDataTable.search(this.value).draw();
  });

  $('#users-table-select').on('change', function() {
    reportUserDataTable.page.len(this.value).draw();
  });

  $('#recipients-table-search').on('keyup', function() {
    reportRecipientsDataTable.search(this.value).draw();
  });

  $('#recipients-table-select').on('change', function() {
    reportRecipientsDataTable.page.len(this.value).draw();
  });

  $(document).on({
    //ajaxStart: function() { 
      //if (!$('#information').is(':visible')) {
        //$('.loading').addClass("active");
      //}
    //},
    ajaxStop: function() { 
      $('.loading').removeClass("active");
    }
  });
  
</script>
</body>
</html>
