/*
 *  The Mana Client
 *  Copyright (C) 2004-2009  The Mana World Development Team
 *  Copyright (C) 2009-2010  The Mana Developers
 *
 *  This file is part of The Mana Client.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "localplayer.h"

#include "client.h"
#include "configuration.h"
#include "effectmanager.h"
#include "equipment.h"
#include "flooritem.h"
#include "graphics.h"
#include "guild.h"
#include "inventory.h"
#include "item.h"
#include "log.h"
#include "map.h"
#include "monster.h"
#include "particle.h"
#include "simpleanimation.h"
#include "sound.h"
#include "statuseffect.h"
#include "flooritemmanager.h"
#include "text.h"
#include "dropshortcut.h"

#include "gui/chat.h"
#include "gui/gui.h"
#include "gui/killstats.h"
#include "gui/ministatus.h"
#include "gui/okdialog.h"
#include "gui/outfitwindow.h"
#include "gui/palette.h"
#include "gui/skilldialog.h"
#include "gui/socialwindow.h"
#include "gui/statuswindow.h"
#include "gui/storagewindow.h"
#include "gui/theme.h"
#include "gui/userpalette.h"

#include "gui/widgets/chattab.h"

#include "net/beinghandler.h"
#include "net/chathandler.h"
#include "net/guildhandler.h"
#include "net/inventoryhandler.h"
#include "net/net.h"
#include "net/partyhandler.h"
#include "net/playerhandler.h"
#include "net/specialhandler.h"
#include "net/tradehandler.h"

#include "resources/animation.h"
#include "resources/imageset.h"
#include "resources/itemdb.h"
#include "resources/iteminfo.h"
#include "resources/resourcemanager.h"

#include "utils/gettext.h"
#include "utils/stringutils.h"

#include <cassert>

// This is the minimal delay between to permitted
// setDestination() calls using the keyboard.
// TODO: This can fine tuned later on when running is added...
const short walkingKeyboardDelay = 1000;

LocalPlayer *player_node = NULL;

LocalPlayer::LocalPlayer(int id, int job):
    Player(id, job, 0),
    mEquipment(new Equipment),
    mAttackRange(0),
    mTargetTime(-1),
    mLastTarget(-1),
    mCharacterPoints(0),
    mCorrectionPoints(0),
    mSpecialRechargeUpdateNeeded(0),
    mExp(0), mExpNeeded(0),
    mMp(0), mMaxMp(0),
    mMoney(0),
    mTotalWeight(1), mMaxWeight(1),
    mHp(1), mMaxHp(1),
    mSkillPoints(0),
    mTarget(NULL),
    mPlayerFollowed(""),
    mPlayerImitated(""),
    mPickUpTarget(NULL),
    mTrading(false), mGoingToTarget(false), mKeepAttacking(false),
    mLastAction(-1),
    mWalkingDir(0),
    mPathSetByMouse(false),
    mInventory(new Inventory(Net::getInventoryHandler()
                             ->getSize(Net::InventoryHandler::INVENTORY))),
    mLocalWalkTime(-1),
    mMessageTime(0),
    awayDialog(NULL),
    mAfkTime(0),
    mAwayMode(false),
    mShowNavigePath(false),
    mNavigateX(0), mNavigateY(0),
    mOldX(0),mOldY(0)
{
    mLevel = 1;

    awayListener = new AwayListener();
/*

    // Variable to keep the local player from doing certain actions before a map
    // is initialized. e.g. drawing a player's name using the TextManager, since
    // it appears to be dependant upon map coordinates for updating drawing.
    mMapInitialized = false;
*/
    mUpdateName = true;

    mTextColor = &Theme::getThemeColor(Theme::PLAYER);
    mNameColor = &userPalette->getColor(UserPalette::SELF);

    mLastTargetX = mLastTargetY = 0;

    mInvertDirection = config.getValue("invertMoveDirection", 0);
    mCrazyMoveType = config.getValue("crazyMoveType", 1);
    mCrazyMoveState = 0;
    mAttackWeaponType = config.getValue("attackWeaponType", 1);
    mQuickDropCounter = config.getValue("quickDropCounter", 1);
    mMoveState = 0;
    mDisableCrazyMove = false;
    mPickUpType = config.getValue("pickUpType", 2);
    mMagicAttackType = config.getValue("magicAttackType", 0);
    mMoveToTargetType = config.getValue("moveToTargetType", 0);
    mDisableGameModifiers = config.getValue("disableGameModifiers", false);
    mTargetDeadPlayers = config.getValue("targetDeadPlayers", false);
    mAttackType = config.getValue("attackType", 1);

    mPingSendTick = 0;
    mWaitPing = false;
    mPingTime = 0;

    loadHomes();
    initTargetCursor();

    config.addListener("showownname", this);
    config.addListener("targetDeadPlayers", this);
    setShowName(config.getValue("showownname", 1));
}

LocalPlayer::~LocalPlayer()
{
    delete mInventory;
    mInventory = 0;

    config.removeListener("showownname", this);
    config.removeListener("targetDeadPlayers", this);

    for (int i = Being::TC_SMALL; i < Being::NUM_TC; i++)
    {
        delete mTargetCursor[0][i];
        mTargetCursor[0][i] = 0;
        delete mTargetCursor[1][i];
        mTargetCursor[1][i] = 0;
        if (mTargetCursorImages[0][i])
            mTargetCursorImages[0][i]->decRef();
        if (mTargetCursorImages[1][i])
            mTargetCursorImages[1][i]->decRef();
    }
}

void LocalPlayer::logic()
{
    // Actions are allowed once per second
    if (get_elapsed_time(mLastAction) >= 1000)
        mLastAction = -1;

    // Show XP messages
    if (!mMessages.empty())
    {
        if (mMessageTime == 0)
        {
            //const Vector &pos = getPosition();

            MessagePair info = mMessages.front();

            particleEngine->addTextRiseFadeOutEffect(
                    info.first,
                    /*(int) pos.x,
                    (int) pos.y - 48,*/
                    getPixelX(),
                    getPixelY() - 48,
                    &userPalette->getColor(info.second),
                    gui->getInfoParticleFont(), true);

            mMessages.pop_front();
            mMessageTime = 30;
        }
        mMessageTime--;
    }

    if ((mSpecialRechargeUpdateNeeded%11) == 0)
    {
        mSpecialRechargeUpdateNeeded = 0;
        for (std::map<int, Special>::iterator i = mSpecials.begin();
             i != mSpecials.end();
             i++)
        {
            i->second.currentMana += i->second.recharge;
            if (i->second.currentMana > i->second.neededMana)
            {
                i->second.currentMana = i->second.neededMana;
            }
        }
    }
    mSpecialRechargeUpdateNeeded++;

    // Targeting allowed 4 times a second
    if (get_elapsed_time(mLastTarget) >= 250)
        mLastTarget = -1;

//    // Remove target if its been on a being for more than a minute
    if (get_elapsed_time(mTargetTime) >= 60000)
    {
        mTargetTime = tick_time;
//        setTarget(NULL);
        mLastTarget = -1;
    }

    if (mTarget)
    {
        if (mTarget->getType() == Being::NPC)
        {
            // NPCs are always in range
            mTarget->setTargetAnimation(
                mTargetCursor[0][mTarget->getTargetCursorSize()]);
        }
        else
        {
            // Find whether target is in range
            // TODO: Make this nicer, probably using getPosition() only
            const int rangeX =
                (Net::getNetworkType() == ServerInfo::MANASERV) ?
                abs(mTarget->getPosition().x - getPosition().x) :
                abs(mTarget->getTileX() - getTileX());
            const int rangeY =
                (Net::getNetworkType() == ServerInfo::MANASERV) ?
                abs(mTarget->getPosition().y - getPosition().y) :
                abs(mTarget->getTileY() - getTileY());

            const int attackRange = getAttackRange();
            const int inRange = rangeX > attackRange || rangeY > attackRange
                                                                    ? 1 : 0;
            mTarget->setTargetAnimation(
                mTargetCursor[inRange][mTarget->getTargetCursorSize()]);

            if (!mTarget->isAlive()
                && (!mTargetDeadPlayers
                    || mTarget->getType() != Being::PLAYER))
            {
                stopAttack();
            }

            if (mKeepAttacking && mTarget)
                attack(mTarget, true);
        }
    }

    Player::logic();
}

void LocalPlayer::setAction(Action action, int attackType)
{
    if (action == DEAD)
    {
        mLastTarget = -1;
        setTarget(NULL);
    }

    Player::setAction(action, attackType);
}

