function eboy_run()
{
    global $session, $inventory;
    if (!isset($inventory)) {
        load_inventory();
    }
    page_header("eBoy's Trading Station");
    addnav("Buy Items");
    addnav("Sell Items");
    require_once "modules/cityprefs/lib.php";
    $cid = get_cityprefs_cityid("location", $session['user']['location']);
    $item = httpget('item');
    if ($item) {
        $curstock = get_item_setting("eboy_stock_" . $cid, $item);
        $curprice = get_item_setting("eboy_price_" . $cid, $item);
    }
    eboy_updateprices();
    $eboy_info = get_items_with_settings("eboy");
    if (httpget('op') == "start") {
        output("Already fearing the worst, you head into eBoy's Trading Station.`n`nYour fears are well-founded.  The place is packed with the heaving, sweaty bodies of the hardcore capitalist, shouting \"`iBuy, buy!`i\" and \"`iSell, sell!`i\" and \"`iPut down the chainsaw and let's talk about this!`i\"`n`neBoy himself - although you suspect that this place, like Mike's Chop Shop, is a franchise of which you'll find one in every outpost, so is his name really eBoy?  Whoever he is, he stands on an elevated section of floor behind a tall mahogany counter, grabbing money with one hand and tossing grenades and ration packs over his shoulder with the other.  His arms are a blur.  His speech is the unintelligible, rapid-fire gabble of a professional auctioneer.  His eyes bulge and swivel.  You know he's loving this.`n`n");
    }
    if (httpget('op') == "buy") {
        $pprice = httpget('price');
        if ($pprice == $curprice) {
            if ($curstock > 0) {
                give_item($item);
                $session['user']['gold'] -= $curprice;
                increment_item_setting("eboy_stock_" . $cid, -1, $item);
                output("You fight your way to the front of the crowd and shout your order up to eBoy, slapping your Requisition tokens down on the counter.  Before you can blink, your money is gone and the item you desired sits in its place.  You grab it hastily and stuff it into your backpack as eBoy turns to deal with the next customer.`n`n");
            } else {
                output("eBoy turns to you and gibbers.`n`n\"Sorrymatejustsoldthelastoneyougottabefasteritsthequickandthedeadaroundherepal.\"  He turns to the next customer in line, leaving you trying to piece together whatever it is that he just said.`n`n");
            }
        } else {
            output("You fight your way to the front of the crowd and shout your order up to eBoy, slapping your Requisition tokens down on the counter.  eBoy turns to you and gibbers.`n`n\"Idontmeantobefunnymatebutlookattheboardthepricehasjustbloodychangedagainyousureyoustillwannabuy?\"  After giving you exactly one microsecond to consider what the hell he just asked, he rolls his eyes and turns to the next customer in line.`n`n");
        }
    }
    if (httpget('op') == "sell") {
        $pprice = httpget('price');
        $requiredprefs = array("inventorylocation" => "main");
        $itemid = has_item($item, $requiredprefs);
        if ($pprice == $curprice) {
            delete_item($itemid);
            if ($curstock < 3) {
                $buy = round($curprice * 0.5);
            } else {
                $buy = round($curprice * 0.7);
            }
            $session['user']['gold'] += $buy;
            increment_item_setting("eboy_stock_" . $cid, 1, $item);
            output("You barge your way through the crowd like a battleship through an ice floe, and toss your item up to eBoy.  eBoy snatches the item out of the air with his left hand while tossing your Requisition tokens back at you with his right, and goes on to serve the next customer.`n`n");
        } else {
            output("You fight your way to the front of the crowd and shout your order up to eBoy, slapping your Requisition tokens down on the counter.  eBoy turns to you and gibbers.`n`n\"Idontmeatobefunnymatebutlookattheboardthepricehasjustbloodychangedagainyousureyoustillwannasell?\"  After giving you exactly one microsecond to consider what the hell he just asked, he rolls his eyes and turns to the next customer in line.`n`n");
        }
    }
    output("You look up above eBoy's head at the trading board, the values of each commodity displayed on a mechanical readout which clatters and changes constantly.`n`n");
    $sellable_inventory = array();
    foreach ($inventory as $itemid => $prefs) {
        if (!$prefs['carrieritem'] && $prefs['eboy'] && $prefs['inventorylocation'] == "main") {
            $sellable_inventory[$prefs['item']]['quantity'] += 1;
            $sellable_inventory[$prefs['item']]['itemids'][] = $itemid;
        }
    }
    eboy_updateprices();
    $eboy_info = get_items_with_settings("eboy");
    //inventory-type display routine
    rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
    $classcount = 1;
    foreach ($eboy_info as $item => $settings) {
        if ($settings['eboy_stock_' . $cid] > 0) {
            $stock = number_format($settings['eboy_stock_' . $cid]) . " available";
        } else {
            $stock = "`4Sold Out`0";
        }
        $classcount++;
        $class = $classcount % 2 ? "trdark" : "trlight";
        rawoutput("<tr class='{$class}'><td>");
        if ($settings['image']) {
            rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td width=100px align=center><img src=\"images/items/" . $settings['image'] . "\"></td><td>");
        }
        output("`b%s`b`n", stripslashes($settings['verbosename']));
        output("%s`n", stripslashes($settings['description']));
        if ($settings['weight']) {
            output("Weight: %s kg`n", $settings['weight']);
        }
        rawoutput("<table width=100%><tr><td width=50%>");
        output("`bStock:`b %s", $stock);
        if ($settings['eboy_stock_' . $cid] < 3) {
            $buy = round($settings['eboy_price_' . $cid] * 0.5);
        } else {
            $buy = round($settings['eboy_price_' . $cid] * 0.7);
        }
        if ($settings['eboy_price_' . $cid] > 0) {
            output("`n`7Buying at: %s Requisition", number_format($buy));
        } else {
            output("`nNot Buying");
        }
        if ($settings['eboy_stock_' . $cid] > 0) {
            output("`n`2Selling at: %s Requisition`n`n", number_format($settings['eboy_price_' . $cid]));
        } else {
            output("`n`n");
        }
        rawoutput("</td><td width=50%>");
        $requiredprefs = array("inventorylocation" => "main");
        if ($sellable_inventory[$item]) {
            addnav("Sell Items");
            if ($settings['eboy_stock_' . $cid] < 3) {
                $buy = round($settings['eboy_price_' . $cid] * 0.5);
            } else {
                $buy = round($settings['eboy_price_' . $cid] * 0.7);
            }
            if ($sellable_inventory[$item]['quantity'] > 0 && $settings['eboy_price_' . $cid] > 0) {
                addnav(array("%s (%s available)", $settings['verbosename'], $sellable_inventory[$item]['quantity']), "runmodule.php?module=eboy&op=sell&item=" . $item . "&price=" . $settings['eboy_price_' . $cid], true);
                addnav("", "runmodule.php?module=eboy&op=sell&item=" . $item . "&price=" . $settings['eboy_price_' . $cid]);
                rawoutput("<a href=\"runmodule.php?module=eboy&op=sell&item=" . $item . "&price=" . $settings['eboy_price_' . $cid] . "\">Sell for <strong>" . number_format($buy) . " </strong> Requisition (" . $sellable_inventory[$item]['quantity'] . " available to sell)</a><br />");
            }
        } else {
            output("`&You don't have any of this item to sell.`0`n");
        }
        if ($session['user']['gold'] >= $settings['eboy_price_' . $cid] && $settings['eboy_stock_' . $cid]) {
            addnav("Buy Items");
            addnav(array("%s (%s Req)", $settings['verbosename'], $settings['eboy_price_' . $cid]), "runmodule.php?module=eboy&op=buy&item=" . $item . "&price=" . $settings['eboy_price_' . $cid], true);
            addnav("", "runmodule.php?module=eboy&op=buy&item=" . $item . "&price=" . $settings['eboy_price_' . $cid]);
            rawoutput("<a href=\"runmodule.php?module=eboy&op=buy&item=" . $item . "&price=" . $settings['eboy_price_' . $cid] . "\">Buy for <strong>" . number_format($settings['eboy_price_' . $cid]) . "</strong> Requisition</a><br />");
        } else {
            if (!$settings['eboy_stock_' . $cid]) {
                output("`&There are no items of this type available.`0`n");
            } else {
                $difference = $settings['eboy_price_' . $cid] - $session['user']['gold'];
                output("`&You need another %s Requisition to buy this item.`0`n", number_format($difference));
            }
        }
        rawoutput("</td></tr></table>");
        if ($settings['image']) {
            rawoutput("</td></tr></table>");
        }
        rawoutput("</td></tr>");
    }
    rawoutput("</td></tr></table>");
    addnav("Leave");
    addnav("Return to the Outpost", "village.php");
    addnav("Inventory");
    addnav("View your Inventory", "inventory.php?items_context=eboy");
    //set_module_objpref("city",$cid,"eboytrades-intelligent",serialize($info));
    page_footer();
    return true;
}
function iitems_hunterslodge_run()
{
    global $session;
    page_header("Hunter's Lodge");
    $op = httpget('op');
    $pointsleft = $session['user']['donation'] - $session['user']['donationspent'];
    $pointstotal = $session['user']['donation'];
    $pointsspent = $session['user']['donationspent'];
    switch ($op) {
        case "superuser":
            $sql = "SELECT * FROM " . db_prefix("purchaselog");
            $result = db_query($sql);
            $peritem = array();
            $now = time();
            while ($row = db_fetch_assoc($result)) {
                $item = $row['purchased'];
                $peritem[$item]['sold'] += 1;
                $peritem[$item]['income'] += $row['amount'];
                $time = strtotime($row['timestamp']);
                if (isset($peritem[$item]['firstpurchase']) && $peritem[$item]['firstpurchase'] > $time) {
                    $peritem[$item]['firstpurchase'] = $time;
                } else {
                    if (!isset($peritem[$item]['firstpurchase'])) {
                        $peritem[$item]['firstpurchase'] = $time;
                    }
                }
            }
            foreach ($peritem as $item => $data) {
                $timesincefirst = $now - $data['firstpurchase'];
                $incomeperday = round($data['income'] / ($timesincefirst / 86400) / 100, 2);
                $peritem[$item]['incomeperday'] = $incomeperday;
                $peritem[$item]['item'] = $item;
            }
            function sortbysold($a, $b)
            {
                if ($b['sold'] > $a['sold']) {
                    return true;
                } else {
                    return false;
                }
            }
            function sortbyincome($a, $b)
            {
                if ($b['income'] > $a['income']) {
                    return true;
                } else {
                    return false;
                }
            }
            function sortbydailyincome($a, $b)
            {
                if ($b['incomeperday'] > $a['incomeperday']) {
                    return true;
                } else {
                    return false;
                }
            }
            rawoutput("<table width=100% border=0 cellpadding=0 cellspacing=0><tr class='trhead'><td>Item</td><td>Item Verbose Name</td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbysold'>Units sold</a></td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbyincome'>Profit total</a></td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbydailyincome'>Profit per day</a></td></tr>");
            $classcount = 1;
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbysold");
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbyincome");
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbydailyincome");
            if (httpget('sort')) {
                usort($peritem, httpget('sort'));
            }
            foreach ($peritem as $item => $data) {
                $classcount++;
                $class = $classcount % 2 ? "trdark" : "trlight";
                $vname = get_item_setting("verbosename", $data['item']);
                if (!$vname) {
                    $vname = $data['item'];
                }
                rawoutput("<tr class='{$class}'><td>" . $data['item'] . "</td><td>" . $vname . "</td><td>" . number_format($data['sold']) . "</td><td>\$" . number_format($data['income'] / 100, 2) . "</td><td>\$" . number_format($data['incomeperday'], 2) . "</td></tr>");
            }
            rawoutput("</table>");
            addnav("Return");
            addnav("Back to the Grotto", "superuser.php");
            break;
        case "explain":
            output("You give a friendly nod to the proprietor, and open your mouth to ask him a question.`n`nHe grins back at you.`n`nThere's a small `ipop`iping sensation in the centre of your skull, like a muscle abruptly shifting - and you suddenly realise what this place is all about.`n`n`bAbout Supporter Points`b`nImprobable Island is entirely funded by donations from its players.  When you donate, you get Supporter Points, which you can use on items in the Hunter's Lodge.  You get one hundred Supporter Points per US Dollar, and donations are accepted through PayPal.  To donate, click the coin slot to the lower right of your screen.  Always use the \"Site Admin\" PayPal button when donating if you wish to receive Supporter Points (donations made through the \"Author\" button go to Eric Stevens, the author of the game engine on which Improbable Island was originally based - you don't get any Supporter Points for donating through this button).  You can also get Supporter Points by referring new players to the site (click the Referrals link to the left) or sometimes in `4Other Ways`0 which will be announced from time to time.`n`n`bTo give presents`b`nAll Hunter's Lodge items (and most other in-game items) can be given as gifts to other players.  Visit the Gifting Station in Common Ground to do so.  Some items can be gifted for free - others cost one Supporter Point each to gift.  Hunter's Lodge items that bestow permanent benefits (IE unlimited title change documents) can only be gifted if they're unused.  In all cases, you'll get to choose your gift-wrap and whether to give anonymously or not.`n`n`bHey, it's my birthday soon.  Can I ask my non-Island-playing mates to buy me points on the Island?`b`nYes!  Just send them to this link:`nhttp://www.improbableisland.com/runmodule.php?module=giftpoints&acctid=%s`n`n", $session['user']['acctid']);
            addnav("Okay");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            addnav("Referrals", "runmodule.php?module=iitems_hunterslodge&op=referrals");
            break;
        case "referrals":
            output("If you help bring new players to Improbable Island, you'll earn one Supporter Point every time those players hit a new Game Day.  To refer players, use this address:`n`n");
            $url = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['REQUEST_URI']));
            if (!preg_match("/\\/\$/", $url)) {
                $url = $url . "/";
                savesetting("serverurl", $url);
            }
            output_notl("%shome.php?r=%s`n`n", $url, rawurlencode($session['user']['login']));
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE referer={$session['user']['acctid']} ORDER BY dragonkills,level";
            $result = db_query($sql);
            $number = db_num_rows($result);
            if ($number) {
                output("Accounts you've referred:`n");
                for ($i = 0; $i < $number; $i++) {
                    $row = db_fetch_assoc($result);
                    output_notl("%s`0`n", $row['name']);
                }
            }
            addnav("Okay");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "start":
            output("You head into the Hunter's Lodge.  It's a bright, shiny place, with many expensive-looking items arranged inside glass cabinets.  The proprietor, a snappily-dressed male Joker, grins at you from behind the counter.`n`n");
            if (!has_item("lodgebag")) {
                output("The joker silently hands you a small bag, with a look that suggests you put your purchases inside.`n`n");
                give_item("lodgebag");
            }
            output("`0You have `b`5%s`0`b Supporter Points left, out of `5%s`0 accumulated in total.`n`n", number_format($pointsleft), number_format($pointstotal));
            addnav("What's all this about, then?");
            addnav("How do I get supporter points, or give presents to people?", "runmodule.php?module=iitems_hunterslodge&op=explain");
            $lodgeitems = get_items_with_settings("lodge");
            //debug($lodgeitems);
            rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
            $boughtitems = array();
            $sql = "SELECT * FROM " . db_prefix("purchaselog") . " WHERE acctid = '" . $session['user']['acctid'] . "'";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $boughtitems[$row['purchased']] = 1;
            }
            foreach ($lodgeitems as $key => $vals) {
                if (!$vals['lodge']) {
                    continue;
                }
                $classcount += 1;
                $class = $classcount % 2 ? "trdark" : "trlight";
                rawoutput("<tr class='{$class}'><td>");
                if ($vals['image']) {
                    rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td width=100px align=center><img src=\"images/items/" . $vals['image'] . "\"></td><td>");
                }
                output("`b%s`b`n", stripslashes($vals['verbosename']));
                output("%s`0`n", stripslashes($vals['description']));
                if ($vals['weight']) {
                    output("Weight: %s kg`n`0", $vals['weight']);
                }
                rawoutput("<table width=100%><tr><td width=50%>");
                if ($vals['tradable']) {
                    output("`5Giftable Item`0`n");
                }
                if ($vals['lodge_cost']) {
                    $disp = "`b`5" . number_format($vals['lodge_cost']) . "`0`b Supporter Points";
                    $sdisp = $vals['lodge_cost'] . " Points";
                    output("Price: %s`n", $disp);
                    if ($vals['lodge_limited']) {
                        output("`4Limited Item`0: %s available`n", $vals['lodge_stock']);
                    }
                }
                if ($vals['lodge_limited'] && $vals['lodge_stock'] > 0 || !$vals['lodge_limited']) {
                    if ($vals['lodge_singlebuy'] && $boughtitems[$key]) {
                        output("`7You've already obtained and used this item.  No need to get it again!`n");
                    } else {
                        if ($pointstotal >= $vals['lodge_freebie_threshold'] && $vals['lodge_freebie_threshold']) {
                            output("`2This item is now `bfree`b!`0`n");
                            addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&freebie=true");
                            rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&freebie=true\">Get it!</a><br />");
                        } else {
                            if ($vals['lodge_freebie_threshold']) {
                                output("`2This item becomes free once you have accumulated more than %s Supporter Points, spent or unspent.`0`n", $vals['lodge_freebie_threshold']);
                            }
                            if ($pointsleft >= $vals['lodge_cost']) {
                                addnav("Buy Items");
                                addnav(array("%s (%s)", stripslashes($vals['verbosename']), $sdisp), "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key, true);
                                addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key);
                                rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "\">More Details / Buy for " . appoencode($disp) . "</a><br />");
                            } else {
                                output("`&You need another %s Supporter Points for this item.`0`n", number_format($vals['lodge_cost'] - $pointsleft));
                                addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&cannotafford=1");
                                rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&cannotafford=1\">More Details</a><br />");
                            }
                        }
                    }
                } else {
                    output("`&Sold out!`0`n");
                }
                rawoutput("</td></tr></table>");
                if ($vals['image']) {
                    rawoutput("</td></tr></table>");
                }
                rawoutput("</td></tr>");
            }
            rawoutput("</td></tr></table>");
            modulehook("hunterslodge");
            break;
        case "buy":
            $itemid = httpget("item");
            $item = get_item_settings($itemid);
            $free = httpget("freebie");
            $cannotafford = httpget("cannotafford");
            //debug($item);
            if ($item['lodge_longdesc']) {
                output_notl("`0%s`0`n`n", stripslashes($item['lodge_longdesc']));
            }
            if (!$cannotafford) {
                if (!$free) {
                    output("You're about to buy a %s for %s Supporter Points, leaving you with %s points available to spend afterwards.`n`n", $item['verbosename'], number_format($item['lodge_cost']), number_format($pointsleft - $item['lodge_cost']));
                    addnav("Confirm");
                    addnav(array("Buy %s for %s Points", stripslashes($item['verbosename']), $item['lodge_cost']), "runmodule.php?module=iitems_hunterslodge&op=buyconfirm&item={$itemid}");
                    addnav("No, I don't want to do that!");
                    addnav("Back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
                } else {
                    redirect("runmodule.php?module=iitems_hunterslodge&op=buyconfirm&item={$itemid}&freebie=true");
                }
            } else {
                output("`0You need another %s Supporter Points to get this item.`0`n`n", number_format($item['lodge_cost'] - $pointsleft));
                addnav("Okay");
                addnav("Back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
                addnav("How do I get supporter points?", "runmodule.php?module=iitems_hunterslodge&op=explain");
            }
            break;
        case "buyconfirm":
            $itemid = httpget("item");
            $iteminside = httpget("item_inside");
            $item = get_item_settings($itemid);
            $free = httpget("freebie");
            if (!$free) {
                $cost = $item['lodge_cost'];
                output("You have purchased a %s for %s Supporter Points.  You can find the item in your Inventory.  Thank you for your support!`n`n", $item['verbosename'], $item['lodge_cost']);
                give_item($itemid);
                $session['user']['donationspent'] += $item['lodge_cost'];
            } else {
                //handle freebie items
                give_item($itemid);
                output("`0You now have a %s`0!  Thank you for your support!`n`n", $item['verbosename']);
                $cost = 0;
            }
            if ($item['lodge_limited']) {
                increment_item_setting("lodge_stock", -1, $itemid);
            }
            //log purchase
            $sql = "INSERT INTO " . db_prefix("purchaselog") . " (acctid,purchased,amount,data,giftwrap,timestamp) VALUES ('" . $session['user']['acctid'] . "','" . $itemid . "','" . $cost . "','" . addslashes(serialize($item)) . "','" . $wrap . "','" . date("Y-m-d H:i:s") . "')";
            //debug($sql);
            db_query($sql);
            addnav("Yay!");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    addnav("Leave");
    addnav("Return to the Outpost", "village.php");
    addnav("Inventory");
    addnav("View your Inventory", "inventory.php?items_context=lodge");
    page_footer();
    return true;
}