<?php

ob_start("ob_gzhandler");
session_start();
if (!isset($_SESSION['uid'])) {
    header("Location: index.php");
}
if (isset($_POST['end'])) {
    header("Location: main.php");
}

include('config.php');
include('functions.php');
include('cave/cave_bots.php');
$cavebots = $botnames;

db::c()->query('LOCK TABLES `bots` WRITE, `laba_obj` WRITE, `qst_user` WRITE, `qst` WRITE, `` WRITE, `battle` WRITE, `logs` WRITE, `users` WRITE, `inventory` WRITE, `magic` WRITE, `effects` WRITE, `online` WRITE, `clans` WRITE, `variables` WRITE, `logs_arena` WRITE, `cavebots` WRITE, `caveparties` WRITE');
if (isset($user['id'])) {
    db::c()->query('UPDATE `online` SET `real_time` = ?i WHERE  `id` = ?i', time(), $user['id']);
}

include('./classes/battle_new.class.php');

$fbattle = new fbattle($user['battle']);
?>
    <html>
    <head>
        <link rel="stylesheet" href="css/main.css">
        <meta charset="utf-8">
        <script type="text/javascript" src="js/ZeroClipboard.js"></script>
        <script type="text/javascript" src="js/sl2.js"></script>
        <script type="text/javascript" src="js/ch.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script src="js/tooltip.js"></script>
        <link rel="stylesheet" type="text/css" href="css/tooltip.css"/>
        <SCRIPT>
            function refreshPeriodic() {
                <?php if($fbattle->battle) { ?>location.href = '<?=$_SERVER['PHP_SELF']?>?batl=<?=$_REQUEST['batl']?>';//reload();
                <?}?>
                var timerID = setTimeout("refreshPeriodic()", 20000);
            }
            timerID = setTimeout("refreshPeriodic()", 20000);
        </SCRIPT>
        <script>
            var Hint3Name = '';

            function findlogin(title, script, name) {
                document.all("hint3").innerHTML = '<table width=100% cellspacing=1 cellpadding=0 bgcolor=CCC3AA><tr><td align=center><B>' + title + '</td><td width=20 align=right valign=top style="cursor: pointer" onclick="closehint3();"><BIG><B>x</td></tr><tr><td colspan=2>' +
                    '<form action="' + script + '" method=POST><table width=100% cellspacing=0 cellpadding=2 bgcolor=FFF6DD><tr><INPUT TYPE=hidden name=sd4 value="6"><td colspan=2>' +
                    'Укажите логин персонажа:<small><BR>(можно щелкнуть по логину в чате)</TD></TR><TR><TD width=50% align=right><INPUT TYPE=text NAME="' + name + '"></TD><TD width=50%><INPUT TYPE="submit" value=" »» "></TD></TR></TABLE></FORM></td></tr></table>';
                document.all("hint3").style.visibility = "visible";
                document.all("hint3").style.left = 100;
                document.all("hint3").style.top = 100;
                document.all(name).focus();
                Hint3Name = name;
            }

            var attack = false;
            var defend = false;

            function check() {
                if ((!attack) || (!defend)) {
                    alert('Блок или удар не выбран.');
                    return false;
                }
                return true;
            }

            function Prv(logins) {
                top.frames['bottom'].window.document.F1.text.focus();
                top.frames['bottom'].document.forms[0].text.value = logins + top.frames['bottom'].document.forms[0].text.value;
            }

            function setattack() {
                attack = true;
            }

            function setdefend() {
                defend = true;
            }

            function refreshPeriodic() {
                <?php if($fbattle->battle) {    ?>location.href = '<?=$_SERVER['PHP_SELF']?>?batl=<?=$_REQUEST['batl']?>'; <? } ?>
                var timerID = setTimeout("refreshPeriodic()", 30000);
            }

            timerID = setTimeout("refreshPeriodic()", 30000);

            function checksubmit() {
                var ajaxload = 1;
                if (ajaxload > 0) {
                    var enemy = <?=$fbattle->enemy;?>;
                    var batl = <?=($user['battle'] ? $user['battle'] : $_REQUEST['batl'])?>;
                    var tac_at = $('input[name=attack]:checked').val();
                    var att = "&attack=" + $('input[name=attack]:checked').val();
                    var def = $('input[name=defend]:checked').val();

                    if (tac_at >= 1 && def >= 1) {
                        $.ajax({
                            url: "fbattle.php",
                            type: "POST",
                            cache: false,
                            data: "batl=" + batl + "&myid=1053012363" + att + "&defend=" + def + "&enemy=" + enemy + "",
                            success: function (html) {
                                $("body").html(html);
                            }
                        });
                    } else {
                        alert('Выберите зону атаки и блока!');
                        $("#at").prop("disabled", false);
                    }
                } else {
                    document.f1.submit();
                }
            }

            $("document").ready(function () {
                $('#refresh').click(function () {
                    $.ajax({
                        url: "fbattle.php",
                        cache: false,
                        success: function (html) {
                            $("body").html(html);
                        }
                    });
                });
                $(".tooltip").tipTip({maxWidth: "auto", edgeOffset: 0, fadeIn: 300, fadeOut: 500});
            });
        </script>
        <style type="text/css">
            span {
                font-family: Verdana, Arial, Helvetica, Tahoma, sans-serif;
                text-decoration: none;
                font-weight: bold;
                cursor: pointer;
            }
        </style>
    </head>
    <body onLoad="top.setHP(<?= $user['hp'] ?>,<?= $user['maxhp'] ?>)">
    <div id="hint3" class="ahint"></div>
    <form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST" name="f1" id="f1">
        <table width=100% cellspacing=0 cellpadding=0 border=0>
            <input type="hidden" value="<?= ($user['battle'] ? $user['battle'] : $_REQUEST['batl']) ?>"
                   name="batl"/><input
                    type="hidden" value="<?= $enemy ?>" name="enemy1"/><input type="hidden" name="myid"
                                                                              value="1053012363"/>
            <tr>
                <td valign=top>
                    <table width=250 cellspacing=0 cellpadding=0>
                        <tr>
                            <td valign=top width=250 nowrap>
                                <?php echo showinf_pers($user['id'], 1, 1); ?>
                            </td>
                        </tr>
                    </table>
                </td>

                <td valign=top width=80%>
                    <?php switch ($fbattle->return) {
                        case 1 :
                            ?>
                            <table width=100% cellspacing=0 cellpadding=0>
                                <tr>
                                    <td colspan=2><h3>Поединок</td>
                                </tr>
                                <tr>
                                    <td><font color=660000><b>Ваш ход</b></td>
                                    <td align=right>&nbsp;</td>
                                </tr>
                            </table>
                            <center>
                                <? if ($user['level'] > 3) {
                                    if (@$_GET['use']) {
                                        $dressed = mysql_fetch_row(mysql_query("SELECT `id` FROM `inventory` WHERE `id` = '" . (int)$_GET['use'] . "' AND `dressed` = 1"));
                                        if ((int)$dressed[0] > 0) {
                                            $my_class = $fbattle->my_class;
                                            ob_start();
                                            usemagic($_GET['use'], "" . $_POST['target']);
                                            $bb = explode("<!--", ob_get_clean());
                                            $bb = str_replace('"', "&quot;", (strip_tags($bb[0])));
                                            header("Location: " . $_SERVER['PHP_SELF'] . "?buf=" . $bb);
                                        } else {
                                            die();
                                        }
                                    }

                                    if ($_GET['buf']) {
                                        echo "<font color=red><b>" . $_GET['buf'] . "</b></font><br />";
                                    }

                                    echoscroll('m1');
                                    echoscroll('m2');
                                    echoscroll('m3');
                                    echoscroll('m4');
                                    echoscroll('m5');
                                    echoscroll('m6');
                                    echoscroll('m7');
                                    echoscroll('m8');
                                    echoscroll('m9');
                                    echoscroll('m10');
                                }
                                ?>
                                <table cellspacing=0 cellpadding=0>
                                    <tr>
                                        <td align=center bgcolor=f2f0f0><b>Атака</b></td>
                                        <td>&nbsp;</td>
                                        <td align=center bgcolor=f2f0f0><b>Защита</b></td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <table cellspacing=0 cellpadding=0>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="A1" name="attack" value="1"
                                                               onclick="setattack()"/><label for="A1">удар в
                                                            голову</label>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="A2" name="attack" value="2"
                                                               onclick="setattack()"/><label for="A2">удар в
                                                            корпус</label>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="A3" name="attack" value="3"
                                                               onclick="setattack()"/><label for="A3">удар в
                                                            пояс(пах)</label>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="A4" name="attack" value="4"
                                                               onclick="setattack()"/><label for="A4">удар по
                                                            ногам</label>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                        <td>&nbsp;</td>
                                        <td>
                                            <table cellspacing=0 cellpadding=0>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="D1" name="defend" value="1"
                                                               onclick="setdefend()"/><label for="D1">блок головы и
                                                            корпуса</label>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="D2" name="defend" value="2"
                                                               onclick="setdefend()"/><label for="D2">блок корпуса и
                                                            пояса</label>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="D3" name="defend" value="3"
                                                               onclick="setdefend()"/><label for="D3">блок пояса и
                                                            ног</label>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <input type="radio" id="D4" name="defend" value="4"
                                                               onclick="setdefend()"/><label for="D4">блок головы и
                                                            ног</label>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=3 align=center bgcolor=f2f0f0>
                                            <table cellspacing=0 cellpadding=0 width=100%>
                                                <tr>
                                                    <td align=center>
                                                        <input type="submit" name="go" value="Ударить!"
                                                               onclick="this.disabled = true; checksubmit(); return false;"
                                                               id="at"/>
                                                    </td><!--checksubmit(); -->
                                                    <td align=right>
                                                        <a onclick="location.href='<?= $_SERVER['PHP_SELF'] ?>?batl=<?= $_REQUEST['batl'] ?>';">
                                                            <img src='i/ico_refresh.gif' width=16 height=19
                                                                 style='cursor:pointer' alt='Обновить'>
                                                        </a>
                                                        <a onClick="findlogin('Сменить противника', 'fbattle.php?smena=1', 'smena'); ">
                                                            <img src='ico_change.gif' width=16 height=19
                                                                 style='cursor:pointer' alt='Сменить противника'>
                                                        </a>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <input type="hidden" name="enemy" value="<?= $fbattle->enemy ?>"/>
                                </TABLE>
                            </CENTER>
                            <?
                            break;
                        case 2 :
                            if (($user['hp'] > 0) && $fbattle->battle) {
                                echo '<center><FONT COLOR=red><b>Ожидаем хода противника...</b></FONT><BR><INPUT TYPE=submit value="Обновить" name=' . (($user['battle'] > 0) ? "battle" : "end") . '><BR></CENTER>';
                            } elseif ($user['hp'] <= 0 && $fbattle->battle) {
                                ref_drop();
                                echo '<center><FONT COLOR=red><b>Ожидаем, пока бой закончат другие игроки...</b></FONT><BR><INPUT TYPE=submit value="Обновить" name=' . (($user['battle'] > 0) ? "battle" : "end") . '><BR></CENTER>';
                            }
                            break;
                        case 3 :
                            echo "<center><BR>Противник долго не делает свой ход, вы можете закончить бой победителем<BR>
					<INPUT TYPE=submit value=\"Да, я победил!!!\" name=victory_time_out id=\"refreshb\"><BR>";
                            if (!$fbattle->user['in_tower'] && $fbattle->user['room'] != 200) {
                                echo "или признать ничью<BR>
					<INPUT TYPE=submit id=\"refreshb\" value=\"Считаем, что этого боя не было\" name=victory_time_out2><BR>";
                            }
                            echo "или<BR>
					<INPUT TYPE=submit value=\"Подождать еще немного\" name=", (($user['battle'] > 0) ? "battle" : "end"), ">
					</center>";
                            break;
                    }

                    if ($enemy == 0) {
                        // проверяем на вшивость
                        if (!$fbattle->battle) {
                            if ($user['battle']) {
                                $ll = $user['battle'];
                            } else {
                                $ll = $_POST['batl'];
                            }
                            if (!$ll) {
                                $ll_r = mysql_fetch_array(mysql_query("SELECT `id` FROM `battle` WHERE (`t1` LIKE '%{$user['id']}%' || `t2` LIKE '%{$user['id']}%') AND `win` = '3' LIMIT 1"));
                                $ll = $ll_r['id'];
                            }
                            $data = @mysql_fetch_array(mysql_query("SELECT * FROM `battle` WHERE `id` = {$ll} LIMIT 1"));
                            $damage = unserialize($data['damage']);
                            $exp = unserialize($data['exp']);
                            if (empty($damage[$user['id']])) {
                                $damage[$user['id']] = 0;
                            }
                            if ($user['caveleader'] > 0 || $user['laba'] > 0) {
                                $rep = floor($damage[$user['id']] / 300);
                                if ($rep <= 0) {
                                    $rep = 0;
                                }
                                $ads = '. Репутации: ' . $rep . ' ед.';
                            } else {
                                $rep = 0;
                                $ads = '.';
                            }

                            echo '<center><br /><b><font color=red>Бой закончен! Всего вами нанесено урона ' . $damage[$user['id']] . ' HP. Получено опыта ' . (int)$exp[$user['id']] . ' (' . check_proc($user['id']) . '%)' . $ads . '</FONT></B><br /><input type="submit" value="Вернуться" name="end" /><br /></center>';
                        }
                    } else {
                        ?>


                        </center>
                    <? }
                    if ($fbattle->battle) {
                        ?>
                        <hr/>
                        <div id=mes>
                            <?
                            foreach ($fbattle->t1 as $k => $v) {
                                if (in_array($v, array_keys($fbattle->battle))) {
                                    ++$i;
                                    if ($i > 1) {
                                        $cc = ', ';
                                    } else {
                                        $cc = '';
                                    }
                                    $ffs .= $cc . nick4($v, "B1");
                                    $zz .= "private [" . nick::id($v)->short() . "] ";
                                }
                            }

                            $i = 0;
                            ?>
                            <img src="i/lock.gif" width="20" height="15" border="0" style="cursor: pointer;"
                                 onclick="Prv('<?= $zz ?> ')"/>
                            <?= $ffs ?>
                            против
                            <?
                            $ffs = '';
                            $zz = '';
                            foreach ($fbattle->t2 as $k => $v) {
                                if (in_array($v, array_keys($fbattle->battle))) {
                                    ++$i;
                                    if ($i > 1) {
                                        $cc = ', ';
                                    } else {
                                        $cc = '';
                                    }
                                    $ffs .= $cc . nick4($v, "B2");
                                    $zz .= "private [" . nick::id($v)->short() . "] ";
                                }
                            }
                            $i = 0;
                            ?>
                            <img src="i/lock.gif" width="20" height="15" border="0" style="cursor: pointer;"
                                 onclick="Prv('<?= $zz ?> ')"/>
                            <?= $ffs ?>
                            <hr/>
                            На данный момент вами нанесено урона: <b><?= (int)$fbattle->damage[$user['id']] ?> HP</b>.
                            <? if (!$user['in_tower']) { ?>
                                <font style="margin-left: 200px;">(Бой идет с
                                    таймаутом <?= $fbattle->battle_data['timeout'] ?> мин.)</font>
                            <? } ?>
                            <br/>
                            <hr/>
                        </div>
                        <?
                    } else {
                        echo "<HR>";
                    }

                    if ($user['battle']) {
                        $ll = $user['battle'];
                    } elseif ($_REQUEST['batl']) {
                        $ll = $_REQUEST['batl'];
                    } else {
                        $ll = $_SESSION['batl'];
                    }

                    if (!$ll) {
                        $ll_r = mysql_fetch_array(mysql_query("SELECT `id` FROM `battle` WHERE (`t1` LIKE '%{$user['id']}%' OR `t2` LIKE '%{$user['id']}%') AND `win` = 3 LIMIT 1"));
                        $ll = $ll_r['id'];
                    }

                    $fs = filesize("backup/logs/battle" . $ll . ".txt");
                    $fh = fopen("backup/logs/battle" . $ll . ".txt", "r");
                    fseek($fh, -4256, SEEK_END);
                    $log[0] = fread($fh, 4256);
                    fclose($fh);
                    $log = explode("<BR>", $log[0]);
                    $ic = count($log) - 2;

                    if ($fs >= 4256) {
                        $max = 1;
                    } else {
                        $max = 0;
                    }

                    for ($i = $ic; $i >= 0 + $max; --$i) {
                        if (eregi("<hr>", $log[$i])) {
                            $log[$i] = str_replace("<hr>", "", $log[$i]);
                            $log[$i] = $log[$i] . "<hr>";
                        }
                        if (eregi(">" . $user['login'] . "</span>", $log[$i])) {
                            $log[$i] = str_replace("<span class=date>", "<span class=date2>", $log[$i]);
                        }
                        if ($ll != 0) {
                            if (eregi("<hr>", $log[$i])) {
                                echo $log[$i];
                            } else {
                                echo $log[$i] . "<br />";
                            }
                        }
                    }
                    unset($ic);

                    if ($max == 1) {
                        ?>
                        Обрезано для уменьшения объема информации. Полную версию смотрите <a
                                href="logs.php?log=<?= $user['battle'] ?>" target="_blank">здесь&raquo;</a>
                        <BR><?
                    }
                    if (!$user['in_tower']) {
                        ?>
                        <font class=dsc>(Бой идет с таймаутом <?= $fbattle->battle_data['timeout'] ?> мин.)</font><BR>
                    <? } ?>
                    <BR>
                    На данный момент вами нанесено урона: <B><?= (int)$fbattle->damage[$user['id']] ?> HP</B>.

                </td>
                <td valign=top align=rigth>
                    <table width=250 cellspacing=0 cellpadding=0>
                        <tr>
                            <td valign=top width=250 nowrap>
                                <center>
                                    <?php

                                    if ($fbattle->return == 1) {
                                        echo showinf_pers($fbattle->enemy, 1);
                                    } else {
                                        if ($fbattle->battle_data['type'] == 4 || $fbattle->battle_data['type'] == 5) {
                                            $a = array(6, 16);
                                            echo "<img src='i/im/" . $a[mt_rand(0, 1)] . ".gif' />";
                                        } elseif ($fbattle->return > 1) {
                                            echo "<img src='i/im/" . mt_rand(1, 34) . ".jpg' />";
                                        } elseif ($exp[$user['id']] > 0) {
                                            echo "<img src='i/im/" . mt_rand(113, 115) . ".jpg' />";
                                        } else {
                                            echo "<img src='i/im/" . mt_rand(110, 112) . ".jpg' />";
                                        }
                                    }

                                    if ($fbattle->needrefresh) {
                                        header("Location: fbattle.php?" . time());
                                    }

                                    if ($fbattle->battle_data['needbb']) {
                                        foreach ($fbattle->battle as $k => $v) {
                                            if ($k > _BOTSEPARATOR_) {
                                                foreach ($v as $k2 => $v2) {
                                                    if ($k2 < _BOTSEPARATOR_) continue;
                                                    $hp_1 = mysql_fetch_array(mysql_query('SELECT `hp` FROM `bots` WHERE `id` = "' . $k . '" LIMIT 1'));
                                                    $hp_2 = mysql_fetch_array(mysql_query('SELECT `hp` FROM `bots` WHERE `id` = "' . $k2 . '" LIMIT 1'));
                                                    if ($fbattle->battle[$k][$k2][0] && $fbattle->battle[$k2][$k][0] && $hp_1['hp'] > 0 && $hp_2['hp'] > 0 && time() - $fbattle->battle[$k][$k2][2] > 1 && time() - $fbattle->battle[$k2][$k][2] > 1) {
                                                        $at_1 = $fbattle->battle[$k][$k2][0];
                                                        $def_1 = $fbattle->battle[$k][$k2][1];
                                                        $at_2 = $fbattle->battle[$k2][$k][0];
                                                        $def_2 = $fbattle->battle[$k2][$k][1];
                                                        $fbattle->makechange($k, $k2, $at_1, $at_2, $def_1, $def_2);
                                                        $fbattle->write_log();
                                                        $fbattle->battle[$k][$k2] = array(0, 0, time());
                                                        $fbattle->battle[$k2][$k] = array(0, 0, time());
                                                        $fbattle->needupdate = 1;
                                                    }
                                                }
                                            }
                                        }
                                        if ($fbattle->needupdate) {
                                            $fbattle->UpdateBattle();
                                        }
                                    }
                                    ?>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>

        </td></tr>
        </table>
    </form>

    <div id="oMenu" onmouseout="closeMenu()"
         style="position: absolute; border: 1px solid #666; background-color: #CCC; display: none; "></div>

    </body>
    </html>
<?php mysql_query("UNLOCK TABLES"); ?>