void LocalPlayer::setGM(bool gm)
{
    mIsGM = gm;
}

void LocalPlayer::setGMLevel(int level)
{
    mGMLevel = level;

    if (level > 0)
        setGM(true);
}


void LocalPlayer::nextTile(unsigned char dir = 0)
{
    if (Net::getNetworkType() == ServerInfo::EATHENA)
    {
        // TODO: Fix picking up when reaching target (this method is obsolete)
        // TODO: Fix holding walking button to keep walking smoothly
        if (mPath.empty())
        {
            if (mPickUpTarget)
                pickUp(mPickUpTarget);

            if (mWalkingDir)
                startWalking(mWalkingDir);
        }

        // TODO: Fix automatically walking within range of target, when wanted
        if (mGoingToTarget && mTarget && withinAttackRange(mTarget))
        {
            mAction = Being::STAND;
            attack(mTarget, true);
            mGoingToTarget = false;
            mPath.clear();
            return;
        }
        else if (mGoingToTarget && !mTarget)
        {
            mGoingToTarget = false;
            mPath.clear();
        }


        Player::nextTile();
    }
    else
    {
        if (!mMap || !dir)
            return;

        const Vector &pos = getPosition();

        // Compute where the next step will be set.
        int dx = 0, dy = 0;
        if (dir & UP)
            dy--;
        if (dir & DOWN)
            dy++;
        if (dir & LEFT)
            dx--;
        if (dir & RIGHT)
            dx++;

        // Prevent skipping corners over colliding tiles
        if (dx && !mMap->getWalk(((int) pos.x + dx) / 32,
                                 (int) pos.y / 32, getWalkMask()))
            dx = 16 - (int) pos.x % 32;
        if (dy && !mMap->getWalk((int) pos.x / 32,
                                 ((int) pos.y + dy) / 32, getWalkMask()))
            dy = 16 - (int) pos.y % 32;

        // Choose a straight direction when diagonal target is blocked
        if (dx && dy && !mMap->getWalk((pos.x + dx) / 32,
                                       (pos.y + dy) / 32, getWalkMask()))
            dx = 16 - (int) pos.x % 32;

        int dScaler; // Distance to walk

        // Checks our path up to 1 tiles, if a blocking tile is found
        // We go to the last good tile, and break out of the loop
        for (dScaler = 1; dScaler <= 32; dScaler++)
        {
            if ( (dx || dy) &&
                 !mMap->getWalk( ((int) pos.x + (dx * dScaler)) / 32,
                                 ((int) pos.y + (dy * dScaler)) / 32, getWalkMask()) )
            {
                dScaler--;
                break;
            }
        }

        if (dScaler > 16)
        {
            //effectManager->trigger(15, (int) pos.x + (dx * dScaler), (int) pos.y + (dy * dScaler));
            setDestination((int) pos.x + (dx * dScaler), (int) pos.y + (dy * dScaler));
        }
        else if (dir)
        {
            // If the being can't move, just change direction
            Net::getPlayerHandler()->setDirection(dir);
            setDirection(dir);
        }
    }
}

bool LocalPlayer::checkInviteRights(const std::string &guildName)
{
    Guild *guild = getGuild(guildName);
    if (guild)
    {
        return guild->getInviteRights();
    }

    return false;
}

void LocalPlayer::inviteToGuild(Being *being)
{
    if (being->getType() != PLAYER)
        return;
    Player *player = static_cast<Player*>(being);

    // TODO: Allow user to choose which guild to invite being to
    // For now, just invite to the first guild you have permissions to invite with
    std::map<int, Guild*>::iterator itr = mGuilds.begin();
    std::map<int, Guild*>::iterator itr_end = mGuilds.end();
    for (; itr != itr_end; ++itr)
    {
        if (checkInviteRights(itr->second->getName()))
        {
            Net::getGuildHandler()->invite(itr->second->getId(), player);
            return;
        }
    }
}

void LocalPlayer::clearInventory()
{
    mEquipment->clear();
    mInventory->clear();
}

void LocalPlayer::setInvItem(int index, int id, int amount)
{
    bool equipment = false;
    int itemType = ItemDB::get(id).getType();
    if (itemType != ITEM_UNUSABLE && itemType != ITEM_USABLE)
        equipment = true;
    mInventory->setItem(index, id, amount, equipment);
}

void LocalPlayer::pickUp(FloorItem *item)
{
    int dx = item->getX() - getTileX();
    int dy = item->getY() - getTileY();
    int dist = 6;

    if (mPickUpType == 4 || mPickUpType == 5)
        dist = 4;

    if (dx * dx + dy * dy < dist)
    {
        Net::getPlayerHandler()->pickUp(item);
        mPickUpTarget = NULL;
    }
    else if (mPickUpType == 4 || mPickUpType == 5)
    {
        if (Net::getNetworkType() == ServerInfo::MANASERV)
        {
            setDestination(item->getX() * 32 + 16, item->getY() * 32 + 16);
            mPickUpTarget = item;
        }
        else
        {
            const Vector &playerPos = getPosition();
            Path debugPath = mMap->findPath(
                                            (int) (playerPos.x - 16) / 32,
                                            (int) (playerPos.y - 32) / 32,
                                            item->getX(), item->getY(), 0xFF);
            if (debugPath.size() > 0)
            {
                Position pos(0,0);
                unsigned int f = 0;

                for (Path::const_iterator i = debugPath.begin(), i_end = debugPath.end();
                     i != i_end && f < debugPath.size() - 1; ++i, f++)
                {
                    pos = (*i);
                }
                moveTo(pos.x, pos.y);
            }
            else
                setDestination(item->getX(), item->getY());
            mPickUpTarget = item;
            stopAttack();
        }
    }
}

Being *LocalPlayer::getTarget() const
{
    return mTarget;
}

void LocalPlayer::setTarget(Being *target)
{
    if ((mLastTarget != -1 || target == this) && target)
        return;

    if (target)
        mLastTarget = tick_time;

    if (target == mTarget)
        return;

    if (target || mAction == ATTACK)
    {
        mTargetTime = tick_time;
    }
    else
    {
        mKeepAttacking = false;
        mTargetTime = -1;
    }

    Being *oldTarget = NULL;
    if (mTarget)
    {
        mTarget->untarget();
        oldTarget = mTarget;
        mTarget->updateName();
    }

    if (mTarget && mTarget->getType() == Being::MONSTER)
        mTarget->setShowName(false);

    mTarget = target;

    if (oldTarget)
    {
        oldTarget->updateName();
    }

    if (mTarget)
    {
        mLastTargetX = mTarget->getTileX();
        mLastTargetY = mTarget->getTileY();
        mTarget->updateName();
    }
    if (target && target->getType() == Being::MONSTER)
        target->setShowName(true);
}

void LocalPlayer::setDestination(int x, int y)
{
    // Only send a new message to the server when destination changes
    if (x != mDest.x || y != mDest.y)
    {
        if (mInvertDirection != 1)
        {
            Net::getPlayerHandler()->setDestination(x, y, mDirection);
            mPickUpTarget = NULL;
            mKeepAttacking = false;
            Being::setDestination(x, y);
        }
        else if (mInvertDirection == 1)
        {
            Uint8 newDir = 0;
            if (mDirection&UP)
                newDir |= DOWN;
            if (mDirection&LEFT)
                newDir |= RIGHT;
            if (mDirection&DOWN)
                newDir |= UP;
            if (mDirection&RIGHT)
                newDir |= LEFT;

            Net::getPlayerHandler()->setDestination(x, y, newDir);
            setDirection(newDir);
            Net::getPlayerHandler()->setDirection(newDir);

            mPickUpTarget = NULL;
            mKeepAttacking = false;
            Being::setDestination(x, y);
        }

        // Manaserv:
        // If the destination given to being class is accepted,
        // we inform the Server.
        if ((x == mDest.x && y == mDest.y)
            || Net::getNetworkType() == ServerInfo::EATHENA)
          Net::getPlayerHandler()->setDestination(x, y, mDirection);

        return;
    }

    mPickUpTarget = NULL;
    mKeepAttacking = false;
}

