<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
$_OPTIMIZATION["title"] = "Сёрфинг сайтов";
define('TIME', time());

header("Content-Type: text/html; charset=utf-8");

$db->Query("SELECT * FROM db_users_a WHERE id = '".$_SESSION['user_id']."'");
$users_info = $db->FetchAssoc();

function GeoIpClient()
{
  $xml=@simplexml_load_file('http://ipgeobase.ru:7020/geo?ip='.$_SERVER["REMOTE_ADDR"]);

  $country = ($xml->ip->country) ? $xml->ip->country : FALSE;

  if ($country)
  {
    $_SESSION['country'] = $country;
  }
  else
  {
    $_SESSION['country'] = 'FUCK';
  }
}

if (!isset($_SESSION['country'])) { GeoIpClient(); }

//unset($_SESSION['country']);

//echo 'test = '.$_SESSION['country'];

if (isset($_GET['delete']))
{
  $id = (int)$_GET['delete'];

  if (isset($_SESSION['admin']))
  {
    $db->query("SELECT money, user_name FROM db_serfing WHERE id = '".$id."' LIMIT 1");

    $result = $db->FetchAssoc();

    $db->query("UPDATE db_users_b SET money_b = money_b + '".$result['money']."' WHERE user = '".$result['user_name']."'");

    $db->query("DELETE FROM db_serfing WHERE id = '".$id."'");
    $db->query("DELETE FROM db_serfing_view WHERE ident = '".$id."'");
  }
}


 $db->Query("SELECT * FROM db_serfing WHERE price >= money");
 $sid = $db->FetchAssoc();


 //останавливаем рекламу
 $db->query("UPDATE db_serfing SET `status` = '3' WHERE id = '".$sid['id']."'");
?>
<script>

function getHTTPRequest()
{
    var req = false;
    try {
        req = new XMLHttpRequest();
    } catch(err) {
        try {
            req = new ActiveXObject("MsXML2.XMLHTTP");
        } catch(err) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(err) {
                req = false;
            }
        }
    }
    return req;
}

jQuery(document).ready(function(){
    $(".normalm").click(function(e){
        var oLeft = 0, oTop = 0;
        element = this;
        if (element.className == 'normalm') {
            do {
                oLeft += element.offsetLeft;
                oTop  += element.offsetTop;
            } while (element = element.offsetParent);
            var sx = e.pageX - oLeft;
            var sy = e.pageY - oTop;
            var elid = $(this).attr("id");
            fixed(elid, sx, sy);
        }
    });
})

function goserf(obj)
{
    obj.parentNode.innerHTML = "<span class='textgreen'>Спасибо за визит</span>";
    return false;
}

function fixed(p1, p2, p3)
{
    var myReq = getHTTPRequest();
    var params = "p1="+p1+"&p2="+p2+"&p3="+p3;
    function setstate()
    {
        if ((myReq.readyState == 4)&&(myReq.status == 200)) {
            var resvalue = myReq.responseText;
            if (resvalue != '') {
                if (resvalue.length > 12) {
                    if (elem = document.getElementById(p1)) {
                        elem.style.backgroundImage = 'none';
                        elem.innerHTML = '<a target="_blank" href="/'+resvalue+'" onclick="javascript:goserf(this);">Просмотреть сайт рекламодателя</a>';
                    }
                } else {
                    if (elem = document.getElementById(resvalue)) {
                        $(elem).fadeOut('low', function() {
                            elem.innerHTML = "<td colspan='3'></td>";
                        });
                    }
                }
            }
        }
    }
    myReq.open("POST", "/ajax/us-fixedserf.php", true);
    myReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    myReq.setRequestHeader("Content-lenght", params.length);
    myReq.setRequestHeader("Connection", "close");
    myReq.onreadystatechange = setstate;
    myReq.send(params);
    return false;
}
</script>
<div class="page-content-wrapper ">
  <div class="container">
