function iitems_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "superuser":
            if (get_module_pref("superuser") == 1) {
                addnav("Item Editor", "runmodule.php?module=iitems&op=superuser&superop=start");
            }
            break;
        case "village":
        case "forest":
        case "worldnav":
            addnav("Inventory");
            addnav("Show Inventory", "runmodule.php?module=iitems&op=inventory&from=" . $hookname);
            break;
        case "fightnav-specialties":
            $script = $args['script'];
            iitems_show_fight_items($script);
            break;
        case "apply-specialties":
            if (httpget('skill') == "iitems") {
                $item = httpget('item');
                iitems_use_item($item, false, "fight");
            }
            break;
        case "dragonkill":
            $oldinventory = iitems_get_player_inventory();
            $newinventory = array();
            foreach ($oldinventory as $key => $vals) {
                $details = iitems_get_item_details($vals['itemid']);
                if ($details['dkpersist']) {
                    $newinventory[$key] = $vals;
                }
            }
            set_module_pref("items", serialize($newinventory), "iitems");
            break;
        case "newday":
            $use = iitems_has_property("useatnewday", 1, true, false, false, "all");
            debug($use);
            if (count($use) && is_array($use)) {
                foreach ($use as $item => $details) {
                    iitems_use_item($details['itemid'], false, $details['inventorylocation']);
                }
            }
            break;
    }
    return $args;
}
function iitemstestextension_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "iitems-give-item":
            if ($args['master']['power']) {
                $args['player']['power'] = $args['master']['power'];
            }
            if ($args['master']['donotadd']) {
                $args['player']['blockadd'] = 1;
            }
            break;
        case "iitems-use-item":
            $args['player']['usecount'] += 1;
            if ($args['player']['power']) {
                $args['player']['power']--;
            }
            break;
        case "iitems-inventory":
            if ($args['player']['usecount']) {
                output("You have used this item %s times.`n", $args['player']['usecount']);
            }
            if ($args['player']['power']) {
                output("Power: %s points", $args['player']['power']);
            }
            break;
        case "village":
            $inventory = iitems_get_player_inventory();
            foreach ($inventory as $item => $details) {
                if ($details['villagehooknav']) {
                    output("`bYou can use your %s here...`b`n", $details['verbosename']);
                }
            }
            break;
        case "forest":
            break;
    }
    return $args;
}
function iitems_mountaccessories_strip_player_accessories($payback = 0.6, $returngold = false)
{
    global $session;
    require_once "modules/iitems/lib/lib.php";
    $ret = array();
    $inv = iitems_get_player_inventory();
    $allitems = iitems_get_all_item_details();
    if (!count($inv)) {
        return $ret;
    }
    foreach ($inv as $item => $details) {
        $master = $allitems[$details['itemid']];
        if ($master['mountaccessory']) {
            $safe = 0;
            $compatibilitylist = explode(",", $master['formount']);
            foreach ($compatibilitylist as $cmount) {
                if ($cmount == $session['user']['hashorse']) {
                    $safe = 1;
                }
            }
            if (!$safe) {
                //remove the item, pay back the money
                $gold = ceil($master['goldcost'] * $payback);
                $gems = ceil($master['gemcost'] * $payback);
                $session['user']['gems'] += $gems;
                $ret['gems'] += $gems;
                if ($returngold) {
                    $session['user']['gold'] += $gold;
                    $ret['gold'] += $gold;
                }
                iitems_discard_item($item);
            }
        }
    }
    return $ret;
}
function iitems_giftstation_run()
{
    global $session;
    page_header("The Gifting Station");
    require_once "modules/iitems/lib/lib.php";
    $inventory = iitems_get_player_inventory();
    $op = httpget('op');
    $itemlimit = get_module_setting("itemlimit");
    $weightlimit = get_module_setting("weightlimit");
    switch ($op) {
        case "start":
            if (httpget("subop") == "continue") {
                output("The KittyMorph shows you a big smile, closing the box and beginning to wrap it up.  \"`1Okay, that'll be delivered first thing in the morning.  Should make for a nice surprise when they wake up.  All gifts are anonymous by default, so if you want them to know who sent the package, you'd better send them a Distraction.  Anyone else you'd like to send a gift to?`0\"`n`n");
                addnav("No, I think that'll do, thanks.", "village.php");
            } else {
                if (httpget("subop") == "searchagain") {
                    output("The KittyMorph nods, scratching out the contestant's name on his clipboard.  \"`1No problem.  Let's take it from the top.`0\"`n`n");
                    addnav("Actually, forget the whole thing.", "village.php");
                } else {
                    output("`0You head into the Gift Exchange.  A black-furred KittyMorph stands behind a counter.`n`n\"`1Hey there!`0\" he says.  \"`1As part of our continued diplomatic efforts, we provide a free gift-wrapping service for any consumable items you'd like to send to your fellow contestants.  Interested?`0\"`n`n");
                    addnav("No thanks.", "village.php");
                }
            }
            output("Search below for a player to send a present to.");
            rawoutput("<form action='runmodule.php?module=iitems_giftstation&op=findplayer' method='post'>");
            rawoutput("<input name='name'>");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("search") . "'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=iitems_giftstation&op=findplayer");
            break;
        case "findplayer":
            $search = "%";
            $n = httppost('name');
            for ($x = 0; $x < strlen($n); $x++) {
                $search .= substr($n, $x, 1) . "%";
            }
            $search = " AND name LIKE '" . addslashes($search) . "' ";
            $uid = $session['user']['uniqueid'];
            $lastip = $session['user']['lastip'];
            $sql = "SELECT uniqueid, acctid, name FROM " . db_prefix("accounts") . " WHERE locked=0 {$search} ORDER BY name DESC ";
            $result = db_query($sql);
            output("The KittyMorph nods.  \"`1Okay, let's have a look at who I've got written down here whose name sounds like that...`0\"`n`n");
            $matches = 0;
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['uniqueid'] != $session['user']['uniqueid']) {
                    addnav("", "runmodule.php?module=iitems_giftstation&op=give&id=" . $row['acctid'] . "&sub=first");
                    output_notl("<a href='runmodule.php?module=iitems_giftstation&op=give&id=" . $row['acctid'] . "&sub=first'>" . $row['name'] . "</a>", true);
                    output("`n");
                    $matches++;
                }
            }
            if ($matches == 0) {
                output("He looks down at his list.  \"`1Oh.  Actually, it doesn't look like there's `ianyone`i matching that description who you can send a present to.  Bummer.  Wanna try that again?`0\"");
            }
            addnav("Return to the Outpost", "village.php");
            addnav("Search Again", "runmodule.php?module=iitems_giftstation&op=start");
            break;
        case "give":
            $id = httpget('id');
            $item = httpget('item');
            //Check to see if this box already has something inside - calculate weight and number of items
            $inventory = iitems_get_player_inventory();
            $giftee_all = iitems_get_player_inventory($id);
            $giftee_gifts = array();
            $giftee_weight = 0;
            $giftee_items = 0;
            foreach ($giftee_all as $key => $details) {
                if ($details['inventorylocation'] == "giftstation") {
                    $giftee_gifts[] = $key;
                    $giftee_items++;
                    if ($details['weight']) {
                        $giftee_weight += $details['weight'];
                    }
                }
            }
            if ($giftee_items < $itemlimit && $giftee_weight < $weightlimit) {
                $okaytoadd = true;
            } else {
                $okaytoadd = false;
            }
            if (httpget('sub') == "first") {
                output("The KittyMorph reaches below his counter and brings up a package of roughly shoebox-like proportions, along with a clipboard on which he writes down the name of your nominated contestant.  \"`1Okay, I've got the name - here's their box.`0\"`n`n");
                if (!$giftee_items) {
                    //giftee has no items in their box
                    output("\"`1It looks like their box is empty, so let's start filling it up.  We'll send up to %s items at a time, and the box will hold up to %s kilos in weight.`0\"", $itemlimit, $weightlimit);
                } else {
                    if ($okaytoadd) {
                        output("\"`1It looks like their box has something in already, but we can put some more in there.  Right now the box weighs %s kilos, and has %s items inside.  We'll send up to %s items at a time, and the box will hold up to %s kilos in weight.`0\"", $giftee_weight, $giftee_items, $itemlimit, $weightlimit);
                    } else {
                        output("The KittyMorph peeks inside.  \"`1Sorry - looks like this is full.  We only make one delivery a day, you see.  You can try coming back tomorrow, if you'd like?`0\"`n`n");
                    }
                }
                addnav("Wait, I've changed my mind.  Let's back up a step.", "runmodule.php?module=iitems_giftstation&op=start&subop=searchagain");
                addnav("Actually, forget the whole thing.", "village.php");
            } else {
                //now adding more items
                //check for overweight - shouldn't happen, but players may all come to the gifting screen at once
                if ($inventory[$item]['weight'] + $giftee_weight <= $weightlimit) {
                    //we're just going to copy the items straight over into the player's Inventory, not do anything special with them, since at newday they'll be transferred over for us and the transfer will make them display properly.
                    $additem = $inventory[$item];
                    $additem['inventorylocation'] = "giftstation";
                    unset($additem['instance']);
                    unset($additem['quantity']);
                    $giftee_all[] = $additem;
                    set_module_pref("items", serialize($giftee_all), "iitems", $id);
                    output("The KittyMorph takes the item, wraps it in tissue and places it gently in the box. \"`1Marvellous.  Anything else you've got that we can fit in there?`0\"");
                    addnav("Nope.", "runmodule.php?module=iitems_giftstation&op=start&subop=continue");
                } else {
                    output("The KittyMorph looks down into the box and frowns. \"`1Hmm.  That's odd - something else has just appeared in there, and now I can't fit your present in the box.  How very strange!`0\"");
                    addnav("Hmm.  Best start over again, I suppose.", "runmodule.php?module=iitems_giftstation&op=start&subop=continue");
                }
            }
            $inventory = iitems_get_player_inventory();
            $giftee_all = iitems_get_player_inventory($id);
            $giftee_gifts = array();
            $giftee_weight = 0;
            $giftee_items = 0;
            foreach ($giftee_all as $key => $details) {
                if ($details['inventorylocation'] == "giftstation") {
                    $giftee_gifts[] = $key;
                    $giftee_items++;
                    if ($details['weight']) {
                        $giftee_weight += $details['weight'];
                    }
                }
            }
            if ($giftee_items < $itemlimit && $giftee_weight < $weightlimit) {
                $okaytoadd = true;
            } else {
                $okaytoadd = false;
            }
            if ($okaytoadd) {
                $giftables = array();
                foreach ($inventory as $key => $details) {
                    $iteminfo = iitems_get_item_details($details['itemid']);
                    //check that the item is in an accessible inventorylocation
                    $storageinfo = iitems_get_item_details($inventory[$details['inventorylocation']]['itemid']);
                    if ($storageinfo['giftable'] && $iteminfo['giftable'] && $iteminfo['type'] != "inventory") {
                        $giftables[$key] = $details;
                    }
                }
                foreach ($giftables as $key => $details) {
                    if ($details['weight'] + $giftee_weight <= $weightlimit) {
                        //item is light enough, add navs
                        addnav("Items");
                        if ($details['quantity'] > 1) {
                            addnav(array("Give %s (%s available)", $details['verbosename'], $details['quantity']), "runmodule.php?module=iitems_giftstation&op=give&item=" . $key . "&id=" . $id, true);
                        } else {
                            addnav(array("Give %s", $details['verbosename']), "runmodule.php?module=iitems_giftstation&op=give&item=" . $key . "&id=" . $id, true);
                        }
                    } else {
                        addnav(array("%s is too heavy to give", $details['verbosename']), "", true);
                    }
                }
            }
            break;
    }
    // addnav("Inventory");
    // addnav("View your Inventory","runmodule.php?module=iitems&op=inventory&from=giftstation");
    page_footer();
    return true;
}
function iitems_show_inventory_new($from, $userid = false)
{
    global $session, $masteriitems, $weightinfo;
    if ($userid === false) {
        $userid = $session['user']['acctid'];
    }
    modulehook("iitems-inventory-top");
    $inventory = iitems_get_player_inventory($userid);
    //debug($inventory);
    //Preload master records of all iitems in player's posession
    $masteriitems = array();
    foreach ($inventory as $key => $details) {
        if (!isset($masteriitems[$details['itemid']])) {
            $masteriitems[$details['itemid']] = iitems_get_item_details($details['itemid']);
        }
    }
    //Obtain list of carrier iitems
    $carriers = array();
    foreach ($inventory as $key => $details) {
        if ($masteriitems[$details['itemid']]['type'] == "inventory") {
            $carriers[$key] = iitems_get_item_details($details['itemid']);
        }
        if ($masteriitems[$details['itemid']]['inventorylocation'] == "mount") {
            $addmount = 1;
        }
    }
    //debug($carriers);
    if ($addmount) {
        $carriers['mount'] = array('verbosename' => "Mount", 'description' => "Here's all the equipment currently attached to your Mount, not counting saddlebags and other carrier items.", 'blocktransfer' => "true");
    }
    foreach ($carriers as $ckey => $cdetails) {
        //display carrier
        rawoutput("<table width=100% style='border: dotted 1px #000000'><tr><td>");
        $central = $masteriitems[$inventory[$ckey]['itemid']];
        if ($central['image']) {
            rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td>");
        }
        $vn = $inventory[$ckey]['verbosename'];
        if (!$vn) {
            $vn = $carriers[$ckey]['verbosename'];
        }
        $desc = stripslashes($central['description']);
        if (!$desc) {
            $desc = stripslashes($carriers[$ckey]['description']);
        }
        output("`b%s`b`n", $vn);
        output("%s`n", $desc);
        $hookitem = array();
        $hookitem['master'] = $central;
        $hookitem['player'] = $inventory[$ckey];
        $hookitem['inventorykey'] = $ckey;
        modulehook("iitems-inventory", $hookitem);
        //debug($hookitem);
        if ($hookitem['master']['image']) {
            rawoutput("</td><td align='right'><img src=\"images/iitems/" . $hookitem['master']['image'] . "\"></td></tr></table>");
        }
        //display items
        rawoutput("<table width=100% style='border: dotted 1px #000000; margin-left:10px; padding-right:-10px;'>");
        $classcount = 1;
        foreach ($inventory as $key => $details) {
            if ($details['inventorylocation'] == $ckey && $masteriitems[$details['itemid']]['type'] != "inventory") {
                $central = $masteriitems[$details['itemid']];
                $classcount++;
                $class = $classcount % 2 ? "trdark" : "trlight";
                rawoutput("<tr class='{$class}'><td>");
                if ($central['image']) {
                    rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td width=100px align=center><img src=\"images/iitems/" . $central['image'] . "\"></td><td>");
                }
                if (!isset($details['instance']) || $details['instance'] == 1) {
                    output("`b%s`b`n", stripslashes($details['verbosename']));
                } else {
                    output("`b%s (%s)`b`n", $details['verbosename'], $details['instance']);
                }
                if ($details['quantity']) {
                    output("Quantity: %s`n", $details['quantity']);
                }
                $hookitem = array();
                $hookitem['master'] = $central;
                $hookitem['player'] = $details;
                $hookitem['inventorykey'] = $key;
                $hookitem = modulehook("iitems-inventory", $hookitem);
                //debug($hookitem);
                //if module adds the "blockuse" param to the $player array, the item cannot be used.
                if (($hookitem['player'][$from . 'hooknav'] || $hookitem['master'][$from . 'hooknav']) && !$hookitem['player']['blockuse']) {
                    rawoutput("<a href=\"runmodule.php?module=iitems&op=useitem&key={$key}&from={$from}&invloc=" . $hookitem['player']['inventorylocation'] . "\">Use this item</a><br />");
                    addnav("", "runmodule.php?module=iitems&op=useitem&key={$key}&from={$from}&invloc=" . $hookitem['player']['inventorylocation']);
                }
                if (!$hookitem['master']['cannotdiscard']) {
                    $itemid = $hookitem['player']['verbosename'];
                    rawoutput("<a href=\"runmodule.php?module=iitems&op=discarditem&key={$key}&from={$from}\">Discard this item</a><br />");
                    addnav("", "runmodule.php?module=iitems&op=discarditem&key={$key}&from={$from}");
                }
                //Evaluate potential carriers for this iitem
                if (!$carriers[$hookitem['player']['inventorylocation']]['blocktransfer']) {
                    //the carrier that the item is currently in doesn't restrict transfer of items
                    foreach ($carriers as $ckey1 => $cdetails1) {
                        if (!$cdetails1['blocktransfer'] || $hookitem['master']['allowtransfer'] == $ckey1) {
                            //the carrier to be evaluated does not restrict transfer of iitems in OR the item is excluded
                            if ($hookitem['player']['inventorylocation'] != $ckey1) {
                                //the iitem is not already in the carrier we're evaluating
                                if (!$hookitem['master']['blockcarrier_' . $ckey1]) {
                                    //the iitem is not blocked from being in this carrier
                                    if (!$hookitem['master']['blocktransfer'] || $hookitem['master']['allowtransfer'] == $ckey1) {
                                        //the iitem is not blocked from being transferred completely OR the iitem is allowed to be transferred to only this carrier
                                        if ($ckey1 == "fight" && !$hookitem['master']['fightnav']) {
                                            continue;
                                        }
                                        //skip if we're looking at the fight carrier and this thing can't go in fights
                                        $cvname = $cdetails1['verbosename'];
                                        $transferto = $ckey1;
                                        //check hard weight limits
                                        //debug($weightinfo);
                                        if ($weightinfo[$ckey1]['wlimit_hardlimit']) {
                                            //debug($ckey1." has hard weight limit");
                                            //check weight
                                            if ($weightinfo[$ckey1]['max'] < $weightinfo[$ckey1]['current'] + $hookitem['player']['weight']) {
                                                //rawoutput("This item won't fit in your $cvname<br />");
                                                continue;
                                            }
                                        }
                                        rawoutput("<a href=\"runmodule.php?module=iitems&op=transferitem&key={$key}&from={$from}&transferto={$transferto}\">Transfer this item to your {$cvname}</a><br />");
                                        addnav("", "runmodule.php?module=iitems&op=transferitem&key={$key}&from={$from}&transferto={$transferto}");
                                        //debug("Item can be transferred to ".$transferto);
                                    }
                                }
                            }
                        }
                    }
                }
                output("%s`n", stripslashes($hookitem['master']['description']));
                $finalhookitem = array();
                $finalhookitem['master'] = $hookitem['master'];
                $finalhookitem['player'] = $hookitem['player'];
                $finalhookitem['inventorykey'] = $key;
                //modulehook("iitems-inventory", $finalhookitem);
                if ($finalhookitem['master']['image']) {
                    rawoutput("</td></tr></table>");
                }
                rawoutput("</td></tr>");
            }
        }
        rawoutput("</table>");
        rawoutput("</td></tr></table><br />");
    }
}
function iitems_weightandmass_process_weights($applybuffs = false, $showbars = false, $returnlocation = false)
{
    global $session, $weightinfo;
    require_once "modules/iitems/lib/lib.php";
    $inventory = iitems_get_player_inventory();
    $weightinfo = array();
    foreach ($inventory as $key => $values) {
        if ($values['wlimit_capacity']) {
            $weightinfo[$values['inventorylocation']]['max'] += $values['wlimit_capacity'];
            if ($values['wlimit_display_name']) {
                $weightinfo[$values['inventorylocation']]['wlimit_display_name'] = $values['wlimit_display_name'];
            }
            if ($values['wlimit_sbuff_name']) {
                $weightinfo[$values['inventorylocation']]['wlimit_sbuff_name'] = $values['wlimit_sbuff_name'];
            }
            if ($values['wlimit_sbuff_roundmsg']) {
                $weightinfo[$values['inventorylocation']]['wlimit_sbuff_roundmsg'] = $values['wlimit_sbuff_roundmsg'];
            }
            if ($values['wlimit_sbuff_action']) {
                $weightinfo[$values['inventorylocation']]['wlimit_sbuff_action'] = $values['wlimit_sbuff_action'];
            }
            if ($values['wlimit_use_sbuff']) {
                $weightinfo[$values['inventorylocation']]['wlimit_use_sbuff'] = $values['wlimit_use_sbuff'];
            }
            if ($values['wlimit_hardlimit']) {
                $weightinfo[$values['inventorylocation']]['wlimit_hardlimit'] = $values['wlimit_hardlimit'];
            }
        }
        if ($values['quantity']) {
            $weightinfo[$values['inventorylocation']]['current'] += $values['weight'] * $values['quantity'];
        } else {
            $weightinfo[$values['inventorylocation']]['current'] += $values['weight'];
        }
    }
    require_once "modules/staminasystem/lib/lib.php";
    if ($applybuffs) {
        foreach ($weightinfo as $invloc => $details) {
            $sbuffid = "wlimit_" . $invloc;
            if ($details['current'] > $details['max']) {
                if ($details['wlimit_use_sbuff']) {
                    $penalty = $details['current'] / $details['max'];
                    apply_stamina_buff($sbuffid, array("name" => $details['wlimit_sbuff_name'], "action" => $details['wlimit_sbuff_action'], "costmod" => $penalty, "expmod" => 1, "rounds" => -1, "roundmsg" => $details['wlimit_sbuff_roundmsg'], "wearoffmsg" => ""));
                }
            } else {
                strip_stamina_buff($sbuffid);
            }
        }
    }
    if ($showbars) {
        foreach ($weightinfo as $invloc => $details) {
            $cur = $details['current'] * 5;
            $max = $details['max'] * 5;
            $left = $max - $cur;
            if ($left >= 0) {
                rawoutput("<table><tr><td>" . $details['wlimit_display_name'] . "</td><td><table style='border: solid 1px #000000' width='{$max}' height='7' bgcolor='#333333' cellpadding=0 cellspacing=0><tr><td width='{$cur}' bgcolor='#00ff00'></td><td width='{$left}'></td></tr></table></td><td>" . $details['current'] . "kg / " . $details['max'] . "kg</td></tr></table>");
            } else {
                $over = $cur - $max;
                $totalwidth = $max + $over;
                rawoutput("<table><tr><td>" . $details['wlimit_display_name'] . "</td><td><table style='border: solid 1px #000000' height='7' width='{$totalwidth}' cellpadding=0 cellspacing=0><tr><td width='{$max}' bgcolor='#990000'></td><td width='{$over}' bgcolor='#ff0000'></td></tr></table></td><td>" . $details['current'] . "kg / " . $details['max'] . "kg</td></tr></table>");
            }
        }
    }
    if ($returnlocation) {
        return $weightinfo[$returnlocation];
    } else {
        return true;
    }
}