void LocalPlayer::setWalkingDir(int dir)
{
    // This function is called by Game::handleInput()

    if (Net::getNetworkType() == ServerInfo::MANASERV)
    {
        // First if player is pressing key for the direction he is already
        // going, do nothing more...

        // Else if he is pressing a key, and its different from what he has
        // been pressing, stop (do not send this stop to the server) and
        // start in the new direction
        if (dir && (dir != getWalkingDir()))
            player_node->stopWalking(false);

        // Else, he is not pressing a key,
        // and the current path hasn't been sent by mouse,
        // then, stop (sending to server).
        else if (!dir)
        {
            if (!mPathSetByMouse)
                player_node->stopWalking(true);
            return;
        }

        // If the delay to send another walk message to the server hasn't expired,
        // don't do anything or we could get disconnected for spamming the server
        if (get_elapsed_time(mLocalWalkTime) < walkingKeyboardDelay)
            return;
    }

    mWalkingDir = dir;

    // If we're not already walking, start walking.
    if (mAction != WALK && dir)
    {
        startWalking(dir);
    }
    else if (mAction == WALK && (Net::getNetworkType() == ServerInfo::MANASERV))
    {
        nextTile(dir);
    }
}

void LocalPlayer::startWalking(unsigned char dir)
{
    // This function is called by setWalkingDir(),
    // but also by nextStep() for eAthena...

    // TODO: Evaluate the implementation of this method for Manaserv
    if (!mMap || !dir)
        return;

    if (mAction == WALK && !mPath.empty())
    {
        // Just finish the current action, otherwise we get out of sync
        if (Net::getNetworkType() == ServerInfo::MANASERV)
        {
            const Vector &pos = getPosition();
            Being::setDestination(pos.x, pos.y);
        }
        else
            Being::setDestination(getTileX(), getTileY());
        return;
    }

    int dx = 0, dy = 0;
    if (dir & UP)
        dy--;
    if (dir & DOWN)
        dy++;
    if (dir & LEFT)
        dx--;
    if (dir & RIGHT)
        dx++;

    if (Net::getNetworkType() == ServerInfo::EATHENA)
    {
        // Prevent skipping corners over colliding tiles
        if (dx && !mMap->getWalk(getTileX() + dx, getTileY(), getWalkMask()))
            dx = 0;
        if (dy && !mMap->getWalk(getTileX(), getTileY() + dy, getWalkMask()))
            dy = 0;

        // Choose a straight direction when diagonal target is blocked
        if (dx && dy && !mMap->getWalk(getTileX() + dx, getTileY() + dy, getWalkMask()))
            dx = 0;

        // Walk to where the player can actually go
        if ((dx || dy) && mMap->getWalk(getTileX() + dx, getTileY() + dy, getWalkMask()))
        {
            setDestination(getTileX() + dx, getTileY() + dy);
        }
        else if (dir)
        {
            // If the being can't move, just change direction
            Net::getPlayerHandler()->setDirection(dir);
            setDirection(dir);
        }
    }
    else
        nextTile(dir);
}

void LocalPlayer::stopWalking(bool sendToServer)
{
    if (mAction == WALK && mWalkingDir)
    {
        mWalkingDir = 0;
        mLocalWalkTime = 0;

        setDestination((int) getPosition().x, (int) getPosition().y);
        if (sendToServer)
             Net::getPlayerHandler()->setDestination((int) getPosition().x,
                                                     (int) getPosition().y);
        setAction(STAND);
    }

    // No path set anymore, so we reset the path by mouse flag
    mPathSetByMouse = false;

    clearPath();
}

void LocalPlayer::toggleSit()
{
//    if (mLastAction != -1)
//        return;
//    mLastAction = tick_time;

    Being::Action newAction;
    switch (mAction)
    {
        case STAND: newAction = SIT; break;
        case SIT: newAction = STAND; break;
        default: return;
    }

    Net::getPlayerHandler()->changeAction(newAction);
}

void LocalPlayer::emote(Uint8 emotion)
{
//    if (mLastAction != -1)
//        return;
//    mLastAction = tick_time;

    Net::getPlayerHandler()->emote(emotion);
}

void LocalPlayer::useSpecial(int special)
{
    Net::getSpecialHandler()->use(special);
}

void LocalPlayer::setSpecialStatus(int id, int current, int max, int recharge)
{
    logger->log("SpecialUpdate Skill #%d -- (%d/%d) -> %d", id, current, max, recharge);
    mSpecials[id].currentMana = current;
    mSpecials[id].neededMana = max;
    mSpecials[id].recharge = recharge;
}

void LocalPlayer::attack(Being *target, bool keep, bool dontChangeEquipment)
{
    if (Net::getNetworkType() == ServerInfo::MANASERV)
    {
        if (mLastAction != -1)
            return;

        // Can only attack when standing still
        if (mAction != STAND && mAction != ATTACK)
            return;
    }

    mKeepAttacking = keep;

    if (!target || target->getType() == Being::NPC)
        return;

    if (mTarget != target || !mTarget)
    {
        mLastTarget = -1;
        setTarget(target);
    }
    if (Net::getNetworkType() == ServerInfo::MANASERV)
    {
        Vector plaPos = this->getPosition();
        Vector tarPos = mTarget->getPosition();
        int dist_x = plaPos.x - tarPos.x;
        int dist_y = plaPos.y - tarPos.y;

        if (abs(dist_y) >= abs(dist_x))
        {
            if (dist_y < 0)
                setDirection(DOWN);
            else
                setDirection(UP);
        }
        else
        {
            if (dist_x < 0)
                setDirection(RIGHT);
            else
                setDirection(LEFT);
        }

        mLastAction = tick_time;
    }
    else
    {
        int dist_x = target->getTileX() - getTileX();
        int dist_y = target->getTileY() - getTileY();

        // Must be standing or sitting to attack
        if (mAction != STAND && mAction != SIT)
            return;

        if (abs(dist_y) >= abs(dist_x))
        {
            if (dist_y > 0)
                setDirection(DOWN);
            else
                setDirection(UP);
        }
        else
        {
            if (dist_x > 0)
                setDirection(RIGHT);
            else
                setDirection(LEFT);
        }

        mWalkTime = tick_time;
        mTargetTime = tick_time;
    }

    setAction(ATTACK);

    if (mEquippedWeapon)
    {
        std::string soundFile = mEquippedWeapon->getSound(EQUIP_EVENT_STRIKE);
        if (!soundFile.empty())
            sound.playSfx(soundFile);
    }
    else
    {
        sound.playSfx("sfx/fist-swish.ogg");
    }

    if (!dontChangeEquipment && target)
        changeEquipmentBeforeAttack(target);

    Net::getPlayerHandler()->attack(target->getId());
    if ((Net::getNetworkType() == ServerInfo::EATHENA) && !keep)
        stopAttack();
}

void LocalPlayer::stopAttack()
{
    if (mTarget)
    {
        if (mAction == ATTACK)
            setAction(STAND);
        setTarget(NULL);
    }
    mLastTarget = -1;
}

void LocalPlayer::raiseAttribute(int attr)
{
    // we assume that the server allows the change. When not we will undo it later.
    mCharacterPoints--;
    IntMap::iterator it = mAttributeBase.find(attr);
    if (it != mAttributeBase.end())
        (*it).second++;
    Net::getPlayerHandler()->increaseAttribute(attr);
}

void LocalPlayer::lowerAttribute(int attr)
{
    // we assume that the server allows the change. When not we will undo it later.
    mCorrectionPoints--;
    mCharacterPoints++;
    IntMap::iterator it = mAttributeBase.find(attr);
    if (it != mAttributeBase.end())
        (*it).second--;
    Net::getPlayerHandler()->decreaseAttribute(attr);
}

void LocalPlayer::setAttributeBase(int num, int value, bool notify)
{
    int old = mAttributeBase[num];

    mAttributeBase[num] = value;
    if (skillDialog)
    {
        if (skillDialog->update(num).empty() || !(value > old))
            return;

        if (old != 0 && notify)
            effectManager->trigger(1, this);
    }

    if (statusWindow)
        statusWindow->update(num);
}

void LocalPlayer::setAttributeEffective(int num, int value)
{
    mAttributeEffective[num] = value;
    if (skillDialog)
        skillDialog->update(num);

    if (statusWindow)
        statusWindow->update(num);
}

void LocalPlayer::setCharacterPoints(int n)
{
    mCharacterPoints = n;

    if (statusWindow)
        statusWindow->update(StatusWindow::CHAR_POINTS);
}

void LocalPlayer::setCorrectionPoints(int n)
{
    mCorrectionPoints = n;

    if (statusWindow)
        statusWindow->update(StatusWindow::CHAR_POINTS);
}

void LocalPlayer::setSkillPoints(int points)
{
    mSkillPoints = points;
    if (skillDialog)
        skillDialog->update();
}