<div class="row">
      <div class="col-lg-8 col-lg-12">
        <div class="panel panel-default">
          <div class="panel-body">
            <p class="raceinfotext m-b-0">Нажмите по заголовку любой из доступных ссылок, дождитесь окончания таймера и получайте деньги на свой <b>баланс для вывода</b>! Средства заработанные в сёрфинге Вы можете <a href="/outpay">вывести</a> их из проекта любым удобным для Вас способом!</p>
          </div>
        </div>
      </div>
      <div class="col-lg-4 col-lg-12">
        <div class="panel panel-default racerespan1">
          <div class="panel-body text-center">
            <p class="text-muted m-b-10 m-t-0"><code class="profilemsd">Вам необходимы посетители или рефералы?</code></p>
            <button type="button" class="btn waves-effect btn-default" onclick="location.href='/serfing/add';"> <i class="mdi mdi-bullhorn"></i> Разместить сайт в сёрфинге</button>
          </div>
        </div>
      </div>
    </div>
  <?php
  $db->query("SELECT ident, time_add FROM db_serfing_view WHERE user_id = '".$_SESSION['user_id']."' and time_add + INTERVAL 24*60*60 SECOND > NOW()");

  while ($row_view = $db->FetchAssoc())
  {
    $visits[$row_view['ident']] = $row_view;
  }

  $db->Query("SELECT * FROM db_serfing WHERE money >= price and status = '2' ORDER BY high DESC, time_add DESC");

  if ($db->NumRows())
  {
    while ($row = $db->FetchAssoc())
    {
      if (isset($visits[$row['id']])) continue;

      if ($row['speed'] > 1)
      {
        if (mt_rand(1, $row['speed']) != 1) continue;
      }

      $high = ($row['high']) ? 'serfimghigh' : 'serfimg';
      //$pay_user = number_format($row['price'] - $row['price'] * (15/100), 2); //оплата пользователю



      if($row['timer'] == 20){
      $pay_user = 0.025; //оплата пользователю
      }

      if($row['timer'] == 30){
      $pay_user = 0.045; //оплата пользователю
      }

      if($row['timer'] == 40){
      $pay_user = 0.065; //оплата пользователю
      }




      if ($row['country'])
      {
	      $country = explode('|', $row['country']);

	      if ($row['crev'])
	      {
	        if (in_array($_SESSION['country'], $country)) continue; //показывать всем кроме указаных
	      }
	      else
	      {
	        if (!in_array($_SESSION['country'], $country)) continue; //показывать только указаным
	      }
      }

      if ($row['rating'])
      {
        if ($row['rating'] == 1 && $users_info['insert_sum'] > 10)
        {
          continue;
        }

        if ($row['rating'] == 2 && ($users_info['insert_sum'] < 10 && $users_info['insert_sum'] > 100))
        {
          continue;
        }

        if ($row['rating'] == 3 && ($users_info['insert_sum'] < 100 && $users_info['insert_sum'] > 500))
        {
          continue;
        }

        if ($row['rating'] == 4 && ($users_info['insert_sum'] < 500 && $users_info['insert_sum'] > 1000))
        {
          continue;
        }

        if ($row['rating'] == 5 && $users_info['insert_sum'] < 1000)
        {
          continue;
        }
      }
      ?>
       <div class="panel panel-default surfblock<?php echo $row['high']; ?>" id="tr<?php echo $row['id']; ?>">
          <div class="panel-body">
            <div class="surflink">
              <img src="https://www.google.com/s2/favicons?domain=<?php echo $row['url']; ?>">
              <h4 id="<?php echo $row['id']; ?>" class="normalm" valign="top" style="cursor:pointer;">
              <?php echo $row['title']; ?>
              </h4>
              <h6><span class="surftimer"><i class="fa fa-clock-o"></i> Время просмотра: <?php echo $row['timer']; ?> сек.</span><span class="surfprice"><i class="fa fa-money"></i> Оплата: <?php echo $pay_user; ?> руб.</span><span class="surfviewleft">Осталось <?php echo (int)($row['money']/$row['price']); ?> просмотров</span></h6>
            </div>
          </div>
        </div>
      <?php
    }
  }
  else
  {

  }
  ?>
    </div></div>
