function monsterkills_run()
{
    page_header("Most Monster Kills");
    $acc = db_prefix("accounts");
    $mp = db_prefix("module_userprefs");
    $sql = "SELECT {$acc}.name AS name,\r\n\t\t{$acc}.acctid AS acctid,\r\n\t\t{$mp}.value AS kills,\r\n\t\t{$mp}.userid FROM {$mp} INNER JOIN {$acc}\r\n\t\tON {$acc}.acctid = {$mp}.userid \r\n\t\tWHERE {$mp}.modulename = 'monsterkills' \r\n\t\tAND {$mp}.setting = 'kills' \r\n\t\tAND {$mp}.value > 0 ORDER BY ({$mp}.value+0)\t\r\n\t\tDESC limit " . get_module_setting("list") . "";
    $result = db_query($sql);
    $rank = translate_inline("Kills");
    $name = translate_inline("Name");
    output("`n`b`c`@Most`\$ Monster `@Kills`n`n`c`b");
    rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center'>");
    rawoutput("<tr class='trhead'><td align=center>{$name}</td><td align=center>{$rank}</td></tr>");
    for ($i = 0; $i < db_num_rows($result); $i++) {
        $row = db_fetch_assoc($result);
        if ($row['name'] == $session['user']['name']) {
            rawoutput("<tr class='trhilight'><td>");
        } else {
            rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td align=left>");
        }
        output_notl("%s", $row['name']);
        rawoutput("</td><td align=right>");
        output_notl("%s", $row['kills']);
        rawoutput("</td></tr>");
    }
    rawoutput("</table>");
    addnav("Back to HoF", "hof.php");
    villagenav();
    page_footer();
}
function dwellings_run()
{
    checkday();
    page_header("Dwellings");
    global $session;
    $op = httpget("op");
    $dwid = httpget('dwid');
    $type = httpget('type');
    debug(get_module_pref("location_saver"));
    if ($type == "" && $dwid > 0) {
        $sql = "SELECT type FROM " . db_prefix("dwellings") . " WHERE dwid={$dwid}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $type = $row['type'];
    }
    $cityid = httpget('cityid');
    require_once "modules/dwellings/run/case_{$op}.php";
    if ($op != "list" && $op != "") {
        addnav("Leave");
        addnav("Return to Hamlet", "runmodule.php?module=dwellings");
    } else {
        addnav("Navigation");
        villagenav();
    }
    page_footer();
}
function forest($noshowmessage = false)
{
    global $session, $playermount;
    tlschema("forest");
    //	mass_module_prepare(array("forest", "validforestloc"));
    addnav("Heal");
    addnav("H?Hospital Tent", "healer.php");
    addnav("Fight");
    addnav("L?Look for Something to Kill", "forest.php?op=search");
    if ($session['user']['level'] > 1) {
        addnav("S?Go Slumming", "forest.php?op=search&type=slum");
    }
    addnav("T?Go Thrillseeking", "forest.php?op=search&type=thrill");
    if (getsetting("suicide", 0)) {
        if (getsetting("suicidedk", 10) <= $session['user']['dragonkills']) {
            addnav("*?Search `\$Suicidally`0", "forest.php?op=search&type=suicide");
        }
    }
    if ($session['user']['level'] >= 15 && $session['user']['seendragon'] == 0) {
        // Only put the green dragon link if we are a location which
        // should have a forest.   Don't even ask how we got into a forest()
        // call if we shouldn't have one.   There is at least one way via
        // a superuser link, but it shouldn't happen otherwise.. We just
        // want to make sure however.
        $isforest = 0;
        $vloc = modulehook('validforestloc', array());
        foreach ($vloc as $i => $l) {
            if ($session['user']['location'] == $i) {
                $isforest = 1;
                break;
            }
        }
        if ($isforest || count($vloc) == 0) {
            addnav("G?`@Seek Out the Green Dragon", "forest.php?op=dragon");
        }
    }
    addnav("Other");
    villagenav();
    if ($noshowmessage != true) {
        output("`c`7`bThe Forest`b`0`c");
        output("The Forest, home to evil creatures and evildoers of all sorts.`n`n");
        output("The thick foliage of the forest restricts your view to only a few yards in most places.");
        output("The paths would be imperceptible except for your trained eye.");
        output("You move as silently as a soft breeze across the thick moss covering the ground, wary to avoid stepping on a twig or any of the numerous pieces of bleached bone that populate the forest floor, lest you betray your presence to one of the vile beasts that wander the forest.`n");
        modulehook("forest-desc");
    }
    modulehook("forest", array());
    module_display_events("forest", "forest.php");
    addnav("Inventory");
    addnav("View your Inventory", "inventory.php?items_context=forest");
    tlschema();
}
function strategyhut_run()
{
    global $session;
    $cost = get_module_setting("cost");
    $op = httpget("op");
    page_header("The Strategy Hut");
    output("`5`c`bThe Strategy Hut`b`c");
    if ($op == "") {
        addnav(array("Ask for Advice (`^%s gold`0)", $cost), "runmodule.php?module=strategyhut&op=ask");
        output("`&You enter the hut, to find `6Atrus `&busy at his desk.");
        output("\"`^Well, a young warrior in search of help!");
        output("For a small fee, I will offer advice to you.`3\"`n`n");
        output("`&Hesitantly, you approach the burly warrior.`n`n");
        output("`&You blink a few times before you realize he was actually talking to you.");
        output("`6Atrus `&doesn't seem very patient, so you'd better decide quickly if you want to hear his advice!`n");
    } elseif ($session['user']['gold'] < $cost) {
        output("`&You go through your pockets, searching for money, but you don't have enough.");
        output("After a moment of intense searching, `6Atrus `&starts to scowl, and you decide to leave before he gets annoyed.`n`n");
    } else {
        $session['user']['gold'] -= $cost;
        debuglog("spent {$cost} gold at the strategy hut");
        output("`&You give `6Atrus `^%s gold`7.", $cost);
        output("`&He nods, and thinks for a moment.`n`n");
        $phrases = array("\"`^Heal often, bank often.`3\"", "\"`^Think balance: weapons and armor must be close in level, not enough defense and your first attack will be your last.`3\"", "\"`^Don't be afraid to slum, in the lower DK levels, speed is NOT a priority. Later is different.`3\"", "\"`^That stat bar is your life, when it gets into the yellow zone, heal. When it goes red, pray.`3\"", "\"`^In PvP, pick your targets with care. If not sure, DON'T... or you'll be explaining to {deathoverlord}`^ what happened.`3\"", "\"`^You don't always need to resurrect. There will be times to save favor for emergencies.`3\"", "\"`^If it's a game bug, petition it. If it's a gameplay issue, petition it.`3\"", "\"`^A good offense is not always a good defense, even the strongest players die in the forest.`3\"", "\"`^Confidence is one thing: attacking a God is suicide. Check the bio first.`3\"", "\"`^Keep an open mind and think it through. Only a fool fights blindly.`3\"", "\"`^There is a dragon, and when you are ready, it will be too. Patience.`3\"", "\"`^Travelling between towns can be dangerous. Heal first.`3\"", "\"`^Talk to everyone in all the villages, visit the shops and stalls. Explore. Learn.`3\"", "\"`^Lower DK players die often in the beginning. It happens to all of us.`3\"", "\"`^When you face the dragon, be ready and fully healed... or it will eat you for lunch.`3\"", "\"`^Your mount or familiar is an asset... learn what it can do, and know its limits. *And* yours, as well.`3\"", "\"`^There is no shame in knowing when to run. Better a bruised ego than a visit to {deathoverlord}`^.`3\"", "\"`^Log in ONCE per game day only, or you will be killed repeatedly... and lose experience as a result. There is no safe place.`3\"", "\"`^If you can't resurrect, log off and wait for New Day. You are already dead.`3\"", "\"`^A good player treats his fellows with courtesy and respect. A wise player knows that new friends can help him succeed.`3\"", "\"`^Don't forget to feed your mount or familiar.`3\"");
        $question = e_rand(0, count($phrases) - 1);
        $phrases = translate_inline($phrases);
        $myphrase = $phrases[$question];
        $myphrase = str_replace('{deathoverlord}', getsetting('deathoverlord', '`$Ramius'), $myphrase);
        output_notl("%s`n`n", $myphrase);
        output("`&You ponder his advice for a moment, before thanking him and making your exit.`n`n");
        if (is_module_active("medals")) {
            require_once "modules/medals.php";
            medals_award_medal("strategyhut", "Strategy Seeker", "This player asked for help in the Strategy Hut.", "medal_strategy.png");
        }
    }
    villagenav();
    page_footer();
}
function kissingbooth_run()
{
    global $session;
    require_once "lib/villagenav.php";
    $gardens = get_module_setting("gardens");
    $smackloss = get_module_setting("smackloss");
    $cost = get_module_setting("cost");
    $totalcost = $cost * $session['user']['level'];
    page_header("The Kissing Booth");
    $op = httpget('op');
    $kissedtoday = get_module_pref("kissedtoday");
    $kissee = get_module_pref("kissee");
    output("`c`b`QThe `\$Kissing`Q Booth`0`b`c`n");
    if ($op == "") {
        while ($kissee == "") {
            $guys = array(getsetting("barkeep", '`tCedrik'), "`!Lonestrider", "`@JR`3Min`!ga", "`6Smiythe", getsetting("bard", "`^Seth"), "`&Oliver", "`#MightyE", "`%Kendaer");
            $girls = array("`)Heidi", "`7Petra", "`QSaucy`\$Wench", "`@Foil`&wench", getsetting('barmaid', "`%Violet"), "`^Ella");
            if ($session['user']['sex'] != SEX_MALE) {
                $kissee = $guys[e_rand(0, count($guys) - 1)];
            } else {
                $kissee = $girls[e_rand(0, count($girls) - 1)];
            }
            set_module_pref("kissee", $kissee);
        }
        // will change this if it's in a town (which town? romar? glorfy?
        // d'burg? rather than a special area (carnival, esoterron (ew!))
        output("`QYou walk towards the booth marked \"`@LOGD Kissing Booth`Q\".`n");
        output("`QThere seems to be a decent line, possibly because %s`Q is behind the booth today!`n", $kissee);
        if (!$kissedtoday) {
            output("`QYou find yourself shuffled into the line, which seems to suddenly be moving fairly quickly.`n");
            output("`QFinally, you reach the front!");
            output("`QYour eyes dart to the jar marked \"`@Donations`Q\", and then meet the gaze of %s`Q, who looks up at you expectantly.`n", $kissee);
            if ($totalcost > $session['user']['gold']) {
                output("`!You can't afford the donation at the moment.");
                output("%s`! smiles at you sadly as you slink off, dejected.", $kissee);
                if ($gardens) {
                    addnav("G?Return to the Gardens", "gardens.php");
                } else {
                    villagenav();
                }
            } else {
                output("`QWhat will you do?");
                addnav(array("Make donation (%s gold)", $totalcost), "runmodule.php?module=kissingbooth&op=stay");
                addnav("Chicken out", "runmodule.php?module=kissingbooth&op=flee");
            }
        } else {
            output("`Q`nYou know, that line seems really long, and you've already taken your turn today.`n");
            output("`QMaybe you should wait until later, and let somebody else have their fun.");
            if ($gardens) {
                addnav("G?Return to the Gardens", "gardens.php");
            } else {
                villagenav();
            }
        }
    } elseif ($op == "flee") {
        output("`#You freeze with embarrasment at the thought of kissing %s`#.`n", $kissee);
        output("`#After about a minute has passed and you're still standing there stammering, %s`# sighs and beckons the person behind you to come forward and take your place.`n", $kissee);
        output("`#A helper gently takes you aside and seats you under a nearby tree to recover.");
        if ($gardens) {
            addnav("Leave", "gardens.php");
        } else {
            addnav("Leave", "village.php");
        }
    } elseif ($op == "stay") {
        set_module_pref("kissedtoday", 1);
        $session['user']['gold'] -= $totalcost;
        if ($session['user']['sex'] != SEX_MALE) {
            $heshe = "he";
            $Cheshe = "He";
            // "capital he/she." capital idea, wot?
            $hisher = "his";
        } else {
            $heshe = "she";
            $Cheshe = "She";
            $hisher = "her";
        }
        $rnd = e_rand(1, 16);
        switch ($rnd) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                //charm++ (1-5)
                output("`6You drop the coins in the jar.`n");
                output("%s`6 leans forward and kisses you gently on the lips.", $kissee);
                output("{$Cheshe} holds it slightly longer than you expected and pulls back with an impressed look on {$hisher} face.`n");
                output("\"`#Not bad`6\", {$heshe} says, \"come back anytime!\"`n");
                output("You blush slightly, but find a new confidence in your step as you walk away.`n");
                output("You feel `\$charming`6!");
                $session['user']['charm']++;
                break;
            case 6:
            case 7:
            case 8:
            case 9:
                //hp++ (6-9) (tee hee)
                output("`6Stepping forward, you deposit your coins in the jar.`n");
                output("%s`6 leans forward and kisses you softly but warmly.`n", $kissee);
                output("`6The warmth floods your body, and eases your pain.`n");
                output("%s`6 smiles and waves as you wander off.", $kissee);
                if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                    $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
                } else {
                    $session['user']['hitpoints'] = $session['user']['hitpoints'] * 1.1;
                }
                break;
            case 10:
            case 11:
            case 12:
                //ff++ (10-12)
                output("`6You place your donation in the jar.`n");
                output("%s`6's eyes light up as you approach, and {$heshe} kisses you with enthusiasm.`n", $kissee);
                output("`6You feel an energy spread throughout your entire body, making you `^tingle!`n`n");
                output("`6As you walk away, you feel a light tap on your bottom!`n");
                output("`6You turn around to see %s`6 winking at you! \"`#Go get 'em, tiger!`6\", {$heshe} says.`n", $kissee);
                output("`6The tingling fills you, and you feel enthusiastic about life in general!  You gain some Stamina`n");
                $session['user']['turns']++;
                if (is_module_active("medals")) {
                    require_once "modules/medals.php";
                    medals_award_medal("goodkiss", "Really Awesome Kiss", "This player received a totally awesome kiss at the Kissing Booth!", "medal_kissingbooth.png");
                }
                break;
            case 13:
            case 14:
                //charm-- (13-14)
                output("`6You eagerly place your donation in the jar and rush forward to kiss %s.`n", $kissee);
                output("`6However, in your enthusiasm, you fumble the kiss and end up bumping noses!`n");
                output("`6You look up and see nearby people trying to stifle giggles!`n");
                output("`6You wander off, feeling somewhat embarrassed.`n`n");
                output("`6However, looking down as you walk off, you spot something `#shiny`6 in the dust!`n");
                output("`QYou lose charm, but you gain a gem!`n");
                if ($session['user']['charm'] > 0) {
                    $session['user']['charm']--;
                }
                $session['user']['gems']++;
                debuglog("gained a gem at the kissing booth");
                break;
            case 15:
                //hp-- (15)
                output("`6You drop your coins in the jar and reach forward to kiss %s.`n", $kissee);
                output("`6\"`#Hey! Not so hard!`6\", {$heshe} yells, and smacks you across the face!`n");
                $loss = round($session['user']['maxhitpoints'] * ($smackloss / 100), 0);
                if ($loss >= $session['user']['hitpoints']) {
                    $loss = $session['user']['hitpoints'] - 1;
                }
                output("`QYou `\$lose %s `Q hitpoints!`n", $loss);
                $session['user']['hitpoints'] -= $loss;
                if ($session['user']['hitpoints'] <= 0) {
                    $session['user']['hitpoints'] = 1;
                }
                break;
            case 16:
                //ff-- (16)
                output("`6As you walk forward and place your donation in the jar, your foot finds a banana peel thrown by an errant reveller.`n");
                output("`6You attempt to maintain your balance, but pitch forward and hit your head on one of the posts holding up the booth!`n");
                output("`6When you come to, %s`6 is cradling your head in {$hisher} lap.`n", $kissee);
                output("{$Cheshe} `6bends down and kisses you on the forehead, and sets you on your feet.`n");
                if ($session['user']['turns'] > 0) {
                    output("`QYou `\$lost`Q some Stamina!`n");
                    $session['user']['turns']--;
                }
                break;
        }
        if ($gardens) {
            addnav("G?Return to the Gardens", "gardens.php");
        } else {
            villagenav();
        }
    }
    page_footer();
}
function ella_run()
{
    global $session;
    $op = httpget("op");
    require_once "lib/partner.php";
    $partner = get_partner();
    $candance = get_module_pref("candance");
    $dkhp = 0;
    while (list($key, $val) = each($session['user']['dragonpoints'])) {
        if ($val == "hp") {
            $dkhp++;
        }
    }
    $maxhitpoints = 10 * $session['user']['level'] + $dkhp * 5;
    suspend_temp_stats();
    if ($session['user']['maxhitpoints'] < $maxhitpoints + get_module_setting("hitpointcost")) {
        $notenough = true;
    } else {
        $notenough = false;
    }
    restore_temp_stats();
    page_header("Dance Studio");
    output("`&`c`bLady Ella's Dance Studio`b`c");
    if (!$candance) {
        output("`7Your muscles are still too stiff and sore from your last lesson.`n");
        output("`7Perhaps in a day or so, you'll feel up to another lesson.");
    } elseif ($notenough) {
        output("`7You don't feel like you could take a lesson with Ella today.`n");
        output("`7Perhaps if your constitution has risen a bit.");
    } elseif ($op == "") {
        output("`7A statuesque teacher in intricately-beaded garb stands at one end of a small studio, intently watching the movements of the  dancers in the room.");
        output("Partnered and solo dancers sway and spin in fast rhythms, matching their movements to the piano that sings from one side of the room, where a delicate Felyne moves her paws to create the sound.`n`n");
        output("Noting your interest, Lady Ella smiles at you as she walks towards you.`n`n");
        output("\"`&Lovely movement, everyone, keep going, I'll have you all as polished performers yet!`7\"`n`n");
        output("`7She approaches you and beckons you into her office.");
        $cost = get_module_setting("turncost");
        if ($session['user']['turns'] >= $cost) {
            output("Once there, she explains what she can offer.");
            output("\"`&You'll like our lessons very much.");
            output("We pride ourselves in making sure it's fun AND helpful.");
            output("Who knows, you might land the %s of your dreams!`n`n", translate_inline($session['user']['sex'] ? "man" : "girl"));
            output("Now, it takes a lot of time and effort to learn to dance, so you can't expect to have nearly as much time for galivanting around the forest.");
            if ($session['user']['sex']) {
                output("So, are you sure you want to make that commitment and learn to make the men chase you?`7\"");
            } else {
                output("So, are you sure you want to make that commitment and learn to sweep the ladies off their feet?`7\"");
            }
            output("`qYou realize she's asking for a sacrifice of time you would normally spend hunting in the forest.");
            output("`qYou ponder for a moment on whether you want to make that large a commitment.");
            addnav(array("Take Lesson (%s %s)", $cost, translate_inline($cost == 1 ? "turn" : "turns")), "runmodule.php?module=ella&op=dance");
        } else {
            output("Once there, she regards you gravely.");
            output("\"`&Darling, there's nothing I love more than teaching someone the love of the dance.");
            output("I'd be more than happy to let you watch, but by the looks of how tired out you are, you'd fall over from the exertion of actually dancing with us today.`7\"`n`n");
            output("You nod your understanding, that you perhaps need more free time to get the most out of the strenuous training she has to offer.");
        }
    } else {
        output("`7You agree to take a dancing lesson today, and eagerly move forward to join the other dancers.`n`n");
        output("The music begins slowly, giving you the chance to start gradually, but it quickly becomes difficult and tiring.");
        output("You're not sure how impressed %s`7 would be with your efforts, but you're determined not to give up too easily.`n`n", $partner);
        output("After the lesson concludes, you feel weary, and wonder whether you have the strength to keep this up for many weeks to come.");
        output("You sure hope %s`7 appreciates your efforts today.`n`n", $partner);
        output("You feel `5charming!`n");
        $turncost = (int) get_module_setting("turncost");
        $hitpointcost = (int) get_module_setting("hitpointcost");
        if ($turncost > 0 && $hitpointcost > 0) {
            output("Your efforts had their price.");
            output("You feel a little tired and not that enduring anymore.");
        } else {
            if ($turncost > 0) {
                output("Your efforts had their price.");
                output("You feel a little tired.");
            } else {
                if ($hitpointcost > 0) {
                    output("Your efforts had their price.");
                    output("You feel not that enduring anymore.");
                }
            }
        }
        debuglog("lost {$turncost} turns and {$hitpointcost} maxhitpoints for taking a dancing lesson.");
        $session['user']['turns'] -= $turncost;
        $session['user']['maxhitpoints'] -= $hitpointcost;
        if ($session['user']['maxhitpoints'] < $session['user']['level'] * 10) {
            $session['user']['maxhitpoints'] = $session['user']['level'] * 10;
        }
        $session['user']['charm'] += get_module_setting("charmgain");
        set_module_pref("candance", 0);
        $danceday = get_module_setting("danceday");
        set_module_pref("dayswait", $danceday);
    }
    villagenav();
    page_footer();
}
function villhut_run()
{
    global $session;
    $op = httpget('op');
    $eattoday = get_module_pref("eattoday");
    $turn = e_rand(1, 8);
    page_header("Villager's Hut");
    output("`&`c`bThe Villager's Hut`b`c");
    if ($eattoday >= 3) {
        output("`7`nYou walk towards the hut again, but your stomach can't bear the thought of more of those sweets today!`n`n");
        $turn = 2;
    } elseif ($op == "") {
        $turn = 2;
        output("`7You walk towards the well-lit front porch of the house, wondering at the lovely colored lights in the windows.`n`n");
        output("As you get to the door, there's a bowl filled with bags of sweets, and a note.`n`n");
        output("`7\"`%Hello Children!`7\" it reads.`n`n");
        output("`7\"`%Please help yourselves to a bag!`7\"`n`n");
        output("You stand there for a moment, wondering what to do.");
        output("The residents obviously aren't home.`n`n");
        output("How many bags should you take?`n`n");
        addnav("Eat 1", "runmodule.php?module=villhut&op=1");
        addnav("Eat 2", "runmodule.php?module=villhut&op=2");
        addnav("Eat 3", "runmodule.php?module=villhut&op=3");
        addnav("Eat 4", "runmodule.php?module=villhut&op=4");
    } elseif ($op == "3") {
        output("`7A shout emerges from the shadows nearby.`n`n");
        output("\"`%You greedy pig!`7\" it screams.`n`n");
        output("The next thing you realize, you're sopping wet, and `QSaucy`\$Wench `7is standing there with an empty bucket in her hands.`n`n");
        output("You feel miserable, and `4lose `7some hitpoints.`n`n");
        $session['user']['hitpoints'] = $session['user']['hitpoints'] * 0.85;
        if ($session['user']['hitpoints'] < 1) {
            $session['user']['hitpoints'] = 1;
        }
        $eattoday += 3;
        $turn = 2;
        set_module_pref("eattoday", $eattoday);
    } elseif ($op == "4") {
        output("`7A shout emerges from the shadows nearby.`n`n");
        output("\"`%You greedy pig!`7\" it screams.`n`n");
        output("You flee in terror, jumping over some thorn bushes as you run, and your arms and legs are ripped painfully.`n`n");
        output("You finally make it to the village square, only to trip onto your face in a most embarrassing manner.`n`n");
        output("You flush in shame, and `4lose `7some hitpoints and some charm.`n`n");
        $session['user']['hitpoints'] = $session['user']['hitpoints'] * 0.65;
        if ($session['user']['hitpoints'] < 1) {
            $session['user']['hitpoints'] = 1;
        }
        if ($session['user']['charm'] > 0) {
            $session['user']['charm']--;
        }
        $eattoday += 4;
        $turn = 2;
        set_module_pref("eattoday", $eattoday);
    } elseif ($op == "1") {
        output("`7You help yourself to a bag and begin to eat as you walk away.`n`n");
        output("You feel `@healthy!`n`n");
        $session['user']['hitpoints'] = max($session['user']['hitpoints'] + 3, $session['user']['hitpoints'] * 1.02);
        $eattoday += 1;
        set_module_pref("eattoday", $eattoday);
        if ($eattoday > 0 && $eattoday < 3) {
            addnav("M?Return for More", "runmodule.php?module=villhut");
        }
    } elseif ($op == "2") {
        output("`7You snatch two bags and greedily begin to eat as you walk away.`n`n");
        output("You feel `@healthy!`n`n");
        $session['user']['hitpoints'] = max($session['user']['hitpoints'] + 5, $session['user']['hitpoints'] * 1.03);
        $eattoday += 2;
        set_module_pref("eattoday", $eattoday);
        if ($eattoday > 0 && $eattoday < 3) {
            addnav("M?Return for More", "runmodule.php?module=villhut");
        }
    }
    if ($turn == 1) {
        output("`7Swallowing the last sweet, you realize there was something unusual mixed in with the mountain of sugar.`n`n");
        output("You feel `@energized!`n`n");
        $session['user']['turns'] += 2;
    }
    villagenav();
    page_footer();
}
function oldchurch_run()
{
    global $session;
    page_header("Old Church");
    $op = httpget('op');
    $bloodgift = get_module_pref("bloodgift");
    if ($bloodgift == 1) {
        output("`7As you approach the old church, you are beset with troubling flashes of what happened last time you were here.");
        output("`n`nYou decide to come back another day.");
        villagenav();
    } elseif ($op == "") {
        output("`7An ancient church stands alone, apart from the other buildings, centuries-old scorchmarks marring the once grand walls and curling round the belltower.");
        output("`n`nA thin path winds its way up the hill between sinister-looking memorials covered in mist.");
        output("While the church has obviously been abandoned for a long time, the windows flicker with light from the inside and shadows can be seen dancing on the tall broken shards of glass which fill the windows.");
        addnav("Enter the Church", "runmodule.php?module=oldchurch&op=enter");
        addnav("Return to the Village", "village.php");
    } elseif ($op == "enter") {
        output("`3You make your way up the hill and edge through the sundered doors, taking in the wrecked interior.");
        output("A flickering torch inhabits an iron holder to one side, above a dusty font.");
        output("Beyond the shattered pews lies an altar which has fresh cloths on it and six candles burning dimly.`n`n");
        output("From out of a small door to one side of the altar walks a curiously hearty figure dressed in grey robes who, ignoring the desolate surroundings, opens his arms wide and bids you welcome to the church, \"`^Greetings, greetings, welcome to this little sanctuary. I am `5Capelthwaite`^, and it is good to see people once again visiting this holy place, feel free to look around. My apologies for the current... disarray... but the world is as the Gods decree it, and we must merely live with such things.`3\"");
        output("He casts an appraising eye over you and smiles even more broadly before continuing,");
        output("\"`^Naturally we are always in need of funds for various charitable projects, and if you wish to donate you will of course gain an appropriate reward.");
        output("For those as hardy an adventurer as you there are obviously other ways to earn a blessing if you are short of funds.`3\"");
        output("He smiles to himself and waits at the altar for your decision.");
        addnav("Climb to the Belfry", "runmodule.php?module=oldchurch&op=belfry");
        addnav("Examine the Font", "runmodule.php?module=oldchurch&op=font");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "belfry") {
        output("`7You walk to the back of the church and climb the unsteady steps up to the belfry, where a large rusted bell hangs from rotting timbers.");
        output("Though you'd expect to get a great view from up here, even the nearby buildings seem shrouded in fog.");
        $random = e_rand(1, 3);
        if ($random >= 2) {
            output("`n`nAs you hurry down from the belfry, you accidentally knock into the bell, which makes an eerily resonant sound as it tolls.");
        }
        output("Spooked slightly, you hurry down the stairs and back into the church.");
        addnav("Examine the Font", "runmodule.php?module=oldchurch&op=font");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "font") {
        output("`\$As you wander over to the alcove by the door and look inside, there seem to be dark stains inside the font, as though it was not usually used for water.");
        output("`n`n`^Slightly troubled by this, you return to the main part of the church.");
        addnav("Climb to the Belfry", "runmodule.php?module=oldchurch&op=belfry");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "donate") {
        output("`5Capelthwaite `^grins as you walk over to the donation plate, waiting to see how much you will put in before making any preparations.");
        $donate = array("donation" => "Donation,int");
        require_once "lib/showform.php";
        rawoutput("<form action='runmodule.php?module=oldchurch&op=afterdonate' method='POST'>");
        showform($donate, array(), true);
        addnav("", "runmodule.php?module=oldchurch&op=afterdonate");
        $give = translate_inline("Give Money");
        rawoutput("<input type='submit' class='button' value='{$give}'>");
        rawoutput("</form><br>");
        addnav("Change your mind", "runmodule.php?module=oldchurch&op=enter");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "afterdonate") {
        $donation = httppost('donation');
        if ($donation > $session['user']['gold'] || $donation < 0) {
            output("`5Capelthwaite `^looks somewhat grim as you try to persuade him that it is the spirit of giving which counts.`n`n");
            output("You are hastily ejected from the church.");
        } elseif ($donation >= $session['user']['level'] * 103) {
            output("`^As you put a hefty amount of gold in the bowl, `5Capelthwaite`^'s grin widens and he beckons you over to the altar for a blessing.");
            output("`n`nAfter muttering something a little too fast for you to catch, he places his hand on your head and blesses you.");
            output("`n`n`@You feel energy flowing through you!");
            $session['user']['gold'] -= $donation;
            debuglog("donated {$donation} gold at the old church");
            $donated = get_module_pref("donated");
            apply_buff('capelthwaite_blessing', array("name" => "`5Capelthwaite's Blessing", "rounds" => 15, "wearoff" => "The burst of energy passes.", "atkmod" => $donated ? 1.05 : 1.2, "defmod" => $donated ? 1.01 : 1.1, "roundmsg" => "Energy flows through you!", "schema" => "module-oldchurch"));
            output("Filled with energy you stumble out of the church.");
            set_module_pref("donated", 1);
        } else {
            output("`^As the few coins you decided to spare rattle into the bowl, `5Capelthwaite`^'s grin turns sickening as he beckons you over to the altar.`n`n");
            output("After muttering something too low for you to catch, he places his hand on your head and places the enchantment on you.`n`n");
            output("`4Dark energy flows through you!");
            apply_buff('capelthwaite_curse', array("name" => "`5Capelthwaite's \"Blessing\"", "rounds" => 10, "wearoff" => "The burst of energy passes.", "atkmod" => 0.8, "defmod" => 0.9, "roundmsg" => "Dark Energy flows through you!", "schema" => "module-oldchurch"));
            output("Filled with energy you stumble out of the church.");
            $session['user']['gold'] -= $donation;
            debuglog("donated {$donation} gold at the old church");
            set_module_pref("donated", 1);
        }
        villagenav();
    } elseif ($op == "ritual") {
        output("`3You nervously inquire about another way that you could earn a blessing as `5Capelthwaite`3 looks on you magnanimously.`n`n");
        output("\"`^No need to be so nervous my friend, simply a short rite to honour the master, you'll feel fine the next day. Just take this potion and I'll take care of everything.`3\".`n`n");
        output("He holds out a small black potion he produced from somewhere for you to drink and smiles encouragingly.");
        addnav("Take the Potion", "runmodule.php?module=oldchurch&op=darkritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "darkritual") {
        output("`^Trusting in `5Capelthwaite`^'s friendly smile, you drink down the potion. You feel funny for a moment, then the world begins to swim before your eyes, and you black out.`n`n");
        $ritual = e_rand(1, 100);
        if ($ritual >= 100) {
            output("`7Though the potion sapped all will from your body, you remain conscious as you are dragged somewhere, hooded, by several people.");
            output("When the hood is removed you are in a cavern deep underground, trapped in what looks like some artist's rendition of the underworld.");
            output("You are dressed in a grey robe and placed on the edge of a smoke-filled circle with many others similarly outfitted.");
            output("For what seems like hours you are surrounded by chanting, smoke and the sensation of life being drained from your very soul.");
            output("Eventually you are dragged back up through some tunnels like a sack of grain before being dumped in front of the altar, where `5Capelthwaite`7 feeds you another potion.`n`n");
        } else {
            output("You dream of smoke and a glowing light.`n`n");
        }
        output("`^You regain your faculties with `5Capelthwaite`^ leaning over you, looking red-faced.");
        output("He quickly blesses you before helping you out of the church.`n`n");
        output("`@You feel energy flowing through you!`n`n");
        apply_buff('capelthwaite_blessing', array("name" => "`5Capelthwaite's Blessing", "rounds" => 15, "wearoff" => "The burst of energy passes.", "atkmod" => 1.2, "defmod" => 1.1, "roundmsg" => "Energy flows through you!", "schema" => "module-oldchurch"));
        output("You hurry away from this place as fast as your unsteady legs can take you.");
        $ritualenergy = get_module_setting("ritualenergy");
        $ritualenergy++;
        set_module_setting("ritualenergy", $ritualenergy);
        set_module_pref("bloodgift", 1);
        if ($session['user']['turns'] >= 5) {
            $session['user']['turns']--;
        }
        $session['user']['hitpoints'] *= 0.5;
        if ($session['user']['hitpoints'] < 1) {
            $sesson['user']['hitpoints'] = 1;
        }
        villagenav();
    }
    page_footer();
}
function proveyourself_run()
{
    global $session, $badguy, $battle;
    $op = httpget('op');
    page_header("Nightmare Court");
    switch ($op) {
        case "start":
            output("You head inside a large warehouse-type building.  A black-robed Mutant in a small reception area notices you and steps forward.  \"`4Welcome,`0\" he says, spreading his three misshapen arms dramatically.  \"`4This is a place where all of my kind will one day come to face their deepest fears.`0\"`n`nAh, the Obligatory Drama.  You nod and smile patiently as he explains.`n`n\"`4In this place, we teach how to accept one's limitations, and how to face and fight one's nightmares regardless.  It's a deeply intense and spiritual experience`0\"`n`n\"`#How much?`0\" you ask.`n`n\"`4Ah, the unfortunate topic of coin, how sadly necessary in a world obsessed with material wealth...`0\"`n`n\"`#`iHow much.`i`0\"`n`n\"`4It'll cost you a cigarette.`0\"`n`n\"`#Right, then.`0\"`n`n");
            if (!get_module_pref("playedtoday") && $session['user']['gems'] && $session['user']['hitpoints'] >= $session['user']['maxhitpoints']) {
                addnav("What will you do?");
                addnav("Fight", "runmodule.php?module=proveyourself&op=enter");
                addnav("Flee", "village.php");
            } else {
                if (get_module_pref("playedtoday")) {
                    addnav("You've already played today");
                    addnav("Back to the Outpost", "village.php");
                } else {
                    if (!$session['user']['gems']) {
                        addnav("You don't have a Cigarette handy");
                        addnav("Back to the Outpost", "village.php");
                    } else {
                        if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                            addnav("You need to heal up first");
                            addnav("Back to the Outpost", "village.php");
                        }
                    }
                }
            }
            break;
        case "enter":
            output("You drop your cigarette into an unnecessarily ornate box, and the Mutant ushers you through a wooden door and into the mouth of a long, dark, red-carpeted corridor.`n`n\"`4Drink this,`0\" he says, passing you a simple wooden goblet filled with a sticky-looking fluid.  You sniff cautiously, then drink.  It tastes of dust and steel.`n`n\"`4Now remember; nothing in here can hurt you unless you allow it to.`0\"  His voice drops to a whisper as he presses a battery-operated torch into your hand.  \"`4Good luck.`0\"`n`nThe door closes gently behind him, and a faint `iclick`i is heard.`n`nYou flick on the torch and take a few steps away from the single overhead lamp.`n`nYou begin the long walk down the corridor.  Before long the red carpet runs out, leaving you walking on a bare concrete floor.`n`nAs you proceed further away from the light, the corridor becomes narrower, and cracks appear every few feet in the plaster.  Another half a minute of putting one foot in front of the other, and you look down to find that you're now walking on steel treadplate.`n`nYou mark off the cracks in the walls as you proceed, noting their increasing frequency.  Within another minute, the walls are crumbling away to reveal a cold chain-link fence, behind which, nothing but darkness.`n`nYou feel the steel give way to rust which bends worryingly beneath your feet, little pieces of dead metal sticking to your boots and falling back with a quiet tinny rustling.`n`nYou still cannot see the end of the corridor.`n`nThe sour metallic scent of oily, corroded metal lingers around oxidized chain-link fences.  You tread warily around the holes in the floor; even with your torch, you can't see what's underneath the thinning treadplate.  You see something shining in the distance, and quicken your pace.  A heavy steel door.`n`nYou look back over your shoulder.  You cannot see the entrance.  Through the steel door, then.  You grip the handle to the right, and pull.`n`nYou hadn't realized how silent this place was until you opened the door; a throaty rushing noise issued from its tracks as corroded bearings spun in dust-blackened oil.  You step through.`n`nIs the battery in your torch dying?`n`nYou pull out your lighter, and ignite.`n`nThe flame is a dull, dirty orange, plumes of soot-darkened smoke billowing from your mundane, butane-driven lighter.`n`nYou tell yourself that the torch is not dying; its cone of light is not dimming to a deep orange, not turning redder and dimmer by the second.  None of that is happening.`n`nThe torch is just as bright as ever.  The problem is that the darkness is getting thicker.`n`nWithin seconds you are blind, and aware of how far away you are from other people, and medical attention.`n`nAware that if you get knocked out here, you won't be going to the FailBoat.`n`nYou feel the hot, damp breath on your face before you hear the growl.`n`n");
            addnav("Continue");
            addnav("Continue", "runmodule.php?module=proveyourself&op=beginfighting");
            break;
        case "beginfighting":
            $session['user']['gems']--;
            restore_buff_fields();
            $badguy = array();
            $badguy['creaturename'] = "Nightmare";
            $badguy['creatureweapon'] = "Serrated Blades";
            $badguy['creaturelevel'] = 1;
            $badguy['creaturegold'] = 0;
            $badguy['creatureexp'] = 0;
            $badguy['creaturehealth'] = 1000000000000.0;
            $badguy['creatureattack'] = 1;
            $badguy['creaturedefense'] = 1;
            $badguy['hidehitpoints'] = 1;
            calculate_buff_fields();
            $badguy['playerstarthp'] = $session['user']['hitpoints'];
            $badguy['diddamage'] = 0;
            $badguy['type'] = 'nightmare';
            $badguy['creatureaiscript'] = "require(\"ai/nightmare.php\");";
            $session['user']['badguy'] = createstring($badguy);
            $battle = true;
            break;
        case "run":
            output("You can't run from your nightmare.`n`n");
            $op = "fight";
            httpset('op', $op);
            $battle = true;
            break;
        case "fight":
            $battle = true;
            break;
        case "end":
            $points = httpget("points");
            $highscore = get_module_pref("highscore");
            output("You regain your senses while rolling around on the floor, waving your weapon at the empty air.  You're at the end of the corridor.  You look back to see the entryway not thirty feet away, and your Mutant friend striding along the corridor.`n`n\"`4Feeling better now?`0\"`n`n\"`#What the `ihell`i was in that drink?`0\"`n`n\"`4Died, did you?  Ah, well.  It's an experience, anyway.`0\"  He looks around at the chunks you've taken out of the walls.  \"`4Well, I reckon you knocked about %s hitpoints out of your imagination.  Naturally it'll all go on the Hall O' Fame.`0\"`n`nYou take a deep breath and begin to point a recriminating finger.  After a moment you shrug, get to your feet and leave, smacking the Mutant around the back of the head as you go.`n`n", $points);
            if ($points > $highscore) {
                output("`4You beat your personal record!`0`n`n");
                set_module_pref("highscore", $points);
            }
            addnav("Exit");
            addnav("Back to the Outpost", "village.php");
            break;
        case "hof":
            page_header("Nightmare Enthusiasts");
            $acc = db_prefix("accounts");
            $mp = db_prefix("module_userprefs");
            $sql = "SELECT {$acc}.name AS name,\r\n\t\t\t\t{$acc}.acctid AS acctid,\r\n\t\t\t\t{$mp}.value AS highscore,\r\n\t\t\t\t{$mp}.userid FROM {$mp} INNER JOIN {$acc}\r\n\t\t\t\tON {$acc}.acctid = {$mp}.userid \r\n\t\t\t\tWHERE {$mp}.modulename = 'proveyourself' \r\n\t\t\t\tAND {$mp}.setting = 'highscore' \r\n\t\t\t\tAND {$mp}.value > 0 ORDER BY ({$mp}.value+0)\t\r\n\t\t\t\tDESC limit 200";
            $result = db_query($sql);
            $rank = translate_inline("Damage Points");
            $name = translate_inline("Name");
            output("`n`b`c`4Nightmare Enthusiasts`0`n`n`c`b");
            rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center'>");
            rawoutput("<tr class='trhead'><td align=center>{$name}</td><td align=center>{$rank}</td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['name'] == $session['user']['name']) {
                    rawoutput("<tr class='trhilight'><td>");
                } else {
                    rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td align=left>");
                }
                output_notl("%s", $row['name']);
                rawoutput("</td><td align=right>");
                output_notl("%s", number_format($row['highscore']));
                rawoutput("</td></tr>");
            }
            rawoutput("</table>");
            addnav("Back to HoF", "hof.php");
            villagenav();
            break;
    }
    if ($battle) {
        include_once "battle.php";
        if ($defeat) {
            addnav("You have been killed.");
            $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            $points = 1000000000000.0 - $badguy['creaturehealth'];
            addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
        } else {
            if ($victory) {
                addnav("Now what?");
                addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
            } else {
                require_once "lib/fightnav.php";
                fightnav(true, true, "runmodule.php?module=proveyourself", true);
            }
        }
    }
    page_footer();
}
function applebob_run()
{
    require_once 'lib/villagenav.php';
    global $session;
    $op = httpget('op');
    $cost = get_module_setting('cost');
    $eatAllowed = get_module_setting('allowed');
    $eatToday = get_module_pref('ate_today');
    page_header("Sichae's Apple Stand");
    output("`&`c`bApple Bobbing Stand`b`c");
    switch ($op) {
        case 'bob':
            increment_module_pref('ate_today', 1);
            $session['user']['gold'] -= $cost;
            debuglog("spent {$cost} gold on an apple.");
            $appleChance = e_rand(1, 10);
            $color = e_rand(1, 4);
            $colors = [1 => '`4red', 2 => '`2green', 3 => '`^yellow', 4 => '`@green'];
            output("`7You hand Sichae your %s gold, and place your hands on the edge of the barrel.", $cost);
            output("Taking a deep breath, you plunge your head forwards into the chilly water, and vainly attempt to grab hold of an apple with your teeth.");
            output("You finally emerge from the water with a %s`7 coloured apple in your mouth, gasping for breath.", $colors[$color]);
            output("Sichae smiles at your success.`n`n");
            output("`&\"Well done, fair warrior!\"`n`n");
            if ($appleChance == 1) {
                output("`7She grins mischievously, `&\"'Tis a rare warrior that plucks the hallowed blue apple!");
                output("There you have my finest achievement.");
                output("Go forth and slay all in your path, enchanted one!\"`n`n");
                output("`7Your jaw slackens in astonishment at the thought of a blue apple, but you manage to catch the fruit in one hand as it falls.");
                output("As you do, its delicious flavor hits you with surprise.");
                output("Your muscles tingle and a warm buzz flows into your very bones.`n`n");
                output("You feel `5mystical!");
                apply_buff('sichae', ['name' => '`!Blue Apple Mystique', 'rounds' => 20, 'defmod' => 1.03, 'roundmsg' => '`!The Blue Apple\'s power tingles in your bones.']);
                apply_buff('sichae', array("name" => "`!Blue Apple Mystique", "rounds" => 20, "defmod" => 1.03, "roundmsg" => "`!The Blue Apple's power tingles in your bones."));
            } else {
                if ($color == 4) {
                    output("`7As she says this though, you realize that something is very odd about this apple.");
                    output("It looks and tastes just like an ordinary green apple, but you begin to feel very strange.`n`n");
                    output("Bizarre creatures appear before your eyes.");
                    output("You realize that someone has poisoned the apple!`n`n");
                    output("All of the imaginary monsters from your nightmares close in on you, and you feel the terrifying urge to flee this place!");
                    apply_buff('sichae', ['name' => '`@Poisoned Appled', 'rounds' => 20, 'defmod' => 0.97, 'roundmsg' => '`@Strange hallucinations taunt you as you fight.']);
                    blocknav("runmodule.php?module=applebob&op=bob");
                }
            }
            addnav(['Try again (%s gold)', $cost], 'runmodule.php?module=applebob&op=bob');
            villagenav();
            break;
        default:
            output("`7You begin to approach the apple stand, peering into the barrels with interest.");
            output("Inside are apples of red, yellow and green.");
            output("Sichae stands with her hands on her hips, and regards you with a mysterious smile.`n`n");
            output("Her silken garments of jade and blue swish in the cool breeze, and her lithe muscles flex as she pads over to where you stand.`n`n");
            output("`&\"Ah! A visitor to the realms! So you think you can do this, do you?");
            output("It shall be amusing to see you try.\"`n`n");
            output("`7She arches her delicate neck back, and laughs a deep and beautiful sound, that immediately makes you relax.");
            output("She motions to the barrel in front of you.");
            output("`&\"%s gold to show me what talent you posess.", $cost);
            output("And one of the apples is special indeed...\"");
            if ($eatToday >= $eatAllowed) {
                output("`7Much as you'd like to play, your stomach protests fitfully.");
            } else {
                if ($session['user']['gold'] < $cost) {
                    output("`7Unfortunately your pockets do not seem to be full enough to play!");
                } else {
                    addnav(['Try your luck (`^%s gold`0)', $cost], 'runmodule.php?module=applebob&bob=bob');
                }
            }
            villagenav();
            break;
    }
    page_footer();
}
function settings_run()
{
    global $session;
    $op = httpget('op');
    $category = stripslashes(rawurldecode(httpget('cat'))) ?: 'Account';
    page_header("Settings - {$category}");
    switch ($op) {
        case 'save':
            $accounts = db_prefix('accounts');
            $post = httpallpost();
            unset($post['showFormTabIndex']);
            foreach ($post as $key => $val) {
                $post[$key] = stripcslashes($val);
            }
            $post['oldvalues'] = json_decode($post['oldvalues'], true);
            foreach ($post['oldvalues'] as $key => $val) {
                $post['oldvalues'][$key] = stripslashes($val);
            }
            $post = modulehook('prefs-change', $post);
            if ($post['return'] != '') {
                $return = $post['return'];
                unset($post['return']);
            }
            //Fix template changes.
            if (md5(md5($post['oldpass'])) == $session['user']['password'] && $post['newpass'] != '') {
                require_once 'lib/systemmail.php';
                $newPass = md5(md5($post['newpass']));
                db_query("UPDATE {$accounts}\n                    SET password = '******'\n                    WHERE acctid = '{$session['user']['acctid']}'");
                systemmail($session['user']['acctid'], 'Account Settings', "`@Your password was changed successfully!");
            }
            unset($post['newpass']);
            unset($post['oldpass']);
            foreach ($post as $key => $val) {
                if ($key == 'bio' && $val != $post['oldvalues']['bio']) {
                    $session['user']['bio'] = $val;
                } else {
                    if (!is_array($val) && $val != $post['oldvalues'][$key]) {
                        if (strpos($key, '__user') || strpos($key, '__check')) {
                            $moduleKey = explode('__', $key);
                            set_module_pref($moduleKey[1], $val, $moduleKey[0]);
                            unset($moduleKey);
                        } else {
                            $session['user']['prefs'][$key] = $val;
                        }
                    }
                }
            }
            $prefs = @serialize($session['user']['prefs']);
            db_query("UPDATE {$accounts} SET prefs = '{$prefs}'\n                WHERE acctid = '{$session['user']['acctid']}'");
            redirect("runmodule.php?module=settings&cat={$return}&save=true");
            addnav('Go back', 'runmodule.php?module=settings');
            break;
        default:
            $modules = db_prefix('modules');
            $userprefs = db_prefix('module_userprefs');
            $rewrite = trim(get_module_setting('rewrite'));
            $rewrite = json_decode($rewrite, true);
            $languages = getsetting('serverlanguages', 'en, English');
            $prefs = $session['user']['prefs'];
            $prefs['bio'] = $session['user']['bio'];
            $prefs['template'] = $_COOKIE['template'] ?: getsetting('defaultskin', 'jade.htm');
            $prefs['email'] = $session['user']['emailaddress'];
            $prefsFormat = ['Account' => ['bio' => 'Short biography, textarea', 'newpass' => 'New password, password', 'oldpass' => 'If you are changing your password&comma; type your old one, password', 'email' => 'Email, text'], 'Display' => ['template' => 'Skin, theme', 'language' => 'Which language do you prefer?, enum, ' . $languages, 'timestamp' => 'Show timestamps in commentary?, enum, 0, None, 1, Real Time, 2, Relative Time'], 'Game Behavior' => ['emailonmail' => 'Receive emails when you receive a mail?, bool', 'systemmail' => 'Receive emails for system messages?, bool', 'Be sure to check your email\'s spam folder and add our email as a trusted sender!, note', 'dirtyemail' => 'Allow profanity in mail?, bool', 'timeoffset' => sprintf_translate('Hours to offset time (currently %s)?, int', date($prefs['timeformat'], strtotime('now') + $prefs['timeoffset'] * 3600)), 'ihavenocheer' => 'Disable holiday text?, bool', 'nojump' => 'Disable jumping to the commentary when posting or refreshing?, bool']];
            if (count(explode(',', $languages)) < 3) {
                unset($prefs['Display']['language']);
            }
            $prefsFormat = modulehook('prefs-format', $prefsFormat);
            $prefsTemp = [];
            $modulesFound = [];
            $sql = db_query("SELECT modulename, formalname FROM {$modules}\n                WHERE infokeys LIKE '%|prefs|%'\n                AND active = 1\n                ORDER BY modulename");
            while ($row = db_fetch_assoc($sql)) {
                $formal = $row['formalname'];
                $modulesFound[$row['modulename']] = true;
                if (module_status($row['modulename']) == MODULE_FILE_NOT_PRESENT) {
                    foreach ($rewrite as $key => $moduleName) {
                        if ($moduleName == $formal || strpos($key, $row['modulename']) !== false) {
                            unset($rewrite[$key]);
                        }
                    }
                    set_module_setting('rewrite', json_encode($rewrite));
                } else {
                    $prefsTemp[$formal] = get_module_info($row['modulename'])['prefs'];
                }
                unset($prefsTemp[$formal][0]);
                foreach ($prefsTemp[$formal] as $setting => $description) {
                    $description = explode('|', $description)[0];
                    if (strpos($setting, 'user_') === false) {
                        unset($prefsTemp[$formal][$setting]);
                    } else {
                        $structuredKey = "{$row['modulename']}__{$setting}";
                        if ($rewrite[$structuredKey] != $formal) {
                            $prefsTemp[$rewrite[$structuredKey]][$structuredKey] = $description;
                        } else {
                            $prefsTemp[$formal][$structuredKey] = $description;
                        }
                        unset($prefsTemp[$formal][$setting]);
                    }
                }
                if (count($prefsTemp[$formal]) == 0) {
                    unset($prefsTemp[$formal]);
                    unset($modulesFound[$row['modulename']]);
                }
            }
            foreach ($modulesFound as $name => $true) {
                $sql = db_query("SELECT modulename, setting, value FROM {$userprefs}\n                    WHERE modulename = '{$name}'\n                    AND (setting LIKE 'user_%' OR setting LIKE 'check_%')\n                    AND userid = '{$session['user']['acctid']}'\n                    ");
                while ($row = db_fetch_assoc($sql)) {
                    $prefs["{$row['modulename']}__{$row['setting']}"] = $row['value'];
                }
            }
            $prefsFormat = array_merge_recursive($prefsFormat, $prefsTemp);
            $prefsFormat = modulehook('prefs-format', $prefsFormat);
            require_once 'lib/villagenav.php';
            villagenav();
            addnav('Refresh', 'runmodule.php?module=settings');
            addnav('Categories');
            foreach (array_keys($prefsFormat) as $int => $name) {
                addnav($name, "runmodule.php?module=settings&cat=" . rawurlencode($name));
            }
            output("`c`b`i`Q{$category} Settings`b`i`c");
            if (httpget('save')) {
                output("`@`iYour Settings have been saved!`i`n");
            }
            rawoutput("<form action='runmodule.php?module=settings&op=save' method = 'POST'>");
            require_once 'lib/showform.php';
            showform($prefsFormat[$category], $prefs);
            rawoutput(sprintf("<input type='hidden' name='oldvalues' value='%s' />", json_encode($prefs)));
            rawoutput("<input type='hidden' name='return' value='{$category}' />");
            rawoutput("</form>");
            rawoutput("<script type='text/javascript'>\n                document.getElementsByName('template')[0].onchange = function () {\n                    var index = this.selectedIndex;\n                    var selection = this.children[index].value;\n                    document.cookie = 'template=' + selection + ';expires=86400';\n                }\n\n                </script>");
            addnav('', 'runmodule.php?module=settings&op=save');
            break;
    }
    page_footer();
}
function scry_run()
{
    global $session;
    addcommentary();
    $area = httpget("area");
    $village = httpget("village");
    $op = httpget("op");
    $cost = $session['user']['level'] * get_module_setting("cost");
    if ($op == "pay") {
        if ($session['user']['gold'] >= $cost) {
            $session['user']['gold'] -= $cost;
            set_module_pref("talks", 0);
            set_module_pref("speaking", 1);
            debuglog("spent {$cost} gold to scry a remote village");
            redirect("runmodule.php?module=scry&op=talk&area=" . htmlentities($area, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "&village=" . htmlentities($village, ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            page_footer();
        } else {
            page_header("Gypsy Seer's tent");
            villagenav();
            addnav("Continue looking around", "gypsy.php");
            output("`5You offer the old gypsy woman your `^%s`5 gold for her scrying services, but she informs you that such a pittance is far too little.", $session['user']['gold']);
            page_footer();
        }
    } elseif ($op == "talk") {
        $times = get_module_setting("uses");
        if ($times && get_module_pref("talks") >= $times) {
            page_header("Gypsy Seer's tent");
            output("`5Looking around dazedly, it takes you a moment to realize that you are no longer viewing the village of %s and that the gypsy woman is staring at you with her hand out.", $village);
            output("`5\"`!I'll need more gold if you want to keep taking up space for my other paying customers!`5\", she demands.`n`n");
            output("You start to demand, \"`&What other customers?`5\" but decide that it's best not to annoy someone who has such power.");
            addnav(array("Scrying (%s gold)", $cost));
            addnav(array("Scry %s", $village), "runmodule.php?module=scry&op=pay&area=" . htmlentities($area, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "&village=" . htmlentities($village, ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            addnav("Other");
            addnav("Return to the tent", "gypsy.php");
            villagenav();
            page_footer();
        } else {
            page_header("Peering in the bowl, you view %s", $village);
            output("`5While staring into the inky water, you are able to make out the people of %s:`n", $village);
            commentdisplay("", $area, "Project", 25, "projects");
            addnav("Look up from the bowl", "gypsy.php");
            page_footer();
        }
    }
}
function sethsong_run()
{
    $op = httpget('op');
    $visits = get_module_setting("visits");
    $been = get_module_pref("been");
    $iname = getsetting("innname", LOCATION_INN);
    tlschema("inn");
    page_header($iname);
    rawoutput("<span style='color: #9900FF'>");
    output_notl("`c`b");
    output($iname);
    output_notl("`b`c");
    tlschema();
    // Short circuit out if we've heard enough
    if ($been >= $visits) {
        output("%s`0 clears his throat and drinks some water.", getsetting("bard", "`^Seth"));
        output("\"I'm sorry, my throat is just too dry.\"");
    } else {
        sethsong_sing();
    }
    addnav("Where to?");
    addnav("I?Return to the Inn", "inn.php");
    villagenav();
    rawoutput("</span>");
    page_footer();
}
function gauntlet_run()
{
    page_header("The Gauntlet");
    require_once "lib/villagenav.php";
    global $session;
    $op = httpget("op");
    $goldcost = get_module_setting("goldcost");
    $gold = $session['user']['gold'];
    $minhpadd = get_module_setting("minhpadd");
    $maxhpadd = get_module_setting("maxhpadd");
    $maxhp = $session['user']['maxhitpoints'];
    $mincharmcost = get_module_setting("mincharmcost");
    $maxcharmcost = get_module_setting("maxcharmcost");
    $charm = $session['user']['charm'];
    $minturnscost = get_module_setting("minturnscost");
    $maxturnscost = get_module_setting("maxturnscost");
    $turns = $session['user']['turns'];
    $minhpcost = get_module_setting("minhpcost");
    $maxhpcost = get_module_setting("maxhpcost");
    $hp = $session['user']['hitpoints'];
    $seen = get_module_pref("seen");
    $seendk = get_module_pref("seendk");
    $visits = get_module_setting("visits");
    $visitsdk = get_module_setting("visitsdk");
    output("`c`b`4The Gauntlet`b`c`n");
    if ($op == "") {
        output("`)A mean looking figure sits in front of a mean looking building.");
        output("A mean looking sign reading \"`4The Gauntlet`)\" hangs on the mean looking building.");
        if ($gold >= $goldcost && $charm >= $maxcharmcost && $turns >= $maxturnscost && ($visitsdk == 0 || $seendk < $visitsdk) && ($visits == 0 || $seen < $visits)) {
            output("`n`nThe mean looking figure gives you a mean look, summing you up, then says, \"`4Enter if you dare: only `^%s `4gold.`)\"", $goldcost);
            addnav("Enter The Gauntlet", "runmodule.php?module=gauntlet&op=enter");
        } else {
            output("`n`nThe mean looking figure gives you a mean look, summing you up, then says, \"`4Go away.`)\"");
        }
        villagenav();
    } elseif ($op == "enter") {
        set_module_pref("seen", $seen + 1);
        set_module_pref("seendk", $seendk + 1);
        $session['user']['gold'] -= $goldcost;
        debuglog("paid {$goldcost} to enter The Gauntlet");
        $hpadd = e_rand($minhpadd, $maxhpadd);
        $session['user']['maxhitpoints'] += $hpadd;
        set_module_pref("extrahps", get_module_pref("extrahps") + $hpadd);
        $charmcost = e_rand($mincharmcost, $maxcharmcost);
        $session['user']['charm'] -= $charmcost;
        $turnscost = e_rand($minturnscost, $maxturnscost);
        $session['user']['turns'] -= $turnscost;
        $hpcost = e_rand($minhpcost, $maxhpcost);
        $session['user']['hitpoints'] -= round($hpcost / 100 * $hp);
        if ($session['user']['hitpoints'] <= 0) {
            $session['user']['hitpoints'] = 1;
        }
        output("`)You pay your `^%s`) gold, hold your head high, and bravely enter The Gauntlet.`n`n", $goldcost);
        output("You're met by a hideous device with a moving floor and many dangerously swinging masses.");
        output("You're helplessly fed through the mechanism which puts you through a painful process of hits and blows.`n`n");
        output("Finally, The Gauntlet dumps you outside in a relatively undignified manner.`n`n");
        output("You're not quite sure what happened.`n");
        if ($hpcost) {
            output("You took a beating.`n");
        }
        if ($charmcost) {
            output("You feel uglier.`n");
        }
        if ($turnscost) {
            output("You feel worn out.`n");
        }
        if ($hpadd) {
            output("However, for all of that, you feel tougher.");
        }
        villagenav();
    }
    page_footer();
}
function pktrack_run()
{
    global $session;
    $op = httpget('op');
    $page = httpget('page');
    if (get_module_setting("shz") == 1) {
        $f = 0;
    } else {
        $f = 1;
    }
    if (get_module_setting("dispad") == 1) {
        $hide = SU_HIDE_FROM_LEADERBOARD;
        $g = "AND ((superuser & {$hide}) = 0)";
    } else {
        $g = "";
    }
    $mu = db_prefix("module_userprefs");
    $ac = db_prefix("accounts");
    switch ($op) {
        case "hof":
            page_header("Hall of Fame");
            $pp = get_module_setting("pp");
            $pageoffset = (int) $page;
            if ($pageoffset > 0) {
                $pageoffset--;
            }
            $pageoffset *= $pp;
            $from = $pageoffset + 1;
            $limit = "LIMIT {$pageoffset},{$pp}";
            $sql = "SELECT COUNT(userid) AS c FROM {$mu} \r\n\t\t\t\t\tWHERE modulename = 'pktrack' \r\n\t\t\t\t\tAND setting = 'count' \r\n\t\t\t\t\tAND value >= '{$f}'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $total = $row['c'];
            if ($from + $pp < $total) {
                $cond = $pageoffset + $pp;
            } else {
                $cond = $total;
            }
            $sql = "SELECT {$mu}.value, {$ac}.name, {$ac}.level FROM {$mu} , {$ac} \r\n\t\t\t\t\tWHERE acctid = userid \r\n\t\t\t\t\tAND modulename = 'pktrack' \r\n\t\t\t\t\tAND setting = 'count' \r\n\t\t\t\t\tAND value >= '{$f}' {$g} \r\n\t\t\t\t\tORDER BY (value+0) DESC {$limit}";
            $result = db_query($sql);
            $count = db_num_rows($result);
            $rank = translate_inline("Rank");
            $name = translate_inline("Name");
            $pk = translate_inline("Player Kills");
            $ran = translate_inline("In PvP Range?");
            rawoutput("<big>");
            output("`c`b`^Fiercest Warriors in the Land`b`c`0`n");
            rawoutput("</big>");
            rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center' bgcolor='#999999'>");
            rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$pk}</td><td>{$ran}</td></tr>");
            if (db_num_rows($result) > 0) {
                $i = 0;
                while ($row = db_fetch_assoc($result)) {
                    $i++;
                    if ($row['name'] == $session['user']['name']) {
                        rawoutput("<tr class='trhilight'><td>");
                    } else {
                        rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td>");
                    }
                    output_notl("{$i}.");
                    rawoutput("</td><td>");
                    output_notl("`&%s`0", $row['name']);
                    rawoutput("</td><td>");
                    output_notl("`c`@%s`c`0", $row['value']);
                    rawoutput("</td><td>");
                    if ($row['level'] <= $session['user']['level'] + 2 && $row['level'] >= $session['user']['level'] - 1) {
                        $q = translate_inline("Yes");
                    } else {
                        $q = translate_inline("No");
                    }
                    if ($row['name'] == $session['user']['name']) {
                        $q = translate_inline("N/A");
                    }
                    output_notl("`c`@%s`c`0", $q);
                    rawoutput("</td></tr>");
                }
            }
            rawoutput("</table>");
            if ($total > $pp) {
                addnav("Pages");
                for ($p = 0; $p < $count && $cond; $p += $pp) {
                    addnav(array("Page %s (%s-%s)", $p / $pp + 1, $p + 1, min($p + $pp, $count)), "runmodule.php?module=pktrack&op=hof&page=" . ($p / $pp + 1));
                }
            }
            break;
    }
    addnav("Other");
    addnav("Back to HoF", "hof.php");
    villagenav();
    page_footer();
}
function lottery_run()
{
    global $session;
    $op = httpget("op");
    $cost = get_module_setting("ticketcost");
    $numbers = get_module_setting("todaysnumbers");
    $n = $numbers;
    $prize = get_module_setting("prize");
    $prizecount = get_module_setting("howmany");
    $jackpot = (int) get_module_setting("currentjackpot");
    $bleed = (int) get_module_setting("percentbleed");
    $roundnum = (int) get_module_setting("roundnum");
    $msg = "";
    if ($op == "buy") {
        $op = "store";
        httpset("op", $op);
        if ($session['user']['gold'] >= $cost) {
            $lotto = httppost("lotto");
            if ($lotto) {
                sort($lotto);
                set_module_pref("pick", join("", $lotto));
                set_module_pref("roundnum", $roundnum);
                $session['user']['gold'] -= $cost;
                debuglog("spent {$cost} on a lottery ticket");
                $jackpot += round($cost * (100 - $bleed) / 100, 0);
                set_module_setting("currentjackpot", $jackpot);
            } else {
                $msg = translate_inline("`\$You seem to have mumbled when you requested the lottery tickets.  Please restate your numbers.`0`n`n");
            }
        } else {
            $msg = translate_inline("`\$You do not have enough to buy a lottery ticket!`0`n`n");
        }
    }
    if ($op == "store") {
        require_once "lib/villagenav.php";
        page_header("%s's Lottery", getsetting("barkeep", "`tCedrik"));
        output("Today's lottery numbers are `^%s-%s-%s-%s`7.", $n[0], $n[1], $n[2], $n[3]);
        output("The jackpot is now up to `^%s`0 gold!`n`n", $jackpot);
        if ($prize > 0) {
            if ($prizecount == 1) {
                output("The winner of the last jackpot got `^%s`0 gold!`n`n", $prize);
            } else {
                output("The %s winners of the last jackpot each got `^%s`0 gold!`n`n", $prizecount, $prize);
            }
        } else {
            output("There were no recent jackpot winners!`n`n");
        }
        $pick = get_module_pref("pick");
        if ($pick > "") {
            $n = $pick;
            output("You bought a lottery ticket for tomorrow's drawing; the numbers you chose are: `^%s-%s-%s-%s`7`n`n", $n[0], $n[1], $n[2], $n[3]);
        } else {
            output("%s", $msg);
            output("Lottery tickets cost `^%s`0 gold.", $cost);
            output("If you would like to buy one for tomorrow's drawing, please choose your numbers below and click \"Buy\".");
            rawoutput("<form action='runmodule.php?module=lottery&op=buy' method='POST'>", true);
            addnav("", "runmodule.php?module=lottery&op=buy");
            for ($i = 0; $i < 4; $i++) {
                $j = $i + 1;
                if ($j == 4) {
                    $k = "buy";
                } else {
                    $k = $j + 1;
                }
                rawoutput("<select id='lotto{$j}' name='lotto[{$i}]' onChange='document.getElementById(\"lotto{$k}\").focus()'>");
                for ($x = 0; $x < 10; $x++) {
                    rawoutput("<option value='{$x}'>{$x}</option>");
                }
                rawoutput("</select>");
            }
            $b = translate_inline("Buy");
            rawoutput("<input type='submit' class='button' value='{$b}' id='lottobuy'>");
            rawoutput("</form>");
            rawoutput("<script language='JavaScript'>document.getElementById('lotto1').focus();</script>");
        }
        output("A drawing is held at the start of each game day.");
        output("If the numbers you chose match, in any order, you win the jackpot for the day!");
        output("If no one matches the jackpot on a particular day, the sum will roll over for the following game day.");
        output("A portion of the proceeds of the lottery go to help injured forest creatures.");
        addnav("Return");
        addnav("I?Return to the Inn", "inn.php");
        villagenav();
        page_footer();
    }
}
function daysave_run()
{
    global $session;
    $op = httpget('op');
    $return = httpget('return');
    if ($return == "house") {
        $hid = httpget('hid');
        $rid = httpget('rid');
        $sid = httpget('sid');
    }
    //handle new players
    if (!get_module_pref("initsetup")) {
        set_module_pref("slots", get_module_setting("startslots"));
        set_module_pref("days", get_module_setting("startdays"));
        set_module_pref("initsetup", 1);
    }
    $days = get_module_pref("days");
    $slots = get_module_pref("slots");
    $startdays = get_module_setting("startdays");
    $startslots = get_module_setting("startslots");
    //$boughttoday = get_module_pref("instantbuys");
    $boughttoday = 0;
    $buyslotcost = get_module_setting("buyslotcost");
    $buydaycost = get_module_setting("buydaycost");
    $fillslotcost = get_module_setting("fillslotcost");
    $maxbuyday = get_module_setting("maxbuyday");
    $dps = $session['user']['donation'] - $session['user']['donationspent'];
    page_header("Saved Days");
    switch ($op) {
        case "start":
            output("Here are your Chronospheres.  Each coloured sphere represents one saved-up game day.`n`n");
            if ($startdays && $session['user']['dragonkills'] < 1) {
                output("New players start the game with some days already saved up, so that they can get a feel for how this works.`n`n");
            }
            for ($full = 1; $full <= $days; $full++) {
                rawoutput("<img src=\"images/daysphere-full.png\" alt=\"Saved Day\" title=\"Saved Day\">");
            }
            for ($empty = $full; $empty <= $slots; $empty++) {
                rawoutput("<img src=\"images/daysphere-empty.png\" alt=\"Empty Day Slot\" title=\"Empty Day Slot\">");
            }
            if ($days == 1) {
                $daydisp = "Day";
            } else {
                $daydisp = "Days";
            }
            output("`n`nChronospheres essentially allow you to save up game days for later play, simply by not logging in.  As you can see, you have %s Game %s saved up, out of a maximum of %s.`n`n", $days, $daydisp, $slots);
            addnav("Chronofiddling");
            if ($days) {
                addnav("Use a saved day", "runmodule.php?module=daysave&op=useday&hid=" . $hid . "&rid=" . $rid . "&sid=" . $sid);
            } else {
                addnav("You have no saved days", "");
            }
            addnav("Refresh this page", "runmodule.php?module=daysave&op=start&return=" . $return . "&hid=" . $hid . "&rid=" . $rid . "&sid=" . $sid);
            if ($maxbuyday == 1) {
                $maxdisp = "Day";
            } else {
                $maxdisp = "Days";
            }
            addnav("Donator Options");
            output("Site supporters have several extra options.  As a site supporter, you can instantly start a new Game Day for your character at any time in exchange for %s Donator Points.  You can also add more Chronospheres, allowing you to save up more days to play later.  Each additional Chronosphere costs %s Donator Points, and come pre-filled.  When adding Chronospheres, you have the option of refilling your empty Spheres for a discount cost of %s Donator Points per empty Sphere.`n`nYou currently have %s Donator Points available.  See the Hunter's Lodge in any Outpost for a more detailed explanation of how to get Donator Points, and other cool things you can do with them.`n`n`c`b`4Careful!`0`b`cAlways check the time to the next Game Day (displayed under your Stats) before you use a Chronosphere or buy an Instant New Day!  Nothing sucks worse than paying for a new day and then finding out that you would have gotten one in five minutes anyway.`n`nA quick point to note - if you leave the Island without logging out, and then log back in to arrive at this page, the number of Chronospheres displayed may be out of date.  To fix this, click the Refresh link.`n`nAlso be aware that if you've just logged in to see this page after being logged out for a while, you might have a natural New Day (IE one that won't affect your Chronospheres) waiting for you anyway, which will be triggered when you leave this page.", $buydaycost, $buyslotcost, $fillslotcost, number_format($dps));
            if ($dps >= $buydaycost && $boughttoday < $maxbuyday) {
                addnav(array("Buy an Instant New Day for %s Donator Points", $buydaycost), "runmodule.php?module=daysave&op=buyday&hid=" . $hid . "&rid=" . $rid . "&sid=" . $sid);
            } else {
                if ($dps < $buydaycost) {
                    addnav("Not enough Donator Points for an Instant New Day", "");
                } else {
                    addnav("Instant New Day limit reached", "");
                }
            }
            if ($dps >= $buyslotcost) {
                addnav(array("Buy an extra Chronosphere for %s Donator Points", $buyslotcost), "runmodule.php?module=daysave&op=buyslot&return=" . $return . "&hid=" . $hid . "&rid=" . $rid . "&sid=" . $sid);
            } else {
                addnav("Not enough Donator Points for a new Chronosphere", "");
            }
            addnav("Exit");
            if ($return == "village") {
                tlschema('nonav');
                villagenav();
            } else {
                if ($return == "shades") {
                    tlschema('nonav');
                    addnav("Back to the FailBoat", "shades.php");
                } else {
                    if ($return == "worldmapen") {
                        tlschema('nonav');
                        addnav("Return to the World Map", "runmodule.php?module=worldmapen&op=continue");
                    } else {
                        if ($return == "house") {
                            addnav("Return to the Dwelling", "runmodule.php?module=improbablehousing&op=sleep&sub=sleep&hid=" . $hid . "&rid=" . $rid . "&slot=" . $sid);
                        } else {
                            addnav("Your navs are corrupted!", "badnav.php");
                        }
                    }
                }
            }
            break;
        case "useday":
            $days -= 1;
            if ($days < 0) {
                $days = 0;
            }
            set_module_pref("days", $days);
            output("You have used one of your Chronospheres.  Now go forth and have fun!`n`n");
            for ($full = 1; $full <= $days; $full++) {
                rawoutput("<img src=\"images/daysphere-full.png\" alt=\"Saved Day\" title=\"Saved Day\">");
            }
            for ($empty = $full; $empty <= $slots; $empty++) {
                rawoutput("<img src=\"images/daysphere-empty.png\" alt=\"Empty Day Slot\" title=\"Empty Day Slot\">");
            }
            debug($session['user']['restorepage']);
            addnav("It is a New Day!", "newday.php");
            break;
        case "buyday":
            output("You have bought one new Game Day in exchange for %s Donator Points, leaving you with %s points left to spend.  Your Chronospheres are unaffected.  Now go forth and have fun!`n`n", $buydaycost, number_format($dps - $buydaycost));
            for ($full = 1; $full <= $days; $full++) {
                rawoutput("<img src=\"images/daysphere-full.png\" alt=\"Saved Day\" title=\"Saved Day\">");
            }
            for ($empty = $full; $empty <= $slots; $empty++) {
                rawoutput("<img src=\"images/daysphere-empty.png\" alt=\"Empty Day Slot\" title=\"Empty Day Slot\">");
            }
            addnav("It is a New Day!", "newday.php");
            $session['user']['donationspent'] += $buydaycost;
            increment_module_pref("instantbuys");
            break;
        case "buyslot":
            $session['user']['donationspent'] += $buyslotcost;
            increment_module_pref("days");
            increment_module_pref("slots");
            $days = get_module_pref("days");
            $slots = get_module_pref("slots");
            $dps = $session['user']['donation'] - $session['user']['donationspent'];
            output("You have bought one additional Chronosphere in exchange for %s Donator Points, leaving you with %s points left to spend.`n`n", $buyslotcost, number_format($dps));
            for ($full = 1; $full <= $days; $full++) {
                rawoutput("<img src=\"images/daysphere-full.png\" alt=\"Saved Day\" title=\"Saved Day\">");
            }
            for ($empty = $full; $empty <= $slots; $empty++) {
                rawoutput("<img src=\"images/daysphere-empty.png\" alt=\"Empty Day Slot\" title=\"Empty Day Slot\">");
            }
            if ($days < $slots && $dps >= $fillslotcost) {
                addnav("Fill up Chronospheres", "");
                output("`n`nYou now have the option of refilling your empty Chronospheres for %s Donator Points each.`n`n", $fillslotcost);
                $empty = $slots - $days;
                for ($i = 1; $i <= $empty; $i++) {
                    $cost = $i * $fillslotcost;
                    if ($dps >= $cost) {
                        if ($i == 1) {
                            $p = "Sphere";
                        } else {
                            $p = "Spheres";
                        }
                        addnav(array("Fill up %s %s for %s Donator Points", $i, $p, $cost), "runmodule.php?module=daysave&op=fillup&fill=" . $i . "&return=" . $return . "&hid=" . $hid . "&rid=" . $rid . "&sid=" . $sid);
                    }
                }
            }
            addnav("Return");
            addnav("Back to the menu", "runmodule.php?module=daysave&op=start&return=" . $return . "&hid=" . $hid . "&rid=" . $rid . "&sid=" . $sid);
            break;
        case "fillup":
            $fill = httpget('fill');
            $session['user']['donationspent'] += $fill * $fillslotcost;
            $dps = $session['user']['donation'] - $session['user']['donationspent'];
            increment_module_pref("days", $fill);
            $days = get_module_pref("days");
            if ($fill == 1) {
                $p = "Chronosphere";
            } else {
                $p = "Chronospheres";
            }
            output("You have filled up %s %s in exchange for %s Donator Points, leaving you with %s points left to spend.`n`n", $fill, $p, number_format($fill * $fillslotcost), number_format($dps));
            for ($full = 1; $full <= $days; $full++) {
                rawoutput("<img src=\"images/daysphere-full.png\" alt=\"Saved Day\" title=\"Saved Day\">");
            }
            for ($empty = $full; $empty <= $slots; $empty++) {
                rawoutput("<img src=\"images/daysphere-empty.png\" alt=\"Empty Day Slot\" title=\"Empty Day Slot\">");
            }
            addnav("Return", "");
            addnav("Back to the menu", "runmodule.php?module=daysave&op=start&return=" . $return . "&hid=" . $hid . "&rid=" . $rid . "&sid=" . $sid);
            break;
    }
    page_footer();
}
function dragonplace_run()
{
    global $session;
    require_once "lib/partner.php";
    $partner = get_partner();
    $op = httpget('op');
    page_header('The Forest');
    switch ($op) {
        case "scry":
            $cost = get_module_setting("scrygems");
            if ($session['user']['gems'] < $cost) {
                page_header("Gypsy Seer's tent");
                villagenav();
                addnav("Continue looking around", "gypsy.php");
                if ($session['user']['gems'] == 0) {
                    output("`5You turn out your pockets looking for gems, but don't find any.`n");
                } else {
                    output("`5You turn out your pockets looking for gems, but only find %s, which is not enough.`n", $session['user']['gems']);
                }
                output("Disenheartened, you step away from the dragon's eye.");
                page_footer();
            } else {
                $session['user']['gems'] -= $cost;
                page_header("Gypsy Seer's tent");
                villagenav();
                addnav("Continue looking around", "gypsy.php");
                $vloc = modulehook("validforestloc", array());
                while (1) {
                    // Don't look at the same place twice in a row.
                    $vil = array_rand($vloc);
                    if ($vil != get_module_pref("lastscry")) {
                        break;
                    }
                }
                set_module_pref("lastscry", $vil);
                output("`5Bending forward, you peer intently into the eye of the dragon.`n");
                output("As you stare, the tent around you seems to fade away and is replaced by a vision of %s.`n`n", $vil);
                if ($vil == get_module_pref("dragonloc") || $vil == get_module_pref("dragonloc2")) {
                    output("%sFrom high above, you see the villagers of %s walking to and fro, and even some adventurers entering and leaving the gates to go into the forest.`n", "`\$", $vil);
                    output("As you continue to watch, the villagers get closer and closer and then one of them is right in front of you as you swoop down into a forest clearing outside a cave.");
                    output("You see the villager turn and scream just before being engulfed in flames!!`5`n`n");
                    output("Stunned at the death you have just witnessed, you lift your eyes from the orb and the tent regains focus.");
                } else {
                    output("%sFrom high above, you see the villagers of %s walking to and fro, and even some adventurers entering and leaving the gates to go into the forest.`n", "`^", $vil);
                    output("As you continue to watch, the village disappears in the distance behind you.`5`n");
                    output("Obviously the dragon isn't hunting in %s today.`n`n", $vil);
                    output("You lift your eyes from the orb, and the tent regains focus.");
                }
                page_footer();
            }
        case "dragon":
            addnav("Enter the cave", "runmodule.php?module=dragonplace&op=cave");
            addnav("Run away like a baby", "inn.php?op=fleedragon");
            output("`\$You approach the blackened entrance of a cave deep in the forest, though the trees are scorched to stumps for a hundred yards all around.");
            output("A thin tendril of smoke escapes the roof of the cave's entrance, and is whisked away by a suddenly cold and brisk wind.");
            output("The mouth of the cave lies up a dozen feet from the forest floor, set in the side of a cliff, with debris making a conical ramp to the opening.");
            output("Stalactites and stalagmites near the entrance trigger your imagination to inspire thoughts that the opening is really the mouth of a great leech.`n`n");
            output("You cautiously approach the entrance of the cave, and as you do, you hear, or perhaps feel a deep rumble that lasts thirty seconds or so, before silencing to a breeze of sulfur-air which wafts out of the cave.");
            output("The sound starts again, and stops again in a regular rhythm.`n`n");
            output("You clamber up the debris pile leading to the mouth of the cave, your feet crunching on the apparent remains of previous heroes, or perhaps hors d'oeuvres.`n`n");
            output("Every instinct in your body wants to run, and run quickly, back to the warm inn, and the even warmer %s`\$.", $partner);
            output("What do you do?`0");
            if (get_module_setting('sdrag')) {
                $session['user']['seendragon'] = 1;
                set_module_pref("search", get_module_pref("search") + 1);
            }
            break;
        case "cave":
            // Okay, if this is the REAL dragon cave, redirect them to dragon.php
            if ($session['user']['location'] == get_module_pref('dragonloc') || $session['user']['location'] == get_module_pref('dragonloc2')) {
                redirect('dragon.php', 'Redirecting to dragon.php from dragonplace.php');
            }
            // We could get here from a module (peerpressure) so let's make sure
            // that since they have gone into the cave, we are nice to them and
            // don't force them back in again and again.
            $session['user']['specialinc'] = "";
            // Otherwise, empty cave.
            output("`@You enter the cave.... `%and it's empty!`n");
            output("It may have been a dragon's cave once, but now... there are only a few bones, and a flaming pile of logs.`n");
            output("A giant Stag runs out of the cave.... so much for heavy breathing!");
            output("`n`@`iMaybe in another village?`i");
            debuglog("found an empty dragon cave in " . $session['user']['location']);
            $num = e_rand(1, 4);
            $found = false;
            $max = get_module_setting("maxsearch");
            switch ($num) {
                case 1:
                    if (get_module_setting('gold') > 0 && (get_module_pref('gold') == 0 || $max)) {
                        $gold = get_module_setting('gold');
                        output("`n`n`c`^You find %s gold!`c", $gold);
                        $session['user']['gold'] += $gold;
                        set_module_pref('gold', 1);
                        $found = true;
                        debuglog("found {$gold} gold in an empty dragon cave");
                    }
                    break;
                case 2:
                    if (get_module_setting('gems') > 0 && (get_module_pref('gems') == 0 || $max)) {
                        $gems = get_module_setting('gems');
                        if ($gems == 1) {
                            output("`n`n`c`^You find a `%gem`^!`c");
                        } else {
                            output("`n`n`c`^You find `%%s gems`^!`c", $gems);
                        }
                        $session['user']['gems'] += $gems;
                        set_module_pref('gems', 1);
                        debuglog("found {$gems} gems in an empty dragon cave");
                        $found = true;
                    }
                    break;
                case 3:
                    if (get_module_setting('hp') > 0 && (get_module_pref('hp') == 0 || $max)) {
                        output("`n`n`c`^You trip over a bone, and lose some hitpoints!`c");
                        $session['user']['hitpoints'] -= get_module_setting('hp');
                        if ($session['user']['hitpoints'] <= 1) {
                            $session['user']['hitpoints'] = 1;
                        }
                        set_module_pref('hp', 1);
                        $found = true;
                    }
                    break;
            }
            if (!$found) {
                output("`n`n`c`\$Nothing happens...`c");
            }
            $isforest = 0;
            $vloc = modulehook('validforestloc', array());
            foreach ($vloc as $i => $l) {
                if ($l == $session['user']['location']) {
                    $isforest = 1;
                    break;
                }
            }
            if ($isforest) {
                forest(true);
            } else {
                require_once "lib/villagenav.php";
                villagenav();
            }
            break;
    }
    page_footer();
}
function heidi_run()
{
    global $session;
    $op = httpget("op");
    $addgold = get_module_pref("addgold");
    $addgold *= round(min(1, $session['user']['dragonkills']) * max(1, $session['user']['dragonkills'] * 0.5 / $session['user']['maxhitpoints']));
    $addgold -= max(1000, $session['user']['maxhitpoints']);
    if ($addgold <= 0) {
        $addgold = 10 * $session['user']['level'];
    }
    $pvpchange = get_module_pref("pvpchange");
    $changeallowed = get_module_setting("changeallowed");
    $allowgift = get_module_setting("allowgift");
    $allowdp = get_module_setting("allowdp");
    $turnadd = get_module_setting("turnadd");
    $turnmult = get_module_setting("turnmult");
    $newdayturns = get_module_pref("newdayturns");
    $turngain = ceil($newdayturns * $turnmult / 100) + $turnadd;
    $gemspaid = get_module_pref("gemspaid");
    $dk = $session['user']['dragonkills'];
    page_header("Heidi's Place");
    villagenav();
    output("`&`c`bHeidi, the Well-wisher`b`c`n");
    if ($changeallowed) {
        addnav("Burn Blue Candle - lose 1 PvP", "runmodule.php?module=heidi&op=blue");
    }
    if ($allowdp && $session['user']['dragonkills'] > 10) {
        addnav("O?Ask about the Orange candles", "runmodule.php?module=heidi&op=orange");
    }
    if ($allowgift) {
        addnav(array("Make a Donation - %s gold", $addgold), "runmodule.php?module=heidi&op=give");
    }
    modulehook("heidi-start", array("changeallowed" => $changeallowed, "allowdp" => $allowdp && $session['user']['dragonkills'] > 10, "allowgift" => $allowgift, "giftgold" => $addgold));
    if ($op == "") {
        output("`7You step into Heidi's small hut, gazing around at the multitude of colored candles that flicker from the shelves on every wall.`n`n");
        output("`7After a moment you are greeted by a pleasant-looking felyne with a smile on her face.`n`n");
        output("\"`&It is so lovely to see you, %s!", $session['user']['name']);
        output("`&Welcome, then, and reflect on the beauty of the well.`7\"`n`n");
        output("`7A small fountain trickles into what looks more like a pool than a well.");
        output("`7As Heidi whistles softly, crystals in the bottom of the pool begin to glow, eventually forming the numbers: %s.`n`n", $addgold);
        output("`7\"`&Perhaps ye have come to give! Or to burn a candle for a spell?`7\"");
    } elseif ($op == "give" && $session['user']['gold'] < $addgold && $allowgift) {
        // you don't have enough money.
        output("`7Heidi eyes you with concern.`n`n");
        output("\"`&Child, ye be trying to give, when ye have not the affluence to give.`7`n`n");
        output("`&Take comfort, for the mother sees inside thy heart today.`7\"`n`n");
        output("You're not so sure you understand who this mother is, but you realize that you haven't enough gold to donate what the well requests, and so you leave quietly.`n`n");
    } elseif ($op == "give" && $allowgift) {
        output("`7You lean forward, and place %s gold into the well.`n`n", $addgold);
        output("Heidi concentrates on a small candle for several moments, whispering words you cannot understand.`n`n");
        output("\"`&Somewhere, come the morning fair, someone less fortunate shall wake up with a gift of gold.`7`n`n");
        output("`&The pleasure in giving, be within you today!`7\" she exclaims.`n`n");
        debuglog("gave {$addgold} gold as an anonymous gift to someone less fortunate.");
        $session['user']['gold'] -= $addgold;
        apply_buff('heidi', array("name" => "`QUnselfishness`0", "rounds" => 15, "defmod" => 1.05, "survivenewday" => 1, "roundmsg" => "`QGiving to others makes you feel empowered.`0", "schema" => "module-heidi"));
    } elseif ($op == "orange") {
        output("`7Heidi smiles and motions to the small box of orange candles on a shelf nearby.`n`n");
        output("\"`&Orange is the color of change!");
        output("What's done in life is done, but we can mend bridges if we wish to make the change in ourselves.`7\"`n`n");
        if (!get_module_pref("pendingdp")) {
            output("`7For a cost of %s gems, you will be able to rechoose your dragon point allocation after new day.`n`n", $dk);
        }
        $gemsremain = $dk - $gemspaid;
        if (get_module_pref("pendingdp")) {
            output("`7Heidi looks at you deeply for a moment and then smiles tenderly, \"`&Child, child, you must give time for the past changes to take effect before trying again.`7\"`n`n");
        } elseif ($session['user']['gems']) {
            addnav("Payment");
            // User has enough to pay in full
            if ($session['user']['gems'] >= $gemsremain) {
                // You can always pay what you still owe if you have it.
                addnav(array("Pay in full (%s %s)", $gemsremain, translate_inline($gemsremain == 1 ? "gem" : "gems")), "runmodule.php?module=heidi&op=orangepay&amt={$gemsremain}");
            }
            // Don't make user pay in full if he doesn't want to
            if ($session['user']['gems'] < $gemsremain) {
                addnav(array("Pay an installment (%s %s)", $session['user']['gems'], translate_inline($session['user']['gems'] == 1 ? "gem" : "gems")), "runmodule.php?module=heidi&op=orangepay&amt=" . $session['user']['gems']);
            }
            if ($gemsremain > 25 && $session['user']['gems'] >= 25) {
                addnav(array("Pay an installment (%s %s)", 25, translate_inline("gems")), "runmodule.php?module=heidi&op=orangepay&amt=25");
            }
            // Give some text about the installment
            if ($gemspaid == 0 && ($dk > 25 || $session['user']['gems'] < $gemsremain)) {
                output("`7As your total price is %s gems you might not wish to pay in full immediately, and instead pay in installments.`n`n", $dk);
                output("`\$You will not be able to rechoose your dragon point allocation until the whole amount has been paid, and you cannot regain any gems you have already given once you start to make the installments.`n`n");
                output("`\$Once you pay the full cost, you will lose any hitpoints, attack or defense that you have purchased with dragonpoints until the next new day when you will be able to once again choose their allocation.`n`n");
            } elseif ($gemspaid) {
                output("`^You have paid %s gems so far and have %s remaining in order to rechoose your dragon points at new day.`n`n", $gemspaid, $gemsremain);
                output("`\$You will not be able to rechoose your dragon point allocation until the whole amount has been paid, and you cannot regain any gems you have already given once you start to make the installments.`n`n");
                output("`\$Once you pay the full cost, you will lose any hitpoints, attack or defense that you have purchased with dragonpoints until the next new day when you will be able to once again choose their allocation.`n`n");
                output("`\$Additionally, any buffs you have from visiting Tynan will be immediately reset.  Such is the cost of change.`n`n");
            }
        } else {
            // User doesn't have any gems on him.
            output("`7You don't have enough gems to pay right now.`n`n");
        }
    } elseif ($op == "orangepay") {
        $amt = httpget("amt");
        $gemspaid += $amt;
        $gemsremain = $dk - $gemspaid;
        set_module_pref("gemspaid", $gemspaid);
        if ($gemsremain) {
            debuglog("Spent {$amt} gems on dp reallocation installment with Heidi. {$gemspaid} spent in total.  {$gemsremain} left to pay.");
        } else {
            debuglog("Spent {$amt} gems to pay remaining amount on dp reallocation with Heidi.  {$dk} spent total.");
        }
        $session['user']['gems'] -= $amt;
        if ($gemsremain) {
            output("`7Heidi thanks you for the gems and reminds you that you have now paid %s of the %s total gems you owe.`n`n", $gemspaid, $dk);
        } else {
            output("`7Heidi thanks you for the payment and smiles.");
            output("She takes a small, orange candle, lights it and places it in a small silver holder, before whispering words that seem foreign to your ears.");
            output("She finally opens her eyes and reminds you that you will be able to rechoose your dragon point allocation at new day.`n`n");
            set_module_pref("gemspaid", 0);
            $hpcount = 0;
            $atcount = 0;
            $defcount = 0;
            reset($session['user']['dragonpoints']);
            while (list($key, $val) = each($session['user']['dragonpoints'])) {
                if ($val == "hp") {
                    $hpcount += 5;
                }
                if ($val == "at") {
                    $atcount++;
                }
                if ($val == "de") {
                    $defcount++;
                }
            }
            restore_buff_fields();
            $session['user']['maxhitpoints'] -= $hpcount;
            $session['user']['hitpoints'] -= $hpcount;
            $session['user']['attack'] -= $atcount;
            $session['user']['defense'] -= $defcount;
            set_module_pref("attack", 0, "tynan");
            set_module_pref("defense", 0, "tynan");
            set_module_pref("hitpoints", 0, "tynan");
            strip_buff("tynanSTAT");
            if ($session['user']['hitpoints'] <= 1) {
                $session['user']['hitpoints'] = 1;
            }
            // call the reset hook before we wipe the array just in case
            // something cares!
            modulehook("dkpointspentreset");
            $session['user']['dragonpoints'] = array();
            set_module_pref("pendingdp", 1);
            calculate_buff_fields();
        }
    } elseif ($session['user']['playerfights'] == 0 || $pvpchange >= $changeallowed) {
        // you have no PvP left today or have already burned the blue
        // enough today
        output("`7Heidi eyes you with a smile.`n`n");
        if ($session['user']['playerfights'] == 0) {
            output("\"`&'Tis all very well to want peace, when one has none extra to give!`7\"`n`n");
        } else {
            // No more burning allowed today.
            output("\"`&Your desire for peace is noble, but is misplaced at this time.`7\"`n`n");
        }
        output("\"`&Perhaps tomorrow ye will come to see me, before ye slay your enemies in fury?`7\"`n`n");
    } else {
        output("`7Heidi takes a small, sky-blue candle, lights it and places it in a small silver holder.");
        output("She regards you with a smile.`n`n");
        output("\"`&Your gesture of kindness to your fellow beings shall reward you.");
        output("Go in peace, warrior.`7\"`n`n");
        output("`6You `@gain`6 %s turns!`n`n", $turngain);
        $session['user']['turns'] += $turngain;
        $session['user']['playerfights']--;
        $pvpchange++;
        set_module_pref("pvpchange", $pvpchange);
        debuglog("exchanged one PvP fight for {$turngain} forest fights.");
        $newdayturns *= 0.75;
        // second and subsequent burns have lower benefit
        set_module_pref("newdayturns", $newdayturns);
    }
    modulehook("heidi-end", array("changeallowed" => $changeallowed, "allowdp" => $allowdp && $session['user']['dragonkills'] > 10, "allowgift" => $allowgift, "giftgold" => $addgold));
    page_footer();
}
function tutor_run()
{
    global $session;
    $op = httpget("op");
    $city = getsetting("villagename", LOCATION_FIELDS);
    // name of capital city
    $iname = getsetting("innname", LOCATION_INN);
    // name of capital's inn
    $age = $session['user']['age'];
    if ($op == "helpfiles") {
        page_header("Help!");
        output("`%`c`bHelp Me, I'm Lost!`b`c`n");
        output("`@Feeling lost?`n`n");
        output("`#Legend of the Green Dragon started out small, but with time it has collected many new things to explore.`n`n");
        output("To a newcomer, it can be a little bit daunting.`n`n");
        output("To help new players, the Central staff created Eibwen, the imp.");
        output("He's the little blue guy who told you to buy weapons when you first joined, and helped you choose a race.");
        output("But what happens next, where should you go, and what are all the doors, alleys, and shops for?`n`n");
        output("First of all: The game is about discovery and adventure.");
        output("For this reason, you won't find all the answers to every little question.");
        output("For most things, you should read the FAQs, or just try them and see.`n`n");
        output("But we recognize that some things aren't at all obvious.");
        output("So while we won't tell you what everything does, we've put together a list of things that you might want to try first, and that new players commonly ask us.`n`n");
        output("Please understand that these hints are spoilers.");
        output("If you'd rather discover on your own, don't read any further.`n`n");
        output("`%What are all those things in my Vital Info, and Personal Info, I'm confused?");
        output("A lot of it you don't need to worry about for the most part.");
        output("The ones you should watch carefully are your hitpoints, and your experience.");
        output("Ideally, you should keep that hitpoint bar green.");
        output("And beware if it begins to turn yellow, or worse still, red.");
        output("That tells you that death is near.");
        output("Sometimes running would be smarter than risking death.");
        output("Perhaps there's someone close by who can help you feel better.`n`n");
        output("Lower down is the experience bar, which starts all red, and will gradually fill up with white.");
        output("Wait until it goes blue before you challenge your master.");
        output("If you can't see a blue bar, you aren't ready yet!`n`n");
        output("Looking for someone you know?");
        output("The List Warriors area will tell you if your friend is online right now or not.");
        output("If they are, Ye Olde Mail is a good way to contact them.`n`n");
        output("What are gems for?");
        output("Hang onto these and be careful how you spend them.");
        output("There are some things that you can only obtain with gems.`n`n");
        output("Have you been into %s, in %s? Perhaps you'd like to try a drink, listen to some entertainment, or chat to people.", $iname, $city);
        output("It's also a good idea to get to know the characters in the %s, because they can be quite helpful to a young warrior.", $iname);
        output("You might even decide that sleeping in %s would be safer than in the fields.`n`n", $iname);
        output("Travelling can be dangerous.");
        output("Make sure you've placed your valuables somewhere safe, and that you're feeling healthy before you leave.`n`n");
        output("Hungry, tired, feeling adventurous, or looking for a pet?");
        output("The Spa, the Kitchen, the Tattoo Parlor, and the Stables are all places you might want to visit.");
        output("These things are just some of the shops in different towns.");
        output("Some of them give turns, charm or energy, and some take it away.`n`n");
        output("Where's the dragon?");
        output("They all ask this.");
        output("You'll see her when you are ready to fight her, and not before, and you will need to be patient and build your strength while you wait.`n`n");
        output("`QIf you have any questions which are not covered in the FAQ, you may wish to Petition for Help - bear in mind that the staff won't give you the answer if it will spoil the game for you.");
        villagenav();
        page_footer();
    }
}
function drpap_run()
{
    global $session;
    $c = get_module_pref("count");
    // if ($c){
    // if (is_module_active("medals")){
    // require_once "modules/medals.php";
    // medals_award_medal("sexchange","Gender Reassignment","This player switched their gender at Doc Paprika's office!","medal_museumquest.png");
    // }
    // }
    $t = get_module_setting("times");
    $gold = get_module_setting("gold");
    $gems = get_module_setting("gems");
    $op = httpget('op');
    $dec = httpget('dec');
    $gen = translate_inline($session['user']['sex'] == 0 ? "sir" : "madam");
    $ngen = translate_inline($session['user']['sex'] == 1 ? "sir" : "madam");
    $g = translate_inline($gems == 1 ? "Gem" : "Gems");
    page_header("Dr Paprika's Office");
    switch ($op) {
        case "enter":
            if ($c < $t) {
                output("`3Subtle tunes play in the background; classic rock.");
                output("In the Center of the waiting room, is a large table - covered with out-of-date magazines.");
                output("A beautiful receptionist looks at you, across a pane of glass.");
                output("She glances at you, and waves, \"`%Hello there %s.", $gen);
                output("Are you here to see `QDr Paprika`%?");
                output("He is the only doctor in %s, excelling in the field of `\$Gender Changes`%.`3\"", get_module_setting("paploc"));
                addnav("Where to?");
                addnav("Dr Paprika's Room", "runmodule.php?module=drpap&op=office");
                addnav("Waiting Room", "runmodule.php?module=drpap&op=waitroom");
            } else {
                output("`3\"`%I am sorry %s, but you have already had %s `\$Gender Changes`%.", $gen, $c);
                output("Since the limit is %s, we are able to deny you service now.", $t);
                output("Please take care.`3\"");
                if (get_module_setting("reset") == 1) {
                    output("`3The receptionist adds, \"`%If you come back with some `@dragon's blood`%, we might be able to work something out.`3\"");
                }
            }
            break;
        case "office":
            if ($dec != "yes") {
                if ($session['user']['gold'] >= $gold && $session['user']['gems'] >= $gems) {
                    output("`3You walk in a white room, very white.");
                    output("A long operating table, is accompanied by a small swivel chair.");
                    output("Strutting out from the shadows, `QDr Paprika `3appears, and shakes your hand.");
                    output("\"`\$So, you wish to have a `%Gender Change `\$operation?`3\"");
                    addnav("Choices");
                    addnav("Yes", "runmodule.php?module=drpap&op=office&dec=yes");
                    addnav("Return to the Waiting Room", "runmodule.php?module=drpap&op=waitroom");
                } else {
                    output("`QDr Paprika `3stares at your blankly.");
                    output("\"`\$I am sorry %s, but you do not have the proper funds for this operation.`3\"", $gen);
                    output("`QDr Paprika `3points to a sign, stating \"`%Gender Operations cost `^%s `%Gold and `5%s `%%s.`3\"", $gold, $gems, $g);
                }
            } else {
                output("`QDr Paprika `3nods and begins to prep himself.");
                output("\"`\$Please lay down on the operating table... I will be with your shortly...`3\"");
                output("`QDr Paprika `3hovers over you and then pulls out a tiny bottle of ether.");
                output("He presses it to your nose and instructs, \"`\$Please count to One Hundred...`3\"");
                output("You begin to count...`n`n");
                for ($i = 1; $i <= $session['user']['level']; $i++) {
                    output("%s...`n", $i);
                }
                if ($session['user']['sex'] == 0) {
                    $session['user']['sex'] = 1;
                } else {
                    $session['user']['sex'] = 0;
                }
                $c++;
                set_module_pref("count", $c);
                $session['user']['gold'] -= $gold;
                $session['user']['gems'] -= $gems;
                require_once "lib/titles.php";
                $newtitle = get_dk_title($session['user']['dragonkills'], $session['user']['sex']);
                require_once "lib/names.php";
                $newname = change_player_title($newtitle);
                $session['user']['title'] = $newtitle;
                $session['user']['name'] = $newname;
                output("`nYou awaken hours later, your muscles shuddering.");
                output("You grasp the mirror to your side, and then look at yourself.");
                output("Surprisingly, you are now a healthy looking %s.", $ngen);
                output("You stand quickly, and shake `QDr Paprika's `3hand, thanking him profusely.");
                output("Taking up your clothes, you strut out from the office, smiling happily.");
            }
            break;
        case "waitroom":
            output("`3All around you, people are sitting.");
            output("Some are thumbing through magazines, whilst others are tapping their feet in anticipation.`n`n");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("drpap", "Nervous People are Around", 15, "says");
            addnav("Return to Lobby", "runmodule.php?module=drpap&op=enter");
            break;
    }
    addnav("Leave");
    villagenav();
    page_footer();
}
function jeweler_run()
{
    global $session;
    $totalheld = get_module_pref("totalheld");
    $sellpercent = get_module_setting("sellpercent");
    $op = httpget("op");
    $type = httpget("type");
    page_header("Oliver, the Jeweler");
    output("`&`c`bOliver's Jewelry`b`c`n");
    if ($op == "") {
        $itemarray = array("choker" => "C", "amulet" => "A", "necklace" => "N", "bracelet" => "B", "ring" => "R");
        $prefsarray = get_all_module_prefs();
        addnav("Examine");
        while (list($key, $val) = each($itemarray)) {
            if (!$prefsarray[$key . "held"]) {
                $navstring = "runmodule.php?module=jeweler&op=examine&type={$key}";
                $key = str_replace("_", " ", $key);
                $key = ucwords($key);
                $displaystring = "Examine {$key}";
                if ($val !== false) {
                    $displaystring = $val . "?" . $displaystring;
                }
                addnav($displaystring, $navstring);
            }
        }
        reset($itemarray);
        addnav("Sell");
        while (list($key, $val) = each($itemarray)) {
            if ($prefsarray[$key . "held"]) {
                $navstring = "runmodule.php?module=jeweler&op=sell&type={$key}";
                $key = str_replace("_", " ", $key);
                $key = ucwords($key);
                $displaystring = " ?Sell Back {$key}";
                addnav($displaystring, $navstring);
            }
        }
        output("`7You step into Oliver's Jewelry Store and are greeted by a dwarf in spectacles.");
        output("`3Oliver`7 folds his hands on a small bench and his eyes twinkle.`n`n");
        output("\"`&Good day, warrior, come to see the fine wares, have ye?`7\"`n`n");
        output("`7You see another bench showcasing some of his fine work, and wonder whether to take a closer look.");
    } elseif ($op == "examine") {
        switch ($type) {
            case "choker":
                output("`3Oliver `7gets up from his stool and moves towards the magnificent choker sitting on a mannequin's torso.");
                output("Glittering jewels are held together by gold chains, meshed in a design larger than your hand.`n`n");
                output("\"`&Ye have a fine eye for quality there!`7\" he says.`n`n");
                output("\"`&More than a hundred pieces of crystal and fifty more precious stones went into this.");
                output("It isn't every day I put my heart into a piece like this!");
                break;
            case "amulet":
                output("`3Oliver `7rises and moves towards the amulet on the stand.");
                output("Polished silver sports gems in all colors of the spectrum.`n`n");
                output("\"`&Ah, the amulet in silver!`7\" he says.`n`n");
                output("\"`&So many hours of work, so many precious stones!");
                output("This is no cheap item, no, ye've spotted a quality work, here.");
                break;
            case "necklace":
                output("`3Oliver `7gets up from his stool and moves towards the beautiful necklace draped around a mannequin neck.");
                output("Silky strands of silver fall in an elegant V, with pearls and diamonds in a cluster at the bottom.`n`n");
                output("\"`&I see ye looking at the necklace with the diamonds and pearls!`7\" he says.`n`n");
                output("\"`&It's so simple, and yet so elegant, nay?");
                output("It's a true show piece, this one.");
                break;
            case "bracelet":
                output("`3Oliver `7moves from behind his workbench and approaches the copper bracelet studded with crystals.");
                output("As you look closer, you see the colors emerge.`n`n");
                output("\"`&Ye see the twinkles, I can see!`7\" he says.`n`n");
                output("\"`&Not just white, but green, yellow, blue in this one.");
                output("I keep these for special customers!`7\" he says with a wink.`n`n\"`&");
                break;
            case "ring":
                output("`3Oliver `7sees you eyeing the ring, and he moves over to show you more.`n`n");
                output("\"`&What ye have there's the finest gold in these lands!");
                output("The emerald, oh, such an emerald that even the king wouldst think fine!`7\" he says.`n`n");
                output("\"`&My gems are specially sourced, you know.");
                output("Other jewelers can't all claim such a special thing!");
                break;
        }
        $buycost = get_module_setting($type);
        addnav("Purchase");
        output("It can be yours, for `%%s`& gems.`7\"`n`n", $buycost);
        if ($session['user']['gems'] >= $buycost) {
            addnav("Buy This Item", "runmodule.php?module=jeweler&op=buy&type=" . $type);
        }
        addnav("Shop");
        addnav("Continue Looking", "runmodule.php?module=jeweler");
    } elseif ($op == "buy") {
        set_module_pref($type . "held", 1);
        $buycost = get_module_setting($type);
        $session['user']['gems'] -= $buycost;
        debuglog("spent " . $buycost . " gems on a {$type}");
        $totalheld++;
        set_module_pref("totalheld", $totalheld);
        output("`7You hand `3Oliver `7the gems and take the %s from him with a smile, putting it on and admiring yourself in the mirror in front of you.", translate_inline($type));
        addnav("Shop");
        addnav("Continue Looking", "runmodule.php?module=jeweler");
    } elseif ($op == "sell") {
        output("`3Oliver `7picks up the %s and eyes you carefully.", translate_inline($type));
        output("\"`&Are ye sure ye wish to sell it back to me?");
        output("I have a few of them now, and can't offer ye the same price you paid.`7\"`n`n");
        output("`7He examines the %s, then counts out some gems into a pile.", translate_inline($type));
        $sellcost = round(get_module_setting($type) * $sellpercent * 0.01);
        output("`7You consider his offer of %s gems.", $sellcost);
        addnav("Sell");
        addnav("Confirm Sale", "runmodule.php?module=jeweler&op=confirm&type=" . $type);
        addnav("Shop");
        addnav("Continue Looking", "runmodule.php?module=jeweler");
    } elseif ($op == "confirm") {
        $sellcost = round(get_module_setting($type) * $sellpercent * 0.01);
        $session['user']['gems'] += $sellcost;
        set_module_pref($type . "held", 0);
        debuglog("received " . $sellcost . " gems refund for a {$type}");
        $totalheld--;
        set_module_pref("totalheld", $totalheld);
        output("`7You hand `3Oliver `7your %s and take the tidy pile of gems from him with a smile, placing them in your purse.", translate_inline($type));
        addnav("Shop");
        addnav("Continue Looking", "runmodule.php?module=jeweler");
    }
    villagenav();
    page_footer();
}
function hundredpointrally_run()
{
    global $session;
    page_header("Rally Headquarters");
    $op = httpget('op');
    //load settings
    $joincost = get_module_setting("joincost", "hundredpointrally");
    $data = @unserialize(get_module_setting("data", "hundredpointrally"));
    if (!is_array($data)) {
        $data = array();
        set_module_setting("data", serialize($data), "hundredpointrally");
    }
    //load pref
    $player = @unserialize(get_module_pref("data", "hundredpointrally"));
    if (!is_array($player)) {
        $player = array();
        set_module_pref("data", serialize($player), "hundredpointrally");
    }
    switch ($op) {
        case "start":
            do_forced_nav(false, false);
            require_once "lib/datetime.php";
            $nextstarttime = reltime($data['next']['starttime'], false);
            if (!$data['next']['starttime']) {
                $nextstarttime = "Undetermined amount of time";
            }
            $seed = get_module_setting("jackpotseed", "hundredpointrally");
            if (!isset($data['next']['jackpot']) || $data['next']['jackpot'] < $seed) {
                $data['next']['jackpot'] = $seed;
                set_module_setting("data", serialize($data), "hundredpointrally");
            }
            output("You head into a building decked out with chequered flags.  It smells of petrol and burning rubber, although there are no cars or motorbikes to be seen.  Noticing that the receptionist is a Robot, you surmise that she must be pumping the scent in artificially in order to create atmosphere.  Which figures, really.`n`n\"`7Hello!`0\" she says in a tinny, cheery warble.  \"`7Are you here to sign up for the Hundred-Point Rally?  The next one starts in -`0\" her voice becomes stilted and mechanical for a moment - \"`&%s TO RACE START JACKPOT VALUE OF %s CIGARETTES ENTRY FEE OF %s CIGARETTES`7.`0\"`n`n", strtoupper($nextstarttime), $data['next']['jackpot'], $joincost);
            if ($data['current']['open']) {
                $currentstarttime = reltime($data['current']['starttime'], false);
                output("\"`7Or, if you prefer, the current Rally is still open.  It started -`0\" the same mechanical, halting tone - \"`&%s AGO CURRENT JACKPOT %s CIGARETTES`7.  You'd have a better chance if you waited for the next one, but you can join this one if you're impatient.  It'll cost you the same either way.\"`n`n", strtoupper($currentstarttime), $data['current']['jackpot']);
            }
            addnav("Join a Rally");
            if ($session['user']['gems'] >= $joincost) {
                if (!$player['activenext']) {
                    addnav("Join the `bnext`b Hundred-Point Rally", "runmodule.php?module=hundredpointrally&op=joinnext");
                }
                if (!$player['activecurrent'] && $data['current']['open']) {
                    addnav("Join the `bcurrent`b Hundred-Point Rally", "runmodule.php?module=hundredpointrally&op=joincurrent");
                }
            }
            addnav("What?");
            addnav("Explain this Rally business to me.", "runmodule.php?module=hundredpointrally&op=explain");
            addnav("Exit");
            villagenav();
            break;
        case "explain":
            do_forced_nav(false, false);
            output("\"`7It's very simple,`0\" says the Robot.  \"`7The Hundred-Point Rally is a race around the World Map.  The winner takes the jackpot - the more people signed up for the Rally, the bigger the Jackpot.  You'll be given a series of fifty co-ordinates that you have to visit in sequence, and you'll also be given another fifty co-ordinates that can be visited in any order you like.  The challenge is not only in speed, but also in your ability to determine the most efficient path to hit all one hundred co-ordinates.  Because the race can be quite long, and because the co-ordinates are only revealed once the race has begun, it may or may not be a good idea to spend some time plotting out your route before heading to the first Rally Point.  Each new Rally starts exactly twenty-four hours `&WARNING SYSTEM CLOCK ERROR WHAT THE HELL WHY IS 24 HOURS THE SAME AS SIX DAYS`7 after the last one ends, and a Rally can last for up to 48 hours.`0\"`n`nYou nod.  \"`#Could you explain that part about the system clock error again?`0\"`n`n\"`&What part?`0\"`n`n\"`#Ah.`0\"`n`n`JTo ensure that players from different time zones have a fair shake every now and then, Rallies aren't tied to game time.  When the Robot says \"24 hours,\" she means 24 hours of your time, not game time (which runs six times faster).  If you're signing up for the next Rally and a start time isn't determined yet, you'll get a Distraction exactly 24 hours before the race begins, and another one at the drop of the chequered flag.  We highly recommend that you have Distractions sent to your E-mail if you're a Rally fan, and you can find the relevant option in your Preferences menu in any Outpost.`n`nRallies end as soon as someone hits all one hundred points - so, for example, if a Rally starts at midnight and ends at 2am, the next Rally will start at 2am the next day - and if `ithat`i Rally takes three hours to complete, then the Rally ends at 5am and the next Rally begins at 5am the next day.  This way, we eventually end up going all the way around the clock, giving players in different timezones a chance to compete in the Rally.`0");
            addnav("Okay, then.");
            addnav("Back to Reception", "runmodule.php?module=hundredpointrally&op=start");
            break;
        case "joinnext":
            do_forced_nav(false, false);
            output("You hand over your Cigarettes.  \"`7Very well.  Your entry has been accepted and you will be notified via Distraction when the race starts.  In the meantime, I suggest you buy a very, very fast Mount.`0\"  The Robot tries to smile.  It doesn't come out too well.");
            $data['next']['competitors'][$session['user']['acctid']]['points'] = 0;
            $data['next']['competitors'][$session['user']['acctid']]['name'] = $session['user']['name'];
            $player['activenext'] = true;
            $session['user']['gems'] -= $joincost;
            $data['next']['jackpot'] += floor($joincost * 0.75);
            set_module_pref("data", serialize($player), "hundredpointrally");
            set_module_setting("data", serialize($data), "hundredpointrally");
            addnav("Exit");
            villagenav();
            break;
        case "joincurrent":
            do_forced_nav(false, false);
            output("You hand over your Cigarettes.  \"`7Very well.  Your entry has been accepted.  Now you had better get out there and race!`0\"  The Robot tries to smile.  It doesn't come out too well.");
            $data['current']['competitors'][$session['user']['acctid']]['points'] = 0;
            $data['current']['competitors'][$session['user']['acctid']]['name'] = $session['user']['name'];
            $session['user']['gems'] -= $joincost;
            $data['current']['jackpot'] += floor($joincost * 0.75);
            $player['activecurrent'] = true;
            set_module_pref("data", serialize($player), "hundredpointrally");
            set_module_setting("data", serialize($data), "hundredpointrally");
            addnav("Exit");
            villagenav();
            break;
        case "showpoints":
            popup_header("Rally Points");
            rawoutput("<table cellpadding=5 cellspacing=5 border=0><tr><td valign='top'>");
            output("`0`bSequenced Points`b`nHit each of these World Map points in the prescribed order:`n");
            foreach ($data['current']['sequencedpoints'] as $order => $loc) {
                list($sx, $sy, $sz) = explode(",", $data['current']['sequencedpoints'][$order]);
                if ($player['sequencedpoints'] > $order) {
                    rawoutput("<del>");
                    output("Point %s: `@%s,%s`0`n", $order, $sx, $sy);
                    rawoutput("</del>");
                } else {
                    if ($player['sequencedpoints'] < $order) {
                        output("Point %s: `\$%s,%s`0`n", $order, $sx, $sy);
                    } else {
                        output(">> Point %s: `Q%s,%s`0`n", $order, $sx, $sy);
                    }
                }
            }
            rawoutput("</td><td valign='top'>");
            output("`0`bUnordered Points`b`nHit each of these World Map points in whatever order seems best to you:`n");
            foreach ($data['current']['unorderedpoints'] as $order => $loc) {
                list($ux, $uy, $uz) = explode(",", $loc);
                if (@in_array($loc, $player['unorderedpoints'])) {
                    rawoutput("<del>");
                    output("`@%s,%s`0`n", $ux, $uy);
                    rawoutput("</del>");
                } else {
                    output("`\$%s,%s`0`n", $ux, $uy);
                }
            }
            rawoutput("</td><td valign='top'>");
            $rankings = hundredpointrally_getrankings();
            output("`bCurrent Rankings`b`n");
            foreach ($rankings as $rank => $info) {
                if ($info['acctid'] == $session['user']['acctid']) {
                    output("`J`b>>`b ");
                }
                output("#%s: %s`0 (%s points)`n", $rank + 1, $info['name'], $info['points']);
            }
            rawoutput("</td></tr></table>");
            popup_footer();
            break;
    }
    page_footer();
}
function worldmapen_run_real()
{
    global $session, $badguy, $pvptimeout, $options, $outdoors, $shady;
    $outdoors = true;
    $op = httpget("op");
    $battle = false;
    if ($op == 'move' && rawurldecode(httpget('oloc')) != get_module_pref('worldXYZ')) {
        debug(get_module_pref('worldXYZ'));
        $op = 'continue';
        httpset('op', $op);
    }
    //	debug("Worldmap running op={$op} ...");
    // handle the admin editor first
    if ($op == "edit") {
        if (!get_module_pref("canedit")) {
            check_su_access(SU_EDIT_USERS);
        }
        if (get_module_setting("worldmapenInstalled") != 1) {
            set_module_setting('worldmapenInstalled', "1");
            worldmapen_defaultcityloc();
        }
        worldmapen_editor();
    }
    if ($op == "destination") {
        $cname = httpget("cname");
        $session['user']['location'] = $cname;
        addnav(array("Enter %s", $cname), "village.php");
        output("`c`4`bYou've Arrived in %s.`b`0`c`n", $cname);
        output("`cYou have reached the outer gates of the city.`c");
    }
    if (!get_module_setting("worldmapenInstalled")) {
        page_header("A rip in the fabric of space and time");
        require_once "lib/villagenav.php";
        villagenav();
        output("`^The admins of this game haven't yet finished installing the worldmapen module.");
        output("You should send them a petition and tell them that they forgot to generate the initial locations of the cities.");
        output("Until then, you are kind of stuck here, so I hope you like where you are.`n`n");
        output("After all, remember:`nWherever you go, there you are.`0");
        page_footer();
    }
    $subop = httpget("subop");
    $act = httpget("act");
    $type = httpget("type");
    $name = httpget("name");
    $direction = httpget("dir");
    $su = httpget("su");
    $buymap = httpget("buymap");
    $worldmapCostGold = get_module_setting("worldmapCostGold");
    $pvp = httpget('pvp');
    require_once "lib/events.php";
    if ($session['user']['specialinc'] != "" || httpget("eventhandler")) {
        $in_event = handle_event(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue&", "Travel");
        if ($in_event) {
            addnav("Continue", "runmodule.php?module=worldmapen&op=continue");
            module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
            page_footer();
        }
    }
    page_header("Journey");
    //is the player looking at chat?
    if (httpget('comscroll') || httpget('comscroll') === 0 || httpget('comment') || httpget('refresh')) {
        $chatoverride = 1;
        require_once "lib/commentary.php";
        addcommentary();
        $loc = get_module_pref("worldXYZ", "worldmapen");
        viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
    }
    if ($op == "beginjourney") {
        $loc = $session['user']['location'];
        $x = get_module_setting($loc . "X");
        $y = get_module_setting($loc . "Y");
        $z = get_module_setting($loc . "Z");
        $xyz = $x . "," . $y . "," . $z;
        set_module_pref("worldXYZ", $xyz);
        output("`b`&The gates of %s`& stand closed behind you.`0`b`n`n", $session['user']['location']);
        $num = e_rand(1, 5);
        $msg = get_module_setting("leaveGates{$num}");
        output("`c`n`^%s`0`n`c`n", $msg);
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "continue") {
        checkday();
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
        //Turns Trading bit, added by CavemanJoe
    } elseif ($op == "tradeturn") {
        checkday();
        $pointstrade = get_module_setting("turntravel");
        output("You can trade one Turn for %s Travel Points.  Do you want to do this now?", $pointstrade);
        addnav("Yes, use a turn", "runmodule.php?module=worldmapen&op=tradeturnconfirm");
        addnav("No, cancel and return to the map", "runmodule.php?module=worldmapen&op=continue");
    } elseif ($op == "tradeturnconfirm") {
        $pointstrade = get_module_setting("turntravel");
        output("By conserving energy that you would have otherwise used for fighting creatures, you have gained %s Travel Points.", $pointstrade);
        $session['user']['turns']--;
        $ttoday = get_module_pref("traveltoday", "cities");
        set_module_pref("traveltoday", $ttoday - $pointstrade, "cities");
        addnav("Continue", "runmodule.php?module=worldmapen&op=continue");
    } elseif ($op == "move" && !$chatoverride) {
        checkday();
        if ($session['user']['location'] != 'World') {
            set_module_pref("lastCity", $session['user']['location']);
            $session['user']['location'] = "World";
        }
        $session['user']['restorepage'] = "runmodule.php?module=worldmapen&op=continue";
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        if ($direction == "north") {
            $y += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "northeast") {
            $y += 1;
            $x += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "northwest") {
            $y += 1;
            $x -= 1;
        }
        if ($direction == "east") {
            $x += 1;
        }
        if ($direction == "south") {
            $y -= 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "southeast") {
            $y -= 1;
            $x += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "southwest") {
            $y -= 1;
            $x -= 1;
        }
        if ($direction == "west") {
            $x -= 1;
        }
        $terraincost = worldmapen_terrain_cost($x, $y, $z);
        $encounterbase = worldmapen_encounter($x, $y, $z);
        $encounterchance = get_module_pref("encounterchance");
        $encounter = $encounterbase * $encounterchance / 100;
        debug($encounterbase . " * " . $encounterchance . " / 100 = " . $encounter);
        $ttoday = get_module_pref("traveltoday", "cities");
        set_module_pref("traveltoday", $ttoday + $terraincost, "cities");
        worldmapen_terrain_takestamina($x, $y, $z);
        $xyz = $x . "," . $y . "," . $z;
        set_module_pref("worldXYZ", $xyz);
        // $randchance = get_module_setting("randchance");
        // if (e_rand(0,100) < $randchance){
        // $eventravel = "travel";
        // set_module_setting("randevent", $eventravel);
        // }else{
        // $eventravel = "forest";
        // set_module_setting("randevent", $eventravel);
        // }
        //Extra Gubbins pertaining to trading Turns for Travel, added by Caveman Joe
        $useturns = get_module_setting("useturns");
        $allowzeroturns = get_module_setting("allowzeroturns");
        $playerturns = $session['user']['turns'];
        $proceed = 1;
        //the Proceed value is used when the player has hit a monster, to make sure it's okay to actually run the event/monster.
        if ($playerturns == 0 && $allowzeroturns == 0) {
            $proceed = 0;
        }
        if (e_rand(0, 100) < $encounter && $su != '1' && $proceed == 1 && !$chatoverride) {
            // They've hit a monster!
            if (module_events(get_module_setting("randevent"), get_module_setting("wmspecialchance"), "runmodule.php?module=worldmapen&op=continue&") != 0) {
                page_header("Something Special!");
                if (checknavs()) {
                    page_footer();
                } else {
                    // Reset the special for good.
                    $session['user']['specialinc'] = "";
                    $session['user']['specialmisc'] = "";
                    $skipvillagedesc = true;
                    $op = "";
                    httpset("op", "");
                    addnav("Continue", "runmodule.php?module=worldmapen&op=continue&");
                    module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
                    page_footer();
                }
            }
            //Check if we're removing a turn when the player encounters a monster, and if so, do it
            if ($useturns == 1) {
                $session['user']['turns']--;
            }
            //Fix to only search for Forest type creatures, added by CavemanJoe
            $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = '{$session['user']['level']}' AND forest = 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
            $result = db_query($sql);
            restore_buff_fields();
            if (db_num_rows($result) == 0) {
                // There is nothing in the database to challenge you,
                // let's give you a doppleganger.
                $badguy = array();
                $badguy['creaturename'] = "An evil doppleganger of " . $session['user']['name'];
                $badguy['creatureweapon'] = $session['user']['weapon'];
                $badguy['creaturelevel'] = $session['user']['level'];
                $badguy['creaturegold'] = rand($session['user']['level'] * 15, $session['user']['level'] * 30);
                $badguy['creatureexp'] = round($session['user']['experience'] / 10, 0);
                $badguy['creaturehealth'] = $session['user']['maxhitpoints'];
                $badguy['creatureattack'] = $session['user']['attack'];
                $badguy['creaturedefense'] = $session['user']['defense'];
            } else {
                $badguy = db_fetch_assoc($result);
                require_once "lib/forestoutcomes.php";
                $badguy = buffbadguy($badguy);
            }
            calculate_buff_fields();
            $badguy['playerstarthp'] = $session['user']['hitpoints'];
            $badguy['diddamage'] = 0;
            $badguy['type'] = 'world';
            //debug("Worldmap run.php is debugging badguy");
            //debug($badguy);
            $session['user']['badguy'] = createstring($badguy);
            $battle = true;
        } else {
            // $args = modulehook("count-travels", array('available'=>0, 'used'=>0));
            // $free = max(0, $args['available'] - $args['used']);
            // if (get_module_setting("usestamina")==1){
            // output("`c`nYou think to yourself what a nice day it is.`c`n");
            // } else {
            // output("`c`nYou think to yourself what a nice day it is.`nYou have %s Travel Points remaining.%s`c`n",$free);
            // }
            $free = 100;
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            if (!$chatoverride) {
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
            }
            worldmapen_viewmapkey(true, false);
            module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
        }
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "gypsy") {
        $outdoors = false;
        if ($buymap == '') {
            output("`5\"`!Ah, yes.  An adventurer.  I could tell by looking into your eyes,`5\" the gypsy says.`n");
            output("\"`!Many people have lost their way while journeying without a guide such as this.");
            output("It will let you see all the world.`5\"`n");
            output("\"`!Yes, yes.  Let's see...  What sort of price should we put on this?");
            output("Hmm.  How about `^%s`! gold?`5\"", $worldmapCostGold);
            addnav(array("Buy World Map `0(`^%s gold`0)", $worldmapCostGold), "runmodule.php?module=worldmapen&op=gypsy&buymap=yes");
            addnav("Forget it", "village.php");
        } elseif ($buymap == 'yes') {
            if ($session['user']['gold'] < $worldmapCostGold) {
                output("`5\"`!What do you take me for?  A blind hag?  Come back when you have the money`5\"");
                addnav("Leave quickly", "village.php");
            } else {
                output("`5\"`!Enjoy your newfound sight,`5\"  the gypsy says as she walks away to greet some patrons that have just strolled in.");
                $session['user']['gold'] -= $worldmapCostGold;
                set_module_pref("worldmapbuy", 1);
                require_once "lib/villagenav.php";
                villagenav();
            }
        }
    } elseif ($op == "viewmap") {
        worldmapen_determinenav();
        worldmapen_viewmap(true);
        if (is_module_active("medals")) {
            require_once "modules/medals.php";
            medals_award_medal("boughtmap", "Bearer of the Map", "This player purchased the World Map from the Comms Tent!", "medal_islandmap.png");
        }
    } elseif ($op == "camp") {
        if ($session['user']['loggedin']) {
            $session['user']['loggedin'] = 0;
            $session['user']['restorepage'] = "runmodule.php?module=worldmapen&op=wake";
            saveuser();
            invalidatedatacache("charlisthomepage");
            invalidatedatacache("list.php-warsonline");
        }
        $session = array();
        redirect("index.php", "Redirected to Index from World Map");
    } elseif ($op == "wake") {
        if ($session['user']['hitpoints'] > 0) {
            // runmodule.php calls do_forced_nav,
            $session['user']['alive'] = true;
            // and that resets ['alive'], so
        } else {
            // this is from common.php to make sure
            $session['user']['alive'] = false;
            // the player is not half-dead after log-in.
        }
        output("You yawn and stretch and look around your campsite.`n`n");
        output("Ah, how wonderful it is to sleep in the open air!`n");
        output("The world seems full of possibilities today.`n`n");
        checkday();
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "combat") {
        // Okay, we've picked a person to fight.
        require_once "lib/pvpsupport.php";
        $name = httpget("name");
        $badguy = setup_target($name);
        $failedattack = false;
        if ($badguy === false) {
            output("`0`n`nYou survey the area again.`n");
            worldmapen_determinenav();
        } else {
            $battle = true;
            $badguy['type'] = 'pvp';
            //$options['type'] = 'pvp';
            $session['user']['badguy'] = createstring($badguy);
            $session['user']['playerfights']--;
        }
    } elseif ($op == "fight" || $op == "run") {
        if (!$chatoverride && !httpget("frombio")) {
            $battle = true;
        } else {
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            worldmapen_viewmapkey(true, false);
        }
        // $args = modulehook("count-travels", array('available'=>0,'used'=>0));
        // $free = max(0, $args['available'] - $args['used']);
        // if (get_module_setting("usestamina")==1){
        $free = 100;
        // }
        if ($op == "run" && !$pvp) {
            if (!$chatoverride) {
                if (e_rand(1, 5) < 3 && $free) {
                    // They managed to get away.
                    output("You set off running at a breakneck pace!`n`n");
                    output("A short time later, you have managed to avoid your opponent, so you stop to catch your breath.");
                    $ttoday = get_module_pref("traveltoday", "cities");
                    set_module_pref("traveltoday", $ttoday + 1, "cities");
                    output("As you look around, you realize that all you really managed was to run in circles.");
                    $battle = false;
                    worldmapen_determinenav();
                    if (get_module_setting("smallmap")) {
                        worldmapen_viewsmallmap();
                    }
                    require_once "lib/commentary.php";
                    addcommentary();
                    $loc = get_module_pref("worldXYZ", "worldmapen");
                    viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
                    worldmapen_viewmapkey(true, false);
                } else {
                    output("You try to run, but you don't manage to get away!`n");
                    $op = "fight";
                    httpset('op', $op);
                }
            } else {
                if (get_module_setting("smallmap")) {
                    worldmapen_viewsmallmap();
                }
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
                worldmapen_determinenav();
                worldmapen_viewmapkey(true, false);
            }
        } elseif ($op == "run" && $pvp) {
            output("Your pride prevents you from running");
            $op = "fight";
            httpset('op', $op);
        }
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    }
    if ($battle) {
        include_once "battle.php";
        if (isset($enemies) && !$pvp) {
            $badguy =& $enemies;
        }
        if ($victory) {
            if ($pvp) {
                require_once "lib/pvpsupport.php";
                $aliveloc = $badguy['location'];
                pvpvictory($badguy, $aliveloc, $options);
                addnews("`4%s`3 defeated `4%s`3 while they were camped in the wilderness.`0", $session['user']['name'], $badguy['creaturename']);
                $badguy = array();
            } else {
                if (!$chatoverride && !httpget('frombio')) {
                    //is talking
                    require_once "lib/forestoutcomes.php";
                    forestvictory($badguy, false);
                }
            }
            //has just beaten a badguy
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            if (!$chatoverride) {
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
            }
            worldmapen_viewmapkey(true, false);
        } elseif ($defeat) {
            // Reset the players body to the last city they were in
            $session['user']['location'] = get_module_pref('lastCity');
            if ($pvp) {
                require_once "lib/pvpsupport.php";
                require_once "lib/taunt.php";
                $killedloc = $badguy['location'];
                $taunt = select_taunt();
                pvpdefeat($badguy, $killedloc, $taunt, $options);
                addnews("`4%s`3 was defeated while attacking `4%s`3 as they were camped in the wilderness.`0`n%s", $session['user']['name'], $badguy['creaturename'], $taunt);
            } else {
                require_once "lib/forestoutcomes.php";
                forestdefeat($badguy, "in the wild");
            }
            output("`n`n`&You are sure that someone, sooner or later, will stumble over your corpse and return it to %s`& for you.`0", $session['user']['location']);
        } else {
            require_once "lib/fightnav.php";
            $allow = true;
            $extra = "";
            if ($pvp) {
                $allow = false;
                $extra = "pvp=1&";
            }
            fightnav($allow, $allow, "runmodule.php?module=worldmapen&{$extra}");
        }
    }
    page_footer();
}
function drinks_run_private()
{
    require_once "modules/drinks/misc_functions.php";
    require_once "lib/partner.php";
    global $session;
    $partner = get_partner();
    $act = httpget('act');
    if ($act == "editor") {
        drinks_editor();
    } elseif ($act == "buy") {
        $texts = drinks_gettexts();
        $drinktext = modulehook("drinks-text", $texts);
        tlschema($drinktext['schemas']['title']);
        page_header($drinktext['title']);
        rawoutput("<span style='color: #9900FF'>");
        output_notl("`c`b");
        output($drinktext['title']);
        output_notl("`b`c");
        tlschema();
        $drunk = get_module_pref("drunkeness");
        $end = ".";
        if ($drunk > get_module_setting("maxdrunk")) {
            $end = ",";
        }
        tlschema($drinktext['schemas']['demand']);
        $remark = translate_inline($drinktext['demand']);
        $remark = str_replace("{lover}", $partner . "`0", $remark);
        $remark = str_replace("{barkeep}", $drinktext['barkeep'] . "`0", $remark);
        tlschema();
        output_notl("%s{$end}", $remark);
        $drunk = get_module_pref("drunkeness");
        if ($drunk > get_module_setting("maxdrunk")) {
            tlschema($drinktext['schemas']['toodrunk']);
            $remark = translate_inline($drinktext['toodrunk']);
            tlschema();
            $remark = str_replace("{lover}", $partner . "`0", $remark);
            $remark = str_replace("{barkeep}", $drinktext['barkeep'] . "`0", $remark);
            output($remark);
            tlschema();
        } else {
            $sql = "SELECT * FROM " . db_prefix("drinks") . " WHERE drinkid='" . httpget('id') . "'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $drinkcost = $session['user']['level'] * $row['costperlevel'];
            if ($session['user']['gold'] >= $drinkcost) {
                $drunk = get_module_pref("drunkeness");
                $drunk += $row['drunkeness'];
                set_module_pref("drunkeness", $drunk);
                $session['user']['gold'] -= $drinkcost;
                debuglog("spent {$drinkcost} on {$row['name']}");
                $remark = str_replace("{lover}", $partner . "`0", $row['remarks']);
                $remark = str_replace("{barkeep}", $drinktext['barkeep'] . "`0", $remark);
                if (count($drinktext['drinksubs']) > 0) {
                    $keys = array_keys($drinktext['drinksubs']);
                    $vals = array_values($drinktext['drinksubs']);
                    $remark = preg_replace($keys, $vals, $remark);
                }
                output($remark);
                output_notl("`n`n");
                if ($row['harddrink']) {
                    $drinks = get_module_pref("harddrinks");
                    set_module_pref("harddrinks", $drinks + 1);
                }
                $givehp = 0;
                $giveturn = 0;
                if ($row['hpchance'] > 0 || $row['turnchance'] > 0) {
                    $tot = $row['hpchance'] + $row['turnchance'];
                    $c = e_rand(1, $tot);
                    if ($c <= $row['hpchance'] && $row['hpchance'] > 0) {
                        $givehp = 1;
                    } else {
                        $giveturn = 1;
                    }
                }
                if ($row['alwayshp']) {
                    $givehp = 1;
                }
                if ($row['alwaysturn']) {
                    $giveturn = 1;
                }
                if ($giveturn) {
                    $turns = e_rand($row['turnmin'], $row['turnmax']);
                    $oldturns = $session['user']['turns'];
                    $session['user']['turns'] += $turns;
                    // sanity check
                    if ($session['user']['turns'] < 0) {
                        $session['user']['turns'] = 0;
                    }
                    if ($oldturns < $session['user']['turns']) {
                        output("`&You feel vigorous!`n");
                    } else {
                        if ($oldturns > $session['user']['turns']) {
                            output("`&You feel lethargic!`n");
                        }
                    }
                }
                if ($givehp) {
                    $oldhp = $session['user']['hitpoints'];
                    // Check for percent increase first
                    if ($row['hppercent'] != 0.0) {
                        $hp = round($session['user']['maxhitpoints'] * ($row['hppercent'] / 100), 0);
                    } else {
                        $hp = e_rand($row['hpmin'], $row['hpmax']);
                    }
                    $session['user']['hitpoints'] += $hp;
                    // Sanity check
                    if ($session['user']['hitpoints'] < 1) {
                        $session['user']['hitpoints'] = 1;
                    }
                    if ($oldhp < $session['user']['hitpoints']) {
                        output("`&You feel healthy!`n");
                    } else {
                        if ($oldhp > $session['user']['hitpoints']) {
                            output("`&You feel sick!`n");
                        }
                    }
                }
                $buff = array();
                $buff['name'] = $row['buffname'];
                $buff['rounds'] = $row['buffrounds'];
                if ($row['buffwearoff']) {
                    $buff['wearoff'] = $row['buffwearoff'];
                }
                if ($row['buffatkmod']) {
                    $buff['atkmod'] = $row['buffatkmod'];
                }
                if ($row['buffdefmod']) {
                    $buff['defmod'] = $row['buffdefmod'];
                }
                if ($row['buffdmgmod']) {
                    $buff['dmgmod'] = $row['buffdmgmod'];
                }
                if ($row['buffdmgshield']) {
                    $buff['damageshield'] = $row['buffdmgshield'];
                }
                if ($row['buffroundmsg']) {
                    $buff['roundmsg'] = $row['buffroundmsg'];
                }
                if ($row['buffeffectmsg']) {
                    $buff['effectmsg'] = $row['buffeffectmsg'];
                }
                if ($row['buffeffectnodmgmsg']) {
                    $buff['effectnodmgmsg'] = $row['buffeffectnodmgmsg'];
                }
                if ($row['buffeffectfailmsg']) {
                    $buff['effectfailmsg'] = $row['buffeffectfailmsg'];
                }
                $buff['schema'] = "module-drinks";
                apply_buff('buzz', $buff);
            } else {
                output("You don't have enough money.  How can you buy %s if you don't have any money!?!", $row['name']);
            }
        }
        rawoutput("</span>");
        if ($drinktext['return'] > "") {
            tlschema($drinktext['schemas']['return']);
            addnav($drinktext['return'], $drinktext['returnlink']);
            tlschema();
        } else {
            addnav("I?Return to the Inn", "inn.php");
            addnav(array("Go back to talking to %s`0", getsetting("barkeep", "`tCedrik")), "inn.php?op=bartender");
        }
        require_once "lib/villagenav.php";
        villagenav();
        page_footer();
    }
}
function switch_run()
{
    global $session;
    $op = httpget('op');
    $id = httpget('id');
    $accounts = db_prefix('accounts');
    $allAccounts = json_decode(get_module_pref('accounts'), true);
    page_header('Switch Accounts');
    switch ($op) {
        case 'add':
            addnav('Go back', 'runmodule.php?module=switch');
            output("`@Please enter the information of the account you want to add to your switch list. Note that this link is symbolic, meaning it will be added both ways!`n`n`0");
            rawoutput("<form action='runmodule.php?module=switch&op=verify' method='POST'>\n                <input type='text' name='login' placeholder='Login' />\n                <input type='password' name='password' placeholder='Password' />\n                <input type='submit' value='Create Link' />\n                </form>");
            addnav('', 'runmodule.php?module=switch&op=verify');
            break;
        case 'verify':
            $post = httpallpost();
            $post['password'] = md5(md5($post['password']));
            $post['login'] = filter_var($post['login'], FILTER_SANITIZE_STRING);
            $sql = db_query("SELECT acctid, name, uniqueid, lastip\n                FROM {$accounts}\n                WHERE password = '******'password']}'\n                AND login = '******'login']}'");
            if (db_num_rows($sql) == 0) {
                addnav('Go back', 'runmodule.php?module=switch&op=add');
                output("`\$Sorry, no account was found with those credentials!");
                break;
            } else {
                $row = db_fetch_assoc($sql);
                addnav('Go back', 'runmodule.php?module=switch');
                if ($row['acctid'] == $session['user']['acctid']) {
                    output("`\$Sorry, but you cannot add a link to yourself!");
                    break;
                }
                output("`@Success! Adding a link between`^ %s `@and `^%s`@!`0", $session['user']['name'], $row['name']);
                $targetPref = json_decode(get_module_pref('accounts', 'switch', $row['acctid']), true);
                $targetPref = array_merge($targetPref, [$session['user']['acctid']]);
                set_module_pref('accounts', json_encode($targetPref), 'switch', $row['acctid']);
                $userPref = json_decode(get_module_pref('accounts'), true);
                $userPref = array_merge($userPref, [$row['acctid']]);
                set_module_pref('accounts', json_encode($userPref));
            }
            break;
        case 'remove':
            addnav('Go back', 'runmodule.php?module=switch');
            if (!in_array($id, $allAccounts)) {
                output("`\$Woops! That account is not linked to yours!");
                break;
            }
            $unsetId = array_search($id, $allAccounts);
            unset($allAccounts[$unsetId]);
            set_module_pref('accounts', json_encode($allAccounts));
            $targetPref = get_module_pref('accounts', false, $id);
            $targetPref = json_decode($targetPref, true);
            $key = array_search($session['user']['acctid'], $targetPref);
            unset($targetPref[$key]);
            set_module_pref('accounts', json_encode($targetPref), 'switch', $id);
            output("`@The link between your accounts has been destroyed!");
            break;
        case 'switch':
            require_once 'lib/redirect.php';
            require_once 'lib/checkban.php';
            if (!in_array($id, $allAccounts)) {
                addnav('Go back', 'runmodule.php?module=switch');
                output("`\$There was an error. We could not validate your link between these accounts!");
                debuglog('tried to switch into an account they do not have access to!');
                break;
            }
            $sql = db_query("UPDATE {$accounts} SET loggedin = 0 WHERE acctid = '{$session['user']['acctid']}'");
            $sql = db_query("UPDATE {$accounts} SET loggedin = 1 WHERE acctid = '{$id}'");
            $sql = db_query("SELECT * FROM {$accounts} WHERE acctid = '{$id}'");
            $session['user'] = db_fetch_assoc($sql);
            $session['loggedin'] = true;
            $session['laston'] = date('Y-m-d H:i:s');
            $session['user']['laston'] = $session['laston'];
            redirect($session['user']['restorepage'] ?: 'news.php');
            break;
        default:
            require_once 'lib/villagenav.php';
            villagenav();
            addnav('Link an account', 'runmodule.php?module=switch&op=add');
            if (count($allAccounts) > 0) {
                output("`i`@Which account would you like to sign in to?`i`n`n`0");
                rawoutput("<table class='switchAccounts'>\n                        <tr>\n                            <th>\n                                Ops\n                            </th>\n                            <th>\n                                Name\n                            </th>\n                        </tr>\n                    ");
                foreach ($allAccounts as $acctid) {
                    debug($acctid);
                    $sql = db_query("SELECT name\n                        FROM {$accounts}\n                        WHERE acctid = '{$acctid}'");
                    $row = db_fetch_assoc($sql);
                    output("<tr>\n                            <td>\n                                [<a href='runmodule.php?module=switch&op=remove&id=%s'>Del</a>]\n                            </td>\n                            <td>\n                                <a href='runmodule.php?module=switch&op=switch&id=%s'>%s</a>\n                            </td>\n                        </tr>", $acctid, $acctid, $row['name'], true);
                    addnav('', 'runmodule.php?module=switch&op=remove&id=' . $acctid);
                    addnav('', 'runmodule.php?module=switch&op=switch&id=' . $acctid);
                }
                rawoutput("</table>");
            } else {
                output("`@You need to add accounts! Click 'Link an account' to get started!");
            }
            break;
    }
    page_footer();
}
}
addnav("`bHeal Companions`b");
$compheal = false;
foreach ($companions as $name => $companion) {
    if (isset($companion['cannotbehealed']) && $companion['cannotbehealed'] == true) {
    } else {
        $points = $companion['maxhitpoints'] - $companion['hitpoints'];
        if ($points > 0) {
            $compcost = round(log($session['user']['level'] + 1) * ($points + 10) * 1.33);
            addnav(array("%s`0 (`^%s Gold`0)", $companion['name'], $compcost), "healer.php?op=companion&name=" . rawurlencode($name) . "&compcost={$compcost}{$returnline}");
            $compheal = true;
        }
    }
}
tlschema("nav");
addnav("`bReturn`b");
if ($return == "") {
    if ($playerheal || $compheal) {
        addnav("F?Back to the Forest", "forest.php");
        villagenav();
    } else {
        forest(true);
    }
} elseif ($return == "village.php") {
    villagenav();
} else {
    addnav("R?Return whence you came", $return);
}
tlschema();
output_notl("`0");
page_footer();
function crazyaudrey_run()
{
    global $session;
    $op = httpget('op');
    if ($op == "pet") {
        page_header("Crazy Audrey's Zoo");
        $cost = get_module_setting("cost");
        $animal = get_module_setting("animal");
        $lcanimal = get_module_setting("lanimal");
        $plural = get_module_setting("animals");
        $lcplural = get_module_setting("lanimals");
        $profit = get_module_setting("profit");
        output("`5You cautiously approach Crazy Audrey.");
        output("Next to her is a sign that reads, \"`#%s gold to pet %s`#,`5\" and a basket filled with `^%s`5 gold!", $cost, $lcplural, $profit);
        if ($session['user']['gold'] >= $cost) {
            output("You place your `^%s`5 gold in the basket, and spend a few minutes petting one of the %s`5.", $cost, $lcplural);
            output("Soon though, Crazy Audrey chases you off, and you stand at a distance admiring the %s`5.", $lcplural);
            $session['user']['gold'] -= $cost;
            debuglog("spent {$cost} gold to pet audrey's pets");
            $profit += $cost;
            set_module_setting("profit", $profit);
            $buffname = get_module_setting("buffname");
            apply_buff('crazyaudrey', array("name" => $buffname, "rounds" => 5, "activate" => "defense", "defmod" => 1.05, "schema" => "module-crazyaudrey"));
            output("`5After a few minutes, you once again try to approach in order to look into her baskets.");
            if (get_module_pref("played") == 0) {
                addnav("Look at Crazy Audrey's baskets", "runmodule.php?module=crazyaudrey&op=baskets");
            } else {
                output("`5As you approach closer, Crazy Audrey looks up and screams at you. \"`%Hey!!  I recognize you!  You've already played with my %s`% today!  Get away from here, you pervy %s`% fancier!`5\"", $lcplural, $lcanimal);
                output("You quickly step back and admire the %s`5 from a safe distance.", $lcplural);
            }
        } else {
            output("Not having `^%s`5 gold, you wander sadly away.", $cost);
        }
    } elseif ($op == "baskets" || $op == "play" || $op == "run") {
        page_header("Crazy Audrey");
        crazyaudrey_baskets("module-internal", "runmodule.php?module=crazyaudrey");
    }
    if ($op != "baskets") {
        require_once "lib/villagenav.php";
        villagenav();
    }
    page_footer();
}
function bloodbank_run()
{
    global $session;
    $op = httpget("op");
    page_header("Blood Bank Donation Center");
    $loglev = $session['user']['level'];
    $cost = $loglev * ($session['user']['hitpoints'] - 1) + $loglev * 9;
    $cost = round($cost, 0);
    $half = ($session['user']['hitpoints'] - 1) / 2;
    $half = round($half, 0);
    $cost2 = $loglev * $half + $loglev * 9;
    $cost2 = round($cost, 0);
    if ($op == "") {
        output("`3You walk into a sterile room bathed in a harsh white light.");
        output("You notice a man standing in front of a large shelf filled with bottles of red liquid.");
        output("For one moment you think you've made a mistake entering.`n`n");
        if ($session['user']['level'] == 1) {
            output("`3The old vampire glares at you. \"");
            output("`6You look a bit too small to donate blood.");
            output("You should come back when you have another training under your belt and a bit more hearty blood to sell.`3\"");
            output("The man then turns around and ignores you.`n`n");
            output("Might want to train a bit more before you return.");
            addnav("Return");
            villagenav();
        } elseif ($session['user']['hitpoints'] == 1) {
            output("`3The old vampire glares at you. \"");
            output("`6You look a bit pale.");
            output("You should come back when you have blood to sell.`3\" says the hideous thing.");
            output("\"`6Hurry before I change my mind and take your last drop.`3\"");
            addnav("Return");
            villagenav();
        } else {
            if ($session['user']['hitpoints'] > 1) {
                $loglev = log($session['user']['level']);
                $cost = $loglev * ($session['user']['hitpoints'] - 1) + $loglev * 9;
                $cost = round(100 * $cost / 100, 0);
                $half = ($session['user']['hitpoints'] - 1) / 2;
                $half = round($half, 0);
                $cost2 = $loglev * $half + $loglev * 9;
                $cost2 = round(50 * $cost2 / 100, 0);
                output("\"`6Looking to make a donation?`3\" the man remarks.");
                output("\"`6We pay well for your blood if you are in need of coin. `3\"`n`n");
                output("\"`5My blood?  How much?`3\" you ask, ready to be out of the chilling place.`n`n");
                output("The man looks you up and down.  \"`6For your type... `\$`b%s`b`6 gold pieces for a complete drain!!", $cost);
                output("You'll have just enough blood left to walk away`3\" he says as it bends over and pulls out a long needle from a drawer.");
                output("`n`nThe size of the needle is enough to drain your blood without help.`n`n");
                output("\"`6We will also buy just a portion of your blood if you are faint of heart... We can offer `\$`b%s`b`6 gold pieces for a half drain. `3\" he says with a smirk.", $cost2);
                output("`n`n\"`6Interested?`3\"");
                addnav("Donations");
                addnav("`^Full Donation`0", "runmodule.php?module=bloodbank&op=full{$returnline}");
                addnav("`^Half Donation`0", "runmodule.php?module=bloodbank&op=half{$returnline}");
                addnav("`bReturn`b");
                villagenav();
            }
        }
    }
    switch ($op) {
        case "full":
            $full = $session['user']['hitpoints'] - 1;
            $loglev = log($session['user']['level']);
            $cost = $loglev * $full + $loglev * 9;
            $cost = round(100 * $cost / 100, 0);
            $session['user']['hitpoints'] = 1;
            $session['user']['gold'] += $cost;
            output("`3The old  vampire smiles at you, then takes you to a chair where he painfully inserts a needle into your arm. Slowly the blood starts to drip down the needle's tube.");
            output("You turn pale as your blood slowly drains.`n`n");
            output("You become a bit dizzy from your blood lose.`n`n");
            output("You have had %s health points drained ", $full);
            output("and have earned %s gold coins.`n`n", $cost);
            villagenav();
            break;
        case "half":
            $half = ($session['user']['hitpoints'] - 1) / 2;
            $half = round($half, 0);
            $loglev = log($session['user']['level']);
            $cost = $loglev * $half + $loglev * 9;
            $cost = round($cost * 50 / 100, 0);
            $session['user']['hitpoints'] -= $half;
            $session['user']['gold'] += $cost;
            output("`3The old  vampire smiles at you, then takes you to a chair where he painfully inserts a needle into your arm.");
            output(" Slowly the blood starts to drip down the needle's tube.");
            output("You turn pale as your blood slowly drains.`n`n");
            output("You become a bit dizzy from your blood lose.`n`n");
            output("You have had %s health points drained ", $half);
            output("and have earned %s gold coins.`n`n", $cost);
            villagenav();
            break;
    }
    page_footer();
}
function tynan_run()
{
    global $session;
    $op = httpget("op");
    page_header("Tynan's Gym");
    require_once "lib/villagenav.php";
    villagenav();
    addnav("Training");
    addnav("M?Train Muscles from Tone", "runmodule.php?module=tynan&op=train&what=muscles");
    addnav("T?Train Tone from Muscles", "runmodule.php?module=tynan&op=train&what=tonemuscles");
    addnav("o?Train Tone from Agility", "runmodule.php?module=tynan&op=train&what=toneagility");
    addnav("A?Train Agility from Tone", "runmodule.php?module=tynan&op=train&what=agility");
    output("`&`c`bTynan's Gym`b`c");
    $attack = get_module_pref("attack");
    $defense = get_module_pref("defense");
    $hitpoints = get_module_pref("hitpoints");
    if ($op == "gym") {
        output("You walk in to a large gleaming building, the outside of which is adorned with a sign reading, \"`#Tynan's Gym`&.\"");
        output("The sign itself is decorated with the appearance of a perfectly sculpted male silhouette holding a curved bar at arms length over his head, either side of which is a T representing the illustrious establishment's name.");
        output("A smaller slogan under the bold title reads, \"`#Turning the average boy into an Adonis, or girl into Artemis`&.\"`n`n");
        output("`&Walking in, you're greeted by the warm musk of concentrated human effort as around you other warriors work various weight machines.");
        output("Spotting you, Tynan approaches. \"`^Vaht do vee hav here?  Eet eez ein leetle scrawny perzon I sink.  Vell, I sink I can help you vit zee muscles odor ze tonink of your flahbby arms, ja.  Eef you verk on zee muscles, you vill heet ze badguys harder, odor eef you verk on zee tone, you veel hav ze endurance, und if you verk on zee ageelity you vill be harder for ze badguys to be hitting you.`&\"`n`n");
        output("`&After puzzling through what Tynan just said, you figure out that training for muscles will give you more attack, training for tone will give you more hitpoints, and training for agility will give you more defense.");
        output("Knowing what a rigorous workout Tynan typically gives, you realize you'll lose the endurance you'd usually use for a forest fight in the process of this workout.`n");
    } elseif ($op == "train") {
        if ($session['user']['turns'] > 0) {
            $what = httpget("what");
            $weakmessage = translate_inline("`&\"`#Vaht, you seenk you can leeft zeese veights?  Look, zay are veighink two times as much as you!`&\" Tynan scoffs.`n`n`^You think you need more attack or defense to sustain this type of training.");
            $scrawnymessage = translate_inline("`&\"`#Vaht, you seenk you hav zee bones to support such muscles?  Your muscles, zey vould break you like ein twig!`&\" Tynan scoffs.`n`n`^You think you need more hitpoints to sustain this type of training.");
            $nodiemessage = translate_inline("`&\"`#Vaht are you tryink to do, be keelink yourselv?  All zat you be doink iz gettink blud on ze equipment if you don' bandeege ze woundz!`&\" smirks Tynan.`n`n`^You think you should heal yourself before you try to work out any more.");
            $workoutmessage = translate_inline("`&Tynan hands you a training schedule involving several machines which he's conveniently numbered.  Approaching the machines, you're not certain you even understand how to use them, but after fumbling around for a bit, you manage to seriously injure yourself.  Tynan, seeing this, hollers over to you, \"`#Ja, ja, zat is eet, you veel be zee person vit zee perfekt muscles soon!`&\"`n`n");
            if ($what == "muscles") {
                //attack
                // Let's see how many perm hitpoints can be carried over.
                reset($session['user']['dragonpoints']);
                $dkpoints = 0;
                while (list($key, $val) = each($session['user']['dragonpoints'])) {
                    if ($val == "hp") {
                        $dkpoints += 5;
                    }
                }
                $hpgain = array('total' => $session['user']['maxhitpoints'], 'dkpoints' => $dkpoints, 'extra' => $session['user']['maxhitpoints'] - $dkpoints - $session['user']['level'] * 10, 'base' => $dkpoints + $session['user']['level'] * 10);
                $hpgain = modulehook("hprecalc", $hpgain);
                // $extra + $dkpoint corresponds to the total we are
                // allowed by the code to carry over.  Because of the way
                // the stats code works, the user's stats already reflect
                // the change in stats from here.
                // so if that sum is < 10 we cannot work out here.
                if ($hpgain['extra'] + $hpgain['dkpoints'] < 10) {
                    //too scrawny
                    output_notl("%s", $scrawnymessage);
                } elseif ($session['user']['hitpoints'] <= 10) {
                    //too damaged
                    output_notl("%s", $nodiemessage);
                } else {
                    output_notl("%s", $workoutmessage);
                    output("`^You've gained muscles!");
                    $attack++;
                    $hitpoints -= 10;
                    $session['user']['turns']--;
                    $session['user']['hitpoints'] -= 10;
                }
            } elseif ($what == "tonemuscles") {
                //hitpoints
                if ($session['user']['attack'] < $session['user']['level'] + $session['user']['weapondmg'] + 1) {
                    //too weak
                    output_notl("%s", $weakmessage);
                } else {
                    output_notl("%s", $workoutmessage);
                    output("`^You've gained tone!");
                    $hitpoints += 10;
                    $attack -= 1;
                    $session['user']['turns']--;
                    $session['user']['hitpoints'] += 10;
                }
            } elseif ($what == "toneagility") {
                //hitpoints
                if ($session['user']['defense'] < $session['user']['level'] + $session['user']['armordef'] + 1) {
                    //too weak
                    output_notl("%s", $weakmessage);
                } else {
                    output_notl("%s", $workoutmessage);
                    output("`^You've gained tone!");
                    $hitpoints += 10;
                    $defense -= 1;
                    $session['user']['turns']--;
                    $session['user']['hitpoints'] += 10;
                }
            } elseif ($what == "agility") {
                //defense
                // Let's see how many perm hitpoints can be carried over.
                reset($session['user']['dragonpoints']);
                $dkpoints = 0;
                while (list($key, $val) = each($session['user']['dragonpoints'])) {
                    if ($val == "hp") {
                        $dkpoints += 5;
                    }
                }
                $hpgain = array('total' => $session['user']['maxhitpoints'], 'dkpoints' => $dkpoints, 'extra' => $session['user']['maxhitpoints'] - $dkpoints - $session['user']['level'] * 10, 'base' => $dkpoints + $session['user']['level'] * 10);
                $hpgain = modulehook("hprecalc", $hpgain);
                // $extra + $dkpoint corresponds to the total we are
                // allowed by the code to carry over.  Because of the way
                // the stats code works, the user's stats already reflect
                // the change in stats from here.
                // so if that sum is < 10 we cannot work out here.
                if ($hpgain['extra'] + $hpgain['dkpoints'] < 10) {
                    //too scrawny
                    output_notl("%s", $scrawnymessage);
                } elseif ($session['user']['hitpoints'] <= 10) {
                    //too damaged
                    output_notl("%s", $nodiemessage);
                } else {
                    output_notl("%s", $workoutmessage);
                    output("`^You've gained agility!");
                    $defense++;
                    $hitpoints -= 10;
                    $session['user']['turns']--;
                    $session['user']['hitpoints'] -= 10;
                }
            }
            apply_buff("tynanSTAT", array("name" => $session['user']['superuser'] & SU_DEBUG_OUTPUT ? "DEBUG:tynanSTAT" : "", "rounds" => -1, "tempstat-maxhitpoints" => round($hitpoints, 0), "tempstat-defense" => round($defense, 0), "tempstat-attack" => round($attack, 0), "schema" => "module-tynan"));
            set_module_pref("attack", $attack);
            set_module_pref("defense", $defense);
            set_module_pref("hitpoints", $hitpoints);
            if ($session['user']['hitpoints'] < 1) {
                $session['user']['hitpoints'] = 1;
            }
        } else {
            output("`&Tynan scoffs, \"`#Vaht, you seenk you can verk on zeese machines veet your eyes almost goink to fall to ze sleepsies?  Nein, Ich veel not vaste mein time so you can fail you girly girl.`&\"");
        }
    }
    page_footer();
}