void LocalPlayer::setExperience(int skill, int current, int next, bool notify)
{
    std::pair<int, int> cur = getExperience(skill);
    int diff = current - cur.first;

    cur = std::pair<int, int>(current, next);

    mSkillExp[skill] = cur;

    std::string name;
    if (skillDialog)
        name = skillDialog->update(skill);

    if (mMap && notify && cur.first != -1 && diff > 0 && !name.empty())
        addMessageToQueue(strprintf("%d %s xp", diff, name.c_str()));

    if (statusWindow)
        statusWindow->update(skill);
}

std::pair<int, int> LocalPlayer::getExperience(int skill)
{
    return mSkillExp[skill];
}

void LocalPlayer::setHp(int value)
{
    mHp = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::HP);
}

void LocalPlayer::setMaxHp(int value)
{
    mMaxHp = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::HP);
}

void LocalPlayer::setLevel(int value)
{
    mLevel = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::LEVEL);
}

void LocalPlayer::setExp(int value, bool notify)
{
    if (mMap && notify && value > mExp)
    {
        addMessageToQueue(toString(value - mExp) + " xp");
        killStats->gainXp(value);
    }
    mExp = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::EXP);
}

void LocalPlayer::setExpNeeded(int value)
{
    mExpNeeded = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::EXP);
}

void LocalPlayer::setMP(int value)
{
    mMp = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::MP);
}

void LocalPlayer::setMaxMP(int value)
{
    mMaxMp = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::MP);
}

void LocalPlayer::setMoney(int value)
{
    mMoney = value;

    if (statusWindow)
        statusWindow->update(StatusWindow::MONEY);
}

void LocalPlayer::pickedUp(const ItemInfo &itemInfo, int amount)
{
    if (!amount)
    {
        if (config.getValue("showpickupchat", 1))
            localChatTab->chatLog(_("Unable to pick up item."), BY_SERVER);
    }
    else
    {
        if (config.getValue("showpickupchat", 1))
        {
            // TRANSLATORS: This sentence may be translated differently
            // for different grammatical numbers (singular, plural, ...)
            localChatTab->chatLog(strprintf(ngettext("You picked up %d "
                    "[@@%d|%s@@].", "You picked up %d [@@%d|%s@@].", amount),
                    amount, itemInfo.getId(), itemInfo.getName().c_str()),
                    BY_SERVER);
        }

        if (mMap && config.getValue("showpickupparticle", 0))
        {
            // Show pickup notification
            addMessageToQueue(itemInfo.getName(), UserPalette::PICKUP_INFO);
        }
    }
}

int LocalPlayer::getAttackRange()
{
    if (mAttackRange > -1)
    {
        return mAttackRange;
    }
    else
    {
        Item *weapon = mEquipment->getEquipment(EQUIP_FIGHT1_SLOT);
        if (weapon)
        {
            const ItemInfo info = weapon->getInfo();
            return info.getAttackRange();
        }
        return 48; // unarmed range
    }
}

bool LocalPlayer::withinAttackRange(Being *target)
{
    if (Net::getNetworkType() == ServerInfo::MANASERV)
    {
        const Vector &targetPos = target->getPosition();
        const Vector &pos = getPosition();
        const int dx = abs(targetPos.x - pos.x);
        const int dy = abs(targetPos.y - pos.y);
        const int range = getAttackRange();

        return !(dx > range || dy > range);
    }
    else
    {
        int dist_x = abs(target->getTileX() - getTileX());
        int dist_y = abs(target->getTileY() - getTileY());

        if (dist_x > getAttackRange() || dist_y > getAttackRange())
            return false;

        return true;
    }
}

void LocalPlayer::setGotoTarget(Being *target)
{
    mLastTarget = -1;
    if (Net::getNetworkType() == ServerInfo::MANASERV)
    {
        mTarget = target;
        mGoingToTarget = true;
        const Vector &targetPos = target->getPosition();
        setDestination(targetPos.x, targetPos.y);
    }
    else
    {
        setTarget(target);
        mGoingToTarget = true;
        setDestination(target->getTileX(), target->getTileY());
    }
}

extern MiniStatusWindow *miniStatusWindow;
extern SkillDialog *skillDialog;

void LocalPlayer::handleStatusEffect(StatusEffect *effect, int effectId)
{
    Being::handleStatusEffect(effect, effectId);

    if (effect)
    {
        effect->deliverMessage();
        effect->playSFX();

        AnimatedSprite *sprite = effect->getIcon();

        if (!sprite)
        {
            // delete sprite, if necessary
            for (unsigned int i = 0; i < mStatusEffectIcons.size();)
                if (mStatusEffectIcons[i] == effectId)
                {
                    mStatusEffectIcons.erase(mStatusEffectIcons.begin() + i);
                    miniStatusWindow->eraseIcon(i);
                }
                else
                    i++;
        }
        else
        {
            // replace sprite or append
            bool found = false;

            for (unsigned int i = 0; i < mStatusEffectIcons.size(); i++)
                if (mStatusEffectIcons[i] == effectId)
                {
                    miniStatusWindow->setIcon(i, sprite);
                    found = true;
                    break;
                }

            if (!found)
            { // add new
                int offset = mStatusEffectIcons.size();
                miniStatusWindow->setIcon(offset, sprite);
                mStatusEffectIcons.push_back(effectId);
            }
        }
    }
}

void LocalPlayer::initTargetCursor()
{
    // Load target cursors
    loadTargetCursor("target-cursor-blue-s.png", 44, 35, false, TC_SMALL);
    loadTargetCursor("target-cursor-red-s.png", 44, 35, true, TC_SMALL);
    loadTargetCursor("target-cursor-blue-m.png", 62, 44, false, TC_MEDIUM);
    loadTargetCursor("target-cursor-red-m.png", 62, 44, true, TC_MEDIUM);
    loadTargetCursor("target-cursor-blue-l.png", 82, 60, false, TC_LARGE);
    loadTargetCursor("target-cursor-red-l.png", 82, 60, true, TC_LARGE);
}

void LocalPlayer::loadTargetCursor(const std::string &filename,
                                   int width, int height,
                                   bool outRange, TargetCursorSize size)
{
    assert(size > -1);
    assert(size < 3);

    ImageSet *currentImageSet = Theme::getImageSetFromTheme(filename,
                                                            width, height);
    Animation *anim = new Animation;

    for (unsigned int i = 0; i < currentImageSet->size(); ++i)
    {
        anim->addFrame(currentImageSet->get(i), 75,
                      (16 - (currentImageSet->getWidth() / 2)),
                      (16 - (currentImageSet->getHeight() / 2)));
    }

    SimpleAnimation *currentCursor = new SimpleAnimation(anim);

    const int index = outRange ? 1 : 0;

    mTargetCursorImages[index][size] = currentImageSet;
    mTargetCursor[index][size] = currentCursor;
}

unsigned short LocalPlayer::getSkillLv(int id)
{
    IntMap::iterator it = mAttributeEffective.find(id);
    if (it != mAttributeEffective.end())
        return (*it).second;
    return 0;
}

void LocalPlayer::addMessageToQueue(const std::string &message, int color)
{
    mMessages.push_back(MessagePair(message, color));
}

void LocalPlayer::optionChanged(const std::string &value)
{
    if (value == "showownname")
        setShowName(config.getValue("showownname", 1));
    else if (value == "targetDeadPlayers")
        mTargetDeadPlayers = config.getValue("targetDeadPlayers", false);
}

void LocalPlayer::moveTo(int x, int y)
{
    setDestination(x, y);
}

void LocalPlayer::move(int dX, int dY)
{
    moveTo(getTileX() + dX, getTileY() + dY);
}

void LocalPlayer::moveToTarget(unsigned int dist)
{
    if (mTarget)
    {
        if ((int)dist == -1)
        {
            dist = mMoveToTargetType;
            if (mMoveToTargetType == 0)
            {
                dist = 0;
            }
            else
            {
                switch (mMoveToTargetType)
                {
                    case 1:
                        dist = 1;
                        break;
                    case 2:
                        dist = 3;
                        break;
                    case 3:
                        dist = 5;
                        break;
                    case 4:
                        dist = 7;
                        break;
                    case 5:
                        dist = mAttackRange;
                    default:
                        break;
                }
            }
        }

        if (dist == 0)
        {
            setDestination(mTarget->getTileX(), mTarget->getTileY());
        }
        else
        {
            const Vector &playerPos = getPosition();
//            unsigned int dist = 0;

            Path debugPath = mMap->findPath((int) (playerPos.x - 16) / 32,
                                            (int) (playerPos.y - 32) / 32,
                                            mTarget->getTileX(), mTarget->getTileY(), 0xFF);

            if (debugPath.size() < dist)
            {
                return;
            }

            Position pos(0,0);
            unsigned int f = 0;
            for (Path::const_iterator i = debugPath.begin(), i_end = debugPath.end();
                 i != i_end && f < debugPath.size() - dist; ++i, f++)
            {
                pos = (*i);
            }
            moveTo(pos.x, pos.y);
        }
    }
    else if (mLastTargetX != 0 || mLastTargetY != 0)
    {
        setDestination(mLastTargetX, mLastTargetY);
    }
}

void LocalPlayer::moveToHome()
{
    std::map<std::string,Vector>::iterator iter = mHomes.find(mMap->getProperty("_filename"));

    if (iter != mHomes.end())
    {
        Vector pos = mHomes[(*iter).first];
        if (getTileX() == pos.x && getTileY() == pos.y)
            Net::getPlayerHandler()->setDestination(pos.x, pos.y, mDirection);
        else if (abs(getTileX() - pos.x) < 40 && abs(getTileY() - pos.y) < 40)
            moveTo(pos.x, pos.y);
    }
}

void LocalPlayer::changeAttackWeaponType()
{
    mAttackWeaponType++;
    if (mAttackWeaponType > 3)
        mAttackWeaponType = 1;

    config.setValue("attackWeaponType", mAttackWeaponType);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::changeAttackType()
{
    mAttackType++;
    if (mAttackType > 2)
        mAttackType = 0;

    config.setValue("attackType", mAttackType);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::invertDirection()
{
    mMoveState = 0;
    mInvertDirection ++;
    if (mInvertDirection > 4)
        mInvertDirection = 0;
    config.setValue("invertMoveDirection", mInvertDirection);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::changeCrazyMoveType()
{
    mCrazyMoveState = 0;
    mCrazyMoveType++;
    if (mCrazyMoveType > 10)
        mCrazyMoveType = 1;

    config.setValue("crazyMoveType", mCrazyMoveType);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::changePickUpType()
{
    mPickUpType++;
    if (mPickUpType > 5)
        mPickUpType = 0;

    config.setValue("pickUpType", mPickUpType);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::changeEquipmentBeforeAttack(Being* target)
{
    if (mAttackWeaponType == 1)
        return;

    bool allowSword = false;
    int dx = target->getTileX() - getTileX();
    int dy = target->getTileY() - getTileY();
    Item *item = NULL;

    if (dx * dx + dy * dy > 80)
        return;

    if (dx * dx + dy * dy < 8)
        allowSword = true;

    //if attack distance for sword
    if (allowSword)
    {
        //finding sword
        item = player_node->getInventory()->findItem(571);

        if (!item)
            item = player_node->getInventory()->findItem(570);

        if (!item)
            item = player_node->getInventory()->findItem(536);

        //no swords
        if (!item)
            return;

        //if sword not equiped
        if (!item->isEquipped())
        {
            Net::getInventoryHandler()->equipItem(item);

        }

        //if need equip shield too
        if (mAttackWeaponType == 3)
        {
            //finding shield
            item = player_node->getInventory()->findItem(601);
            if (!item)
                item = player_node->getInventory()->findItem(602);
            if (item && !item->isEquipped())
            {
                Net::getInventoryHandler()->equipItem(item);
            }
        }

    }
    //big distance. allowed only bow
    else
    {
        //finding bow
        item = player_node->getInventory()->findItem(545);

        if (!item)
            item = player_node->getInventory()->findItem(530);

        //no bow
        if (!item)
            return;

        if (!item->isEquipped())
        {
            Net::getInventoryHandler()->equipItem(item);
        }
    }

}


void LocalPlayer::crazyMove()
{
    bool oldDisableCrazyMove = mDisableCrazyMove;
    mDisableCrazyMove = true;
    switch(mCrazyMoveType)
    {
        case 1:
            crazyMove1();
            break;
        case 2:
            crazyMove2();
            break;
        case 3:
            crazyMove3();
            break;
        case 4:
            crazyMove4();
            break;
        case 5:
            crazyMove5();
            break;
        case 6:
            crazyMove6();
            break;
        case 7:
            crazyMove7();
            break;
        case 8:
            crazyMove8();
            break;
        case 9:
            crazyMove9();
            break;
        case 10:
            crazyMoveA();
            break;
        default:
            break;
    }
    mDisableCrazyMove = oldDisableCrazyMove;
}

void LocalPlayer::crazyMove1()
{
    if (mAction == WALK)
        return;

    if (getDirection() == Being::UP)
    {
        setWalkingDir(Being::UP);
        setDirection(Being::LEFT);
        Net::getPlayerHandler()->setDirection(Being::LEFT);
    }
    else if (getDirection() == Being::LEFT)
    {
        setWalkingDir(Being::LEFT);
        setDirection(Being::DOWN);
        Net::getPlayerHandler()->setDirection(Being::DOWN);
    }
    else if (getDirection() == Being::DOWN)
    {
        setWalkingDir(Being::DOWN);
        setDirection(Being::RIGHT);
        Net::getPlayerHandler()->setDirection(Being::RIGHT);
    }
    else if (getDirection() == Being::RIGHT)
    {
        setWalkingDir(Being::RIGHT);
        setDirection(Being::UP);
        Net::getPlayerHandler()->setDirection(Being::UP);
    }
}

void LocalPlayer::crazyMove2()
{
    if (mAction == WALK)
        return;

    if (getDirection() == Being::UP)
    {
        setWalkingDir(Being::UP|Being::LEFT);
        setDirection(Being::RIGHT);
        Net::getPlayerHandler()->setDirection(Being::DOWN|Being::RIGHT);
    }
    else if (getDirection() == Being::RIGHT)
    {
        setWalkingDir(Being::UP|Being::RIGHT);
        setDirection(Being::DOWN);
        Net::getPlayerHandler()->setDirection(Being::DOWN|Being::LEFT);
    }
    else if (getDirection() == Being::DOWN)
    {
        setWalkingDir(Being::DOWN|Being::RIGHT);
        setDirection(Being::LEFT);
        Net::getPlayerHandler()->setDirection(Being::UP|Being::LEFT);
    }
    else if (getDirection() == Being::LEFT)
    {
        setWalkingDir(Being::DOWN|Being::LEFT);
        setDirection(Being::UP);
        Net::getPlayerHandler()->setDirection(Being::UP|Being::RIGHT);
    }
}

void LocalPlayer::crazyMove3()
{
    if (mAction == WALK)
        return;

    switch(mCrazyMoveState)
    {
        case 0:
            move(1,1);
            mCrazyMoveState = 1;
            break;
        case 1:
            move(1,-1);
            mCrazyMoveState = 2;
            break;
        case 2:
            move(-1,-1);
            mCrazyMoveState = 3;
            break;
        case 3:
            move(-1,1);
            mCrazyMoveState = 0;
            break;
        default:
            break;
    }
    setDirection(Being::DOWN);
    Net::getPlayerHandler()->setDirection(Being::DOWN);
}

void LocalPlayer::crazyMove4()
{
    if (mAction == WALK)
        return;

    switch(mCrazyMoveState)
    {
        case 0:
            move(7,0);
            mCrazyMoveState = 1;
        break;
        case 1:
            move(-7,0);
            mCrazyMoveState = 0;
        break;
    }
}

void LocalPlayer::crazyMove5()
{
    if (mAction == WALK)
        return;

    switch(mCrazyMoveState)
    {
        case 0:
            move(0,7);
            mCrazyMoveState = 1;
            break;
        case 1:
            move(0,-7);
            mCrazyMoveState = 0;
            break;
        default:
            break;
    }
}

void LocalPlayer::crazyMove6()
{
    if (mAction == WALK)
        return;

    switch(mCrazyMoveState)
    {
        case 0:
            move(3,0);
            mCrazyMoveState = 1;
            break;
        case 1:
            move(2,-2);
            mCrazyMoveState = 2;
            break;
        case 2:
            move(0,-3);
            mCrazyMoveState = 3;
            break;
        case 3:
            move(-2,-2);
            mCrazyMoveState = 4;
            break;
        case 4:
            move(-3,0);
            mCrazyMoveState = 5;
            break;
        case 5:
            move(-2,2);
            mCrazyMoveState = 6;
            break;
        case 6:
            move(0,3);
            mCrazyMoveState = 7;
            break;
        case 7:
            move(2,2);
            mCrazyMoveState = 0;
            break;
        default:
            break;
    }
}

void LocalPlayer::crazyMove7()
{
    if (mAction == WALK)
        return;

    switch(mCrazyMoveState)
    {
        case 0:
            move(1,1);
            mCrazyMoveState = 1;
            break;
        case 1:
            move(-1,1);
            mCrazyMoveState = 2;
            break;
        case 2:
            move(-1,-1);
            mCrazyMoveState = 3;
            break;
        case 3:
            move(1,-1);
            mCrazyMoveState = 0;
            break;
        default:
            break;
    }
}

void LocalPlayer::crazyMove8()
{
    if (mAction == WALK)
        return;
    int idx = 0;
    int dist = 1;

// look
//      up, ri,do,le
    static const int movesX[][4] = {
        {-1, 0, 1, 0},	//move left
        { 0, 1, 0,-1},	//move up
        { 1, 0,-1, 0},	//move right
        { 0,-1, 0, 1}	//move down
    };

// look
//      up, ri,do,le
    static const int movesY[][4] = {
        { 0,-1, 0, 1},	//move left
        {-1, 0, 1, 0},	//move up
        { 0, 1, 0,-1},	//move right
        { 1, 0,-1, 0}	//move down
    };

    if (getDirection() == Being::UP)
        idx = 0;
    else if (getDirection() == Being::RIGHT)
        idx = 1;
    else if (getDirection() == Being::DOWN)
        idx = 2;
    else if (getDirection() == Being::LEFT)
        idx = 3;


    int mult = 1;
    if (mMap->getWalk(getTileX() + movesX[idx][0], getTileY() + movesY[idx][0], getWalkMask()))
    {
        while (mMap->getWalk(getTileX() + movesX[idx][0]*mult, getTileY() + movesY[idx][0]*mult, getWalkMask()) && mult <= dist)
            mult ++;
        move(movesX[idx][0]*(mult - 1),movesY[idx][0]*(mult - 1));
    }
    else if (mMap->getWalk(getTileX() + movesX[idx][1], getTileY() + movesY[idx][1], getWalkMask()))
    {
        while (mMap->getWalk(getTileX() + movesX[idx][1]*mult, getTileY() + movesY[idx][1]*mult, getWalkMask()) && mult <= dist)
            mult ++;
        move(movesX[idx][1]*(mult - 1),movesY[idx][1]*(mult - 1));
    }
    else if (mMap->getWalk(getTileX() + movesX[idx][2], getTileY() + movesY[idx][2], getWalkMask()))
    {
        while (mMap->getWalk(getTileX() + movesX[idx][2]*mult, getTileY() + movesY[idx][2]*mult, getWalkMask()) && mult <= dist)
            mult ++;
        move(movesX[idx][2]*(mult - 1),movesY[idx][2]*(mult - 1));
    }
    else if (mMap->getWalk(getTileX() + movesX[idx][3], getTileY() + movesY[idx][3], getWalkMask()))
    {
        while (mMap->getWalk(getTileX() + movesX[idx][3]*mult, getTileY() + movesY[idx][3]*mult, getWalkMask()) && mult <= dist)
            mult ++;
        move(movesX[idx][3]*(mult - 1),movesY[idx][3]*(mult - 1));
    }
}

void LocalPlayer::crazyMove9()
{
    int dx = 0;
    int dy = 0;

    if (mAction == WALK)
        return;

    switch (mCrazyMoveState)
    {
        case 0:
            switch (player_node->getDirection())
            {
                case UP   : dy = -1; break;
                case DOWN : dy = 1; break;
                case LEFT : dx = -1; break;
                case RIGHT: dx = 1; break;
                default: break;
            }
            move(dx,dy);
            mCrazyMoveState = 1;
            break;
        case 1:
            Net::getPlayerHandler()->changeAction(SIT);
            mCrazyMoveState = 2;
            break;
        case 2:
            mCrazyMoveState = 3;
            break;
        case 3:
            mCrazyMoveState = 0;
            break;
        default:
            break;
    }
}

void LocalPlayer::crazyMoveA()
{
    std::string mMoveProgram(config.getValue("crazyMoveProgram", "mumrsonmdmlon"));
//"muonsmuopmrmuonmlmlsonmdmdonmdmr");

    if (mAction == WALK)
        return;

    if (mMoveProgram.length() == 0)
        return;

    if (mCrazyMoveState >= mMoveProgram.length())
    {
        mCrazyMoveState = 0;
    }

    int dx = 0;
    int dy = 0;
    Uint8 dir = 0;

    // move command
    if (mMoveProgram[mCrazyMoveState] == 'm')
    {
        mCrazyMoveState ++;
        if (mCrazyMoveState < mMoveProgram.length())
        {
            char param = mMoveProgram[mCrazyMoveState++];
            if (param == '?')
            {
                char cmd[] = {'l', 'r', 'u', 'd'};
                srand(tick_time);
                param = cmd[rand() % 4];
            }
            switch (param)
//            switch (mMoveProgram[mCrazyMoveState++])
            {
                case 'd':
                    move(0, 1);
                    break;
                case 'u':
                    move(0, -1);
                    break;
                case 'l':
                    move(-1, 0);
                    break;
                case 'r':
                    move(1, 0);
                    break;
                case 'f':
                    switch (player_node->getDirection())
                    {
                        case UP   : dy = -1; break;
                        case DOWN : dy = 1; break;
                        case LEFT : dx = -1; break;
                        case RIGHT: dx = 1; break;
                        default: break;
                    }
                    move(dx,dy);
                    break;
                case 'b':
                    switch (player_node->getDirection())
                    {
                        case UP   : dy = 1; break;
                        case DOWN : dy = -1; break;
                        case LEFT : dx = 1; break;
                        case RIGHT: dx = -1; break;
                        default: break;
                    }
                    move(dx,dy);
                    break;
                default:
                    break;
            }
        }
    }
    // direction command
    else if (mMoveProgram[mCrazyMoveState] == 'd')
    {
        mCrazyMoveState ++;

        if (mCrazyMoveState < mMoveProgram.length())
        {
            char param = mMoveProgram[mCrazyMoveState++];
            if (param == '?')
            {
                char cmd[] = {'l', 'r', 'u', 'd'};
                srand(tick_time);
                param = cmd[rand() % 4];
            }
            switch (param)
            {
                case 'd':
                    setDirection(Being::DOWN);
                    Net::getPlayerHandler()->setDirection(Being::DOWN);
                    break;
                case 'u':
                    setDirection(Being::UP);
                    Net::getPlayerHandler()->setDirection(Being::UP);
                    break;
                case 'l':
                    setDirection(Being::LEFT);
                    Net::getPlayerHandler()->setDirection(Being::LEFT);
                    break;
                case 'r':
                    setDirection(Being::RIGHT);
                    Net::getPlayerHandler()->setDirection(Being::RIGHT);
                    break;
                case 'L':
                    switch (player_node->getDirection())
                    {
                        case UP    : dir = Being::LEFT; break;
                        case DOWN  : dir = Being::RIGHT; break;
                        case LEFT  : dir = Being::DOWN; break;
                        case RIGHT : dir = Being::UP; break;
                        default: break;
                    }
                    setDirection(dir);
                    Net::getPlayerHandler()->setDirection(dir);
                    break;
                case 'R':
                    switch (player_node->getDirection())
                    {
                        case UP    : dir = Being::RIGHT; break;
                        case DOWN  : dir = Being::LEFT; break;
                        case LEFT  : dir = Being::UP; break;
                        case RIGHT : dir = Being::DOWN; break;
                        default: break;
                    }
                    setDirection(dir);
                    Net::getPlayerHandler()->setDirection(dir);
                    break;
                case 'b':
                    switch (player_node->getDirection())
                    {
                        case UP    : dir = Being::DOWN; break;
                        case DOWN  : dir = Being::UP; break;
                        case LEFT  : dir = Being::RIGHT; break;
                        case RIGHT : dir = Being::LEFT; break;
                        default: break;
                    }
                    setDirection(dir);
                    Net::getPlayerHandler()->setDirection(dir);
                    break;
                case '0':
                    dropShortcut->dropFirst();
                    break;
                case 'a':
                    dropShortcut->dropItems();
                    break;
                default:
                    break;
            }
        }
    }
    // sit command
    else if (mMoveProgram[mCrazyMoveState] == 's')
    {
        mCrazyMoveState ++;
        toggleSit();
    }
    // wear outfits
    else if (mMoveProgram[mCrazyMoveState] == 'o')
    {
        mCrazyMoveState ++;
        if (mCrazyMoveState < mMoveProgram.length())
        {
            // wear next outfit
            if (mMoveProgram[mCrazyMoveState] == 'n')
            {
                mCrazyMoveState ++;
                outfitWindow->wearNextOutfit();
            }
            // wear previous outfit
            else if (mMoveProgram[mCrazyMoveState] == 'p')
            {
                mCrazyMoveState ++;
                outfitWindow->wearPreviousOutfit();
            }
        }
    }
    // pause
    else if (mMoveProgram[mCrazyMoveState] == 'w')
    {
        mCrazyMoveState ++;
    }
    // pick up
    else if (mMoveProgram[mCrazyMoveState] == 'p')
    {
        mCrazyMoveState ++;
        pickUpItems();
    }
    // emote
    else if (mMoveProgram[mCrazyMoveState] == 'e')
    {
        mCrazyMoveState ++;
        char emo = mMoveProgram[mCrazyMoveState];
        if (emo == '?')
        {
            srand(tick_time);
            player_node->emote(1 + (rand() % 13));
        }
        else
        {
            if (emo >= '0' && emo <= '9')
                player_node->emote(emo - '0' + 1);
            else if (emo >= 'a' && emo <= 'd')
                player_node->emote(emo - 'a' + 11);
        }

        mCrazyMoveState ++;
    }
    else
    {
        mCrazyMoveState ++;
    }

//    mCrazyMoveState ++;
    if (mCrazyMoveState >= mMoveProgram.length())
        mCrazyMoveState = 0;

//    debugMsg("mCrazyMoveState: " + toString(mCrazyMoveState));
}

bool LocalPlayer::isReachable(int x, int y)
{
    if (x - 1 <= getTileX() && x + 1 >= getTileX()
        && y - 1 <= getTileY() && y + 1 >= getTileY() )
    {
        return true;
    }

    const Vector &playerPos = getPosition();

    Path debugPath = mMap->findPath(
            (int) (playerPos.x - 16) / 32,
            (int) (playerPos.y - 32) / 32,
            x, y, 0xFF);

    return (debugPath.size() > 0);
}

bool LocalPlayer::pickUpItems(int pickUpType)
{
    bool status = false;
    Uint16 x = getTileX();
    Uint16 y = getTileY();

    // first pick up item on player position
    FloorItem *item =
        floorItemManager->findByCoordinates(x, y);
    if (item)
    {
        pickUp(item);
        status = true;
    }

    if (pickUpType == 0)
        pickUpType = mPickUpType;

    if (pickUpType == 0)
        return status;

    int x1,y1,x2,y2;
    switch(pickUpType)
    {
        case 1:
            switch (player_node->getDirection())
            {
                case UP   : --y; break;
                case DOWN : ++y; break;
                case LEFT : --x; break;
                case RIGHT: ++x; break;
                default: break;
            }
            item = floorItemManager->findByCoordinates(x, y);
            if (item)
            {
                pickUp(item);
                status = true;
            }
            break;
        case 2:
            switch (player_node->getDirection())
            {
                case UP   : x1=x-1; y1=y-1; x2=x+1; y2=y; break;
                case DOWN : x1=x-1; y1=y; x2=x+1; y2=y+1; break;
                case LEFT : x1=x-1; y1=y-1; x2=x; y2=y+1; break;
                case RIGHT: x1=x; y1=y-1; x2=x+1; y2=y+1; break;
                default: x1=x2=x; y1=y2=y; break;
            }
            if (floorItemManager->pickUpAll(x1, y1, x2, y2))
                status = true;
            break;
        case 3:
            if (floorItemManager->pickUpAll(x - 1, y - 1, x + 1, y + 1))
                status = true;
            break;

        case 4:
            if (!floorItemManager->pickUpAll(x - 1, y - 1, x + 1, y + 1))
            {
                if (floorItemManager->pickUpNearest(x, y, 4))
                    status = true;
            }
            else
            {
                status = true;
            }
            break;

        case 5:
            if (!floorItemManager->pickUpAll(x - 1, y - 1, x + 1, y + 1))
            {
                if (floorItemManager->pickUpNearest(x, y, 8))
                    status = true;
            }
            else
            {
                status = true;
            }
            break;

        default:
            break;

        case 6:
            switch (player_node->getDirection())
            {
                case UP   : x1=x-2; y1=y-2; x2=x+2; y2=y+1; break;
                case DOWN : x1=x-2; y1=y-1; x2=x+2; y2=y+2; break;
                case LEFT : x1=x-2; y1=y-2; x2=x+1; y2=y+2; break;
                case RIGHT: x1=x-1; y1=y-2; x2=x+2; y2=y+2; break;
                default: x1=x2=x; y1=y2=y; break;
            }
            if (floorItemManager->pickUpAll(x1, y1, x2, y2))
                status = true;
            break;
/*
        case 7:
            switch (player_node->getDirection())
            {
                case UP   : x1=x-3; y1=y-3; x2=x+3; y2=y+1; break;
                case DOWN : x1=x-3; y1=y-1; x2=x+3; y2=y+3; break;
                case LEFT : x1=x-3; y1=y-3; x2=x+1; y2=y+3; break;
                case RIGHT: x1=x-1; y1=y-3; x2=x+3; y2=y+3; break;
                default: break;
            }
            if (floorItemManager->pickUpAll(x1, y1, x2, y2))
                status = true;
            break;
*/
    }
    return status;
}

void LocalPlayer::changeQuickDropCounter()
{
    mQuickDropCounter++;
    if (mQuickDropCounter > 9)
        mQuickDropCounter = 1;

    config.setValue("quickDropCounter", mQuickDropCounter);
    miniStatusWindow->update(StatusWindow::STATUS);

}

void LocalPlayer::moveByDirection(unsigned char dir)
{
    int dx = 0, dy = 0;
#ifdef MANASERV_SUPPORT
    if (dir & UP)
        dy -= 32;
    if (dir & DOWN)
        dy += 32;
    if (dir & LEFT)
        dx -= 32;
    if (dir & RIGHT)
        dx += 32;
#else
    if (dir & UP)
        dy--;
    if (dir & DOWN)
        dy++;
    if (dir & LEFT)
        dx--;
    if (dir & RIGHT)
        dx++;
#endif

    move(dx,dy);
}

void LocalPlayer::specialMove(unsigned char direction)
{
    if (direction != 0 && (getInvertDirection() >= 2 && getInvertDirection() <= 4))
    {
        int max;
        if (getInvertDirection() == 2)
            max = 10;
        else
            max = 30;

        if (mAction == WALK)
            return;

        if (getInvertDirection() == 2)
            max = 5;
        else if (getInvertDirection() == 4)
            max = 1;
        else
            max = 3;

        if (getMoveState() < max)
        {
            moveByDirection(direction);
            mMoveState ++;
        }
        else
        {
            mMoveState = 0;
            crazyMove();
        }
    }
    else
    {
//        if (direction != 0 && getInvertDirection() == 4)
//            crazyMove();
        setWalkingDir(direction);
    }

}

void LocalPlayer::debugMsg(std::string str)
{
    debugChatTab->chatLog(str);
}

void LocalPlayer::switchMagicAttack()
{
    mMagicAttackType++;
    if (mMagicAttackType > 4)
        mMagicAttackType = 0;

    config.setValue("magicAttackType", mMagicAttackType);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::magicAttack()
{
    if (player_node->getAttributeEffective(player_node->MATK) <= 0)
        return;

    switch(mMagicAttackType)
    {
        //flar W00
        case 0:
            tryMagic("#flar", 1, 0, 10);
            break;
        //chiza W01
        case 1:
            tryMagic("#chiza", 1, 0,  9);
            break;
        //ingrav W10
        case 2:
            tryMagic("#ingrav", 2, 2,  20);
            break;
        //frillyar W11
        case 3:
            tryMagic("#frillyar", 2, 2, 25);
            break;
        //upmarmu W12
        case 4:
            tryMagic("#upmarmu", 2, 2, 20);
            break;
        default:
            break;
    }
}

void LocalPlayer::tryMagic(std::string spell, int baseMagic, int schoolMagic, int mana)
{
    if (player_node->getSkillLv(340) >= baseMagic && player_node->getSkillLv(342) >= schoolMagic)
    {
        if (player_node->mMp >= mana)
        {
            chatWindow->localChatInput(spell);
        }
    }
}

void LocalPlayer::changeMoveToTargetType()
{
    mMoveToTargetType++;
    if (mMoveToTargetType > 5)
        mMoveToTargetType = 0;

    config.setValue("moveToTargetType", mMoveToTargetType);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::loadHomes()
{
    std::string homeStr = config.getValue("playerHomes", "maps/018-1.tmx 71 76 maps/013-3.tmx 71 24");
    std::string buf;
    std::stringstream ss(homeStr);

    while (ss >> buf)
    {
        Vector pos;
        ss >> pos.x;
        ss >> pos.y;
        mHomes[buf] = pos;
    }

}

void LocalPlayer::setMap(Map *map)
{
    if (map)
    {
        std::map<std::string,Vector>::iterator iter = mHomes.find(map->getProperty("_filename"));

        if (iter != mHomes.end())
        {
            Vector pos = mHomes[(*iter).first];
            SpecialLayer *specialLayer = map->getSpecialLayer();
            if (specialLayer)
            {
                specialLayer->clean();
                specialLayer->setTile(pos.x, pos.y, MapItem::HOME);
            }
        }
        if (socialWindow)
            socialWindow->updateActiveList();
    }
    naviageClean();
    Being::setMap(map);
}

void LocalPlayer::setHome()
{
    if (mMap)
    {
        std::string key = mMap->getProperty("_filename");
        Vector pos = mHomes[key];
        std::map<std::string,Vector>::iterator iter = mHomes.find(key);
        SpecialLayer *specialLayer = mMap->getSpecialLayer();

        if (iter != mHomes.end() && getTileX() ==pos.x && getTileY() == pos.y)
        {
            mHomes.erase(key);
            if (specialLayer)
            {
                specialLayer->clean();
            }
        }
        else
        {
            pos.x = getTileX();
            pos.y = getTileY();
            mHomes[key] = pos;
            if (specialLayer)
            {
                specialLayer->clean();
                specialLayer->setTile(getTileX(), getTileY(), MapItem::HOME);
            }
        }
        saveHomes();
    }
}

void LocalPlayer::saveHomes()
{
    std::string homeStr;
    std::string buf;
    std::stringstream ss(homeStr);

    for (std::map<std::string,Vector>::iterator iter = mHomes.begin(); iter != mHomes.end(); ++iter )
    {
        Vector pos = (*iter).second;

        if (iter != mHomes.begin())
            ss << " ";
        ss << (*iter).first << " " << pos.x << " " << pos.y;
    }

    config.setValue("playerHomes", ss.str());
}


void LocalPlayer::switchGameModifiers()
{
    mDisableGameModifiers = !mDisableGameModifiers;
    config.setValue("disableGameModifiers", mDisableGameModifiers);
    miniStatusWindow->update(StatusWindow::STATUS);
}

void LocalPlayer::pingRequest()
{
    if (mWaitPing == true && mPingSendTick != 0)
    {
        if (tick_time >= mPingSendTick
            && (tick_time - mPingSendTick) > 1000)
        {
            return;
        }
    }

    mPingSendTick = tick_time;
    mWaitPing = true;
    Net::getBeingHandler()->requestNameById(getId());
}

void LocalPlayer::pingResponse()
{
    if (mWaitPing == true && mPingSendTick > 0)
    {
        mWaitPing = false;
        if (tick_time < mPingSendTick)
        {
            mPingSendTick = 0;
            mPingTime = 0;
        }
        else
        {
            mPingTime = (tick_time - mPingSendTick) * 10;
        }
    }
}

void LocalPlayer::tryPingRequest()
{
    if (mPingSendTick == 0 || tick_time < mPingSendTick
        || (tick_time - mPingSendTick) > 200)
    {
        pingRequest();
    }
}

void LocalPlayer::changeAwayMode()
{
    mAwayMode = !mAwayMode;
    mAfkTime = 0;
    miniStatusWindow->update(StatusWindow::STATUS);
    if (mAwayMode)
    {
        cancelFollow();
        outfitWindow->wearAwayOutfit();
        awayDialog = new OkDialog(_("Away"),_("You now away from keyboard"));
        awayDialog->addActionListener(awayListener);
    }
}

void LocalPlayer::setAway(std::string message)
{
    if (!message.empty())
    {
        config.setValue("afkMessage", message);
    }
    changeAwayMode();
}

void LocalPlayer::afkRespond(ChatTab *tab, const std::string &nick)
{
    if (mAwayMode)
    {
        if (mAfkTime == 0
            || cur_time < mAfkTime
            || cur_time - mAfkTime > 1 * 60)
        {
            std::string msg = "*AFK*: "
                              + config.getValue("afkMessage", "I am away from keyboard");

            Net::getChatHandler()->privateMessage(nick, msg);
            if (!tab)
                localChatTab->chatLog(getName() + " : " + msg, ACT_WHISPER, false);
            else
                tab->chatLog(getName(), msg);
            mAfkTime = cur_time;
        }
    }
}

void LocalPlayer::navigateTo(int x, int y)
{
    SpecialLayer *tmpLayer = mMap->getTempLayer();
    if (!tmpLayer)
        return;

    const Vector &playerPos = getPosition();
    mShowNavigePath = true;
    mOldX = playerPos.x;
    mOldY = playerPos.y;
    mNavigateX = x;
    mNavigateY = y;

    Path debugPath = mMap->findPath((int) (playerPos.x - 16) / 32,
                                    (int) (playerPos.y - 32) / 32,
                                    x, y, 0xFF, 0);

    tmpLayer->addRoad(debugPath);
}

void LocalPlayer::naviageClean()
{
    if (!mMap)
        return;

    SpecialLayer *tmpLayer = mMap->getTempLayer();
    if (!tmpLayer)
        return;

    mShowNavigePath = false;
    mOldX = 0;
    mOldY = 0;
    mNavigateX = 0;
    mNavigateY = 0;

    tmpLayer->clean();
}

void LocalPlayer::updateCoords()
{
    Being::updateCoords();
    if (mShowNavigePath)
    {
        const Vector &playerPos = getPosition();
        logger->log("navigate: " + toString(mNavigateX) + "," + toString(mNavigateY));
        logger->log("playerPos: " + toString(playerPos.x) + "," + toString(playerPos.y));


        if (playerPos.x != mOldX || playerPos.y != mOldY)
        {
            SpecialLayer *tmpLayer = mMap->getTempLayer();
            if (!tmpLayer)
                return;

            int x = (int) (playerPos.x - 16) / 32;
            int y = (int) (playerPos.y - 32) / 32;
            if (mNavigateX - 1 <= x && mNavigateX + 1 >= x
                && mNavigateY - 1 <= y && mNavigateY + 1 >= y)
            {
                naviageClean();
                return;
            }
            else
            {
                tmpLayer->clean();
                navigateTo(mNavigateX, mNavigateY);
            }
        }
    }
}

void LocalPlayer::attack2(Being *target, bool keep, bool dontChangeEquipment)
{
    if (!dontChangeEquipment && target)
        changeEquipmentBeforeAttack(target);

    if (!target || getAttackType() == 0
        ||  withinAttackRange(target))
    {
        attack(target, keep);
    }
    else if (!mPickUpTarget)
    {
        if (getAttackType() == 2)
        {
            if (pickUpItems())
                return;
        }
        setTarget(target);
        if (target->getType() != Being::NPC)
        {
            if (mAttackWeaponType == 1)
                moveToTarget();
            else
                moveToTarget(mAttackRange);
        }
    }
}

void LocalPlayer::setFollow(std::string player)
{
    mPlayerFollowed = player;
    if (!mPlayerFollowed.empty())
        debugMsg("Follow: " + player);
    else
        debugMsg("Follow canceled");
}

void LocalPlayer::setImitate(std::string player)
{
    mPlayerImitated = player;
    if (!mPlayerImitated.empty())
        debugMsg("Imitation: " + player);
    else
        debugMsg("Imitation canceled");
}

void LocalPlayer::cancelFollow()
{
    if (!mPlayerFollowed.empty())
        debugMsg("Follow canceled");
    if (!mPlayerImitated.empty())
        debugMsg("Imitation canceled");
    mPlayerFollowed = "";
    mPlayerImitated = "";
}

void AwayListener::action(const gcn::ActionEvent &event)
{
    if (event.getId() == "ok")
    {
        player_node->setAwayMode(false);
        outfitWindow->unwearAwayOutfit();
        miniStatusWindow->update(StatusWindow::STATUS);
    }
}


