All pastes #953940 Raw Edit

Anonymous

public text v1 · immutable
#953940 ·published 2008-03-23 14:54 UTC
rendered paste body
/*
 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
 *
 * 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
 * (at your option) 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "Common.h"
#include "Language.h"
#include "Database/DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "UpdateMask.h"
#include "Player.h"
#include "SkillDiscovery.h"
#include "QuestDef.h"
#include "GossipDef.h"
#include "UpdateData.h"
#include "Channel.h"
#include "ChannelMgr.h"
#include "MapManager.h"
#include "MapInstanced.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "ObjectMgr.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "Formulas.h"
#include "Group.h"
#include "Guild.h"
#include "Pet.h"
#include "SpellAuras.h"
#include "Util.h"
#include "Transports.h"
#include "Weather.h"
#include "BattleGround.h"
#include "BattleGroundMgr.h"
#include "BattleGroundAB.h"
#include "ArenaTeam.h"
#include "Chat.h"
#include "Database/DatabaseImpl.h"
#include "Spell.h"

#include <cmath>

#define ZONE_UPDATE_INTERVAL 1000

#define PLAYER_SKILL_INDEX(x)       (PLAYER_SKILL_INFO_1_1 + ((x)*3))
#define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
#define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)

#define SKILL_VALUE(x)         (uint16(x))
#define SKILL_MAX(x)           (uint16(uint32(x) >> 16))
#define MAKE_SKILL_VALUE(v, m) (uint32(uint32(uint16(v)) | (uint32(uint16(m)) << 16)))

#define SKILL_TEMP_BONUS(x)    (uint16(x))
#define SKILL_PERM_BONUS(x)    (uint16(uint32(x) >> 16))
#define MAKE_SKILL_BONUS(t, p) (uint32(uint32(uint16(t)) | (uint32(uint16(p)) << 16)))

const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};

UpdateMask Player::updateVisualBits;

Player::Player (WorldSession *session): Unit( 0 )
{
    m_transport = 0;

    m_speakTime = 0;
    m_speakCount = 0;

    m_objectType |= TYPE_PLAYER;
    m_objectTypeId = TYPEID_PLAYER;

    m_valuesCount = PLAYER_END;

    m_session = session;

    m_divider = 0;

    m_GMFlags = 0;
    if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
        SetAcceptTicket(true);

    // players always and GM if set in config accept whispers by default
    if(GetSession()->GetSecurity() == SEC_PLAYER || sWorld.getConfig(CONFIG_GM_WISPERING_TO))
        SetAcceptWhispers(true);

    m_curSelection = 0;
    m_lootGuid = 0;

    m_comboTarget = 0;
    m_comboPoints = 0;

    m_usedTalentCount = 0;

    m_regenTimer = 0;
    m_weaponChangeTimer = 0;

    m_zoneUpdateId = 0;
    m_zoneUpdateTimer = 0;

    m_areaUpdateId = 0;

    m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);

    // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
    // this must help in case next save after mass player load after server startup
    m_nextSave = rand32(m_nextSave/2,m_nextSave*3/2);

    m_resurrectGUID = 0;
    m_resurrectX = m_resurrectY = m_resurrectZ = 0;
    m_resurrectHealth = m_resurrectMana = 0;

    m_SpellModRemoveCount = 0;

    memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);

    // group is initialized in the reference constructor
    SetGroupInvite(NULL);
    m_groupUpdateMask = 0;

    duel = 0;

    m_GuildIdInvited = 0;
    m_ArenaTeamIdInvited = 0;

    m_dungeonDifficulty = DUNGEONDIFFICULTY_NORMAL;

    m_atLoginFlags = AT_LOGIN_NONE;

    m_dontMove = false;

    pTrader = 0;
    ClearTrade();

    m_cinematic = 0;

    PlayerTalkClass = new PlayerMenu( GetSession() );
    m_currentBuybackSlot = BUYBACK_SLOT_START;

    for ( int aX = 0 ; aX < 8 ; aX++ )
        m_Tutorials[ aX ] = 0x00;
    m_TutorialsChanged = false;

    m_DailyQuestChanged = false;
    m_lastDailyQuestTime = 0;

    m_regenTimer = 0;
    m_weaponChangeTimer = 0;
    m_breathTimer = 0;
    m_isunderwater = 0;
    m_isInWater = false;
    m_drunkTimer = 0;
    m_drunk = 0;
    m_restTime = 0;
    m_lastManaUse = 0;
    m_deathTimer = 0;
    m_resurrectingSicknessExpire = 0;

    m_DetectInvTimer = 1000;

    m_bgBattleGroundID = 0;
    for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
    {
        m_bgBattleGroundQueueID[j].bgQueueType  = 0;
        m_bgBattleGroundQueueID[j].invited = false;
    }

    m_logintime = time(NULL);
    m_Last_tick = m_logintime;
    m_WeaponProficiency = 0;
    m_ArmorProficiency = 0;
    m_canParry = false;
    m_canDualWield = false;
    m_ammoDPS = 0.0f;
    m_extraAttacks = 0;

    m_oldpetnumber = 0;
    //cache for UNIT_CREATED_BY_SPELL to allow
    //returning reagests for temporarily removed pets
    //when dying/logging out
    m_oldpetspell = 0;

    ////////////////////Rest System/////////////////////
    time_inn_enter=0;
    inn_pos_mapid=0;
    inn_pos_x=0;
    inn_pos_y=0;
    inn_pos_z=0;
    m_rest_bonus=0;
    rest_type=REST_TYPE_NO;
    ////////////////////Rest System/////////////////////

    m_mailsLoaded = false;
    m_mailsUpdated = false;
    unReadMails = 0;
    m_nextMailDelivereTime = 0;

    m_resetTalentsCost = 0;
    m_resetTalentsTime = 0;
    m_itemUpdateQueueBlocked = false;

    for (int i = 0; i < MAX_MOVE_TYPE; ++i)
        m_forced_speed_changes[i] = 0;

    m_stableSlots = 0;

    /////////////////// Instance System /////////////////////

    m_Loaded = false;
    m_HomebindTimer = 0;
    m_InstanceValid = true;

    memset(m_totalSpellMod, 0, sizeof(m_totalSpellMod));

    for (int i = 0; i < BASEMOD_END; i++)
    {
        m_auraBaseMod[i][FLAT_MOD] = 0.0f;
        m_auraBaseMod[i][PCT_MOD] = 1.0f;
    }

    // Honor System
    m_honorPending = 0;
    m_lastHonorDate = 0;
    m_lastKillDate = 0;
    m_flushKills = false;
    m_saveKills = false;

    // Player summoning
    m_summon_expire = 0;
    m_summon_mapid = 0;
    m_summon_x = 0.0f;
    m_summon_y = 0.0f;
    m_summon_z = 0.0f;
}

Player::~Player ()
{
    if(m_uint32Values)                                      // only for fully created Object
        DuelComplete(DUEL_INTERUPTED);

    CleanupsBeforeDelete();

    TradeCancel(false);

    // Note: buy back item already deleted from DB when player was saved
    for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
    {
        if(m_items[i])
            delete m_items[i];
    }
    CleanupChannels();

    for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
        delete itr->second;

    //all mailed items should be deleted, also all mail should be deallocated
    for (PlayerMails::iterator itr =  m_mail.begin(); itr != m_mail.end();++itr)
        delete *itr;

    for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
        delete iter->second;                                //if item is duplicated... then server may crash ... but that item should be deallocated

    delete PlayerTalkClass;

    if (m_transport)
    {
        m_transport->RemovePassenger(this);
    }

    for(size_t x = 0; x < ItemSetEff.size(); x++)
        if(ItemSetEff[x])
            delete ItemSetEff[x];
}

bool Player::Create( uint32 guidlow, WorldPacket& data )
{
    int i;
    uint8 race,class_,gender,skin,face,hairStyle,hairColor,facialHair,outfitId;

    Object::_Create(guidlow, HIGHGUID_PLAYER);

    data >> m_name;

    //if(m_name.size() == 0) //not need double check
    //    return false;

    normalizePlayerName(m_name);

    data >> race >> class_ >> gender >> skin >> face;
    data >> hairStyle >> hairColor >> facialHair >> outfitId;

    PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
    if(!info)
    {
        sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
        return false;
    }

    for (i = 0; i < PLAYER_SLOTS_COUNT; i++)
        m_items[i] = NULL;

    //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
    //{
    //    SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
    //    SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
    //    SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
    //}

    m_race = race;
    m_class = class_;

    SetMapId(info->mapId);
    Relocate(info->positionX,info->positionY,info->positionZ);

    // Taxi nodes setup
    memset(m_taximask, 0, sizeof(m_taximask));
    /*
        // Automatically add the race's taxi hub to the character's taximask at creation time ( 1 << (taxi_node_id-1) )
        ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
        if(!rEntry)
        {
            sLog.outError("Race %u not found in DBŃ (Wrong DBC files?)",race);
            return false;
        }

        m_taximask[0] = rEntry->startingTaxiMask;
    */
    // capital and taxi hub masks
    switch(race)
    {
        case 1:  m_taximask[0]= 1 << ( 2-1); break;         // Human
        case 2:  m_taximask[0]= 1 << (23-1); break;         // Orc
        case 3:  m_taximask[0]= 1 << ( 6-1); break;         // Dwarf
                                                            // Night Elf
        case 4:  m_taximask[0]= (1 << (26-1)) | (1 << (27-1)); break;
        case 5:  m_taximask[0]= 1 << (11-1); break;         // Undead
        case 6:  m_taximask[0]= 1 << (22-1); break;         // Tauren
        case 7:  m_taximask[0]= 1 << ( 6-1); break;         // Gnome
        case 8:  m_taximask[0]= 1 << (23-1); break;         // Troll
        //case 10: m_taximask[0]= 1 << (1-1); break;        // Blood Elf
        case 11: m_taximask[0+94/32]= 1 << (94%32-1); break;// Draenei
    }
    // new continent starting masks (It will be accessible only at new map
    switch(TeamForRace(race))
    {
        case ALLIANCE: m_taximask[3]= 1 << (4-1); break;
        case HORDE:    m_taximask[3]= 1 << (3-1); break;
    }

    ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
    if(!cEntry)
    {
        sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
        return false;
    }

    uint8 powertype = cEntry->powerType;

    uint32 unitfield;

    switch(powertype)
    {
        case POWER_ENERGY:
        case POWER_MANA:
            unitfield = 0x00000000;
            break;
        case POWER_RAGE:
            unitfield = 0x00110000;
            break;
        default:
            sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
            return false;
    }

    SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 0.388999998569489f );
    SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f   );

    switch(gender)
    {
        case GENDER_FEMALE:
            SetUInt32Value(UNIT_FIELD_DISPLAYID, info->displayId_f );
            SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, info->displayId_f );
            break;
        case GENDER_MALE:
            SetUInt32Value(UNIT_FIELD_DISPLAYID, info->displayId_m );
            SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, info->displayId_m );
            break;
        default:
            sLog.outError("Invalid gender %u for player",gender);
            return false;
            break;
    }

    setFactionForRace(m_race);

    SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( race ) | ( class_ << 8 ) | ( gender << 16 ) | ( powertype << 24 ) ) );
    SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield );
    SetUInt32Value(UNIT_FIELD_BYTES_2, ( 0x28 << 8 ) );     // players - 0x2800, 0x2801, units - 0x1001
    SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN1 );
    SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);               // fix cast time showed in spell tooltip on client

                                                            //-1 is default value
    SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));

    SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
    SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
    SetUInt32Value(PLAYER_BYTES_3, gender);
    //SetUInt32Value(PLAYER_FIELD_BYTES, 0xEEE00000 );

    SetUInt32Value( PLAYER_GUILDID, 0 );
    SetUInt32Value( PLAYER_GUILDRANK, 0 );
    SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );

    SetUInt32Value( PLAYER__FIELD_KNOWN_TITLES, 0 );        // 0=disabled
    SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
    SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
    SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
    SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
    SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );

    // set starting level
    SetUInt32Value( UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL) );

    // Played time
    m_Last_tick = time(NULL);
    m_Played_time[0] = 0;
    m_Played_time[1] = 0;

    // base stats and related field values
    InitStatsForLevel();
    InitTalentForLevel();
    InitPrimaryProffesions();                               // to max set before any spell added

    // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
    UpdateMaxHealth();                                      // Update max Health (for add bonus from stamina)
    SetHealth(GetMaxHealth());
    if (getPowerType()==POWER_MANA)
    {
        UpdateMaxPower(POWER_MANA);                         // Update max Mana (for add bonus from intelect)
        SetPower(POWER_MANA,GetMaxPower(POWER_MANA)); 
    }

    uint32 titem_id;
    uint32 titem_amount;
    uint16 tspell, tskill, taction[4];
    std::list<uint16>::const_iterator skill_itr, action_itr[4];
    std::list<CreateSpellPair>::const_iterator spell_itr;

    spell_itr = info->spell.begin();

    for (; spell_itr!=info->spell.end(); spell_itr++)
    {
        tspell = spell_itr->first;
        if (tspell)
        {
            sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
            addSpell(tspell,spell_itr->second);
        }
    }

    skill_itr = info->skill.begin();

    for (; skill_itr!=info->skill.end(); )
    {
        tskill = (*skill_itr);

        if (tskill)
        {
            sLog.outDebug("PLAYER: Adding initial skill line, skillId = %u, value = 5, max = 5", tskill);
            SetSkill(tskill, 5, 5);                         // (5,5) is default values for skill pages
        }

        ++skill_itr;
    }

    for(i=0; i<4; i++)
        action_itr[i] = info->action[i].begin();

    for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
    {
        for( i=0; i<4 ;i++)
            taction[i] = (*action_itr[i]);

        addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);

        for( i=0; i<4 ;i++)
            ++action_itr[i];
    }

    UpdateBlockPercentage();

    uint16 dest;
    uint8 msg;
    Item *pItem;
    for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
    {
        titem_id     = item_id_itr->item_id;
        titem_amount = item_id_itr->item_amount;

        if (titem_id)
        {
            sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);

            pItem = CreateItem( titem_id, titem_amount);
            if( pItem )
            {
                msg = CanEquipItem( NULL_SLOT, dest, pItem, false );
                if( msg == EQUIP_ERR_OK )
                    EquipItem( dest, pItem, true);
                else
                {
                    // store in main bag to simplify second pass
                    msg = CanStoreItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, dest, pItem, false );
                    if( msg == EQUIP_ERR_OK )
                        StoreItem( dest, pItem, true);
                    else
                    {
                        sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,race,class_,msg);
                        delete pItem;
                    }
                }
            }
            else
                sLog.outError("STORAGE: Can't create initial item %u (not existed item id) for race %u class %u , error msg = %u",titem_id,race,class_,msg);
        }
    }

    // bags and main-hand weapon must equipped at this moment
    // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
    // or ammo not equipped in special bag
    for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );

        if(pItem)
        {
            // equip offhand weapon/shield if it attempt equipped before main-hand weapon
            msg = CanEquipItem( NULL_SLOT, dest, pItem, false );
            if( msg == EQUIP_ERR_OK )
            {
                RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
                EquipItem( dest, pItem, true);
            }else
            // move other items to more appropriate slots (ammo not equipped in special bag)
            {
                msg = CanStoreItem( NULL_BAG, NULL_SLOT, dest, pItem, false );
                if( msg == EQUIP_ERR_OK )
                {
                    RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
                    pItem = StoreItem( dest, pItem, true);
                }

                // if  this is ammo then use it
                uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
                if( msg == EQUIP_ERR_OK )
                    SetAmmo( pItem->GetProto()->ItemId );
            }
        }
    }
    // all item positions resolved

    return true;
}

void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
{
    uint32 BreathRegen = (uint32)-1;

    WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
    data << (uint32)Type;
    data << MaxValue;
    data << MaxValue;
    data << BreathRegen;
    data << (uint8)0;
    data << (uint32)0;                                      // spell id
    GetSession()->SendPacket(&data);
}

void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
{
    if(Type==BREATH_TIMER)
        m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;

    WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
    data << (uint32)Type;
    data << CurrentValue;
    data << MaxValue;
    data << Regen;
    data << (uint8)0;
    data << (uint32)0;                                      // spell id
    GetSession()->SendPacket( &data );
}

void Player::StopMirrorTimer(MirrorTimerType Type)
{
    if(Type==BREATH_TIMER)
        m_breathTimer = 0;

    WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
    data << (uint32)Type;
    GetSession()->SendPacket( &data );
}

void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
{
    WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
    data << (uint64)guid;
    data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
    data << (uint32)damage;
    data << (uint32)0;
    data << (uint32)0;
    //m_session->SendPacket(&data);
    //Let other players see that you get damage
    SendMessageToSet(&data, true);
    DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_NORMAL, NULL, false);

    if(type==DAMAGE_FALL && !isAlive())                     // DealDamage not apply item durability loss at self damage
    {
        DEBUG_LOG("We are fall to death, loosing 10 percents durability");
        DurabilityLossAll(0.10);
        // durability lost message
        WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
        GetSession()->SendPacket(&data);
    }
}

void Player::HandleDrowning(uint32 UnderWaterTime)
{
    if(!m_isunderwater)
        return;

    AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
    for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
        UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);

    //if have water breath , then remove bar
    if(waterbreath || isGameMaster() || !isAlive())
    {
        StopMirrorTimer(BREATH_TIMER);
        m_isunderwater = 0;
        return;
    }

    if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
    {
        //single trigger timer
        if (!(m_isunderwater & 0x02))
        {
            m_isunderwater|= 0x02;
            m_breathTimer = UnderWaterTime + 1000;
        }
        //single trigger "Breathbar"
        if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
        {
            m_isunderwater|= 0x04;
            StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
        }
        //continius trigger drowning "Damage"
        if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
        {
            //TODO: Check this formula
            uint64 guid = GetGUID();
            uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);

            EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
            m_breathTimer = 2000;
        }
    }
    //single trigger retract bar
    else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
    {
        m_isunderwater = 0x08;

        uint32 BreathRegen = 10;
        ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
        m_isunderwater = 0x10;
    }
    //remove bar
    else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
    {
        StopMirrorTimer(BREATH_TIMER);
        m_isunderwater = 0;
    }
}

void Player::HandleLava()
{
    bool ValidArea = false;

    if ((m_isunderwater & 0x80) && isAlive())
    {
        //Single trigger Set BreathTimer
        if (!(m_isunderwater & 0x80))
        {
            m_isunderwater|= 0x04;
            m_breathTimer = 1000;
        }
        //Reset BreathTimer and still in the lava
        if (!m_breathTimer)
        {
            uint64 guid = GetGUID();
            uint32 damage = GetMaxHealth() / 3 + urand(0, getLevel()-1);
            uint32 dmgZone = GetZoneId();

            // Deal lava damage only in lava zones.
            switch(dmgZone)
            {
                case 0x8D:
                    ValidArea = false;
                    break;
                case 0x94:
                    ValidArea = false;
                    break;
                case 0x2CE:
                    ValidArea = false;
                    break;
                case 0x2CF:
                    ValidArea = false;
                    break;
                default:
                    if (dmgZone / 5 & 0x408)
                        ValidArea = true;
            }

            // if is valid area and is not gamemaster then deal damage
            if ( ValidArea && !isGameMaster() )
                EnvironmentalDamage(guid, DAMAGE_LAVA, damage);

            m_breathTimer = 1000;
        }

    }
    //Death timer disabled and WaterFlags reset
    else if (m_deathState == DEAD)
    {
        m_breathTimer = 0;
        m_isunderwater = 0;
    }
}

void Player::HandleSobering()
{
    m_drunkTimer = 0;

    uint32 drunk = (m_drunk <= (0xFFFF / 30)) ? 0 : (m_drunk - (0xFFFF / 30));
    SetDrunkValue(drunk);
}

void Player::SetDrunkValue(uint16 newDrunkValue)
{
    m_drunk = newDrunkValue;
    SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));

    // special drunk invisibility detection
    if(m_drunk)
        m_detectInvisibilityMask |= (1<<6);
    else
        m_detectInvisibilityMask &= ~(1<<6);
}

void Player::Update( uint32 p_time )
{
    if(!IsInWorld())
        return;

    // undelivered mail
    if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
    {
        SendNewMail();
        ++unReadMails;

        // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
        m_nextMailDelivereTime = 0;
    }

    Unit::Update( p_time );

    // update player only attacks
    if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
    {
        setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
    }

    if(uint32 off_att = getAttackTimer(OFF_ATTACK))
    {
        setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
    }

    time_t now = time (NULL);

    UpdatePvPFlag(time(NULL));

    UpdateDuelFlag(time(NULL));

    CheckDuelDistance(time(NULL));

    CheckExploreSystem();

    // Update items that have just a limited lifetime
    if (now>m_Last_tick)
        UpdateItemDuration(uint32(now- m_Last_tick));

    if (!m_timedquests.empty())
    {
        std::set<uint32>::iterator iter = m_timedquests.begin();
        while (iter != m_timedquests.end())
        {
            //if( mQuestStatus[*iter].m_timer > 0 )
            //{
            if( mQuestStatus[*iter].m_timer <= p_time )
            {
                uint32 quest_id  = *iter;
                ++iter;                                     // current iter will be removed in FailTimedQuest
                FailTimedQuest( quest_id );
            }
            else
            {
                mQuestStatus[*iter].m_timer -= p_time;
                if (mQuestStatus[*iter].uState != QUEST_NEW) mQuestStatus[*iter].uState = QUEST_CHANGED;
                ++iter;
            }
            //}
        }
    }

    if (isAttacking())
    {
        Unit *pVictim = getVictim();
        if( !IsNonMeleeSpellCasted(false) && pVictim)
        {
            // default combat reach 10
            // TODO add weapon,skill check

            float pldistance = ATTACK_DISTANCE;

            if (m_extraAttacks)
            {
                AttackerStateUpdate(pVictim, BASE_ATTACK);
                --m_extraAttacks;
            }

            if (isAttackReady(BASE_ATTACK))
            {
                if(!IsWithinDistInMap(pVictim, pldistance))
                {
                    setAttackTimer(BASE_ATTACK,1000);
                    SendAttackSwingNotInRange();
                }
                //120 degrees of radiant range
                else if( !HasInArc( 2*M_PI/3, pVictim ))
                {
                    setAttackTimer(BASE_ATTACK,1000);
                    SendAttackSwingBadFacingAttack();
                }
                else
                {
                    // prevent base and off attack in same time, delay attack at 0.2 sec
                    if(haveOffhandWeapon())
                    {
                        uint32 off_att = getAttackTimer(OFF_ATTACK);
                        if(off_att < ATTACK_DISPLAY_DELAY)
                            setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
                    }
                    AttackerStateUpdate(pVictim, BASE_ATTACK);
                    resetAttackTimer(BASE_ATTACK);
                }
            }

            if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
            {
                if(!IsWithinDistInMap(pVictim, pldistance))
                {
                    setAttackTimer(OFF_ATTACK,1000);
                }
                else if( !HasInArc( 2*M_PI/3, pVictim ))
                {
                    setAttackTimer(OFF_ATTACK,1000);
                }
                else
                {
                    // prevent base and off attack in same time, delay attack at 0.2 sec
                    uint32 base_att = getAttackTimer(BASE_ATTACK);
                    if(base_att < ATTACK_DISPLAY_DELAY)
                        setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
                    // do attack
                    AttackerStateUpdate(pVictim, OFF_ATTACK);
                    resetAttackTimer(OFF_ATTACK);
                }
            }

            Unit *owner = pVictim->GetOwner();
            Unit *u = owner ? owner : pVictim;
            if(u->IsPvP() && (!duel || duel->opponent != u))
                UpdatePvP(true);
        }
    }

    else if (isAttacked())
    {
        // Leave here so we don't forget this case
        // Attacked, but not necessarily attacking
    }
    else
    {
        // Leave here so we don't forget this case
        // Not attacking or attacked
    }

    if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
    {
        if(roll_chance_i(3) && GetTimeInnEnter() > 0)       //freeze update
        {
            int time_inn = time(NULL)-GetTimeInnEnter();
            if (time_inn >= 10)                             //freeze update
            {
                float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
                                                            //speed collect rest bonus (section/in hour)
                SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
                UpdateInnerTime(time(NULL));
            }
        }
    }

    if(m_regenTimer > 0)
    {
        if(p_time >= m_regenTimer)
            m_regenTimer = 0;
        else
            m_regenTimer -= p_time;
    }

    if (m_weaponChangeTimer > 0)
    {
        if(p_time >= m_weaponChangeTimer)
            m_weaponChangeTimer = 0;
        else
            m_weaponChangeTimer -= p_time;
    }

    if (m_zoneUpdateTimer > 0)
    {
        if(p_time >= m_zoneUpdateTimer)
        {
            uint32 newzone = GetZoneId();
            if( m_zoneUpdateId != newzone )
                UpdateZone(newzone);                        // also update area
            else
            {
                // use area updates as well
                // needed for free far all arenas for example
                uint32 newarea = GetAreaId();
                if( m_areaUpdateId != newarea )
                    UpdateArea(newarea);

                m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
            }
        }
        else
            m_zoneUpdateTimer -= p_time;
    }

    if (isAlive())
    {
        RegenerateAll();
    }

    if (m_deathState == JUST_DIED)
    {
        KillPlayer();
    }

    if(m_nextSave > 0)
    {
        if(p_time >= m_nextSave)
        {
            // m_nextSave reseted in SaveToDB call
            SaveToDB();
            sLog.outDetail("Player '%u' '%s' Saved", GetGUIDLow(), GetName());
        }
        else
        {
            m_nextSave -= p_time;
        }
    }

    //Breathtimer
    if(m_breathTimer > 0)
    {
        if(p_time >= m_breathTimer)
            m_breathTimer = 0;
        else
            m_breathTimer -= p_time;

    }

    //Handle Water/drowning
    HandleDrowning(60000);

    //Handle lava
    HandleLava();

    //Handle detect stealth players
    if (m_DetectInvTimer > 0)
    {
        if (p_time >= m_DetectInvTimer)
        {
            m_DetectInvTimer = 3000;
            HandleStealthedUnitsDetection();
        }
        else
            m_DetectInvTimer -= p_time;
    }

    // Played time
    if (now > m_Last_tick)
    {
        uint32 elapsed = uint32(now - m_Last_tick);
        m_Played_time[0] += elapsed;                        // Total played time
        m_Played_time[1] += elapsed;                        // Level played time
        m_Last_tick = now;
    }

    if (m_drunk)
    {
        m_drunkTimer += p_time;

        if (m_drunkTimer > 30000)
            HandleSobering();
    }

    // not auto-free ghost from body in instances
    if(m_deathTimer > 0  && !GetBaseMap()->Instanceable())
    {
        if(p_time >= m_deathTimer)
        {
            m_deathTimer = 0;
            BuildPlayerRepop();
            RepopAtGraveyard();
        }
        else
            m_deathTimer -= p_time;
    }

    UpdateEnchantTime(p_time);
    UpdateHomebindTime(p_time);
    UpdateManaRegen();

    // group update
    SendUpdateToOutOfRangeGroupMembers();

    Pet* pet = GetPet();
    if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
    {
        RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
        return;
    }
}

void Player::setDeathState(DeathState s)
{
    uint32 ressSpellId = 0;

    bool cur = isAlive();

    if(s == JUST_DIED && cur)
    {
        // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
        ClearComboPoints();

        // remove resurrection sickness before other mods to prevent incorrect stats calculation
        RemoveAurasDueToSpell(SPELL_PASSIVE_RESURRECTION_SICKNESS);
        // remove form before other mods to prevent incorrect stats calculation
        RemoveAurasDueToSpell(m_ShapeShiftForm);

        //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
        RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);

        // save value before aura remove in Unit::setDeathState
        ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);

        // passive spell
        if(!ressSpellId)
            ressSpellId = GetResurrectionSpellId();
    }
    Unit::setDeathState(s);

    // restore resurrection spell id for player after aura remove
    if(s == JUST_DIED && cur && ressSpellId)
        SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);

    if(isAlive() && !cur)
    {
        //clear aura case after resurrection by another way (spells will be applied before next death)
        SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);

        // restore default warrior stance
        if(getClass()== CLASS_WARRIOR)
            CastSpell(this,SPELL_PASSIVE_BATTLE_STANCE,true);
    }
}

void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
{
    *p_data << GetGUID();
    *p_data << m_name;

    *p_data << getRace();
    uint8 pClass = getClass();
    *p_data << pClass;
    *p_data << getGender();

    uint32 bytes = GetUInt32Value(PLAYER_BYTES);
    *p_data << uint8(bytes);
    *p_data << uint8(bytes >> 8);
    *p_data << uint8(bytes >> 16);
    *p_data << uint8(bytes >> 24);

    bytes = GetUInt32Value(PLAYER_BYTES_2);
    *p_data << uint8(bytes);

    *p_data << uint8(getLevel());                           // player level
    // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
    uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());

    *p_data << zoneId;
    *p_data << GetMapId();

    *p_data << GetPositionX();
    *p_data << GetPositionY();
    *p_data << GetPositionZ();

    *p_data << GetUInt32Value(PLAYER_GUILDID);              // guild id

    *p_data << uint8(0x0);                                  // different values on off, looks like flags
    // 0x01
    // 0x02
    // 0x04 - CHAR_LOGIN_LOCKED_FOR_TRANSFER
    // 0x08
    // 0x10
    // 0x20
    // 0x40

    uint8 flags = 0;
    if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
        flags |= 0x04;
    if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
        flags |= 0x08;
    if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
        flags |= 0x20;
    if(HasAtLoginFlag(AT_LOGIN_RENAME))
        flags |= 0x40;
    *p_data << uint8(flags);                                // flags description below
    // 0x01 - unknown
    // 0x02 - unknown
    // 0x04 - hide helm
    // 0x08 - hide cloak
    // 0x10 - unknown
    // 0x20 - dead(ghost)
    // 0x40 - need rename

    *p_data << uint8(0xa0);                                 // unknown

    *p_data << uint8(0x0);                                  // ?
    // 0x01 - CHAR_LOGIN_LOCKED_BY_BILLING

    *p_data << (uint8)1;                                    // unknown

    // Pets info
    {
        uint32 petDisplayId = 0;
        uint32 petLevel   = 0;
        uint32 petFamily  = 0;

        // show pet at selection character in character list  only for non-ghost character
        if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
        {
            Field* fields = result->Fetch();

            uint32 entry = fields[9].GetUInt32();
            CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
            if(cInfo)
            {
                petDisplayId = fields[10].GetUInt32();
                petLevel     = fields[11].GetUInt32();
                petFamily    = cInfo->family;
            }
        }

        *p_data << (uint32)petDisplayId;
        *p_data << (uint32)petLevel;
        *p_data << (uint32)petFamily;
    }

    /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
    for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
        items[i] = NULL;

    QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
    if (result)
    {
        do
        {
            Field *fields  = result->Fetch();
            uint8  slot    = fields[0].GetUInt8() & 255;
            uint32 item_id = fields[1].GetUInt32();
            if( slot >= EQUIPMENT_SLOT_END )
                continue;

            items[slot] = objmgr.GetItemPrototype(item_id);
            if(!items[slot])
            {
                sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
                continue;
            }
        } while (result->NextRow());
        delete result;
    }*/

    for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
    {
        int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
        uint32 item_id = GetUInt32Value(VisibleBase);
        const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);

        if (proto != NULL)
        {
            *p_data << (uint32)proto->DisplayInfoID;
            *p_data << (uint8)proto->InventoryType;
        }
        else
        {
            *p_data << (uint32)0;
            *p_data << (uint8)0;
        }
    }
    *p_data << (uint32)0;                                   // first bag display id
    *p_data << (uint8)0;                                    // first bag inventory type
}

bool Player::ToggleAFK()
{
    ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);

    bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);

    // afk player not allowed in battleground ( do net check this in arena )
    if(state && InBattleGround() && GetBattleGround() && GetBattleGround()->isBattleGround())
        LeaveBattleground();

    return state;
}

bool Player::ToggleDND()
{
    ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);

    return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
}

uint8 Player::chatTag()
{
    if(isGameMaster())
        return 4;
    else if(isDND())
        return 3;
    if(isAFK())
        return 1;
    else
        return 0;
}

void Player::GetFriendInfo(uint64 friendGUID, FriendInfo &friendInfo)
{
    Player *pFriend = ObjectAccessor::FindPlayer(friendGUID);

    uint32 team = GetTeam();
    uint32 security = GetSession()->GetSecurity();
    bool allowTwoSideWhoList = sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_WHO_LIST);
    bool gmInWhoList = sWorld.getConfig(CONFIG_GM_IN_WHO_LIST) || security > SEC_PLAYER;

    // PLAYER see his team only and PLAYER can't see MODERATOR, GAME MASTER, ADMINISTRATOR characters
    // MODERATOR, GAME MASTER, ADMINISTRATOR can see all
    if( pFriend && pFriend->GetName() &&
        ( security > SEC_PLAYER ||
        ( pFriend->GetTeam() == team || allowTwoSideWhoList ) &&
        ( pFriend->GetSession()->GetSecurity() == SEC_PLAYER || gmInWhoList && pFriend->IsVisibleGloballyFor(this) )))
    {
        if(pFriend->isAFK())
            friendInfo.Status = FRIEND_STATUS_AFK;
        else if(pFriend->isDND())
            friendInfo.Status = FRIEND_STATUS_DND;
        else
            friendInfo.Status = FRIEND_STATUS_ONLINE;
        friendInfo.Area = pFriend->GetZoneId();
        friendInfo.Level = pFriend->getLevel();
        friendInfo.Class = pFriend->getClass();
    }
    else
    {
        friendInfo.Status = FRIEND_STATUS_OFFLINE;
        friendInfo.Area = 0;
        friendInfo.Level = 0;
        friendInfo.Class = 0;
    }
}

bool Player::AddToFriendList(uint64 guid, std::string name)
{
    // prevent list (client-side) overflow
    if(m_friendlist.size() >= (255-1))
        return false;

    CharacterDatabase.PExecute("INSERT INTO character_social (guid,name,friend,flags) "
        "VALUES ('%u', '%s', '%u', 0)", GetGUIDLow(), name.c_str(), GUID_LOPART(guid));
    m_friendlist.insert(GUID_LOPART(guid));
    return true;
}

void Player::RemoveFromFriendList(uint64 guid)
{
    CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' AND friend = '%u' AND flags = 0", GetGUIDLow(), GUID_LOPART(guid));
    m_friendlist.erase(GUID_LOPART(guid));
}

void Player::_LoadFriendList(QueryResult *result)
{
    //QueryResult *result = CharacterDatabase.PQuery("SELECT friend FROM character_social WHERE guid = '%u' AND flags = 0 LIMIT 255",GetGUIDLow());
    if(!result) return;

    do
    {
        Field *fields  = result->Fetch();

        m_friendlist.insert(fields[0].GetUInt64());

        // prevent list (client-side) overflow
        if(m_ignorelist.size() >= 255)
            break;
    }
    while( result->NextRow() );
    delete result;
}

void Player::SendFriendlist()
{
    FriendInfo info;
    uint8 size = (uint8)m_friendlist.size();

    WorldPacket data(SMSG_FRIEND_LIST, (1+size*15));        // just can guess size
    data << size;

    for (FriendList::iterator itr = m_friendlist.begin(); itr != m_friendlist.end(); ++itr)
    {
        GetFriendInfo(*itr, info);
        sLog.outDetail( "WORLD: Adding Friend Guid: %u, Status:%u, Area:%u, Level:%u Class:%u",
            GUID_LOPART(*itr), info.Status, info.Area, info.Level, info.Class);

        data << *itr << info.Status;
        if (info.Status != 0)
            data << info.Area << info.Level << info.Class;
    }

    GetSession()->SendPacket( &data );
    sLog.outDebug( "WORLD: Sent (SMSG_FRIEND_LIST)" );
}

bool Player::AddToIgnoreList(uint64 guid, std::string name)
{
    // prevent list (client-side) overflow
    if(m_ignorelist.size() >= (255-1))
        return false;

    CharacterDatabase.PExecute("INSERT INTO character_social (guid,name,friend,flags) "
        "VALUES ('%u', '%s', '%u', 1)", GetGUIDLow(), name.c_str(), GUID_LOPART(guid));
    m_ignorelist.insert(GUID_LOPART(guid));
    return true;
}

void Player::RemoveFromIgnoreList(uint64 guid)
{
    CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' AND friend = '%u' AND flags = 1",GetGUIDLow(), GUID_LOPART(guid));
    m_ignorelist.erase(GUID_LOPART(guid));
}

void Player::_LoadIgnoreList(QueryResult *result)
{
    //QueryResult *result = CharacterDatabase.PQuery("SELECT friend FROM character_social WHERE guid = '%u' AND flags = 1", GetGUIDLow());

    if(!result) return;

    do
    {
        Field *fields  = result->Fetch();
        m_ignorelist.insert(fields[0].GetUInt32());

        // prevent list (client-side) overflow
        if(m_ignorelist.size() >= 255)
            break;
    }
    while( result->NextRow() );

    delete result;
}

void Player::SendIgnorelist()
{
    if(m_ignorelist.empty() && m_mutelist.empty())
        return;

    WorldPacket data(SMSG_IGNORE_LIST, (1+m_ignorelist.size()*8+1+m_mutelist.size()*8));
    data << uint8(m_ignorelist.size());

    for(IgnoreList::iterator iter = m_ignorelist.begin(); iter != m_ignorelist.end(); ++iter)
    {
        data << uint64(MAKE_GUID(*iter,HIGHGUID_PLAYER));
    }

    data << uint8(0);                                       // 0 muted players for now
    /*data << uint8(m_mutelist.size());

    for(MuteList::iterator iter = m_mutelist.begin(); iter != m_mutelist.end(); ++iter)
    {
        data << uint64(MAKE_GUID(*iter,HIGHGUID_PLAYER));
    }*/

    GetSession()->SendPacket( &data );
    sLog.outDebug( "WORLD: Sent (SMSG_IGNORE_LIST)" );
}

void Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, bool outofrange, bool ignore_transport, bool is_gm_command, bool battleground_port)
{
    // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
    Pet* pet = GetPet();

    MapEntry const* mEntry = sMapStore.LookupEntry(mapid);

    // this map not exist in client
    if(!mEntry)
        return;

    // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
    if(!InBattleGround() && mEntry->map_type == MAP_BATTLEGROUND && !GetSession()->GetSecurity())
        return;

    bool tbc = GetSession()->IsTBC() && sWorld.getConfig(CONFIG_EXPANSION) > 0;

    // normal client and TBC map
    if(!tbc && IsExpansionMap(mEntry))
    {
        sLog.outDebug("Player %s using Normal client and tried teleport to non existing map %u", GetName(), mapid);

        if(GetTransport())
            RepopAtGraveyard();                             // teleport to near graveyard if on transport, looks blizz like :)

        SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL1);

        return;                                             // normal client can't teleport to this map...
    }
    else if(tbc)                                            // can teleport to any existing map
    {
        sLog.outDebug("Player %s have TBC client and will teleported to map %u", GetName(), mapid);
    }
    else
    {
        sLog.outDebug("Player %s have normal client and will teleported to standard map %u", GetName(), mapid);
    }
    /*
    only TBC (no 0x80000 and 0x10 flags...)
    3604590=0x37006E=0x200000 + 0x100000 + 0x40000 + 0x20000 + 0x10000 + 0x40 + 0x20 + 0x8 + 0x4 + 0x2

    Kharazan (normal/TBC??), but not have 0x10 flag (accessible by normal client?)
    4128878=0x3F006E=0x200000 + 0x100000 + 0x80000 + 0x40000 + 0x20000 + 0x10000 + 0x40 + 0x20 + 0x8 + 0x4 + 0x2

    normal+TBC maps
    4128894=0x3F007E=0x200000 + 0x100000 + 0x80000 + 0x40000 + 0x20000 + 0x10000 + 0x40 + 0x20 + 0x10 + 0x8 + 0x4 + 0x2

    normal+TBC maps
    8323198=0x7F007E=0x400000 + 0x200000 + 0x100000 + 0x80000 + 0x40000 + 0x20000 + 0x10000 + 0x40 + 0x20 + 0x10 + 0x8 + 0x4 + 0x2
    */

    // if we were on a transport, leave
    if (ignore_transport && m_transport)
    {
        m_transport->RemovePassenger(this);
        m_transport = NULL;
        m_movementInfo.t_x = 0.0f;
        m_movementInfo.t_y = 0.0f;
        m_movementInfo.t_z = 0.0f;
        m_movementInfo.t_o = 0.0f;
        m_movementInfo.t_time = 0;
    }

    SetSemaphoreTeleport(true);

    // The player was ported to another map and looses the duel immediatly.
    // We have to perform this check before the teleport, otherwise the
    // ObjectAccessor won't find the flag.
    if (duel && this->GetMapId()!=mapid)
    {
        GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
        if (obj)
            DuelComplete(DUEL_FLED);
    }

    // reset movement flags at teleport, because player will continue move with these flags after teleport
    m_movementInfo.SetMovementFlags(0);

    if ((this->GetMapId() == mapid) && (!m_transport))
    {
        // prepare zone change detect
        uint32 old_zone = GetZoneId();

        // near teleport
        WorldPacket data;
        BuildTeleportAckMsg(&data, x, y, z, orientation);
        GetSession()->SendPacket(&data);
        SetPosition( x, y, z, orientation, true);
        //BuildHeartBeatMsg(&data);
        //SendMessageToSet(&data, true);
        if (outofrange)
        {
            //same map, only remove pet if out of range
            if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
            {
                if(pet->isControlled() && !pet->isTemporarySummoned() )
                    m_oldpetnumber = pet->GetCharmInfo()->GetPetNumber();
                else
                    m_oldpetnumber = 0;

                RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
            }
        }

        if (outofrange)
        {
            CombatStop();

            // resummon pet
            if(pet && m_oldpetnumber)
            {
                Pet* NewPet = new Pet(this);
                if(!NewPet->LoadPetFromDB(this, 0, m_oldpetnumber, true))
                    delete NewPet;

                m_oldpetnumber = 0;
            }
        }

        SetSemaphoreTeleport(false);

        UpdateZone(GetZoneId());

        // new zone
        if(old_zone != GetZoneId())
        {
            // honorless target
            if(pvpInfo.inHostileArea)
                CastSpell(this, 2479, true);
        }
    }
    else
    {
        CombatStop();

        // far teleport to another map
        Map* oldmap = MapManager::Instance().GetMap(GetMapId(), this);

        if(outofrange && pet)
        {
            //leaving map -> delete pet right away (doing this later will cause problems)
            if(pet->isControlled() && !pet->isTemporarySummoned())
                m_oldpetnumber = pet->GetCharmInfo()->GetPetNumber();
            else
                m_oldpetnumber = 0;

            RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
        }

        // Check enter rights before map getting to avoid creating instance copy for player
        // this check not dependent from map instance copy and same for all instance copies of selected map
        if (!MapManager::Instance().CanPlayerEnter(mapid, this))
            return;

        // now we must check if we are going to be homebind after teleport, if it is so,
        // we must re-instantiate again (entering instance to be homebind is not very good idea)
        // this only affects entering instances, not re-logging in (teleport is not used on login)
        Map* map = MapManager::Instance().GetMap(mapid, this);
        // verify, if it does want to homebind us (but only if we are not in GM state,
        // GMs are allowed to teleport everywhere they want to be)
        // battlegrounds do NOT homebind
        if (!m_InstanceValid && (!isGameMaster() || !is_gm_command) && !battleground_port)
        {
            // yes, we are going to be homebind, avoid this action :)
            SetInstanceId(0);                               // reset instance id
            m_BoundInstances.erase(mapid);                  // unbind our instance binding
                                                            // obtain new map
            map = MapManager::Instance().GetMap(mapid, this);
        }

        if (map &&  map->AddInstanced(this))
        {
            // send transfer packets
            WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
            data << uint32(mapid);
            if (m_transport)
            {
                data << m_transport->GetEntry() << GetMapId();
            }
            GetSession()->SendPacket(&data);

            data.Initialize(SMSG_NEW_WORLD, (20));
            if (m_transport)
            {
                data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
            }
            else
            {
                data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
            }
            GetSession()->SendPacket( &data );

            data.Initialize(SMSG_UNKNOWN_811, 4);
            data << uint32(0);
            GetSession()->SendPacket( &data );

            // remove from old map now
            if (oldmap) oldmap->Remove(this, false);

            // new final coordinates
            float final_x = x;
            float final_y = y;
            float final_z = z;
            float final_o = orientation;

            if(m_transport)
            {
                final_x += m_movementInfo.t_x;
                final_y += m_movementInfo.t_y;
                final_z += m_movementInfo.t_z;
                final_o += m_movementInfo.t_o;
            }

            // set position
            SetMapId(mapid);
            Relocate(final_x, final_y, final_z, final_o);

            // move packet sent by client always after far teleport
            // SetPosition(final_x, final_y, final_z, final_o, true);
            SetDontMove(true);

            // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
        }
    }
}

void Player::AddToWorld()
{
    ///- Do not add/remove the player from the object storage
    ///- It will crash when updating the ObjectAccessor
    ///- The player should only be added when logging in
    Object::AddToWorld();

    for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
    {
        if(m_items[i])
            m_items[i]->AddToWorld();
    }
}

void Player::RemoveFromWorld()
{
    for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
    {
        if(m_items[i])
            m_items[i]->RemoveFromWorld();
    }

    ///- Do not add/remove the player from the object storage
    ///- It will crash when updating the ObjectAccessor
    ///- The player should only be removed when logging out
    Object::RemoveFromWorld();
}

void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
{
    float addRage;

    float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;

    if(attacker)
    {
        addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);

        // talent who gave more rage on attack
        addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;

        // Berserker Rage effect
        if(GetAura(18499,0))
            addRage *= 1.3;
    }
    else
        addRage = damage/rageconversion*2.5;

    addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);

    ModifyPower(POWER_RAGE, uint32(addRage*10));
}

void Player::RegenerateAll()
{
    if (m_regenTimer != 0)
        return;
    uint32 regenDelay = 2000;

    // Not in combat or they have regeneration
    if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
        HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
    {
        RegenerateHealth();
        if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
            Regenerate(POWER_RAGE);
    }

    Regenerate( POWER_ENERGY );

    Regenerate( POWER_MANA );

    m_regenTimer = regenDelay;
}

void Player::Regenerate(Powers power)
{
    uint32 curValue = GetPower(power);
    uint32 maxValue = GetMaxPower(power);

    float addvalue = 0.0f;
    uint32 msecSinceLastCast = (uint32)getMSTime() - m_lastManaUse;

    switch (power)
    {
        case POWER_MANA:
        {
            float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
            if (msecSinceLastCast < 5000)
                // Mangos Updates Mana in intervals of 2s, which is correct
                addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT) *  ManaIncreaseRate * 2.00f;
            else
            {
                addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN)* ManaIncreaseRate * 2.00f;
            }
        }   break;
        case POWER_RAGE:                                    // Regenerate rage
        {
            float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
            addvalue = 30 * RageDecreaseRate;               // 3 rage by tick
        }   break;
        case POWER_ENERGY:                                  // Regenerate energy (rogue)
            addvalue = 20;
            break;
        case POWER_FOCUS:
        case POWER_HAPPINESS:
            break;
    }

    if(!(msecSinceLastCast < 5000 && power == POWER_MANA))
    {
        AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
        for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
            if ((*i)->GetModifier()->m_miscvalue == power)
                addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0;
    }

    if (power != POWER_RAGE)
    {
        curValue += uint32(addvalue);
        if (curValue > maxValue)
            curValue = maxValue;
    }
    else
    {
        if(curValue <= uint32(addvalue))
            curValue = 0;
        else
            curValue -= uint32(addvalue);
    }
    SetPower(power, curValue);
}

void Player::RegenerateHealth()
{
    uint32 curValue = GetHealth();
    uint32 maxValue = GetMaxHealth();

    if (curValue >= maxValue) return;

    float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);

    float addvalue = 0.0f;

    // polymorphed case
    if ( IsPolymorphed() )
        addvalue = GetMaxHealth()/3;
    // normal regen case (maybe partly in combat case)
    else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
    {
        addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
        if (!isInCombat())
        {
            AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
            for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
                addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
        }
        else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
            addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;

        if(!IsStandState())
            addvalue *= 1.5;
    }

    // always regeneration bonus (including combat)
    addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);

    if(addvalue < 0)
        addvalue = 0;

    ModifyHealth(int32(addvalue));
}

bool Player::isAcceptTickets() const
{
    return GetSession()->GetSecurity() >= SEC_GAMEMASTER && (m_GMFlags & GM_ACCEPT_TICKETS);
}

bool Player::CanInteractWithNPCs(bool alive) const
{
    if(alive && !isAlive())
        return false;
    if(isInFlight())
        return false;
    if(isInCombat())
        return false;

    return true;
}

bool Player::IsUnderWater() const
{
    return IsInWater() &&
        GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
}

void Player::SetInWater(bool apply)
{
    if(m_isInWater==apply)
        return;

    //define player in water by opcodes
    //move player's guid into HateOfflineList of those mobs
    //which can't swim and move guid back into ThreatList when
    //on surface.
    //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
    m_isInWater = apply;

    // form update
    if(apply)
    {
        // remove travel forms
        if(m_form == FORM_TRAVEL || m_form == FORM_GHOSTWOLF)
            RemoveAurasDueToSpell(m_ShapeShiftForm);

        // remove mounts, check flight mounts also (flying=swimming in air :D)
        if(IsMounted() && !IsFlying())
            RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
    }
    else
    {
        // remove aqua form
        if(m_form == FORM_AQUA)
            RemoveAurasDueToSpell(m_ShapeShiftForm);
    }

    getHostilRefManager().updateThreatTables();
}

void Player::SetGameMaster(bool on)
{
    if(on)
    {
        m_GMFlags |= GM_ON;
        setFaction(35);
        SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);

        RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);

        getHostilRefManager().setOnlineOfflineState(false);
        CombatStop();
    }
    else
    {
        m_GMFlags &= ~GM_ON;
        setFactionForRace(getRace());
        RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);

        // restore FFA PvP Server state
        if(sWorld.IsFFAPvPRealm())
            SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);

        // restore FFA PvP area state
        UpdateArea(m_areaUpdateId);

        getHostilRefManager().setOnlineOfflineState(true);
    }

    ObjectAccessor::UpdateVisibilityForPlayer(this);
}

void Player::SetGMVisible(bool on)
{
    if(on)
    {
        m_GMFlags &= ~GM_INVISIBLE;                         //remove flag

        // Reapply stealth/invisibility if active or show if not any
        if(HasAuraType(SPELL_AURA_MOD_STEALTH))
            SetVisibility(VISIBILITY_GROUP_STEALTH);
        else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
            SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
        else
            SetVisibility(VISIBILITY_ON);
    }
    else
    {
        m_GMFlags |= GM_INVISIBLE;                          //add flag

        SetAcceptWhispers(false);
        SetGameMaster(true);

        SetVisibility(VISIBILITY_OFF);
    }
}

bool Player::IsGroupVisibleFor(Player* p) const
{
    switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
    {
        default: return IsInSameGroupWith(p);
        case 1:  return IsInSameRaidWith(p);
        case 2:  return GetTeam()==p->GetTeam();
    }
}

bool Player::IsInSameGroupWith(Player const* p) const
{
    return  GetGroup() != NULL &&
        GetGroup() == p->GetGroup() &&
        GetGroup()->SameSubGroup((Player*)this, (Player*)p);
}

///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
/// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
void Player::UninviteFromGroup()
{
    if(GetGroupInvite())                                    // uninvited invitee
    {
        Group* group = GetGroupInvite();
        group->RemoveInvite(this);

        if(group->GetMembersCount() <= 1)                   // group has just 1 member => disband
        {
            group->Disband(true);
            objmgr.RemoveGroup(group);
            delete group;
        }
    }
}

void Player::RemoveFromGroup(Group* group, uint64 guid)
{
    if(group)
    {
        if (group->RemoveMember(guid, 0) <= 1)
        {
            // group->Disband(); already disbanded in RemoveMember
            objmgr.RemoveGroup(group);
            delete group;
            // removemember sets the player's group pointer to NULL
        }
    }
}

void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
{
    WorldPacket data(SMSG_LOG_XPGAIN, (21));
    data << ( victim ? victim->GetGUID() : uint64(0) );
    data << uint32(GivenXP+RestXP);                         // given experience
    data << ( victim ? (uint8)0 : (uint8)1 );               // 00-kill_xp type, 01-non_kill_xp type
    data << uint32(GivenXP);                                // experience without rested bonus
    data << float(1);                                       // 1 - none 0 - 100% group bonus output
    GetSession()->SendPacket(&data);
}

void Player::GiveXP(uint32 xp, Unit* victim)
{
    if ( xp < 1 )
        return;

    if(!isAlive())
        return;

    uint32 level = getLevel();

    // XP to money conversion processed in Player::RewardQuest
    if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
        return;

    // handle SPELL_AURA_MOD_XP_PCT auras
    Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
    for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
        xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));

    // XP resting bonus for kill
    uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;

    SendLogXPGain(xp,victim,rested_bonus_xp);

    uint32 curXP = GetUInt32Value(PLAYER_XP);
    uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
    uint32 newXP = curXP + xp + rested_bonus_xp;

    while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
    {
        newXP -= nextLvlXP;

        if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
            GiveLevel(level + 1);

        level = getLevel();
        nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
    }

    SetUInt32Value(PLAYER_XP, newXP);
}

// Update player to next level
// Current player experience not update (must be update by caller)
void Player::GiveLevel(uint32 level)
{
    if ( level == getLevel() )
        return;

    PlayerLevelInfo info;
    objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);

    // send levelup info to client
    WorldPacket data(SMSG_LEVELUP_INFO, (7*4+(MAX_STATS-STAT_STRENGTH)+4));
    data << uint32(level);
    data << uint32(int32(info.basehealth) - int32(GetCreateHealth()));
    data << uint32(int32(info.basemana)   - int32(GetCreateMana()));
    data << uint32(0);
    data << uint32(0);
    data << uint32(0);
    data << uint32(0);

    for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
        data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));

    GetSession()->SendPacket(&data);

    SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));

    //update level, max level of skills
    if(getLevel()!= level)
        m_Played_time[1] = 0;                               // Level Played Time reset
    SetLevel( level);
    UpdateMaxSkills ();

    // save base values (bonuses already included in stored stats
    for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetCreateStat(Stats(i), info.stats[i]);

    SetCreateHealth(info.basehealth);
    SetCreateMana(info.basemana);

    InitTalentForLevel();

    UpdateAllStats();

    // set current level health and mana/energy to maximum after applying all mods.
    SetHealth(GetMaxHealth());
    SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
    SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
    if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
        SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
    SetPower(POWER_FOCUS, 0);
    SetPower(POWER_HAPPINESS, 0);

    // give level to summoned pet
    Pet* pet = GetPet();
    if(pet && pet->getPetType()==SUMMON_PET)
        pet->GivePetLevel(level);
}

void Player::InitTalentForLevel()
{
    uint32 level = getLevel();
    // talents base at level diff ( talents = level - 9 but some can be used already)
    if(level < 10)
    {
        // Remove all talent points
        if(m_usedTalentCount > 0)                           // Free any used talents
        {
            resetTalents(true);
            SetFreeTalentPoints(0);

        }
    }
    else
    {
        uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
        // if used more that have then reset
        if(m_usedTalentCount > talentPointsForLevel)
        {
            if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
                resetTalents(true);
            else
                SetFreeTalentPoints(0);
        }
        // else update amount of free points
        else
            SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
    }
}

void Player::InitStatsForLevel(bool reapplyMods)
{
    if(reapplyMods)                                         //reapply stats values only on .reset stats (level) command
        _RemoveAllStatBonuses();

    PlayerLevelInfo info;

    objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);

    SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
    SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));

    UpdateMaxSkills ();

    // set default cast time multiplier
    SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);

    // reset size before reapply auras
    if (getRace() == RACE_TAUREN)
        SetFloatValue(OBJECT_FIELD_SCALE_X,1.35f);
    else
        SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);

    // save base values (bonuses already included in stored stats
    for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetCreateStat(Stats(i), info.stats[i]);

    for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetStat(Stats(i), info.stats[i]);

    SetCreateHealth(info.basehealth);

    //set create powers
    SetCreateMana(info.basemana);

    // restore if need some important flags
    SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN1 );

    SetArmor(int32(m_createStats[STAT_AGILITY]*2));

    for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetPosStat(Stats(i), 0);

    for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetNegStat(Stats(i), 0);

    //reset rating fields values
    for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_ARENA_TEAM_INFO_1_1; ++index)
        SetUInt32Value(index, 0);

    SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
    for (int i = 0; i < 7; i++)
    {
        SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
        SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
        SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00);
    }

    //reset attack power, damage and attack speed fields
    SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
    SetFloatValue(UNIT_FIELD_OFFHANDATTACKTIME, 2000.0f );
    SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );

    SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
    SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
    SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
    SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
    SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
    SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );

    SetUInt32Value(UNIT_FIELD_ATTACK_POWER,            0 );
    SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS,       0 );
    SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
    SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER,     0 );
    SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
    SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);

    // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
    SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
    SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
    SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);

    // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
    for (uint8 i = 0; i < 7; ++i)
        SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);

    // Base parry percents
    SetFloatValue(PLAYER_PARRY_PERCENTAGE, 5.0f);

    //Base block percentage
    SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 5.0f);

    // Base dodge values
    switch(getClass())
    {
        case CLASS_PALADIN: SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.75f); break;
        case CLASS_HUNTER:  SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.64f); break;
        case CLASS_PRIEST:  SetFloatValue(PLAYER_DODGE_PERCENTAGE, 3.0f ); break;
        case CLASS_SHAMAN:  SetFloatValue(PLAYER_DODGE_PERCENTAGE, 1.75f); break;
        case CLASS_MAGE:    SetFloatValue(PLAYER_DODGE_PERCENTAGE, 3.25f); break;
        case CLASS_WARLOCK: SetFloatValue(PLAYER_DODGE_PERCENTAGE, 2.0f ); break;
        case CLASS_DRUID:   SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.75f); break;
        case CLASS_ROGUE:
        case CLASS_WARRIOR:
        default:            SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f ); break;
    }

    // set armor (resistance 0) to original value (create_agility*2)
    SetArmor(int32(m_createStats[STAT_AGILITY]*2));
    SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
    SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
    // set other resistance to original value (0)
    for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
    {
        SetResistance(SpellSchools(i), 0);
        SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
        SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
    }

    SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
    for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
    {
        SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
        SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
    }
    InitDataForForm();

    // save new stats
    for (int i = POWER_MANA; i < MAX_POWERS; i++)
        SetMaxPower(Powers(i),  uint32(GetCreatePowers(Powers(i))));

    SetMaxHealth(info.basehealth);                          // stamina bonus will applied later

    // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
    SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);

    // cleanup unit flags (will be re-applied if need at aura load).
    RemoveFlag( UNIT_FIELD_FLAGS,
        UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE   | UNIT_FLAG_PET_IN_COMBAT  | UNIT_FLAG_SILENCED |
        UNIT_FLAG_PACIFIED       | UNIT_FLAG_DISABLE_ROTATE | UNIT_FLAG_IN_COMBAT      | UNIT_FLAG_DISARMED |
        UNIT_FLAG_CONFUSED       | UNIT_FLAG_FLEEING        | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_MOUNT );

    // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
    RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);

    if(reapplyMods)                                         //reapply stats values only on .reset stats (level) command
        _ApplyAllStatBonuses();

    // set current level health and mana/energy to maximum after applying all mods.
    SetHealth(GetMaxHealth());
    SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
    SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
    if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
        SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
    SetPower(POWER_FOCUS, 0);
    SetPower(POWER_HAPPINESS, 0);
}

void Player::SendInitialSpells()
{
    uint16 spellCount = 0;

    PlayerSpellMap::const_iterator itr;

    for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
    {
        if(itr->second->state == PLAYERSPELL_REMOVED)
            continue;

        if(itr->second->active)
            spellCount +=1;
    }

    WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+2+4*m_spells.size()));
    data << uint8(0);
    data << uint16(spellCount);

    for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
    {
        if(itr->second->state == PLAYERSPELL_REMOVED)
            continue;

        if(!itr->second->active)
            continue;

        data << uint16(itr->first);
        //data << uint16(itr->second->slotId);
        data << uint16(0);                                  // it's not slot id
    }

    uint16 spellCooldowns = m_spellCooldowns.size();
    data << spellCooldowns;
    for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); itr++)
    {
        SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
        if(!sEntry)
            continue;

        data << uint16(itr->first);

        time_t cooldown = 0;
        time_t curTime = time(NULL);
        if(itr->second.end > curTime)
            cooldown = (itr->second.end-curTime)*1000;

        data << uint16(itr->second.itemid);                 // cast item id
        data << uint16(sEntry->Category);                   // spell category
        if(sEntry->Category)                                // may be wrong, but anyway better than nothing...
        {
            data << uint32(0);
            data << uint32(cooldown);
        }
        else
        {
            data << uint32(cooldown);
            data << uint32(0);
        }
    }

    GetSession()->SendPacket(&data);

    sLog.outDetail( "CHARACTER: Sent Initial Spells" );
}

void Player::RemoveMail(uint32 id)
{
    for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
    {
        if ((*itr)->messageID == id)
        {
            //do not delete item, because Player::removeMail() is called when returning mail to sender.
            m_mail.erase(itr);
            return;
        }
    }
}

void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
{
    WorldPacket data(SMSG_SEND_MAIL_RESULT, (12));
    data << (uint32) mailId;
    data << (uint32) mailAction;
    data << (uint32) mailError;
    if(mailAction == MAIL_ITEM_TAKEN)
    {
        data << (uint32) item_guid;                         // item guid low?
        data << (uint32) item_count;                        // item count?
    }
    if (equipError)
        data << (uint32) equipError;
    GetSession()->SendPacket(&data);
}

void Player::SendNewMail()
{
    // deliver undelivered mail
    WorldPacket data(SMSG_RECEIVED_MAIL, 4);
    data << (uint32) 0;
    GetSession()->SendPacket(&data);
}

void Player::UpdateNextMailTimeAndUnreads()
{
    // calculate next delivery time (min. from non-delivered mails
    // and recalculate unReadMail
    time_t cTime = time(NULL);
    m_nextMailDelivereTime = 0;
    unReadMails = 0;
    for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
    {
        if((*itr)->deliver_time > cTime)
        {
            if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
                m_nextMailDelivereTime = (*itr)->deliver_time;
        }
        if(((*itr)->state & READ) == 0)
            ++unReadMails;
    }
}

void Player::AddNewMailDeliverTime(time_t deliver_time)
{
    if(deliver_time <= time(NULL))                          // ready now
    {
        ++unReadMails;
        SendNewMail();
    }
    else                                                    // not ready and no have ready mails
    {
        if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
            m_nextMailDelivereTime =  deliver_time;
    }
}

bool Player::addSpell(uint16 spell_id, uint8 active, PlayerSpellState state, uint16 slot_id)
{
    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
    if (!spellInfo)
    {
        // do character spell book cleanup (all characters)
        if(state == PLAYERSPELL_UNCHANGED)                  // spell load case
        {
            sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
            CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
        }
        else
            sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);

        return false;
    }

    if(!SpellMgr::IsSpellValid(spellInfo,this,false))
    {
        // do character spell book cleanup (all characters)
        if(state == PLAYERSPELL_UNCHANGED)                  // spell load case
        {
            sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
            CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
        }
        else
            sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);

        return false;
    }

    PlayerSpellMap::iterator itr = m_spells.find(spell_id);
    if (itr != m_spells.end())
    {
        if (itr->second->state == PLAYERSPELL_REMOVED)
        {
            delete itr->second;
            m_spells.erase(itr);
            state = PLAYERSPELL_CHANGED;
        }
        else if (state == PLAYERSPELL_UNCHANGED && itr->second->state != PLAYERSPELL_UNCHANGED)
        {
            // can be in case spell loading but learned at some previous spell loading
            itr->second->state = PLAYERSPELL_UNCHANGED;
            return false;
        }
        else
            return false;
    }

    PlayerSpell *newspell = new PlayerSpell;
    newspell->active = active;
    newspell->state = state;

    bool superceded_old = false;

    // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
    if(newspell->active && spellmgr.GetSpellRank(spellInfo->Id) != 0)
    {
        for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
        {
            if(itr->second->state == PLAYERSPELL_REMOVED) continue;
            SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
            if(!i_spellInfo) continue;

            if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) &&
                !SpellMgr::canStackSpellRanks(spellInfo,i_spellInfo) )
            {
                if(itr->second->active)
                {
                    uint8 spell_id_rank = spellmgr.GetSpellRank(spell_id);
                    uint8 itr_rank = spellmgr.GetSpellRank(itr->first);

                    if(spell_id_rank > itr_rank)
                    {
                        WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
                        data << uint16(itr->first);
                        data << uint16(spell_id);
                        GetSession()->SendPacket( &data );

                        // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
                        itr->second->active = 0;
                        itr->second->state = PLAYERSPELL_CHANGED;
                        superceded_old = true;              // new spell replace old in action bars and spell book.
                    }
                    else if(spell_id_rank < itr_rank)
                    {
                        WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
                        data << uint16(spell_id);
                        data << uint16(itr->first);
                        GetSession()->SendPacket( &data );

                        // mark new spell as disable (not learned yet for client and will not learned)
                        newspell->active = 0;
                        if(newspell->state != PLAYERSPELL_NEW)
                            newspell->state = PLAYERSPELL_CHANGED;
                    }
                }
            }
        }
    }

    uint16 tmpslot=slot_id;

    if (tmpslot == 0xffff)
    {
        uint16 maxid = 0;
        PlayerSpellMap::iterator itr;
        for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
        {
            if(itr->second->state == PLAYERSPELL_REMOVED) continue;
            if (itr->second->slotId > maxid) maxid = itr->second->slotId;
        }
        tmpslot = maxid + 1;
    }

    newspell->slotId = tmpslot;
    m_spells[spell_id] = newspell;

    uint32 talentCost = GetTalentSpellCost(spell_id);

    // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
    // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
    if( talentCost > 0 && (spellInfo->Effect[0]==SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[1]==SPELL_EFFECT_LEARN_SPELL || spellInfo->Effect[2]==SPELL_EFFECT_LEARN_SPELL) )
    {
        // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
        CastSpell(this, spell_id, true);
    }
    // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
    else if (IsPassiveSpell(spell_id))
    {
        // if spell doesn't require a stance or the player is in the required stance
        if( ( !spellInfo->Stances &&
            spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
            spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
            spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
            m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
            (spell_id ==  5420 && m_form == FORM_TREE) ||
            (spell_id ==  5419 && m_form == FORM_TRAVEL) ||
            (spell_id ==  7376 && m_form == FORM_DEFENSIVESTANCE) ||
            (spell_id ==  7381 && m_form == FORM_BERSERKERSTANCE) ||
            (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
            (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
            (spell_id == 33948 && m_form == FORM_FLIGHT) ||
            (spell_id == 40121 && m_form == FORM_SWIFT_FLIGHT) )
                                                            //Check CasterAuraStates
            if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
                CastSpell(this, spell_id, true);
    }

    // update used talent points count
    m_usedTalentCount += talentCost;

    // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
    if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
    {
        if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
            SetFreePrimaryProffesions(freeProfs-1);
    }

    // add dependent skills
    uint16 maxskill     = GetMaxSkillValueForLevel();

    SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);

    if(spellLearnSkill)
    {
        uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
        uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);

        if(skill_value < spellLearnSkill->value)
            skill_value = spellLearnSkill->value;

        uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;

        if(skill_max_value < new_skill_max_value)
            skill_max_value =  new_skill_max_value;

        SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
    }

    // learn dependent spells
    SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
    SpellLearnSpellMap::const_iterator spell_end   = spellmgr.GetEndSpellLearnSpell(spell_id);

    for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
    {
        if(!itr->second.autoLearned && (!itr->second.ifNoSpell || !HasSpell(itr->second.ifNoSpell)))
            learnSpell(itr->second.spell);
    }

    // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
    return newspell->active && !superceded_old;
}

void Player::learnSpell(uint16 spell_id)
{
    // prevent duplicated entires in spell book
    if (!addSpell(spell_id,1))
        return;

    WorldPacket data(SMSG_LEARNED_SPELL, 4);
    data <<uint32(spell_id);
    GetSession()->SendPacket(&data);
}

void Player::removeSpell(uint16 spell_id)
{
    PlayerSpellMap::iterator itr = m_spells.find(spell_id);
    if (itr == m_spells.end())
        return;

    if(itr->second->state == PLAYERSPELL_REMOVED)
        return;

    // removing
    WorldPacket data(SMSG_REMOVED_SPELL, 4);
    data << spell_id;
    GetSession()->SendPacket(&data);

    if(itr->second->state == PLAYERSPELL_NEW)
    {
        delete itr->second;
        m_spells.erase(itr);
    }
    else
        itr->second->state = PLAYERSPELL_REMOVED;

    RemoveAurasDueToSpell(spell_id);

    // free talent points
    uint32 talentCosts = GetTalentSpellCost(spell_id);
    if(talentCosts > 0)
    {
        if(talentCosts < m_usedTalentCount)
            m_usedTalentCount -= talentCosts;
        else
            m_usedTalentCount = 0;
    }

    // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
    if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
    {
        uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
        if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
            SetFreePrimaryProffesions(freeProfs);
    }

    // remove dependent skill
    SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);

    if(spellLearnSkill)
    {
        uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
        if(!prev_spell)                                     // first rank, remove skill
            SetSkill(spellLearnSkill->skill,0,0);
        else
        {
            // search prev. skill setting by spell ranks chain
            SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
            while(!prevSkill && prev_spell)
            {
                prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
                prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
            }

            if(!prevSkill)                                  // not found prev skill setting, remove skill
                SetSkill(spellLearnSkill->skill,0,0);
            else                                            // set to prev. skill setting values
            {
                uint32 skill_value = GetPureSkillValue(prevSkill->skill);
                uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);

                if(skill_value >  prevSkill->value)
                    skill_value = prevSkill->value;

                uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;

                if(skill_max_value > new_skill_max_value)
                    skill_max_value =  new_skill_max_value;

                SetSkill(prevSkill->skill,skill_value,skill_max_value);
            }
        }

    }

    // remove dependent spells
    SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
    SpellLearnSpellMap::const_iterator spell_end   = spellmgr.GetEndSpellLearnSpell(spell_id);

    for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
        removeSpell(itr->second.spell);
}

void Player::RemoveArenaSpellCooldowns()
{
    // remove cooldowns on spells that has < 15 min CD
    SpellCooldowns::iterator itr, next;
    // iterate spell cooldowns
    for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
    {
        next = itr;
        ++next;
        SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
        // check if spellentry is present and if the cooldown is less than 15 mins
        if( entry && 
            (entry->RecoveryTime <= 15 * 60000) &&
            (entry->CategoryRecoveryTime <= 15 * 60000))
        {
            // notify player
            WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8+4));
            data << uint32(itr->first);
            data << GetGUID();
            GetSession()->SendPacket(&data);
            // remove cooldown
            m_spellCooldowns.erase(itr);
        }
    }
}

void Player::RemoveAllSpellCooldown()
{
    if(!m_spellCooldowns.empty())
    {
        for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
        {
            WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8+4));
            data << uint32(itr->first);
            data << GetGUID();
            GetSession()->SendPacket(&data);
        }
        m_spellCooldowns.clear();
    }
}

void Player::_LoadSpellCooldowns(QueryResult *result)
{
    m_spellCooldowns.clear();

    //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());

    if(result)
    {
        time_t curTime = time(NULL);

        do
        {
            Field *fields = result->Fetch();

            uint32 spell_id = fields[0].GetUInt32();
            uint32 item_id  = fields[1].GetUInt32();
            time_t db_time  = (time_t)fields[2].GetUInt64();

            if(!sSpellStore.LookupEntry(spell_id))
            {
                sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
                continue;
            }

            // skip outdated cooldown
            if(db_time <= curTime)
                continue;

            AddSpellCooldown(spell_id, item_id, db_time);

            sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
        }
        while( result->NextRow() );

        delete result;
    }
}

void Player::_SaveSpellCooldowns()
{
    CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());

    time_t curTime = time(NULL);

    // remove outdated and save active
    for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
    {
        if(itr->second.end <= curTime)
            m_spellCooldowns.erase(itr++);
        else
        {
            CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
            ++itr;
        }
    }
}

void Player::ResetComboPointsIfNeed(const SpellEntry *spellInfo)
{
    bool needClearCombo = false;

    // Check use combo points in damage calculations
    bool comboDamageUsed =
        spellInfo->EffectPointsPerComboPoint[0] != 0 ||
        spellInfo->EffectPointsPerComboPoint[1] != 0 ||
        spellInfo->EffectPointsPerComboPoint[2] != 0;

    if(comboDamageUsed &&  m_attacking && (m_attacking->GetGUID() == GetComboTarget()))
        needClearCombo = true;

    // Check in duration calculations
    int32 minduration = GetSpellDuration(spellInfo);
    if(minduration != 1 && minduration != GetSpellMaxDuration(spellInfo))
        needClearCombo = true;
    // overpower - need reset combopoints
    else if(spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && (spellInfo->SpellFamilyFlags & 0x4))
        needClearCombo = true;

    // Reset if need
    if (needClearCombo)
        ClearComboPoints();
}

uint32 Player::resetTalentsCost() const
{
    // The first time reset costs 1 gold
    if(m_resetTalentsCost < 1*GOLD)
        return 1*GOLD;
    // then 5 gold
    else if(m_resetTalentsCost < 5*GOLD)
        return 5*GOLD;
    // After that it increases in increments of 5 gold
    else if(m_resetTalentsCost < 10*GOLD)
        return 10*GOLD;
    else
    {
        uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
        if(months > 0)
        {
            // This cost will be reduced by a rate of 5 gold per month
            int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
            // to a minimum of 10 gold.
            return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
        }
        else
        {
            // After that it increases in increments of 5 gold
            int32 new_cost = m_resetTalentsCost + 5*GOLD;
            // until it hits a cap of 50 gold.
            if(new_cost > 50*GOLD)
                new_cost = 50*GOLD;
            return new_cost;
        }
    }
}

bool Player::resetTalents(bool no_cost)
{
    // not need after this call
    if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
    {
        m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
        CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
    }

    uint32 level = getLevel();
    uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));

    if (m_usedTalentCount == 0)
    {
        SetFreeTalentPoints(talentPointsForLevel);
        return false;
    }

    uint32 cost = 0;

    if(!no_cost)
    {
        cost = resetTalentsCost();

        if (GetMoney() < cost)
        {
            SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
            return false;
        }
    }

    for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
    {
        TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);

        if (!talentInfo) continue;

        TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );

        if(!talentTabInfo)
            continue;

        // unlearn only talents for character class
        // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
        // to prevent unexpected lost normal learned spell skip another class talents
        if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
            continue;

        for (int j = 0; j < 5; j++)
        {
            for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
            {
                if(itr->second->state == PLAYERSPELL_REMOVED)
                {
                    ++itr;
                    continue;
                }

                // remove learned spells (all ranks)
                uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);

                // unlearn if first rank is talent or learned by talent
                if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
                {
                    RemoveAurasDueToSpell(itr->first);
                    removeSpell(itr->first);
                    itr = GetSpellMap().begin();
                    continue;
                }
                else
                    ++itr;
            }
        }
    }

    SetFreeTalentPoints(talentPointsForLevel);

    if(!no_cost)
    {
        ModifyMoney(-(int32)cost);

        m_resetTalentsCost = cost;
        m_resetTalentsTime = time(NULL);
    }

    //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
    RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);

    return true;
}

bool Player::_removeSpell(uint16 spell_id)
{
    PlayerSpellMap::iterator itr = m_spells.find(spell_id);
    if (itr != m_spells.end())
    {
        delete itr->second;
        m_spells.erase(itr);
        return true;
    }
    return false;
}

Mail* Player::GetMail(uint32 id)
{
    for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
    {
        if ((*itr)->messageID == id)
        {
            return (*itr);
        }
    }
    return NULL;
}

void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
{
    if(target == this)
    {
        Object::_SetCreateBits(updateMask, target);
    }
    else
    {
        for(uint16 index = 0; index < m_valuesCount; index++)
        {
            if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
                updateMask->SetBit(index);
        }
    }
}

void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
{
    if(target == this)
    {
        Object::_SetUpdateBits(updateMask, target);
    }
    else
    {
        Object::_SetUpdateBits(updateMask, target);
        *updateMask &= updateVisualBits;
    }
}

void Player::InitVisibleBits()
{
    updateVisualBits.SetCount(PLAYER_END);

    updateVisualBits.SetBit(OBJECT_FIELD_GUID);
    updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
    updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);

    updateVisualBits.SetBit(UNIT_FIELD_CHARM);
    updateVisualBits.SetBit(UNIT_FIELD_CHARM+1);

    updateVisualBits.SetBit(UNIT_FIELD_SUMMON);
    updateVisualBits.SetBit(UNIT_FIELD_SUMMON+1);

    updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY);

    updateVisualBits.SetBit(UNIT_FIELD_TARGET);
    updateVisualBits.SetBit(UNIT_FIELD_TARGET+1);

    updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT);
    updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT+1);

    updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
    updateVisualBits.SetBit(UNIT_FIELD_POWER1);
    updateVisualBits.SetBit(UNIT_FIELD_POWER2);
    updateVisualBits.SetBit(UNIT_FIELD_POWER3);
    updateVisualBits.SetBit(UNIT_FIELD_POWER4);
    updateVisualBits.SetBit(UNIT_FIELD_POWER5);

    updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
    updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
    updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
    updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
    updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
    updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);

    updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
    updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
    updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
    updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
    updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
    for(uint16 i = UNIT_FIELD_AURA; i < UNIT_FIELD_AURASTATE; ++i)
        updateVisualBits.SetBit(i);
    updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
    updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME);
    updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
    updateVisualBits.SetBit(UNIT_FIELD_RANGEDATTACKTIME);
    updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
    updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
    updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
    updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
    updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
    updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
    updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
    updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
    updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
    updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
    updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
    updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
    updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);

    updateVisualBits.SetBit(PLAYER_FLAGS);
    updateVisualBits.SetBit(PLAYER_BYTES);
    updateVisualBits.SetBit(PLAYER_BYTES_2);
    updateVisualBits.SetBit(PLAYER_BYTES_3);
    updateVisualBits.SetBit(PLAYER_GUILDID);
    updateVisualBits.SetBit(PLAYER_GUILDRANK);
    updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
    updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
    updateVisualBits.SetBit(PLAYER_DUEL_ARBITER);
    updateVisualBits.SetBit(PLAYER_DUEL_ARBITER+1);

    // PLAYER_QUEST_LOG_x also visible bit on official...
    for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i+=3)
        updateVisualBits.SetBit(i);

    for(uint16 i = 0; i < INVENTORY_SLOT_BAG_END; i++)
    {
        updateVisualBits.SetBit((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + i*2));
        updateVisualBits.SetBit((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (i*2) + 1));
    }
    //Players visible items are not inventory stuff
    //431) = 884 (0x374) = main weapon
    for(uint16 i = 0; i < EQUIPMENT_SLOT_END; i++)
    {
        uint16 visual_base = PLAYER_VISIBLE_ITEM_1_0 + (i*16);

        // item entry
        updateVisualBits.SetBit(visual_base + 0);

        // item enchantment IDs
        for(uint8 j = 0; j < 11; ++j)
            updateVisualBits.SetBit(visual_base +1 + j);

        // random properties
        updateVisualBits.SetBit((uint16)(PLAYER_VISIBLE_ITEM_1_PROPERTIES + (i*16)));
    }

    updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);

    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + 1);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY + 2);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_INFO);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_INFO + 1);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_INFO + 2);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_INFO + 3);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_INFO + 4);
    updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_INFO + 5);
}

void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
{
    for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
    {
        if(m_items[i] == NULL)
            continue;

        m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
    }

    if(target == this)
    {

        for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
        {
            if(m_items[i] == NULL)
                continue;

            m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
        }
        for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
        {
            if(m_items[i] == NULL)
                continue;

            m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
        }
    }

    Unit::BuildCreateUpdateBlockForPlayer( data, target );
}

void Player::DestroyForPlayer( Player *target ) const
{
    Unit::DestroyForPlayer( target );

    for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if(m_items[i] == NULL)
            continue;

        m_items[i]->DestroyForPlayer( target );
    }

    if(target == this)
    {

        for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
        {
            if(m_items[i] == NULL)
                continue;

            m_items[i]->DestroyForPlayer( target );
        }
        for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
        {
            if(m_items[i] == NULL)
                continue;

            m_items[i]->DestroyForPlayer( target );
        }
    }
}

bool Player::HasSpell(uint32 spell) const
{
    PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
    return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED);
}

TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
{
    if (!trainer_spell)
        return TRAINER_SPELL_RED;

    uint32 learned_spell_id = trainer_spell->spell->EffectTriggerSpell[0];

    // get learned spell info
    SpellEntry const *spellInfo = sSpellStore.LookupEntry(learned_spell_id);
    if (!spellInfo)
        return TRAINER_SPELL_RED;

    // known spell
    if(HasSpell(learned_spell_id))
        return TRAINER_SPELL_GRAY;

    // check race/class requirement
    if(!IsSpellFitByClassAndRace(spellInfo->Id))
        return TRAINER_SPELL_RED;

    // check level requirement
    if(getLevel() < ( trainer_spell->reqlevel ? trainer_spell->reqlevel : spellInfo->spellLevel))
        return TRAINER_SPELL_RED;

    // check prev.rank requirement
    uint32 prev_id =  spellmgr.GetPrevSpellInChain(learned_spell_id);
    if(prev_id && !HasSpell(prev_id))
        return TRAINER_SPELL_RED;

    // check skill requirement
    if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
        return TRAINER_SPELL_RED;

    // secondary prof. or not prof. spell
    uint32 skill = spellInfo->EffectMiscValue[1];

    if(spellInfo->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
        return TRAINER_SPELL_GREEN;

    // check primary prof. limit
    if(spellmgr.IsPrimaryProfessionFirstRankSpell(learned_spell_id) && GetFreePrimaryProffesionPoints() == 0)
        return TRAINER_SPELL_RED;

    return TRAINER_SPELL_GREEN;
}

void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
{
    uint32 guid = GUID_LOPART(playerguid);

    // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
    // bones will be deleted by corpse/bones deleting thread shortly
    ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);

    // remove from guild
    uint32 guildId = GetGuildIdFromDB(playerguid);
    if(guildId != 0)
    {
        Guild* guild = objmgr.GetGuildById(guildId);
        if(guild)
            guild->DelMember(guid);
    }

    // the player was uninvited already on logout so just remove from group
    QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
    if(resultGroup)
    {
        uint64 leaderGuid = MAKE_GUID((*resultGroup)[0].GetUInt32(),HIGHGUID_PLAYER);
        delete resultGroup;
        Group* group = objmgr.GetGroupByLeader(leaderGuid);
        if(group)
        {
            RemoveFromGroup(group, playerguid);
        }
    }

    // remove signs from petitions (also remove petitions if owner);
    RemovePetitionsAndSigns(playerguid, 10);

    // return back all mails with COD and Item
    QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
    if(resultMail)
    {
        do
        {
            Field *fields = resultMail->Fetch();

            uint32 mail_id       = fields[0].GetUInt32();
            uint32 sender        = fields[1].GetUInt32();
            std::string subject  = fields[2].GetCppString();
            uint32 itemTextId    = fields[3].GetUInt32();
            uint32 money         = fields[4].GetUInt32();
            bool has_items       = fields[5].GetBool();

            //we can return mail now
            //so firstly delete the old one
            CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);

            MailItemsInfo mi;
            if(has_items)
            {
                QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
                if(resultItems)
                {
                    do
                    {
                        Field *fields2 = resultItems->Fetch();

                        uint32 item_guidlow = fields2[0].GetUInt32();
                        uint32 item_template = fields2[1].GetUInt32();

                        ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
                        if(!itemProto)
                            continue;

                        Item* pItem = NewItemOrBag(itemProto);
                        if(!pItem->LoadFromDB(item_guidlow,MAKE_GUID(guid, HIGHGUID_PLAYER)))
                        {
                            delete pItem;
                            continue;
                        }

                        mi.AddItem(item_guidlow, item_template, pItem);
                    }
                    while (resultItems->NextRow());

                    delete resultItems;
                }
            }

            CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);

            uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_GUID(guid, HIGHGUID_PLAYER));

            WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, 0);
        }
        while (resultMail->NextRow());

        delete resultMail;
    }

    // unsummon and delete for pets is not required: player deleted from CLI or character list with not loaded pet.

    // NOW we can finally clear other DB data related to character
    CharacterDatabase.BeginTransaction();
    CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_instance WHERE leader = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_kill WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_tutorial WHERE guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
    CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
    CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
    CharacterDatabase.CommitTransaction();

    //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
    if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
}

void Player::SetMovement(PlayerMovementType pType)
{
    WorldPacket data;
    switch(pType)
    {
        case MOVE_ROOT:       data.Initialize(SMSG_FORCE_MOVE_ROOT,   GetPackGUID().size()+4); break;
        case MOVE_UNROOT:     data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
        case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK,   GetPackGUID().size()+4); break;
        case MOVE_LAND_WALK:  data.Initialize(SMSG_MOVE_LAND_WALK,    GetPackGUID().size()+4); break;
        default:
            sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
            return;
    }
    data.append(GetPackGUID());
    data << uint32(0);
    GetSession()->SendPacket( &data );
}

void Player::BuildPlayerRepop()
{
    if(getRace() == RACE_NIGHTELF)
        CastSpell(this, 20584, true);                       // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
    CastSpell(this, 8326, true);                            // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)

    // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
    // there must be SMSG.STOP_MIRROR_TIMER
    // there we must send 888 opcode

    // place corpse instead player body
    if(!GetCorpse())
        CreateCorpse();

    Corpse *corpse = GetCorpse();
    if (!corpse)
    {
        sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
        return;
    }

    // now show corpse for all
    if(corpse)
    {
        corpse->SetInstanceId(this->GetInstanceId());
        MapManager::Instance().GetMap(corpse->GetMapId(), this)->Add(corpse);
    }

    // convert player body to ghost
    SetHealth( 1 );

    SetMovement(MOVE_WATER_WALK);
    SetMovement(MOVE_UNROOT);

    // BG - remove insignia related
    RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);

    // setting new speed
    /*if (getRace() == RACE_NIGHTELF)
    {
        SetSpeed(MOVE_RUN,  1.5f*1.2f, true);
        SetSpeed(MOVE_SWIM, 1.5f*1.2f, true);
    }
    else
    {
        SetSpeed(MOVE_RUN,  1.5f, true);
        SetSpeed(MOVE_SWIM, 1.5f, true);
    }*/

    //! corpse reclaim delay 30 * 1000ms
    WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
    data << (uint32)(CORPSE_RECLAIM_DELAY*1000);
    GetSession()->SendPacket( &data );

    // to prevent cheating
    if(corpse)
        corpse->ResetGhostTime();

    data.Initialize(SMSG_UPDATE_AURA_DURATION, 5);          // last check 2.0.10
    data << uint8(0x28) << uint32(0);
    GetSession()->SendPacket( &data );

    StopMirrorTimers();                                     //disable timers(bars)

    //SetUInt32Value(UNIT_FIELD_AURA + 32, 8326);           // set ghost form
    //SetUInt32Value(UNIT_FIELD_AURA + 33, 20584);          //!dono

    //SetUInt32Value(UNIT_FIELD_AURAFLAGS + 4, 0xEE);

    //SetUInt32Value(UNIT_FIELD_AURASTATE, 0x02);

    SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS,(float)1.0);    //see radius of death player?

    SetUInt32Value(UNIT_FIELD_BYTES_1, PLAYER_STATE_FLAG_ALWAYS_STAND);

    //if (getRace() == RACE_NIGHTELF)
    //    SetUInt32Value(UNIT_FIELD_DISPLAYID, 1825);

    // set initial flags + set ghost + restore pvp
    //SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NONE | UNIT_FLAG_UNKNOWN1 | (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP)?UNIT_FLAG_PVP:0) );

    // reserve some flags + ad ghost flag
    //uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_IN_PVP | PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
    //SetUInt32Value(PLAYER_FLAGS, old_safe_flags | PLAYER_FLAGS_GHOST );
}

void Player::SendDelayResponse(const uint32 ml_seconds)
{
    WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
    data << (uint32)time(NULL);
    data << (uint32)0;
    GetSession()->SendPacket( &data );
}

void Player::ResurrectPlayer(float restore_percent, bool updateToWorld)
{
    WorldPacket data(SMSG_SH_POSITION, 4*4);                // remove spirit healer position
    data << uint32(-1);
    data << uint32(0);
    data << uint32(0);
    data << uint32(0);
    GetSession()->SendPacket(&data);

    // speed change, land walk

    // remove death flag + set aura
    //RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
    RemoveFlag(UNIT_FIELD_BYTES_1, PLAYER_STATE_FLAG_ALL);
    if(getRace() == RACE_NIGHTELF)
        RemoveAurasDueToSpell(20584);                       // speed bonuses
    RemoveAurasDueToSpell(8326);                            // SPELL_AURA_GHOST

    setDeathState(ALIVE);

    SetMovement(MOVE_LAND_WALK);
    SetMovement(MOVE_UNROOT);

    //SetSpeed(MOVE_RUN,  1.0f, true);
    //SetSpeed(MOVE_SWIM, 1.0f, true);

    //SetUInt32Value(CONTAINER_FIELD_SLOT_1+29, 0);

    //SetUInt32Value(UNIT_FIELD_AURA+32, 0);
    //SetUInt32Value(UNIT_FIELD_AURALEVELS+8, 0xeeeeeeee);
    //SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS+8, 0xeeeeeeee);
    //SetUInt32Value(UNIT_FIELD_AURAFLAGS+4, 0);
    //SetUInt32Value(UNIT_FIELD_AURASTATE, 0);

    //if(getRace() == RACE_NIGHTELF)
    //{
    //    DeMorph();
    //}

    m_deathTimer = 0;

    // set health/powers (0- will be set in caller)
    if(restore_percent>0.0f)
    {
        SetHealth(uint32(GetMaxHealth()*restore_percent));
        SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
        SetPower(POWER_RAGE, 0);
        SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
    }

    // update world right away
    if(updateToWorld)
        MapManager::Instance().GetMap(GetMapId(), this)->Add(this);

    // some items limited to specific map
    DestroyZoneLimitedItem( true, GetZoneId());

    // set resurrection sickness if not expired
    if(!m_resurrectingSicknessExpire)
        return;

    // check expire
    time_t curTime = time(NULL);
    if(m_resurrectingSicknessExpire <= curTime)
    {
        m_resurrectingSicknessExpire = 0;
        return;
    }

    // set resurrection sickness!
    uint32 delta = m_resurrectingSicknessExpire-time(NULL);

    CastSpell(this,SPELL_PASSIVE_RESURRECTION_SICKNESS,true);

    for(int i =0; i < 3; ++i)
    {
        Aura* Aur = GetAura(SPELL_PASSIVE_RESURRECTION_SICKNESS,i);
        if(Aur)
        {
            Aur->SetAuraDuration(delta*1000);
            Aur->UpdateAuraDuration();
        }
    }
}

void Player::KillPlayer()
{
    SetMovement(MOVE_ROOT);

    StopMirrorTimers();                                     //disable timers(bars)

    setDeathState(CORPSE);
    //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );

    SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);

    // 6 minutes until repop at graveyard
    m_deathTimer = 360000;

    // dead player body showed at this moment, corpse will be show at Player ghost repop
    CreateCorpse();

    // update visibility
    ObjectAccessor::UpdateObjectVisibility(this);
}

void Player::CreateCorpse()
{
    // prevent existence 2 corpse for player
    SpawnCorpseBones();

    uint32 _uf, _pb, _pb2, _cfb1, _cfb2;

    Corpse *corpse = new Corpse(this, CORPSE_RESURRECTABLE);

    if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
        GetPositionY(), GetPositionZ(), GetOrientation()))
    {
        delete corpse;
        return;
    }

    _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
    _pb = GetUInt32Value(PLAYER_BYTES);
    _pb2 = GetUInt32Value(PLAYER_BYTES_2);

    uint8 race       = (uint8)(_uf);
    uint8 skin       = (uint8)(_pb);
    uint8 face       = (uint8)(_pb >> 8);
    uint8 hairstyle  = (uint8)(_pb >> 16);
    uint8 haircolor  = (uint8)(_pb >> 24);
    uint8 facialhair = (uint8)(_pb2);

    _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
    _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));

    corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
    corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );

    uint32 flags = 0x04;
    if(InBattleGround())
        flags |= 0x20;                                      // to be able to remove insignia
    corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );

    corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetUInt32Value(UNIT_FIELD_DISPLAYID) );

    uint32 iDisplayID;
    uint16 iIventoryType;
    uint32 _cfi;
    for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
    {
        if(m_items[i])
        {
            iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
            iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;

            _cfi =  (uint16(iDisplayID)) | (iIventoryType)<< 24;
            corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
        }
    }

    corpse->SaveToDB();

    // register for player, but not show
    ObjectAccessor::Instance().AddCorpse(corpse);
}

void Player::SpawnCorpseBones()
{
    if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
        SaveToDB();                                         // prevent loading as ghost without corpse
}

Corpse* Player::GetCorpse() const
{
    return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
}

void Player::DurabilityLossAll(double percent)
{
    for (uint16 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
        DurabilityLoss(i,percent);
}

void Player::DurabilityLoss(uint8 equip_pos, double percent)
{
    if(!m_items[equip_pos])
        return;

    uint32 pDurability =  m_items[equip_pos]->GetUInt32Value(ITEM_FIELD_DURABILITY);

    if(!pDurability)
        return;

    uint32 pDurabilityLoss = (uint32)(pDurability*percent);

    if(pDurabilityLoss < 1 )
        pDurabilityLoss = 1;

    DurabilityPointsLoss(equip_pos,pDurabilityLoss);
}

void Player::DurabilityPointsLoss(uint8 equip_pos, uint32 points)
{
    if(!m_items[equip_pos])
        return;

    uint32 pDurability =  m_items[equip_pos]->GetUInt32Value(ITEM_FIELD_DURABILITY);

    if(!pDurability)
        return;

    uint32 pNewDurability = pDurability >= points ? pDurability - points : 0;

    // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
    if ( pNewDurability == 0 )
        _ApplyItemMods(m_items[equip_pos],equip_pos, false);

    m_items[equip_pos]->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
    m_items[equip_pos]->SetState(ITEM_CHANGED, this);
}

uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
{
    uint32 TotalCost = 0;
    // equipped, backpack, bags itself
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
        TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);

    // bank, buyback and keys not repaired

    // items in inventory bags
    for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
        for(int i = 0; i < MAX_BAG_SIZE; i++)
            TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
    return TotalCost;
}

uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
{
    Item* item = GetItemByPos(pos);

    uint32 TotalCost = 0;
    if(!item)
        return TotalCost;

    uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
    if(!maxDurability)
        return TotalCost;

    uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);

    if(cost)
    {

        uint32 LostDurability = maxDurability - curDurability;
        if(LostDurability>0)
        {

            ItemPrototype const *ditemProto = sItemStorage.LookupEntry<ItemPrototype>(item->GetEntry());
            if(!ditemProto)
            {
                sLog.outError("ERROR: RepairDurability: Unknown item id %u", ditemProto);
                return TotalCost;
            }

            DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
            if(!dcost)
            {
                sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", dcost);
                return TotalCost;
            }

            DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry((ditemProto->Quality+1)*2);
            if(!dQualitymodEntry)
            {
                sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntry);
                return TotalCost;
            }

            uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
            uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));

            costs = uint32(costs * discountMod);

            if (costs==0)                                   //fix for ITEM_QUALITY_ARTIFACT
                costs= 1;

            if (guildBank)
            {
                if (GetGuildId()==0)
                {
                    DEBUG_LOG("You are not member of a guild");
                    return TotalCost;
                }

                Guild *pGuild = objmgr.GetGuildById(GetGuildId());
                if (!pGuild)
                    return TotalCost;

                if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
                {
                    DEBUG_LOG("You do not have enough money withdraw rights");
                    return TotalCost;
                }

                if (pGuild->GetGuildBankMoney() < costs)
                {
                    DEBUG_LOG("There is not enough money in bank");
                    return TotalCost;
                }

                pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
                TotalCost = costs;
            }
            else if (GetMoney() < costs)
            {
                DEBUG_LOG("You do not have enough money");
                return TotalCost;
            }
            else
                ModifyMoney( -int32(costs) );
        }
    }

    item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
    item->SetState(ITEM_CHANGED, this);

    // reapply mods for total broken and repaired item if equipped
    if(IsEquipmentPos(pos) && !curDurability)
        _ApplyItemMods(item,pos & 255, true);
    return TotalCost;
}

void Player::RepopAtGraveyard()
{
    AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());

    if(zone && zone->flags & 0x1000)                        //Such zones are considered unreachable without flying and the player must be automatically revived
    {
        ResurrectPlayer(0.5f);
        SpawnCorpseBones();
    }

    WorldSafeLocsEntry const *ClosestGrave = NULL;

    // Special handle for battleground maps
    BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());

    if(bg && bg->GetTypeID() == BATTLEGROUND_AB)
        ClosestGrave = ((BattleGroundAB*)bg)->SelectGraveYard(this);
    else
        ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );

    if(ClosestGrave)
    {
        // stop countdown until repop
        m_deathTimer = 0;

        TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());

        if(isDead())                                        // not send if alive, because it used in TeleportTo()
        {
            WorldPacket data(SMSG_SH_POSITION, 4*4);        // show spirit healer position on minimap
            data << ClosestGrave->map_id;
            data << ClosestGrave->x;
            data << ClosestGrave->y;
            data << ClosestGrave->z;
            GetSession()->SendPacket(&data);
        }
    }
}

void Player::JoinedChannel(Channel *c)
{
    m_channels.push_back(c);
}

void Player::LeftChannel(Channel *c)
{
    m_channels.remove(c);
}

void Player::CleanupChannels()
{
    while(!m_channels.empty())
    {
        Channel* ch = *m_channels.begin();
        m_channels.erase(m_channels.begin());               // remove from player's channel list
        ch->Leave(GetGUID(), false);                        // not send to client, not remove from player's channel list
        if (ChannelMgr* cMgr = channelMgr(GetTeam()))
            cMgr->LeftChannel(ch->GetName());               // deleted channel if empty

    }
    sLog.outDebug("Player: channels cleaned up!");
}

void Player::UpdateLocalChannels(uint32 newZone )
{
    if(m_channels.empty())
        return;

    AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
    if(!current_zone)
        return;

    ChannelMgr* cMgr = channelMgr(GetTeam());
    if(!cMgr)
        return;

    std::string current_zone_name = current_zone->area_name[sWorld.GetDBClang()];

    for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
    {
        next = i; ++next;

        // skip non built-in channels
        if(!(*i)->IsConstant())
            continue;

        ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
        if(!ch)
            continue;

        if((ch->flags & 4) == 4)                            // global channel without zone name in pattern
            continue;

        //  new channel
        char new_channel_name_buf[100];
        snprintf(new_channel_name_buf,100,ch->pattern[sWorld.GetDBClang()],current_zone_name.c_str());
        Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);

        if((*i)!=new_channel)
        {
            new_channel->Join(GetGUID(),"");                // will output Changed Channel: N. Name

            // leave old channel
            (*i)->Leave(GetGUID(),false);                   // not send leave channel, it already replaced at client
            std::string name = (*i)->GetName();             // stroe name, (*i)erase in LeftChannel
            LeftChannel(*i);                                // remove from player's channel list
            cMgr->LeftChannel(name);                        // delete if empty
        }
    }
    sLog.outDebug("Player: channels cleaned up!");
}

void Player::LeaveLFGChannel()
{
    for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
    {
        if((*i)->IsLFG())
        {
            (*i)->Leave(GetGUID());
            break;
        }
    }
}

void Player::BroadcastPacketToFriendListers(WorldPacket *packet, bool extern_result, QueryResult *result)
{
    /// this is sent out to those that have the player in their friendlist
    /// (not necessarily those that are in the player's friendlist)
    if(!extern_result)
        result = CharacterDatabase.PQuery("SELECT guid FROM character_social WHERE friend = '%u' AND flags = 0", GetGUIDLow());

    if(!result) return;

    uint32 team              = GetTeam();
    uint32 security          = GetSession()->GetSecurity();
    bool gmInWhoList = sWorld.getConfig(CONFIG_GM_IN_WHO_LIST);
    bool allowTwoSideWhoList = sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_WHO_LIST);

    do
    {
        Field *fields = result->Fetch();
        Player *pFriend = ObjectAccessor::FindPlayer(fields[0].GetUInt64());

        // PLAYER see his team only and PLAYER can't see MODERATOR, GAME MASTER, ADMINISTRATOR characters
        // MODERATOR, GAME MASTER, ADMINISTRATOR can see all
        if( pFriend && pFriend->IsInWorld() &&
            ( pFriend->GetSession()->GetSecurity() > SEC_PLAYER ||
            ( pFriend->GetTeam() == team || allowTwoSideWhoList ) &&
            (security == SEC_PLAYER || gmInWhoList && IsVisibleGloballyFor(pFriend) )))
        {
            pFriend->GetSession()->SendPacket(packet);
        }
    }while( result->NextRow() );

    // note: always deletes the result, even if it was external, use accordingly
    delete result;
}

void Player::UpdateDefense()
{
    if(UpdateSkill(SKILL_DEFENSE))
    {
        // update dependent from defense skill part BlockChanceWithoutMods = 5 + (GetDefenseSkillValue() - getLevel()*5)*0.04);
        UpdateBlockPercentage();
    }
}

uint16 Player::GetDefenseSkillTempBonusValue() const
{
    return GetSkillTempBonusValue(SKILL_DEFENSE) + uint32(GetRatingBonusValue(PLAYER_FIELD_DEFENCE_RATING));
}

void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply, bool affectStats)
{
    if(modGroup >= BASEMOD_END || modType >= MOD_END)
    {
        sLog.outError("ERROR in HandleBaseModValue(): nonexisted BaseModGroup of wrong BaseModType!");
        return;
    }

    float val = 1.0f;

    switch(modType)
    {
        case FLAT_MOD:
            m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
            break;
        case PCT_MOD:
            if(amount <= -100.0f)
                amount = -200.0f;

            val = (100.0f + amount) / 100.0f;
            m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
            break;
    }

    if(!CanModifyStats())
        return;

    switch(modGroup)
    {
        case CRIT_PERCENTAGE:              UpdateCritPercentage(BASE_ATTACK);                          break;
        case BLOCK_PERCENTAGE:             UpdateBlockPercentage();                                    break;
        case DODGE_PERCENTAGE:             UpdateDodgePercentage();                                    break;
        case PARRY_PERCENTAGE:             UpdateParryPercentage();                                    break;
        case RANGED_CRIT_PERCENTAGE:       UpdateCritPercentage(RANGED_ATTACK);                        break;
        case OFFHAND_CRIT_PERCENTAGE:      UpdateCritPercentage(OFF_ATTACK);                           break;
        case SPELL_CRIT_PERCENTAGE:        UpdateAllSpellCritChances();                                break;
        case HOLY_SPELL_CRIT_PERCENTAGE:
        case FIRE_SPELL_CRIT_PERCENTAGE:
        case NATURE_SPELL_CRIT_PERCENTAGE:
        case FROST_SPELL_CRIT_PERCENTAGE:
        case SHADOW_SPELL_CRIT_PERCENTAGE:
        case ARCANE_SPELL_CRIT_PERCENTAGE: UpdateSpellCritChance(GetSpellSchoolByBaseGroup(modGroup)); break;
        case SHIELD_BLOCK_VALUE:

        default:
            break;
    }
}

float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
{
    if(modGroup >= BASEMOD_END || modType > MOD_END)
    {
        sLog.outError("ERROR: trial to access nonexisted BaseModGroup or wrong BaseModType!");
        return 0.0f;
    }

    if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
        return 0.0f;

    return m_auraBaseMod[modGroup][modType];
}

float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
{
    if(modGroup >= BASEMOD_END)
    {
        sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
        return 0.0f;
    }

    if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
        return 0.0f;

    return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
}

uint32 Player::GetShieldBlockValue() const
{
    BaseModGroup modGroup = SHIELD_BLOCK_VALUE;

    float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;

    value = (value < 0) ? 0 : value;

    return uint32(value);
}

uint32 Player::GetSpellSchoolByBaseGroup(BaseModGroup baseGroup) const
{
    if(baseGroup >= BASEMOD_END)
        return MAX_SPELL_SCHOOL;

    uint32 school = MAX_SPELL_SCHOOL;

    switch(baseGroup)
    {
        case SPELL_CRIT_PERCENTAGE:         school = SPELL_SCHOOL_NORMAL;          break;
        case HOLY_SPELL_CRIT_PERCENTAGE:    school = SPELL_SCHOOL_HOLY;            break;
        case FIRE_SPELL_CRIT_PERCENTAGE:    school = SPELL_SCHOOL_FIRE;               break;
        case NATURE_SPELL_CRIT_PERCENTAGE:  school = SPELL_SCHOOL_NATURE;          break;
        case FROST_SPELL_CRIT_PERCENTAGE:   school = SPELL_SCHOOL_FROST;           break;
        case SHADOW_SPELL_CRIT_PERCENTAGE:  school = SPELL_SCHOOL_SHADOW;          break;
        case ARCANE_SPELL_CRIT_PERCENTAGE:  school = SPELL_SCHOOL_ARCANE;          break;

        default:
            break;
    }

    return school;
}

float Player::GetMeleeCritFromAgility()
{
    uint32 level = getLevel();
    uint32 pclass = getClass();

    if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;

    GtChanceToMeleeCritBaseEntry const *critBase  = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
    GtChanceToMeleeCritEntry     const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
    if (critBase==NULL || critRatio==NULL)
        return 0.0f;

    float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
    return crit*100.0f;
}

float Player::GetSpellCritFromIntellect()
{
    uint32 level = getLevel();
    uint32 pclass = getClass();

    if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;

    GtChanceToSpellCritBaseEntry const *critBase  = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
    GtChanceToSpellCritEntry     const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
    if (critBase==NULL || critRatio==NULL)
        return 0.0f;

    float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
    return crit*100.0f;
}

float Player::GetRatingCoefficient(uint16 index) const
{
    uint32 level = getLevel();
    uint32 rating_id = index - PLAYER_FIELD_COMBAT_RATING_1;

    if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;

    GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(rating_id*GT_MAX_LEVEL+level-1);
    if (Rating == NULL)
        return 1.0f;                                        // By default use minimum coefficient (not must be called)

    return Rating->ratio;
}

float Player::GetRatingBonusValue(uint16 index) const
{
    float value = float(GetUInt32Value(index)) / GetRatingCoefficient(index);

    return value;
}

uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
{
    float melee  = GetRatingBonusValue(PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING)*2.0f;
    if (melee>25.0f) melee = 25.0f;
    return uint32 (melee * damage /100.0f);
}

uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
{
    float ranged = GetRatingBonusValue(PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING)*2.0f;
    if (ranged>25.0f) ranged=25.0f;
    return uint32 (ranged * damage /100.0f);
}

uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
{
    float spell = GetRatingBonusValue(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING)*2.0f;
    // In wow script recilience limited to 25%
    if (spell>25.0f)
        spell = 25.0f;
    return uint32 (spell * damage / 100.0f);
}

uint32 Player::GetDotDamageReduction(uint32 damage) const
{
    float spellDot = GetRatingBonusValue(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING);
    // Dot recilience not limited (limit it by 100%)
    if (spellDot > 100.0f)
        spellDot = 100.0f;
    return uint32 (spellDot * damage / 100.0f);
}

float Player::GetExpertiseDodgeOrParryReduction() const
{
    return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
}

float Player::OCTRegenHPPerSpirit()
{
    uint32 level = getLevel();
    uint32 pclass = getClass();

    if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;

    GtOCTRegenHPEntry     const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
    GtRegenHPPerSptEntry  const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
    if (baseRatio==NULL || moreRatio==NULL)
        return 0.0f;

    // Formula from PaperDollFrame script
    float spirit = GetStat(STAT_SPIRIT);
    float baseSpirit = spirit;
    if (baseSpirit>50) baseSpirit = 50;
    float moreSpirit = spirit - baseSpirit;
    float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
    return regen;
}

float Player::OCTRegenMPPerSpirit()
{
    uint32 level = getLevel();
    uint32 pclass = getClass();

    if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;

    GtOCTRegenMPEntry     const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
    GtRegenMPPerSptEntry  const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
    if (baseRatio==NULL || moreRatio==NULL)
        return 0.0f;

    // Formula get from PaperDollFrame script
    float spirit = GetStat(STAT_SPIRIT);
    float baseSpirit = spirit;
    if (baseSpirit>50) baseSpirit = 50;
    float moreSpirit = spirit - baseSpirit;
    float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
    return regen;
}

void Player::ApplyRatingMod(uint16 index, int32 value, bool apply)
{
    ApplyModUInt32Value(index, value, apply);

    float RatingCoeffecient = GetRatingCoefficient(index);
    float RatingChange = 0.0f;

    bool affectStats = CanModifyStats();

    switch (index)
    {
        case PLAYER_FIELD_ALL_WEAPONS_SKILL_RATING:         // Implemended in Unit::RollMeleeOutcomeAgainst
        case PLAYER_FIELD_DEFENCE_RATING:
            UpdateDefenseBonusesMod();
            break;
        case PLAYER_FIELD_DODGE_RATING:
            UpdateDodgePercentage();
            break;
        case PLAYER_FIELD_PARRY_RATING:
            UpdateParryPercentage();
            break;
        case PLAYER_FIELD_BLOCK_RATING:
            UpdateBlockPercentage();
            break;
        case PLAYER_FIELD_MELEE_HIT_RATING:
            RatingChange = value / RatingCoeffecient;
            m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
            break;
        case PLAYER_FIELD_RANGED_HIT_RATING:
            RatingChange = value / RatingCoeffecient;
            m_modRangedHitChance += apply ? RatingChange : -RatingChange;
            break;
        case PLAYER_FIELD_SPELL_HIT_RATING:
            RatingChange = value / RatingCoeffecient;
            m_modSpellHitChance += apply ? RatingChange : -RatingChange;
            break;
        case PLAYER_FIELD_MELEE_CRIT_RATING:
            if(affectStats)
            {
                UpdateCritPercentage(BASE_ATTACK);
                UpdateCritPercentage(OFF_ATTACK);
            }
            break;
        case PLAYER_FIELD_RANGED_CRIT_RATING:
            if(affectStats)
                UpdateCritPercentage(RANGED_ATTACK);
            break;
        case PLAYER_FIELD_SPELL_CRIT_RATING:
            if(affectStats)
                UpdateAllSpellCritChances();
            break;
        case PLAYER_FIELD_HIT_TAKEN_MELEE_RATING:           // Implemended in Unit::MeleeMissChanceCalc
        case PLAYER_FIELD_HIT_TAKEN_RANGED_RATING:
            break;
        case PLAYER_FIELD_HIT_TAKEN_SPELL_RATING:           // Implemended in Unit::SpellMissChanceCalc
            break;
        case PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING:          // Implemended in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
        case PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING:
            break;
        case PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING:          // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
            break;
        case PLAYER_FIELD_MELEE_HASTE_RATING:
            RatingChange = value / RatingCoeffecient;
            ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
            ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
            break;
        case PLAYER_FIELD_RANGED_HASTE_RATING:
            RatingChange = value / RatingCoeffecient;
            ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
            break;
        case PLAYER_FIELD_SPELL_HASTE_RATING:
            RatingChange = value / RatingCoeffecient;
            ApplyCastTimePercentMod(RatingChange,apply);
            break;
        case PLAYER_FIELD_MELEE_WEAPON_SKILL_RATING:        // Implemended in Unit::RollMeleeOutcomeAgainst
        case PLAYER_FIELD_OFFHAND_WEAPON_SKILL_RATING:
        case PLAYER_FIELD_RANGED_WEAPON_SKILL_RATING:
            break;
        case PLAYER_FIELD_EXPERTISE_RATING:
            if(affectStats)
                UpdateExpertise();
            break;
    }
}

void Player::SetRegularAttackTime()
{
    ItemPrototype const *proto = 0;
    uint32 InvType = 0;

    //check for mainhand weapon
    Item *tmpitem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
    if(tmpitem && !tmpitem->IsBroken())
    {
        proto = tmpitem->GetProto();
        InvType = proto->InventoryType;
        if((InvType == INVTYPE_WEAPON || InvType == INVTYPE_2HWEAPON || InvType == INVTYPE_WEAPONMAINHAND )&& proto->Delay)
            SetAttackTime(BASE_ATTACK, proto->Delay);
        else
            SetAttackTime(BASE_ATTACK, BASE_ATTACK_TIME);
    }

    //check for offhand weapon
    tmpitem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
    if(tmpitem && !tmpitem->IsBroken())
    {
        proto = tmpitem->GetProto();
        InvType = proto->InventoryType;
        if((InvType == INVTYPE_WEAPON || InvType == INVTYPE_WEAPONOFFHAND) && proto->Delay)
            SetAttackTime(OFF_ATTACK, proto->Delay);
        else
            SetAttackTime(OFF_ATTACK, BASE_ATTACK_TIME);
    }

    //check for ranged weapons
    tmpitem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
    if(tmpitem && !tmpitem->IsBroken())
    {
        proto = tmpitem->GetProto();
        InvType = proto->InventoryType;
        if((InvType == INVTYPE_THROWN || InvType == INVTYPE_RANGED) && proto->Delay )
            SetAttackTime(RANGED_ATTACK, proto->Delay);
        else
            SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
    }
}

//skill+1, checking for max value
bool Player::UpdateSkill(uint32 skill_id)
{
    if(!skill_id)
        return false;

    uint16 i=0;
    for (; i < PLAYER_MAX_SKILLS; i++)
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
            break;

    if(i>=PLAYER_MAX_SKILLS)
        return false;

    uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
    uint32 value = SKILL_VALUE(data);
    uint32 max = SKILL_MAX(data);

    if ((!max) || (!value) || (value >= max))
        return false;

    if (value*512 < max*urand(0,512))
    {
        SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),data+MAKE_SKILL_VALUE(1,0));
        return true;
    }

    return false;
}

inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
{
    if ( SkillValue >= GrayLevel )
        return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
    if ( SkillValue >= GreenLevel )
        return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
    if ( SkillValue >= YellowLevel )
        return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
    return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
}

bool Player::UpdateCraftSkill(uint32 spellid)
{
    sLog.outDebug("UpdateCraftSkill spellid %d", spellid);

    SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(spellid);
    if ( !pAbility ) return false;

    uint32 SkillId = pAbility->skillId;
    if ( !SkillId ) return false;

    uint32 SkillValue = GetBaseSkillValue(SkillId);

    // Alchemy Discoveries here
    SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
    if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
    {
        if(uint32 discoveredSpell = GetSkillDiscoverySpell(pAbility->skillId, spellid, this))
            learnSpell(discoveredSpell);
    }

    return UpdateSkillPro(pAbility->skillId, SkillGainChance(SkillValue,
        pAbility->max_value,
        (pAbility->max_value + pAbility->min_value)/2,
        pAbility->min_value));
}

bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
{
    sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);

    // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
    switch (SkillId)
    {
        case SKILL_HERBALISM:
        case SKILL_LOCKPICKING:
        case SKILL_JEWELCRAFTING:
            return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator);
        case SKILL_SKINNING:
            if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
                return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator);
            else
                return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)) );
        case SKILL_MINING:
            if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
                return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator);
            else
                return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)) );
    }
    return false;
}

bool Player::UpdateFishingSkill()
{
    sLog.outDebug("UpdateFishingSkill");

    uint32 SkillValue = GetBaseSkillValue(SKILL_FISHING);

    int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);

    return UpdateSkillPro(SKILL_FISHING,chance*10);
}

bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance)
{
    sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
    if ( !SkillId )
        return false;

    if(Chance <= 0)                                         // speedup in 0 chance case
    {
        sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
        return false;
    }

    uint16 i=0;
    for (; i < PLAYER_MAX_SKILLS; i++)
        if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
    if ( i >= PLAYER_MAX_SKILLS )
        return false;

    uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
    uint16 SkillValue = SKILL_VALUE(data);
    uint16 MaxValue   = SKILL_MAX(data);

    if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
        return false;

    int32 Roll = irand(1,1000);

    if ( Roll <= Chance )
    {
        SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),data + MAKE_SKILL_VALUE(1,0));
        sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
        return true;
    }

    sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
    return false;
}

void Player::UpdateWeaponSkill (WeaponAttackType attType)
{
    // no skill gain in pvp
    Unit *pVictim = getVictim();
    if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
        return;

    if(IsInFeralForm())
        return;                                             // always maximized SKILL_FERAL_COMBAT in fact

    if(m_form == FORM_TREE)
        return;                                             // use weapon but not skill up

    switch(attType)
    {
        case BASE_ATTACK:
        {
            Item *tmpitem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);

            if (!tmpitem || tmpitem->IsBroken() || !IsUseEquipedWeapon(true))
                UpdateSkill(SKILL_UNARMED);
            else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
                UpdateSkill(tmpitem->GetSkill());

        };break;
        case OFF_ATTACK:
        {
            Item *tmpitem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);

            if (tmpitem && tmpitem->GetProto()->Class == ITEM_CLASS_WEAPON && !tmpitem->IsBroken() && IsUseEquipedWeapon(false))
                UpdateSkill(tmpitem->GetSkill());
        };break;
        case RANGED_ATTACK:
        {
            Item* tmpitem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);

            if (tmpitem && tmpitem->GetProto()->Class == ITEM_CLASS_WEAPON && !tmpitem->IsBroken() && IsUseEquipedWeapon(false))
                UpdateSkill(tmpitem->GetSkill());
        };break;
    }
}

void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
{
    switch(outcome)
    {
        case MELEE_HIT_CRIT:
        case MELEE_HIT_DODGE:
        case MELEE_HIT_PARRY:
        case MELEE_HIT_BLOCK:
        case MELEE_HIT_BLOCK_CRIT:
            return;

        default:
            break;
    }

    uint32 plevel = getLevel();                             // if defense than pVictim == attacker
    uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
    uint32 moblevel = pVictim->getLevel();
    if(moblevel < greylevel)
        return;

    if (moblevel > plevel + 5)
        moblevel = plevel + 5;

    uint32 lvldif = moblevel - greylevel;
    if(lvldif < 3)
        lvldif = 3;

    uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
    if(skilldif <= 0)
        return;

    float chance = float(3 * lvldif * skilldif) / plevel;
    if(!defence)
    {
        if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
            chance *= 0.1 * GetStat(STAT_INTELLECT);
    }

    chance = chance < 1.0 ? 1.0 : chance;                   //minimum chance to increase skill is 1%

    if(roll_chance_f(chance))
    {
        if(defence)
            UpdateDefense();
        else
            UpdateWeaponSkill(attType);
    }
    else
        return;
}

void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
{
    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
    {
        uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
        uint16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
        uint16 perm_bonus = SKILL_PERM_BONUS(bonus_val);

        if(talent)                                          // permanent bonus stored in high part
            SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
        else                                                // temporary/item bonus stored in low part
            SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
        return;
    }
}

void Player::UpdateMaxSkills()
{
    uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();

    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
        if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
    {
        uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
        if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
            continue;
        uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
        uint32 max = SKILL_MAX(data);
        uint32 val = SKILL_VALUE(data);

        // update only level dependent max skill values
        if(max!=1 && max != maxconfskill)
        {
            uint32 max_Skill = GetMaxSkillValueForLevel();
            SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,max_Skill));
        }
    }
}

void Player::UpdateSkillsToMaxSkillsForLevel()
{
    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
        if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
    {
        uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
        if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
            continue;
        uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));

        uint32 max = SKILL_MAX(data);

        if(max > 1)
            SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));

        if(pskill == SKILL_DEFENSE)
        {
            UpdateBlockPercentage();
        }
    }
}

// This functions sets a skill line value (and adds if doesn't exist yet)
// To "remove" a skill line, set it's values to zero
void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
{
    if(!id) return;
    uint16 i=0;
    for (; i < PLAYER_MAX_SKILLS; i++)
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;

    if(i<PLAYER_MAX_SKILLS)                                 //has skill
    {
        if(currVal)
            SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
        else                                                //remove
        {
            // clear skill fields
            SetUInt64Value(PLAYER_SKILL_INDEX(i),0);
            SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
            SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);

            // remove spells that depend on this skill when removing the skill
            for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
            {
                ++next;
                if(itr->second->state == PLAYERSPELL_REMOVED) continue;
                SkillLineAbilityEntry const *ability = sSkillLineAbilityStore.LookupEntry(itr->first);
                if (ability && ability->skillId == id)
                {
                    // this may remove more than one spell (dependants)
                    removeSpell(itr->first);
                    next = m_spells.begin();
                }
            }
        }
    }
    else if(currVal)                                        //add
    {

        for (i=0; i < PLAYER_MAX_SKILLS; i++)
            if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
        {
            SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
            if(!pSkill)
            {
                sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
                return;
            }
            // enable unlearn button for primary professions only
            if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
                SetUInt32Value(PLAYER_SKILL_INDEX(i), id | (1 << 16));
            else
                SetUInt32Value(PLAYER_SKILL_INDEX(i), id);
            SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));

            // apply skill bonuses
            SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);

            // temporary bonuses
            AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
            for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
                if ((*i)->GetModifier()->m_miscvalue == int32(id))
                    (*i)->ApplyModifier(true);

            // permanent bonuses
            AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
            for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
                if ((*i)->GetModifier()->m_miscvalue == int32(id))
                    (*i)->ApplyModifier(true);

            return;
        }
    }
}

bool Player::HasSkill(uint32 skill) const
{
    if(!skill)return false;
    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
    {
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
        {
            return true;
        }
    }
    return false;
}

uint16 Player::GetSkillValue(uint32 skill) const
{
    if(!skill)
        return 0;

    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
    {
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
        {
            uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));

            int16 result = int16(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)))
                + SKILL_TEMP_BONUS(bonus) + SKILL_PERM_BONUS(bonus));
            return result < 0 ? 0 : result;
        }
    }
    return 0;
}

uint16 Player::GetMaxSkillValue(uint32 skill) const
{
    if(!skill)return 0;
    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
    {
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
        {
            return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)))
                +SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
        }
    }
    return 0;
}

uint16 Player::GetPureMaxSkillValue(uint32 skill) const
{
    if(!skill)return 0;
    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
    {
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
        {
            return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
        }
    }
    return 0;
}

uint16 Player::GetBaseSkillValue(uint32 skill) const
{
    if(!skill)return 0;
    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
    {
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
        {
            return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)))
                +SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
        }
    }
    return 0;
}

uint16 Player::GetPureSkillValue(uint32 skill) const
{
    if(!skill)return 0;
    for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
    {
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
        {
            return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
        }
    }
    return 0;
}

uint16 Player::GetSkillTempBonusValue(uint32 skill) const
{
    if(!skill)
        return 0;

    for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
    {
        if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
        {
            int16 result = SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
            return result < 0 ? 0 : result;
        }
    }

    return 0;
}

void Player::SendInitialActionButtons()
{
    sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );

    WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
    for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
    {
        ActionButtonList::const_iterator itr = m_actionButtons.find(button);
        if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
        {
            data << uint16(itr->second.action);
            data << uint8(itr->second.misc);
            data << uint8(itr->second.type);
        }
        else
        {
            data << uint32(0);
        }
    }

    GetSession()->SendPacket( &data );
    sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
}

void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
{
    if(button >= MAX_ACTION_BUTTONS)
    {
        sLog.outError( "Action %u not added into button %u for player %s: button must be < 120", action, button, GetName() );
        return;
    }

    // check cheating with adding non-known spells to action bar
    if(type==ACTION_BUTTON_SPELL)
    {
        if(!sSpellStore.LookupEntry(action))
        {
            sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
            return;
        }

        if(!HasSpell(action))
        {
            sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
            return;
        }
    }

    if (m_actionButtons.find(button)==m_actionButtons.end())
    {                                                       // just add new button
        m_actionButtons[button] = ActionButton(action,type,misc);
    } else
    {                                                       // change state of current button
        ActionButtonUpdateState uState = m_actionButtons[button].uState;
        m_actionButtons[button] = ActionButton(action,type,misc);
        if (uState != ACTIONBUTTON_NEW) m_actionButtons[button].uState = ACTIONBUTTON_CHANGED;
    };

    sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
}

void Player::removeActionButton(uint8 button)
{
    m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
    sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
}

void Player::SetDontMove(bool dontMove)
{
    m_dontMove = dontMove;
}

bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
{
    // prevent crash when a bad coord is sent by the client
    if(!MaNGOS::IsValidMapCoord(x,y))
    {
        sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
        return false;
    }

    Map *m = MapManager::Instance().GetMap(GetMapId(), this);

    const float old_x = GetPositionX();
    const float old_y = GetPositionY();
    const float old_r = GetOrientation();

    if( teleport || old_x != x || old_y != y || old_r != orientation )
    {
        // remove at movement non-move stealth aura
        if(GetVisibility()==VISIBILITY_GROUP_STEALTH)
            RemoveAurasDueToSpell(20580);

        // remove death simulation at move
        if(hasUnitState(UNIT_STAT_DIED))
            RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);

        // move and update visible state if need
        m->PlayerRelocation(this, x, y, z, orientation);

        // reread after Map::Relocation
        m = MapManager::Instance().GetMap(GetMapId(), this);
        x = GetPositionX();
        y = GetPositionY();
        z = GetPositionZ();
    }

    // code block for underwater state update
    {
        float water_z  = m->GetWaterLevel(x,y);
        float height_z = m->GetHeight(x,y,z, false);        // use .map base surface height
        uint8 flag1    = m->GetTerrainType(x,y);

        //!Underwater check, not in water if underground or above water level
        if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
            m_isunderwater &= 0x7A;
        else if ((z < (water_z - 2)) && (flag1 & 0x01))
            m_isunderwater |= 0x01;

        //!in lava check, anywhere under lava level
        if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
            m_isunderwater |= 0x80;
    }

    CheckExploreSystem();

    // group update
    SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);

    return true;
}

void Player::SaveRecallPosition()
{
    m_recallMap = GetMapId();
    m_recallX = GetPositionX();
    m_recallY = GetPositionY();
    m_recallZ = GetPositionZ();
    m_recallO = GetOrientation();
}

void Player::SendMessageToSet(WorldPacket *data, bool self)
{
    MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self);
}

void Player::SendMessageToOwnTeamSet(WorldPacket *data, bool self)
{
    MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self,true);
}

void Player::SendDirectMessage(WorldPacket *data)
{
    GetSession()->SendPacket(data);
}

void Player::CheckExploreSystem()
{
    if (!isAlive())
        return;

    if (isInFlight())
        return;

    uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
    if(areaFlag==0xffff)return;
    int offset = areaFlag / 32;

    if(offset >= 64)
    {
        sLog.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 64 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
        return;
    }

    uint32 val = (uint32)(1 << (areaFlag % 32));
    uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);

    if( !(currFields & val) )
    {
        SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));

        AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
        if(!p)
        {
            sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
        }
        else if(p->area_level > 0)
        {
            uint32 area = p->ID;
            if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
            {
                SendExplorationExperience(area,0);
            }
            else
            {
                int32 diff = int32(getLevel()) - p->area_level;
                uint32 XP = 0;
                if (diff < -5)
                {
                    XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
                }
                else if (diff > 5)
                {
                    int32 exploration_percent = (100-((diff-5)*5));
                    if (exploration_percent > 100)
                        exploration_percent = 100;
                    else if (exploration_percent < 0)
                        exploration_percent = 0;

                    XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
                }
                else
                {
                    XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
                }

                GiveXP( XP, NULL );
                SendExplorationExperience(area,XP);
            }
            sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
        }
    }
}

uint32 Player::TeamForRace(uint8 race)
{
    ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
    if(!rEntry)
    {
        sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
        return ALLIANCE;
    }

    switch(rEntry->TeamID)
    {
        case 7: return ALLIANCE;
        case 1: return HORDE;
    }

    sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
    return ALLIANCE;
}

uint32 Player::getFactionForRace(uint8 race)
{
    ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
    if(!rEntry)
    {
        sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
        return 0;
    }

    return rEntry->FactionID;
}

void Player::setFactionForRace(uint8 race)
{
    m_team = TeamForRace(race);
    setFaction( getFactionForRace(race) );
}

void Player::UpdateReputation() const
{
    sLog.outDetail( "WORLD: Player::UpdateReputation" );

    for(FactionsList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
    {
        SendSetFactionStanding(&(itr->second));
    }
}

void Player::SendSetFactionStanding(const Faction* faction) const
{
    if(faction->Flags & FACTION_FLAG_VISIBLE)               //If faction is visible then update it
    {
        WorldPacket data(SMSG_SET_FACTION_STANDING, (12));  // last check 2.0.10
        data << (uint32) 1;
        data << (uint32) faction->ReputationListID;
        data << (uint32) faction->Standing;
        GetSession()->SendPacket(&data);
    }
    /*
    Packet SMSG.SET_FACTION_STANDING (292), len: 54
    0000: 24 01 06 00 00 00 13 00 00 00 8f 21 00 00 0b 00 : $..........!....
    0010: 00 00 91 0c 00 00 31 00 00 00 91 0c 00 00 14 00 : ......1.........
    0020: 00 00 22 12 00 00 15 00 00 00 67 45 00 00 12 00 : ..".......gE....
    0030: 00 00 a4 0c 00 00 -- -- -- -- -- -- -- -- -- -- : ......
    */
    //changed in 2.0.x:
    /*uint32 count;
    for (uint32 i = 0; i < count; i++)
    {
        uint32 ReputationListID;
        uint32 Standing;
    }*/
}

void Player::SendInitialReputations()
{
    WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
    data << uint32 (0x00000080);

    RepListID a = 0;

    for (FactionsList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
    {
        // fill in absent fields
        for (; a != itr->first; a++)
        {
            data << uint8  (0x00);
            data << uint32 (0x00000000);
        }

        // fill in encountered data
        data << uint8  (itr->second.Flags);
        data << uint32 (itr->second.Standing);

        ++a;
    }

    // fill in absent fields
    for (; a != 128; a++)
    {
        data << uint8  (0x00);
        data << uint32 (0x00000000);
    }

    GetSession()->SendPacket(&data);
}

bool Player::IsFactionAtWar(const FactionEntry *factionEntry) const
{
    FactionsList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
    if (itr != m_factions.end())
    {
        if((itr->second.Flags & FACTION_FLAG_AT_WAR) != 0)
            return true;
    }
    return false;
}

void Player::SetFactionAtWar(uint32 repListID, bool atWar)
{
    FactionsList::iterator itr = m_factions.find(repListID);
    if (itr != m_factions.end())
        SetFactionAtWar(&itr->second,atWar);
}

void Player::SetFactionAtWar(Faction* faction, bool atWar)
{
    // not allow declare war to own faction
    if(atWar && ((faction->Flags & FACTION_FLAG_OWN_TEAM) != 0))
        return;

    // already set
    if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
        return;

    if( atWar )
        faction->Flags |= FACTION_FLAG_AT_WAR;
    else
        faction->Flags &= ~FACTION_FLAG_AT_WAR;

    faction->Changed = true;
}

void Player::SetFactionInactive(uint32 repListID, bool inactive)
{
    FactionsList::iterator itr = m_factions.find(repListID);
    if (itr != m_factions.end())
    {
                                                            // already set
        if(((itr->second.Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
            return;

        if(inactive)
            itr->second.Flags |= FACTION_FLAG_INACTIVE;
        else
            itr->second.Flags &= ~FACTION_FLAG_INACTIVE;

        itr->second.Changed = true;
    }
}

void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
{
    FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);

    if(!factionTemplateEntry)
        return;

    FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
    if(!factionEntry)
        return;

    if(factionEntry->reputationListID >= 0)
        SetFactionVisible(factionEntry->reputationListID);
}

void Player::SetFactionVisible(uint32 repListID)
{
    FactionsList::iterator itr = m_factions.find(repListID);
    if (itr != m_factions.end())
    {
                                                            // already set
        if(((itr->second.Flags & FACTION_FLAG_VISIBLE) != 0))
            return;

        itr->second.Flags |= FACTION_FLAG_VISIBLE;
        itr->second.Changed = true;

        // make faction visible in reputation list at client
        WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
        data << repListID;
        GetSession()->SendPacket(&data);
    }
}

void Player::SetInitialFactions()
{
    Faction newFaction;
    FactionEntry const *factionEntry = NULL;

    for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
    {
        factionEntry = sFactionStore.LookupEntry(i);

        if( factionEntry && (factionEntry->reputationListID >= 0))
        {
            newFaction.ID = factionEntry->ID;
            newFaction.ReputationListID = factionEntry->reputationListID;
            newFaction.Standing = 0;
            newFaction.Flags = 0x0;
            newFaction.Changed = true;

            // show(1) and disable AtWar button(16) of own team factions
            if( GetTeam() == factionEntry->team )
                newFaction.Flags = FACTION_FLAG_OWN_TEAM | FACTION_FLAG_VISIBLE;

            //If the faction is Hostile or Hated  of my one we are at war!
            if(GetBaseReputationRank(factionEntry) <= REP_HOSTILE)
                newFaction.Flags |= FACTION_FLAG_AT_WAR;

            m_factions[newFaction.ReputationListID] = newFaction;
        }
    }
}

int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
{
    if (!factionEntry)
        return 0;

    uint32 Race = getRace();
    for (int i=0; i < 4; i++)
    {
        if ( factionEntry->BaseRepMask[i] & (1 << (Race-1)))
            return factionEntry->BaseRepValue[i];
    }

    // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepMask[i]==0
    return 0;
}

int32 Player::GetReputation(uint32 faction_id) const
{
    FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);

    if (!factionEntry)
    {
        sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
        return 0;
    }

    return GetReputation(factionEntry);
}

int32 Player::GetReputation(const FactionEntry *factionEntry) const
{
    // Faction without recorded reputation. Just ignore.
    if(!factionEntry)
        return 0;

    FactionsList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
    if (itr != m_factions.end())
        return GetBaseReputation(factionEntry) + itr->second.Standing;

    return 0;
}

ReputationRank Player::GetReputationRank(uint32 faction) const
{
    FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
    if(!factionEntry)
        return MIN_REPUTATION_RANK;

    return GetReputationRank(factionEntry);
}

ReputationRank Player::ReputationToRank(int32 standing) const
{
    int32 Limit = Reputation_Cap + 1;
    for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
    {
        Limit -= ReputationRank_Length[i];
        if (standing >= Limit )
            return ReputationRank(i);
    }
    return MIN_REPUTATION_RANK;
}

ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
{
    int32 Reputation = GetReputation(factionEntry);
    return ReputationToRank(Reputation);
}

ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
{
    int32 Reputation = GetBaseReputation(factionEntry);
    return ReputationToRank(Reputation);
}

bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
{
    FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);

    if(!factionTemplateEntry)
    {
        sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
        return false;
    }

    FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);

    // Faction without recorded reputation. Just ignore.
    if(!factionEntry)
        return false;

    return ModifyFactionReputation(factionEntry, DeltaReputation);
}

bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
{
    SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
    if (flist)
    {
        bool res = false;
        for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
        {
            FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
            if(factionEntryCalc)
                res = ModifyOneFactionReputation(factionEntryCalc, standing);
        }
        return res;
    }
    else
        return ModifyOneFactionReputation(factionEntry, standing);
}

bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
{
    FactionsList::iterator itr = m_factions.find(factionEntry->reputationListID);
    if (itr != m_factions.end())
    {
        int32 BaseRep = GetBaseReputation(factionEntry);
        int32 new_rep = BaseRep + itr->second.Standing + standing;

        if (new_rep > Reputation_Cap)
            new_rep = Reputation_Cap;
        else
        if (new_rep < Reputation_Bottom)
            new_rep = Reputation_Bottom;

        if(ReputationToRank(new_rep) <= REP_HOSTILE)
            SetFactionAtWar(&itr->second,true);

        itr->second.Standing = new_rep - BaseRep;
        itr->second.Flags |= FACTION_FLAG_VISIBLE;
        itr->second.Changed = true;

        SendSetFactionStanding(&(itr->second));
        return true;
    }
    return false;
}

//Calculate total reputation percent player gain with quest/creature level
int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
{
    // for grey creature kill received 20%, in other case 100.
    int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;

    int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);

    percent += rep > 0 ? repMod : -repMod;

    if(percent <=0)
        return 0;

    return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
}

//Calculates how many reputation points player gains in victim's enemy factions
void Player::RewardReputation(Unit *pVictim, float rate)
{
    if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
        return;

    ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(pVictim->GetEntry());

    if(!Rep)
        return;

    if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
    {
        int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
        donerep1 = int32(donerep1*rate);
        FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
        uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
        if(factionEntry1 && current_reputation_rank1 <= Rep->reputration_max_cap1)
            ModifyFactionReputation(factionEntry1, donerep1);

        // Wiki: Team factions value divided by 2
        if(Rep->is_teamaward1)
        {
            FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
            if(team1_factionEntry)
                ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
        }
    }

    if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
    {
        int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
        donerep2 = int32(donerep2*rate);
        FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
        uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
        if(factionEntry2 && current_reputation_rank2 <= Rep->reputration_max_cap2)
            ModifyFactionReputation(factionEntry2, donerep2);

        // Wiki: Team factions value divided by 2
        if(Rep->is_teamaward2)
        {
            FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
            if(team2_factionEntry)
                ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
        }
    }
}

//Calculate how many reputation points player gain with the quest
void Player::RewardReputation(Quest const *pQuest)
{
    // quest reputation reward/loss
    for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
    {
        if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
        {
            int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
            FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
            if(factionEntry)
                ModifyFactionReputation(factionEntry, rep);
        }
    }

    // TODO: implement reputation spillover
}

void Player::UpdateArenaFields(void)
{
    /* arena calcs go here */
}

void Player::UpdateHonorFields(bool force)
{
    /// called when rewarding honor and at each save
    uint32 today = uint32(time(NULL) / DAY) * DAY;

    if ((m_honorPending && m_lastHonorDate < today) || force)
    {
        // if we have pending honor it either got added today or yesterday
        // if the last was added yesterday then this is the first update after midnight

        // update yesterday's contribution
        SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, (uint32)(m_honorPending*10));
        // add the pending honor points, a day has passed
        SetHonorPoints(GetHonorPoints()+uint32(m_honorPending));
        // this is the first update today, reset today's contribution and pending honor
        SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
        m_honorPending = 0;
    }

    uint16 kills_today = GetUInt32Value(PLAYER_FIELD_KILLS) & 0xFFFF;
    if ((kills_today && m_lastKillDate < today) || force)
    {
        // if we have pending kills they were done today or yesterday
        // if the last was done yesterday then this is the first update after midnight

        if(sWorld.getConfig(CONFIG_HONOR_KILL_LIMIT))
        {
            // clear all of today's kills, they will be flushed from the DB on next save
            m_killsPerPlayer.clear();
            m_flushKills = true;
        }

        // this is the first update today, kills_today become yeseterday's kills
        SetUInt32Value(PLAYER_FIELD_KILLS, kills_today << 16);
    }
}

///Calculate the amount of honor gained based on the victim
///and the size of the group for which the honor is divided
///An exact honor value can also be given (overriding the calcs)
bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
{
    uint64 victim_guid = 0;
    uint32 now = time(NULL);
    UpdateHonorFields();

    // do not reward honor in arenas
    if(InBattleGround() && GetBattleGround() && GetBattleGround()->isArena())
        return false;

    if(honor <= 0)
    {
        if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
            return false;

        victim_guid = uVictim->GetGUID();

        if( uVictim->GetTypeId() == TYPEID_PLAYER )
        {
            Player *pVictim = (Player *)uVictim;

            if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
                return false;

            float f = 1;                                    //need for total kills (?? need more info)
            uint32 k_grey = 0;
            uint32 k_level = getLevel();
            uint32 v_level = pVictim->getLevel();
            if(k_level <= 5)
                k_grey = 0;
            else if( k_level <= 39 )
                k_grey = k_level - 5 - k_level/10;
            else
                k_grey = k_level - 1 - k_level/5;

            if(v_level<=k_grey)
                return false;

            float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));

            int32 v_rank =1;                                //need more info

            honor = ((f * diff_level * (190 + v_rank*10))/6);
            honor *= ((float)k_level) / 70.0f;              //factor of dependence on levels of the killer

            uint8 limit = sWorld.getConfig(CONFIG_HONOR_KILL_LIMIT);
            if(limit)
            {
                KillInfo &info = m_killsPerPlayer[uVictim->GetGUIDLow()];
                // gradually decrease the honor for subsequent kills
                // no honor reward for killing a player more than 'limit' times per day
                honor *= (float)(limit - info.count) / (float)limit;
                // if the kill is not present in the DB keep in new state so it will be insterted
                // otherwise adding a kill means it will need to be updated
                if(info.state != KILL_NEW)
                    info.state = KILL_CHANGED;

                // count the number of times a certain player was killed in one day
                if(info.count < limit)
                    ++info.count;
            }

            // count the number of playerkills in one day
            ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
            // and those in a lifetime
            ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);

            m_lastKillDate = now;
            m_saveKills = true;
        }
        else
        {
            Creature *cVictim = (Creature *)uVictim;

            if (!cVictim->isRacialLeader())
                return false;

            honor = 100;                                    // ??? need more info
        }
    }

    if (uVictim != NULL)
        honor *= sWorld.getRate(RATE_HONOR);
    if(groupsize > 1)
        honor /= groupsize;

    float approx_honor = honor * (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor

    WorldPacket data(SMSG_PVP_CREDIT,4+8);
    data << (uint32) approx_honor*10;
    data << (uint64) victim_guid;
    GetSession()->SendPacket(&data);

    m_lastHonorDate = now;
    m_honorPending += honor;

    ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, (uint32)(approx_honor*10), true);
    return true;
}

uint32 Player::GetGuildIdFromDB(uint64 guid)
{
    std::ostringstream ss;
    ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
    QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
    if( result )
    {
        uint32 v = result->Fetch()[0].GetUInt32();
        delete result;
        return v;
    }
    else
        return 0;
}

uint32 Player::GetRankFromDB(uint64 guid)
{
    std::ostringstream ss;
    ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
    QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
    if( result )
    {
        uint32 v = result->Fetch()[0].GetUInt32();
        delete result;
        return v;
    }
    else
        return 0;
}

uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
{
    // need fix it!
    QueryResult *result = CharacterDatabase.PQuery("SELECT arenateamid FROM arena_team_member WHERE guid='%u'", GUID_LOPART(guid));
    if(result)
    {
        // init id to 0, check the arena type before assigning a value to id
        uint32 id = 0;
        do
        {
            QueryResult *result2 = CharacterDatabase.PQuery("SELECT type FROM arena_team WHERE arenateamid='%u'", id);
            if(result2)
            {
                uint8 dbtype = (*result2)[0].GetUInt32();
                delete result2;
                if(dbtype == type)
                {
                    // if the type matches, we've found the id
                    id = (*result)[0].GetUInt32();
                    break;
                }
            }
        } while(result->NextRow());
        delete result;
        return id;
    }
    // no arenateam for the specified guid, return 0
    return 0;
}

uint32 Player::GetZoneIdFromDB(uint64 guid)
{
    std::ostringstream ss;

    ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
    QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
    if (!result)
        return 0;
    Field* fields = result->Fetch();
    uint32 zone = fields[0].GetUInt32();
    delete result;

    if (!zone)
    {
        // stored zone is zero, use generic and slow zone detection
        ss.str("");
        ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
        result = CharacterDatabase.Query(ss.str().c_str());
        if( !result )
            return 0;
        fields = result->Fetch();
        uint32 map  = fields[0].GetUInt32();
        float posx = fields[1].GetFloat();
        float posy = fields[2].GetFloat();
        delete result;

        zone = MapManager::Instance().GetZoneId(map,posx,posy);

        ss.str("");
        ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
        CharacterDatabase.Execute(ss.str().c_str());
    }

    return zone;
}

void Player::UpdateArea(uint32 newArea)
{
    // FFA_PVP flags are area and not zone id dependent
    // so apply them accordingly
    m_areaUpdateId    = newArea;

    AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);

    if(area && (area->flags & 0x80))
    {
        if(!isGameMaster())
            SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
    }
    else
    {
        // remove ffa flag only if not ffapvp realm
        // removal in sanctuaries and capitals is handled in zone update
        if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
            RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
    }

    // unmount if enter in this subzone
    if( newArea == 35)
        RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
}

void Player::UpdateZone(uint32 newZone)
{
    m_zoneUpdateId    = newZone;
    m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;

    // zone changed, so area changed as well, update it
    UpdateArea(GetAreaId());

    AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
    if(!zone)
        return;

    if (sWorld.getConfig(CONFIG_WEATHER))
    {
        Weather *wth = sWorld.FindWeather(zone->ID);
        if(wth)
        {
            wth->SendWeatherUpdateToPlayer(this);
        }
        else
        {
            if(!sWorld.AddWeather(zone->ID))
            {
                // send fine weather packet to remove old zone's weather
                Weather::SendFineWeatherUpdateToPlayer(this);
            }
        }
    }

    pvpInfo.inHostileArea =
        GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
        GetTeam() == HORDE    && zone->team == AREATEAM_ALLY  ||
        sWorld.IsPvPRealm()   && zone->team == AREATEAM_NONE;

    if(pvpInfo.inHostileArea)                               // in hostile area
    {
        if(!IsPvP() || pvpInfo.endTimer != 0)
            UpdatePvP(true, true);
    }
    else                                                    // in friendly area
    {
        if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
            pvpInfo.endTimer = time(0);                     // start toggle-off
    }

    // zonetype is flags
    // flags & 0x00000001   (1)     - snow (only Dun Morogh, Naxxramas, Razorfen Downs and Winterspring)
    // flags & 0x00000002   (2)     - unknown, (only Naxxramas and Razorfen Downs)
    // flags & 0x00000004   (4)     - On Map Dungeon
    // flags & 0x00000008   (8)     - slave capital city flag?
    // flags & 0x00000010   (16)    - unknown
    // flags & 0x00000020   (32)    - slave capital city flag?
    // flags & 0x00000040   (64)    - many zones have this flag
    // flags & 0x00000080   (128)   - arena
    // flags & 0x00000100   (256)   - main capital city flag
    // flags & 0x00000200   (512)   - only for one zone named "City" (where it located?)
    // flags & 0x00000400   (1024)  - outland zones? (only Eye of the Storm not have this flag, but have 0x00004000 flag)
    // flags & 0x00000800   (2048)  - sanctuary area (PvP disabled)
    // flags & 0x00001000   (4096)  - only Netherwing Ledge, Socrethar's Seat, Tempest Keep, The Arcatraz, The Botanica, The Mechanar
    // flags & 0x00002000   (8192)  - not used now (no area/zones with this flag set) ...
    // flags & 0x00004000   (16384) - outland zones? (only Circle of Blood Arena not have this flag, but have 0x00000400 flag)
    // flags & 0x00008000   (32768) - pvp objective area?

    if((zone->flags & 0x800) != 0 || (GetAreaId() == 976) || (GetAreaId() == 35) || (GetAreaId() == 392) || (GetAreaId() == 2255))                          // in sanctuary
    {
        UpdatePvP(false, true);                             // i'm right? need disable PvP in this area...

        if(sWorld.IsFFAPvPRealm())
            RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
    }

    if((zone->flags & 0x100) != 0)                          // in capital city
    {
        SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
        SetRestType(REST_TYPE_IN_CITY);
        InnEnter(time(0),GetMapId(),0,0,0);

        if(sWorld.IsFFAPvPRealm())
            RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
    }
    else                                                    // anywhere else
    {
        if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))     // but resting (walk from city or maybe in tavern or leave tavern recently)
        {
            if(GetRestType()==REST_TYPE_IN_TAVERN)          // has been in tavern. Is still in?
            {
                if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
                {
                    RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
                    SetRestType(REST_TYPE_NO);

                    if(sWorld.IsFFAPvPRealm())
                        SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
                }
            }
            else                                            // not in tavern (leave city then)
            {
                RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
                SetRestType(REST_TYPE_NO);

                // Set player to FFA PVP when not in rested enviroment.
                if(sWorld.IsFFAPvPRealm())
                    SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
            }
        }
    }

    // remove auras from spells with area limitations
    for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
    {
        if(iter->second->GetSpellProto()->AreaId && iter->second->GetSpellProto()->AreaId != newZone)
        {
            RemoveAura(iter);
        }
        else
            ++iter;
    }

    // remove new continent flight forms
    if( !isGameMaster() && 
        GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
    {
        RemoveSpellsCausingAura(SPELL_AURA_MOD_SPEED_MOUNTED_FLIGHT);
        RemoveSpellsCausingAura(SPELL_AURA_FLY);
    }

    // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
    // if player resurrected at teleport this will be applied in resurrect code
    if(isAlive())
        DestroyZoneLimitedItem( true, newZone );

    // recent client version not send leave/join channel packets for built-in local channels
    UpdateLocalChannels( newZone );

    // group update
    SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
}

//If players are too far way of duel flag... then player loose the duel
void Player::CheckDuelDistance(time_t currTime)
{
    if(!duel) return;

    uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
    GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
    if(!obj)
        return;

    if(duel->outOfBound == 0)
    {
        if(!IsWithinDistInMap(obj, 50))
        {
            duel->outOfBound = currTime;

            WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
            GetSession()->SendPacket(&data);
        }
    }
    else
    {
        if(IsWithinDistInMap(obj, 40))
        {
            duel->outOfBound = 0;

            WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
            GetSession()->SendPacket(&data);
        }
        else if(currTime >= (duel->outOfBound+10))
        {
            DuelComplete(DUEL_FLED);
        }
    }
}

void Player::DuelComplete(DuelCompleteType type)
{
    // duel not requested
    if(!duel)
        return;

    WorldPacket data(SMSG_DUEL_COMPLETE, (1));
    data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
    GetSession()->SendPacket(&data);
    duel->opponent->GetSession()->SendPacket(&data);

    if(type != DUEL_INTERUPTED)
    {
        data.Initialize(SMSG_DUEL_WINNER, (1+20));          // we guess size
        data << (uint8)((type==DUEL_WON) ? 0 : 1);          // 0 = just won; 1 = fled
        data << duel->opponent->GetName();
        data << GetName();
        SendMessageToSet(&data,true);
    }

    // cool-down duel spell
    /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);

    data<<GetGUID();
    data<<uint8(0x0);

    data<<(uint32)7266;
    data<<uint32(0x0);
    GetSession()->SendPacket(&data);
    data.Initialize(SMSG_SPELL_COOLDOWN, 17);
    data<<duel->opponent->GetGUID();
    data<<uint8(0x0);
    data<<(uint32)7266;
    data<<uint32(0x0);
    duel->opponent->GetSession()->SendPacket(&data);*/

    //Remove Duel Flag object
    GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
    if(obj)
        duel->initiator->RemoveGameObject(obj,true);

    /* remove auras */
    std::vector<uint32> auras2remove;
    AuraMap& vAuras = duel->opponent->GetAuras();
    for (AuraMap::iterator i = vAuras.begin(); i != vAuras.end(); i++)
    {
        if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
            auras2remove.push_back(i->second->GetId());
    }

    for(size_t i=0; i<auras2remove.size(); i++)
        duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);

    auras2remove.clear();
    AuraMap& Auras = GetAuras();
    for (AuraMap::iterator i = Auras.begin(); i != Auras.end(); i++)
    {
        if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
            auras2remove.push_back(i->second->GetId());
    }
    for(size_t i=0; i<auras2remove.size(); i++)
        RemoveAurasDueToSpell(auras2remove[i]);

    // cleanup combo points
    if(GetComboTarget()==duel->opponent->GetGUID())
        ClearComboPoints();
    else if(GetComboTarget()==duel->opponent->GetPetGUID())
        ClearComboPoints();

    if(duel->opponent->GetComboTarget()==GetGUID())
        duel->opponent->ClearComboPoints();
    else if(duel->opponent->GetComboTarget()==GetPetGUID())
        duel->opponent->ClearComboPoints();

    //cleanups
    SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
    SetUInt32Value(PLAYER_DUEL_TEAM, 0);
    duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
    duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);

    delete duel->opponent->duel;
    duel->opponent->duel = 0;
    delete duel;
    duel = 0;
}

//---------------------------------------------------------//
//       Flight callback
void Player::FlightComplete()
{
    clearUnitState(UNIT_STAT_IN_FLIGHT);
    Unmount();

    RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT );

    getHostilRefManager().setOnlineOfflineState(true);
    if(pvpInfo.inHostileArea)
        CastSpell(this, 2479, true);
}

void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
{
    if(slot >= INVENTORY_SLOT_BAG_END || !item) return;

    // not apply/remove mods for broken item
    if(item->IsBroken()) return;

    ItemPrototype const *proto = item->GetProto();

    if(!proto) return;

    sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());

    if(proto->ItemSet)
    {
        if (apply)
            AddItemsSetItem(this,item);
        else
            RemoveItemsSetItem(this,proto);
    }

    if(IsWeaponSlot(slot))
        _ApplyWeaponDependentAuraMods(item,slot,apply);

    _ApplyItemBonuses(proto,slot,apply);

    if( slot==EQUIPMENT_SLOT_RANGED )
        _ApplyAmmoBonuses();

    if(apply)
        CastItemEquipSpell(item);
    else
        for (int i = 0; i < 5; i++)
            if(proto->Spells[i].SpellId)
                RemoveAurasDueToSpell(proto->Spells[i].SpellId );

    ApplyEnchantment(item, apply);

    if(proto->Socket[0].Color)                              //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
        CorrectMetaGemEnchants(slot, apply);

    sLog.outDebug("_ApplyItemMods complete.");
}

void Player::_ApplyItemBonuses(ItemPrototype const *proto,uint8 slot,bool apply)
{
    if(slot >= INVENTORY_SLOT_BAG_END || !proto) return;

    float val;
    std::string typestr;
    std::string applystr = apply ? "Add" : "Remove";
    for (int i = 0; i < 10; i++)
    {
        val = float (proto->ItemStat[i].ItemStatValue);

        if(val==0)
            continue;

        switch (proto->ItemStat[i].ItemStatType)
        {
            case ITEM_MOD_MANA:
                HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
                //typestr = "Mana";
                break;
            case ITEM_MOD_HEALTH:                           // modify HP
                HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
                //typestr = "Health";
                break;
            case ITEM_MOD_AGILITY:                          // modify agility
                HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
                if(val > 0)
                    ApplyPosStatMod(STAT_AGILITY,         val, apply);
                else
                    ApplyNegStatMod(STAT_AGILITY,        -val, apply);
                //typestr = "AGILITY";
                break;
            case ITEM_MOD_STRENGTH:                         //modify strength
                HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
                if(val > 0)
                    ApplyPosStatMod(STAT_STRENGTH,        val, apply);
                else
                    ApplyNegStatMod(STAT_STRENGTH,       -val, apply);
                //typestr = "STRENGHT";
                break;
            case ITEM_MOD_INTELLECT:                        //modify intellect
                HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
                if(val > 0)
                    ApplyPosStatMod(STAT_INTELLECT,       val, apply);
                else
                    ApplyNegStatMod(STAT_INTELLECT,      -val, apply);
                //ApplyMaxPowerMod(POWER_MANA,              val*15, apply);
                //typestr = "INTELLECT";
                break;
            case ITEM_MOD_SPIRIT:                           //modify spirit
                HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
                if(val > 0)
                    ApplyPosStatMod(STAT_SPIRIT,          val, apply);
                else
                    ApplyNegStatMod(STAT_SPIRIT,         -val, apply);
                //typestr = "SPIRIT";
                break;
            case ITEM_MOD_STAMINA:                          //modify stamina
                HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
                if(val > 0)
                    ApplyPosStatMod(STAT_STAMINA,         val, apply);
                else
                    ApplyNegStatMod(STAT_STAMINA,        -val, apply);
                //typestr = "STAMINA";
                break;

            case ITEM_MOD_DEFENSE_SKILL_RATING:
                ApplyRatingMod(PLAYER_FIELD_DEFENCE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_DODGE_RATING:
                ApplyRatingMod(PLAYER_FIELD_DODGE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_PARRY_RATING:
                ApplyRatingMod(PLAYER_FIELD_PARRY_RATING, int32(val), apply);
                break;
            case ITEM_MOD_BLOCK_RATING:
                ApplyRatingMod(PLAYER_FIELD_BLOCK_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_MELEE_RATING:
                ApplyRatingMod(PLAYER_FIELD_MELEE_HIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_RANGED_RATING:
                ApplyRatingMod(PLAYER_FIELD_RANGED_HIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_SPELL_RATING:
                ApplyRatingMod(PLAYER_FIELD_SPELL_HIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_MELEE_RATING:
                ApplyRatingMod(PLAYER_FIELD_MELEE_CRIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_RANGED_RATING:
                ApplyRatingMod(PLAYER_FIELD_RANGED_CRIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_SPELL_RATING:
                ApplyRatingMod(PLAYER_FIELD_SPELL_CRIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
                ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_MELEE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
                ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_RANGED_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
                ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_SPELL_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HASTE_MELEE_RATING:
                ApplyRatingMod(PLAYER_FIELD_MELEE_HASTE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HASTE_RANGED_RATING:
                ApplyRatingMod(PLAYER_FIELD_RANGED_HASTE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HASTE_SPELL_RATING:
                ApplyRatingMod(PLAYER_FIELD_SPELL_HASTE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_RATING:
                ApplyRatingMod(PLAYER_FIELD_MELEE_HIT_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_RANGED_HIT_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_SPELL_HIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_RATING:
                ApplyRatingMod(PLAYER_FIELD_MELEE_CRIT_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_RANGED_CRIT_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_SPELL_CRIT_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HIT_TAKEN_RATING:
                ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_MELEE_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_RANGED_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_SPELL_RATING, int32(val), apply);
                break;
            case ITEM_MOD_CRIT_TAKEN_RATING:
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING, int32(val), apply);
                break;
            case ITEM_MOD_RESILIENCE_RATING:
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING, int32(val), apply);
                break;
            case ITEM_MOD_HASTE_RATING:
                ApplyRatingMod(PLAYER_FIELD_MELEE_HASTE_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_RANGED_HASTE_RATING, int32(val), apply);
                ApplyRatingMod(PLAYER_FIELD_SPELL_HASTE_RATING, int32(val), apply);
                break;
            case ITEM_MOD_EXPERTISE_RATING:
                ApplyRatingMod(PLAYER_FIELD_EXPERTISE_RATING, int32(val), apply);
                break;
        }
        //sLog.outDebug("%s %s: \t\t%u", applystr.c_str(), typestr.c_str(), val);
    }

    if (proto->Armor)
    {
        HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
        //sLog.outDebug("%s Armor: \t\t%u", applystr.c_str(),  proto->Armor);
    }

    if (proto->Block)
    {
        HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
        //sLog.outDebug("%s Block: \t\t%u", applystr.c_str(),  proto->Block);
    }

    if (proto->HolyRes)
    {
        HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
        //sLog.outDebug("%s HolyRes: \t\t%u", applystr.c_str(),  proto->HolyRes);
    }

    if (proto->FireRes)
    {
        HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
        //sLog.outDebug("%s FireRes: \t\t%u", applystr.c_str(),  proto->FireRes);
    }

    if (proto->NatureRes)
    {
        HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
        //sLog.outDebug("%s NatureRes: \t\t%u", applystr.c_str(),  proto->NatureRes);
    }

    if (proto->FrostRes)
    {
        HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
        //sLog.outDebug("%s FrostRes: \t\t%u", applystr.c_str(),  proto->FrostRes);
    }

    if (proto->ShadowRes)
    {
        HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
        //sLog.outDebug("%s ShadowRes: \t\t%u", applystr.c_str(),  proto->ShadowRes);
    }

    if (proto->ArcaneRes)
    {
        HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
        //sLog.outDebug("%s ArcaneRes: \t\t%u", applystr.c_str(),  proto->ArcaneRes);
    }

    WeaponAttackType attType = BASE_ATTACK;
    float damage = 0.0f;

    if( slot == EQUIPMENT_SLOT_RANGED && (
        proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
        proto->InventoryType == INVTYPE_RANGEDRIGHT ))
    {
        attType = RANGED_ATTACK;
        //typestr = "Ranged";
    }
    else if(slot==EQUIPMENT_SLOT_MAINHAND)
    {
        //typestr = "Mainhand";
    }
    else if(slot==EQUIPMENT_SLOT_OFFHAND)
    {
        attType = OFF_ATTACK;
        //typestr = "Offhand";
    }

    if (proto->Damage[0].DamageMin > 0 )
    {
        damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
        SetBaseWeaponDamage(attType, MINDAMAGE, damage);
        //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
    }

    if (proto->Damage[0].DamageMax  > 0 )
    {
        damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
        SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
        //sLog.outError("applying maxdam: assigning %f to weapon maxdamage, now is: %f", damage, GetWeaponDamageRange(attType, MAXDAMAGE));
    }

    if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
        return;

    if (proto->Delay)
    {
        if(slot == EQUIPMENT_SLOT_RANGED)
        {
            SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
            //typestr = "Range";
            //sLog.outDebug("%s %s Delay: \t\t%u", applystr.c_str(), typestr.c_str(), proto->Delay);
        }
        else if(slot==EQUIPMENT_SLOT_MAINHAND)
        {
            SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
            //typestr = "Mainhand";
            //sLog.outDebug("%s %s Delay: \t\t%u", applystr.c_str(), typestr.c_str(), proto->Delay);
        }
        else if(slot==EQUIPMENT_SLOT_OFFHAND)
        {
            SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
            //typestr = "Offhand";
            //sLog.outDebug("%s %s Delay: \t\t%u", applystr.c_str(), typestr.c_str(), proto->Delay);
        }
    }

    if(CanModifyStats() && (damage || proto->Delay))
        UpdateDamagePhysical(attType);
}

void Player::_ApplyWeaponDependentAuraMods(Item *item,uint8 slot,bool apply)
{
    AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
    for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
        _ApplyWeaponDependentAuraCritMod(item,slot,*itr,apply);

    AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
    for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
        _ApplyWeaponDependentAuraDamageMod(item,slot,*itr,apply);

    AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
    for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
        _ApplyWeaponDependentAuraDamageMod(item,slot,*itr,apply);
}

void Player::_ApplyWeaponDependentAuraCritMod(Item *item, uint8 slot, Aura* aura, bool apply)
{
    // generic not weapon specific case processes in aura code
    if(aura->GetSpellProto()->EquippedItemClass == -1)
        return;

    BaseModGroup mod = BASEMOD_END;
    switch(slot)
    {
        case EQUIPMENT_SLOT_MAINHAND: mod = CRIT_PERCENTAGE;        break;
        case EQUIPMENT_SLOT_OFFHAND:  mod = OFFHAND_CRIT_PERCENTAGE;break;
        case EQUIPMENT_SLOT_RANGED:   mod = RANGED_CRIT_PERCENTAGE; break;
        default: return;
    }

    if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
    {
        HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
    }
}

void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, uint8 slot, Aura* aura, bool apply)
{
    // ignore spell mods
    Modifier const* modifier = aura->GetModifier();
    if((modifier->m_miscvalue & IMMUNE_SCHOOL_PHYSICAL) == 0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
        return;

    // generic not weapon specific case processes in aura code
    if(aura->GetSpellProto()->EquippedItemClass == -1)
        return;

    UnitMods unitMod = UNIT_MOD_END;
    switch(slot)
    {
        case EQUIPMENT_SLOT_MAINHAND: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
        case EQUIPMENT_SLOT_OFFHAND:  unitMod = UNIT_MOD_DAMAGE_OFFHAND;  break;
        case EQUIPMENT_SLOT_RANGED:   unitMod = UNIT_MOD_DAMAGE_RANGED;   break;
        default: return;
    }

    UnitModifierType unitModType = TOTAL_VALUE;
    switch(modifier->m_auraname)
    {
        case SPELL_AURA_MOD_DAMAGE_DONE:         unitModType = TOTAL_VALUE; break;
        case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT;   break;
        default: return;
    }

    if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
    {
        HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
    }
}

void Player::CastItemEquipSpell(Item *item)
{
    if(!item) return;

    ItemPrototype const *proto = item->GetProto();

    if(!proto) return;

    for (int i = 0; i < 5; i++)
    {
        _Spell const& spellData = proto->Spells[i];

        // no spell
        if(!spellData.SpellId )
            continue;

        // wrong triggering type
        if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
            continue;

        DEBUG_LOG("WORLD: cast Item spellId - %i", spellData.SpellId);

        CastSpell(this,spellData.SpellId,true,item);
    }
}

void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
{
    if(!item || item->IsBroken())
        return;

    ItemPrototype const *proto = item->GetProto();
    if(!proto)
        return;

    if (!Target || Target == this )
        return;

    for (int i = 0; i < 5; i++)
    {
        _Spell const& spellData = proto->Spells[i];

        // no spell
        if(!spellData.SpellId )
            continue;

        // wrong triggering type
        if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
            continue;

        SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
        if(!spellInfo)
        {
            sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
            continue;
        }

        float chance = spellInfo->procChance;

        if(spellData.SpellPPMRate)
        {
            uint32 WeaponSpeed = GetAttackTime(attType);
            chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
        }
        else if(chance > 100)
        {
            chance = GetWeaponProcChance();
        }

        if (roll_chance_f(chance))
            this->CastSpell(Target, spellInfo->Id, true, item);
    }

    // item combat enchantments
    for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
    {
        uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
        SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
        if(!pEnchant) continue;
        for (int s=0;s<3;s++)
        {
            if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
                continue;

            SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
            if (!spellInfo)
            {
                sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
                continue;
            }

            float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
            if (roll_chance_f(chance))
            {
                if(IsPositiveSpell(pEnchant->spellid[s]))
                    CastSpell(this, pEnchant->spellid[s], true, item);
                else
                    CastSpell(Target, pEnchant->spellid[s], true, item);
            }
        }
    }
}

void Player::_RemoveAllItemMods()
{
    sLog.outDebug("_RemoveAllItemMods start.");

    for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if(m_items[i])
        {
            if(m_items[i]->IsBroken())
                continue;

            ItemPrototype const *proto = m_items[i]->GetProto();
            if(!proto)
                continue;

            if(proto->ItemSet)
                RemoveItemsSetItem(this,proto);

            for (int m = 0; m < 5; m++)
            {
                if(proto->Spells[m].SpellId)
                    RemoveAurasDueToSpell(proto->Spells[m].SpellId );
            }

            ApplyEnchantment(m_items[i], false);
        }
    }

    for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if(m_items[i])
        {
            if(m_items[i]->IsBroken())
                continue;
            ItemPrototype const *proto = m_items[i]->GetProto();
            if(!proto)
                continue;

            if(IsWeaponSlot(i))
                _ApplyWeaponDependentAuraMods(m_items[i],i,false);

            _ApplyItemBonuses(proto,i, false);

            if( i == EQUIPMENT_SLOT_RANGED )
                _ApplyAmmoBonuses();
        }
    }

    sLog.outDebug("_RemoveAllItemMods complete.");
}

void Player::_ApplyAllItemMods()
{
    sLog.outDebug("_ApplyAllItemMods start.");

    for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if(m_items[i])
        {
            if(m_items[i]->IsBroken())
                continue;

            ItemPrototype const *proto = m_items[i]->GetProto();
            if(!proto)
                continue;

            if(IsWeaponSlot(i))
                _ApplyWeaponDependentAuraMods(m_items[i],i,true);

            _ApplyItemBonuses(proto,i, true);

            if( i == EQUIPMENT_SLOT_RANGED )
                _ApplyAmmoBonuses();
        }
    }

    for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if(m_items[i])
        {
            if(m_items[i]->IsBroken())
                continue;

            ItemPrototype const *proto = m_items[i]->GetProto();
            if(!proto)
                continue;

            if(proto->ItemSet)
                AddItemsSetItem(this,m_items[i]);

            CastItemEquipSpell(m_items[i]);

            ApplyEnchantment(m_items[i], true);
        }
    }

    sLog.outDebug("_ApplyAllItemMods complete.");
}

void Player::_ApplyAmmoBonuses()
{
    // check ammo
    uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
    if(!ammo_id)
        return;

    float currentAmmoDPS;

    ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
    if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
        currentAmmoDPS = 0.0f;
    else
        currentAmmoDPS = ammo_proto->Damage[0].DamageMin;

    if(currentAmmoDPS == GetAmmoDPS())
        return;

    m_ammoDPS = currentAmmoDPS;

    if(CanModifyStats())
        UpdateDamagePhysical(RANGED_ATTACK);
}

bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
{
    if(!ammo_proto)
        return false;

    // check ranged weapon
    Item *weapon = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED );
    if(!weapon  || weapon->IsBroken() )
        return false;

    ItemPrototype const* weapon_proto = weapon->GetProto();
    if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
        return false;

    // check ammo ws. weapon compatibility
    switch(weapon_proto->SubClass)
    {
        case ITEM_SUBCLASS_WEAPON_BOW:
        case ITEM_SUBCLASS_WEAPON_CROSSBOW:
            if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
                return false;
            break;
        case ITEM_SUBCLASS_WEAPON_GUN:
            if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
                return false;
            break;
        default:
            return false;
    }

    return true;
}

/*  If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
    Called by remove insignia spell effect    */
void Player::RemovedInsignia(Player* looterPlr)
{
    if (!GetBattleGroundId())
        return;

    // If not released spirit, do it !
    if(m_deathTimer > 0)
    {
        m_deathTimer = 0;
        RepopAtGraveyard();
        BuildPlayerRepop();
    }

    Corpse *corpse = GetCorpse();
    if (!corpse)
        return;
    corpse->loot.gold = getLevel();

    // We have to convert player corpse to bones, not to be able to resurrect there
    // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
    Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
    if (!bones)
        return;

    // Now we must make bones lootable, and send player loot
    bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);

    // We store the level of our player in the gold field
    // We retrieve this information at Player::SendLoot()
    bones->loot.gold = getLevel();
    bones->lootRecipient = looterPlr;
    looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
}

/*Loot type MUST be
1-corpse, go
2-skinning
3-Fishing
*/

void Player::SendLootRelease( uint64 guid )
{
    WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
    data << guid << uint8(1);
    SendDirectMessage( &data );
}

void Player::SendLoot(uint64 guid, LootType loot_type)
{
    Loot    *loot = 0;
    PermissionTypes permission = ALL_PERMISSION;

    sLog.outDebug("Player::SendLoot");
    if (IS_GAMEOBJECT_GUID(guid))
    {
        sLog.outDebug("       IS_GAMEOBJECT_GUID(guid)");
        GameObject *go =
            ObjectAccessor::GetGameObject(*this, guid);

        // not check distance for GO in case owned GO (fishing bobber case, for example)
        if (!go || (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE))
        {
            SendLootRelease(guid);
            return;
        }

        loot = &go->loot;

        if(go->getLootState() == GO_CLOSED)
        {
            uint32 lootid =  go->GetLootId();

            if(lootid)
            {
                sLog.outDebug("       if(lootid)");
                loot->clear();
                FillLoot(loot, lootid, LootTemplates_Gameobject, this);
            }

            if(loot_type == LOOT_FISHING)
                go->getFishLoot(loot);

            go->SetLootState(GO_OPEN);
        }
    }
    else if (IS_ITEM_GUID(guid))
    {
        Item *item = GetItemByGuid( guid );

        if (!item)
        {
            SendLootRelease(guid);
            return;
        }

        if(loot_type == LOOT_DISENCHANTING)
        {
            loot = &item->loot;

            if(!item->m_lootGenerated)
            {
                item->m_lootGenerated = true;
                loot->clear();
                FillLoot(loot, item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
            }
        }
        else if(loot_type == LOOT_PROSPECTING)
        {
            loot = &item->loot;

            if(!item->m_lootGenerated)
            {
                item->m_lootGenerated = true;
                loot->clear();
                FillLoot(loot, item->GetEntry(), LootTemplates_Prospecting, this);
            }
        }
        else
        {
            loot = &item->loot;

            if(!item->m_lootGenerated)
            {
                item->m_lootGenerated = true;
                loot->clear();
                FillLoot(loot, item->GetEntry(), LootTemplates_Item, this);

                loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
            }
        }
    }
    else if (IS_CORPSE_GUID(guid))                          // remove insignia
    {
        Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);

        if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
        {
            SendLootRelease(guid);
            return;
        }

        loot = &bones->loot;

        if (!bones->lootForBody)
        {
            bones->lootForBody = true;
            uint32 pLevel = bones->loot.gold;
            bones->loot.clear();
            // It may need a better formula
            // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
            bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
        }

        if (bones->lootRecipient != this)
            permission = NONE_PERMISSION;
    }
    else
    {
        Creature *creature = ObjectAccessor::GetCreature(*this, guid);

        // must be in range and creature must be alive for pickpocket and must be dead for another loot
        if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
        {
            SendLootRelease(guid);
            return;
        }

        if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
        {
            SendLootRelease(guid);
            return;
        }

        loot   = &creature->loot;

        if(loot_type == LOOT_PICKPOCKETING)
        {
            uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId;

            if ( !creature->lootForPickPocketed )
            {
                creature->lootForPickPocketed = true;
                loot->clear();

                if (!creature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_VENDOR) && lootid)
                {
                    loot->clear();
                    FillLoot(loot, lootid, LootTemplates_Pickpocketing, this);
                }
                // Generate extra money for pick pocket loot
                const uint32 a = urand(0, creature->getLevel()/2);
                const uint32 b = urand(0, getLevel()/2);
                loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
            }
        }
        else
        {
            uint32 lootid = creature->GetCreatureInfo()->lootid;

            // the player whose group may loot the corpse
            Player *recipient = creature->GetLootRecipient();
            if (!recipient)
            {
                creature->SetLootRecipient(this);
                recipient = this;
            }

            if (creature->lootForPickPocketed)
            {
                creature->lootForPickPocketed = false;
                loot->clear();
            }

            if(!creature->lootForBody)
            {
                creature->lootForBody = true;
                if (!creature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_VENDOR) && lootid)
                {
                    loot->clear();
                    FillLoot(loot, lootid, LootTemplates_Creature, recipient);
                }

                loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);

                if (recipient->GetGroup())
                {
                    // round robin style looting applies for all low
                    // quality items in each loot method except free for all
                    GroupReference &group = recipient->GetGroupRef();

                    // next by circle
                    uint64 next_guid = 0;
                    if (group.next()) next_guid = group.next()->getSource()->GetGUID();
                    else if(group->GetFirstMember() && group->GetFirstMember()->isValid())
                        next_guid = group->GetFirstMember()->getSource()->GetGUID();
                    group->SetLooterGuid(next_guid);

                    switch (group->GetLootMethod())
                    {
                        case GROUP_LOOT:
                            // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
                            group->GroupLoot(recipient->GetGUID(), loot, creature);
                            break;
                        case NEED_BEFORE_GREED:
                            group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
                            break;
                        default:
                            break;
                    }
                }
            }

            if (loot_type == LOOT_SKINNING)
            {
                loot->clear();
                FillLoot(loot, creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
            }

            if (!GetGroup() && recipient == this)
                permission = ALL_PERMISSION;
            else
            {
                if (GetGroup())
                {
                    Group *group = GetGroup();
                    if ((group == recipient->GetGroup()) && (group->GetLooterGuid() == GetGUID() || loot->released || group->GetLootMethod() == FREE_FOR_ALL))
                        permission = ALL_PERMISSION;
                    else
                    if (group == recipient->GetGroup())
                        permission = GROUP_PERMISSION;
                    else
                        permission = NONE_PERMISSION;
                }
                else
                    permission = NONE_PERMISSION;
            }
        }
    }

    m_lootGuid = guid;

    QuestItemList *q_list = 0;
    if (permission != NONE_PERMISSION)
    {
        QuestItemMap::iterator itr = loot->PlayerQuestItems.find(GetGUIDLow());
        if (itr == loot->PlayerQuestItems.end())
            q_list = FillQuestLoot(this, loot);
        else
            q_list = itr->second;
    }

    QuestItemList *ffa_list = 0;
    if (permission != NONE_PERMISSION)
    {
        QuestItemMap::iterator itr = loot->PlayerFFAItems.find(GetGUIDLow());
        if (itr == loot->PlayerFFAItems.end())
            ffa_list = FillFFALoot(this, loot);
        else
            ffa_list = itr->second;
    }

    QuestItemList *conditional_list = 0;
    if (permission != NONE_PERMISSION)
    {
        QuestItemMap::iterator itr = loot->PlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
        if (itr == loot->PlayerNonQuestNonFFAConditionalItems.end())
            conditional_list = FillNonQuestNonFFAConditionalLoot(this, loot);
        else
            conditional_list = itr->second;
    }

    // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
    if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
        loot_type = LOOT_SKINNING;

    WorldPacket data(SMSG_LOOT_RESPONSE, (9+50));           // we guess size

    data << guid;
    data << uint8(loot_type);
    data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);

    SendDirectMessage(&data);

    // add 'this' player as one of the players that are looting 'loot'
    if (permission != NONE_PERMISSION)
        loot->AddLooter(GetGUID());

    if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
        SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
}

void Player::SendNotifyLootMoneyRemoved()
{
    WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
    GetSession()->SendPacket( &data );
}

void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
{
    WorldPacket data(SMSG_LOOT_REMOVED, 1);
    data << uint8(lootSlot);
    GetSession()->SendPacket( &data );
}

void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
{
    WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
    data << Field;
    data << Value;
    SendMessageToSet(&data, true);
    //GetSession()->SendPacket(&data);
}

void Player::SendInitWorldStates()
{
    // data depends on zoneid/mapid...
    BattleGround* bg = GetBattleGround();
    uint16 NumberOfFields = 0;
    uint32 mapid = GetMapId();
    uint32 zoneid = GetZoneId();
    uint32 areaid = GetAreaId();
    sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
    // may be exist better way to do this...
    switch(zoneid)
    {
        case 0:
        case 1:
        case 4:
        case 8:
        case 10:
        case 11:
        case 12:
        case 36:
        case 38:
        case 40:
        case 41:
        case 51:
        case 267:
        case 1519:
        case 1537:
        case 2257:
        case 2918:
            NumberOfFields = 6;
            break;
        case 2597:
            NumberOfFields = 81;
            break;
        case 3277:
            NumberOfFields = 14;
            break;
        case 3358:
            NumberOfFields = 38;
            break;
        case 3483:
            NumberOfFields = 22;
            break;
        case 3519:
            NumberOfFields = 36;
            break;
        case 3521:
            NumberOfFields = 35;
            break;
        case 3698:
        case 3702:
        case 3968:
            NumberOfFields = 9;
            break;
        case 3703:
            NumberOfFields = 9;
            break;
        default:
            NumberOfFields = 10;
            break;
    }

    WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
    data << mapid;                                          // mapid
    data << zoneid;                                         // zone id
    data << areaid;                                         // area id, new 2.1.0
    data << NumberOfFields;                                 // count of uint64 blocks
    data << uint32(0x8d8) << uint32(0x0);                   // 1
    data << uint32(0x8d7) << uint32(0x0);                   // 2
    data << uint32(0x8d6) << uint32(0x0);                   // 3
    data << uint32(0x8d5) << uint32(0x0);                   // 4
    data << uint32(0x8d4) << uint32(0x0);                   // 5
    data << uint32(0x8d3) << uint32(0x0);                   // 6
    if(mapid == 530)                                        // Outland
    {
        data << uint32(0x9bf) << uint32(0x0);               // 7
        data << uint32(0x9bd) << uint32(0xF);               // 8
        data << uint32(0x9bb) << uint32(0xF);               // 9
    }
    switch(zoneid)
    {
        case 1:
        case 11:
        case 12:
        case 38:
        case 40:
        case 51:
        case 1519:
        case 1537:
        case 2257:
            break;
        case 2597:                                          // AV
            data << uint32(0x7ae) << uint32(0x1);           // 7
            data << uint32(0x532) << uint32(0x1);           // 8
            data << uint32(0x531) << uint32(0x0);           // 9
            data << uint32(0x52e) << uint32(0x0);           // 10
            data << uint32(0x571) << uint32(0x0);           // 11
            data << uint32(0x570) << uint32(0x0);           // 12
            data << uint32(0x567) << uint32(0x1);           // 13
            data << uint32(0x566) << uint32(0x1);           // 14
            data << uint32(0x550) << uint32(0x1);           // 15
            data << uint32(0x544) << uint32(0x0);           // 16
            data << uint32(0x536) << uint32(0x0);           // 17
            data << uint32(0x535) << uint32(0x1);           // 18
            data << uint32(0x518) << uint32(0x0);           // 19
            data << uint32(0x517) << uint32(0x0);           // 20
            data << uint32(0x574) << uint32(0x0);           // 21
            data << uint32(0x573) << uint32(0x0);           // 22
            data << uint32(0x572) << uint32(0x0);           // 23
            data << uint32(0x56f) << uint32(0x0);           // 24
            data << uint32(0x56e) << uint32(0x0);           // 25
            data << uint32(0x56d) << uint32(0x0);           // 26
            data << uint32(0x56c) << uint32(0x0);           // 27
            data << uint32(0x56b) << uint32(0x0);           // 28
            data << uint32(0x56a) << uint32(0x1);           // 29
            data << uint32(0x569) << uint32(0x1);           // 30
            data << uint32(0x568) << uint32(0x1);           // 13
            data << uint32(0x565) << uint32(0x0);           // 32
            data << uint32(0x564) << uint32(0x0);           // 33
            data << uint32(0x563) << uint32(0x0);           // 34
            data << uint32(0x562) << uint32(0x0);           // 35
            data << uint32(0x561) << uint32(0x0);           // 36
            data << uint32(0x560) << uint32(0x0);           // 37
            data << uint32(0x55f) << uint32(0x0);           // 38
            data << uint32(0x55e) << uint32(0x0);           // 39
            data << uint32(0x55d) << uint32(0x0);           // 40
            data << uint32(0x3c6) << uint32(0x4);           // 41
            data << uint32(0x3c4) << uint32(0x6);           // 42
            data << uint32(0x3c2) << uint32(0x4);           // 43
            data << uint32(0x516) << uint32(0x1);           // 44
            data << uint32(0x515) << uint32(0x0);           // 45
            data << uint32(0x3b6) << uint32(0x6);           // 46
            data << uint32(0x55c) << uint32(0x0);           // 47
            data << uint32(0x55b) << uint32(0x0);           // 48
            data << uint32(0x55a) << uint32(0x0);           // 49
            data << uint32(0x559) << uint32(0x0);           // 50
            data << uint32(0x558) << uint32(0x0);           // 51
            data << uint32(0x557) << uint32(0x0);           // 52
            data << uint32(0x556) << uint32(0x0);           // 53
            data << uint32(0x555) << uint32(0x0);           // 54
            data << uint32(0x554) << uint32(0x1);           // 55
            data << uint32(0x553) << uint32(0x1);           // 56
            data << uint32(0x552) << uint32(0x1);           // 57
            data << uint32(0x551) << uint32(0x1);           // 58
            data << uint32(0x54f) << uint32(0x0);           // 59
            data << uint32(0x54e) << uint32(0x0);           // 60
            data << uint32(0x54d) << uint32(0x1);           // 61
            data << uint32(0x54c) << uint32(0x0);           // 62
            data << uint32(0x54b) << uint32(0x0);           // 63
            data << uint32(0x545) << uint32(0x0);           // 64
            data << uint32(0x543) << uint32(0x1);           // 65
            data << uint32(0x542) << uint32(0x0);           // 66
            data << uint32(0x540) << uint32(0x0);           // 67
            data << uint32(0x53f) << uint32(0x0);           // 68
            data << uint32(0x53e) << uint32(0x0);           // 69
            data << uint32(0x53d) << uint32(0x0);           // 70
            data << uint32(0x53c) << uint32(0x0);           // 71
            data << uint32(0x53b) << uint32(0x0);           // 72
            data << uint32(0x53a) << uint32(0x1);           // 73
            data << uint32(0x539) << uint32(0x0);           // 74
            data << uint32(0x538) << uint32(0x0);           // 75
            data << uint32(0x537) << uint32(0x0);           // 76
            data << uint32(0x534) << uint32(0x0);           // 77
            data << uint32(0x533) << uint32(0x0);           // 78
            data << uint32(0x530) << uint32(0x0);           // 79
            data << uint32(0x52f) << uint32(0x0);           // 80
            data << uint32(0x52d) << uint32(0x1);           // 81
            break;
        case 3277:                                          // WS
            if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
                bg->FillInitialWorldStates(data);
            else
            {
                data << uint32(0x62d) << uint32(0x0);           // 7 1581 alliance flag captures
                data << uint32(0x62e) << uint32(0x0);           // 8 1582 horde flag captures
                data << uint32(0x609) << uint32(0x0);           // 9 1545 unk, set to 1 on alliance flag pickup...
                data << uint32(0x60a) << uint32(0x0);           // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
                data << uint32(0x60b) << uint32(0x2);           // 11 1547 unk
                data << uint32(0x641) << uint32(0x3);           // 12 1601 unk (max flag captures?)
                data << uint32(0x922) << uint32(0x1);           // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
                data << uint32(0x923) << uint32(0x1);           // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
            }
            break;
        case 3358:                                          // AB
            if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
                bg->FillInitialWorldStates(data);
            else
            {
                data << uint32(0x6e7) << uint32(0x0);           // 7 1767 stables alliance
                data << uint32(0x6e8) << uint32(0x0);           // 8 1768 stables horde
                data << uint32(0x6e9) << uint32(0x0);           // 9 1769 unk, ST?
                data << uint32(0x6ea) << uint32(0x0);           // 10 1770 stables (show/hide)
                data << uint32(0x6ec) << uint32(0x0);           // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
                data << uint32(0x6ed) << uint32(0x0);           // 12 1773 farm (show/hide)
                data << uint32(0x6ee) << uint32(0x0);           // 13 1774 farm color
                data << uint32(0x6ef) << uint32(0x0);           // 14 1775 gold mine color, may be FM?
                data << uint32(0x6f0) << uint32(0x0);           // 15 1776 alliance resources
                data << uint32(0x6f1) << uint32(0x0);           // 16 1777 horde resources
                data << uint32(0x6f2) << uint32(0x0);           // 17 1778 horde bases
                data << uint32(0x6f3) << uint32(0x0);           // 18 1779 alliance bases
                data << uint32(0x6f4) << uint32(0x7d0);         // 19 1780 max resources (2000)
                data << uint32(0x6f6) << uint32(0x0);           // 20 1782 blacksmith color
                data << uint32(0x6f7) << uint32(0x0);           // 21 1783 blacksmith (show/hide)
                data << uint32(0x6f8) << uint32(0x0);           // 22 1784 unk, bs?
                data << uint32(0x6f9) << uint32(0x0);           // 23 1785 unk, bs?
                data << uint32(0x6fb) << uint32(0x0);           // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
                data << uint32(0x6fc) << uint32(0x0);           // 25 1788 gold mine (0 - conflict, 1 - horde)
                data << uint32(0x6fd) << uint32(0x0);           // 26 1789 gold mine (1 - show/0 - hide)
                data << uint32(0x6fe) << uint32(0x0);           // 27 1790 gold mine color
                data << uint32(0x700) << uint32(0x0);           // 28 1792 gold mine color, wtf?, may be LM?
                data << uint32(0x701) << uint32(0x0);           // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
                data << uint32(0x702) << uint32(0x0);           // 30 1794 lumber mill (show/hide)
                data << uint32(0x703) << uint32(0x0);           // 31 1795 lumber mill color color
                data << uint32(0x732) << uint32(0x1);           // 32 1842 stables (1 - uncontrolled)
                data << uint32(0x733) << uint32(0x1);           // 33 1843 gold mine (1 - uncontrolled)
                data << uint32(0x734) << uint32(0x1);           // 34 1844 lumber mill (1 - uncontrolled)
                data << uint32(0x735) << uint32(0x1);           // 35 1845 farm (1 - uncontrolled)
                data << uint32(0x736) << uint32(0x1);           // 36 1846 blacksmith (1 - uncontrolled)
                data << uint32(0x745) << uint32(0x2);           // 37 1861 unk
                data << uint32(0x7a3) << uint32(0x708);         // 38 1955 warning limit (1800)
            }
            break;
        case 3483:                                          // Hellfire Peninsula
            data << uint32(0x9ba) << uint32(0x1);           // 10
            data << uint32(0x9b9) << uint32(0x1);           // 11
            data << uint32(0x9b5) << uint32(0x0);           // 12
            data << uint32(0x9b4) << uint32(0x1);           // 13
            data << uint32(0x9b3) << uint32(0x0);           // 14
            data << uint32(0x9b2) << uint32(0x0);           // 15
            data << uint32(0x9b1) << uint32(0x1);           // 16
            data << uint32(0x9b0) << uint32(0x0);           // 17
            data << uint32(0x9ae) << uint32(0x0);           // 18 horde pvp objectives captured
            data << uint32(0x9ac) << uint32(0x0);           // 19
            data << uint32(0x9a8) << uint32(0x0);           // 20
            data << uint32(0x9a7) << uint32(0x0);           // 21
            data << uint32(0x9a6) << uint32(0x1);           // 22
            break;
        case 3519:                                          // Terokkar Forest
            data << uint32(0xa41) << uint32(0x0);           // 10
            data << uint32(0xa40) << uint32(0x14);          // 11
            data << uint32(0xa3f) << uint32(0x0);           // 12
            data << uint32(0xa3e) << uint32(0x0);           // 13
            data << uint32(0xa3d) << uint32(0x5);           // 14
            data << uint32(0xa3c) << uint32(0x0);           // 15
            data << uint32(0xa87) << uint32(0x0);           // 16
            data << uint32(0xa86) << uint32(0x0);           // 17
            data << uint32(0xa85) << uint32(0x0);           // 18
            data << uint32(0xa84) << uint32(0x0);           // 19
            data << uint32(0xa83) << uint32(0x0);           // 20
            data << uint32(0xa82) << uint32(0x0);           // 21
            data << uint32(0xa81) << uint32(0x0);           // 22
            data << uint32(0xa80) << uint32(0x0);           // 23
            data << uint32(0xa7e) << uint32(0x0);           // 24
            data << uint32(0xa7d) << uint32(0x0);           // 25
            data << uint32(0xa7c) << uint32(0x0);           // 26
            data << uint32(0xa7b) << uint32(0x0);           // 27
            data << uint32(0xa7a) << uint32(0x0);           // 28
            data << uint32(0xa79) << uint32(0x0);           // 29
            data << uint32(0x9d0) << uint32(0x5);           // 30
            data << uint32(0x9ce) << uint32(0x0);           // 31
            data << uint32(0x9cd) << uint32(0x0);           // 32
            data << uint32(0x9cc) << uint32(0x0);           // 33
            data << uint32(0xa88) << uint32(0x0);           // 34
            data << uint32(0xad0) << uint32(0x0);           // 35
            data << uint32(0xacf) << uint32(0x1);           // 36
            break;
        case 3521:                                          // Zangarmarsh
            data << uint32(0x9e1) << uint32(0x0);           // 10
            data << uint32(0x9e0) << uint32(0x0);           // 11
            data << uint32(0x9df) << uint32(0x0);           // 12
            data << uint32(0xa5d) << uint32(0x1);           // 13
            data << uint32(0xa5c) << uint32(0x0);           // 14
            data << uint32(0xa5b) << uint32(0x1);           // 15
            data << uint32(0xa5a) << uint32(0x0);           // 16
            data << uint32(0xa59) << uint32(0x1);           // 17
            data << uint32(0xa58) << uint32(0x0);           // 18
            data << uint32(0xa57) << uint32(0x0);           // 19
            data << uint32(0xa56) << uint32(0x0);           // 20
            data << uint32(0xa55) << uint32(0x1);           // 21
            data << uint32(0xa54) << uint32(0x0);           // 22
            data << uint32(0x9e7) << uint32(0x0);           // 23
            data << uint32(0x9e6) << uint32(0x0);           // 24
            data << uint32(0x9e5) << uint32(0x0);           // 25
            data << uint32(0xa00) << uint32(0x0);           // 26
            data << uint32(0x9ff) << uint32(0x1);           // 27
            data << uint32(0x9fe) << uint32(0x0);           // 28
            data << uint32(0x9fd) << uint32(0x0);           // 29
            data << uint32(0x9fc) << uint32(0x1);           // 30
            data << uint32(0x9fb) << uint32(0x0);           // 31
            data << uint32(0xa62) << uint32(0x0);           // 32
            data << uint32(0xa61) << uint32(0x1);           // 33
            data << uint32(0xa60) << uint32(0x1);           // 34
            data << uint32(0xa5f) << uint32(0x0);           // 35
            break;
        case 3698:                                          // Nagrand Arena
            data << uint32(0xa0f) << uint32(0x0);           // 7
            data << uint32(0xa10) << uint32(0x0);           // 8
            data << uint32(0xa11) << uint32(0x0);           // 9
            break;
        case 3702:                                          // Blade's Edge Arena
            data << uint32(0x9f0) << uint32(0x0);           // 7
            data << uint32(0x9f1) << uint32(0x0);           // 8
            data << uint32(0x9f3) << uint32(0x0);           // 9
            break;
        case 3968:                                          // Ruins of Lordaeron
            data << uint32(0xbb8) << uint32(0x0);           // 7
            data << uint32(0xbb9) << uint32(0x0);           // 8
            data << uint32(0xbba) << uint32(0x0);           // 9
            break;
        case 3703:                                          // Shattrath City
            break;
        default:
            data << uint32(0x914) << uint32(0x0);           // 7
            data << uint32(0x913) << uint32(0x0);           // 8
            data << uint32(0x912) << uint32(0x0);           // 9
            data << uint32(0x915) << uint32(0x0);           // 10
            break;
    }
    GetSession()->SendPacket(&data);
}

uint32 Player::GetXPRestBonus(uint32 xp)
{
    uint32 rested_bonus = (uint32)GetRestBonus();           // xp for each rested bonus

    if(rested_bonus > xp)                                   // max rested_bonus == xp or (r+x) = 200% xp
        rested_bonus = xp;

    SetRestBonus( GetRestBonus() - rested_bonus);

    sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
    return rested_bonus;
}

int32 Player::FishingMinSkillForCurrentZone() const
{
    // special areas (subzones)
    switch(GetAreaId())
    {
        case 297:
            return 205;

        case 3655:
        case 3659:
            return 305;

        case 1112:
        case 1222:
        case 1227:
        case 3140:
            return 330;

        case 3653:
        case 3656:
        case 3658:
        case 3859:
            return 355;

        case 3621:
        case 3690:
        case 3691:
        case 3692:
            return 430;
    }

    // zones
    switch(GetZoneId())
    {
        case 1:
        case 12:
        case 14:
        case 85:
        case 141:
        case 215:
        case 3524:
        case 3430:
            return -70;

        case 17:
        case 38:
        case 40:
        case 130:
        case 148:
        case 206:
        case 718:
        case 719:
        case 1519:
        case 1581:
        case 1637:
        case 1638:
        case 1657:
        case 3525:
        case 3433:
            return -20;

        case 10:
        case 11:
        case 44:
        case 367:
        case 331:
        case 406:
            return 55;

        case 8:
        case 15:
        case 33:
        case 36:
        case 45:
        case 400:
        case 405:
        case 796:
            return 130;

        case 16:
        case 28:
        case 47:
        case 268:
        case 357:
        case 361:
        case 440:
        case 490:
        case 493:
        case 1477:
        case 2100:
            return 205;

        case 41:
        case 46:
        case 139:
        case 618:
        case 1377:
        case 1977:
        case 2017:
        case 2057:
            return 330;

        case 3519:
            return 355;

        case 3518:
        case 3523:
            return 380;
    }

    // impossible or unknown
    return 9999;
}

void Player::SetBindPoint(uint64 guid)
{
    WorldPacket data(SMSG_BINDER_CONFIRM, 8);
    data << guid;
    GetSession()->SendPacket( &data );
}

void Player::SendTalentWipeConfirm(uint64 guid)
{
    WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
    data << guid;
    data << (uint32)resetTalentsCost();
    GetSession()->SendPacket( &data );
}

void Player::SendPetSkillWipeConfirm()
{
    Pet* pet = GetPet();
    if(!pet)
        return;
    WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
    data << pet->GetGUID();
    data << uint32(pet->resetTalentsCost());
    GetSession()->SendPacket( &data );
}

/*********************************************************/
/***                    STORAGE SYSTEM                 ***/
/*********************************************************/

void Player::SetVirtualItemSlot( uint8 i, Item* item)
{
    assert(i < 3);
    SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO + 2*i,    item ? item->GetGUIDLow()              : 0);
    SetUInt32Value(UNIT_VIRTUAL_ITEM_INFO + 2*i +1, item ? item->GetProto()->Sheath        : 0);
    SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY+i,item ? item->GetProto()->DisplayInfoID : 0);
    if(i < 2 && item)
    {
        if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
            return;
        uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
        if(charges == 0)
            return;
        if(charges > 1)
            item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
        else if(charges <= 1)
        {
            ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
            item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
        }
    }
}

void Player::SetSheath( uint32 sheathed )
{
    Item* item;
    switch (sheathed)
    {
        case 0:                                             // no prepeared weapon
            SetVirtualItemSlot(0,NULL);
            SetVirtualItemSlot(1,NULL);
            SetVirtualItemSlot(2,NULL);
            break;
        case 1:                                             // prepeared melee weapon
        {
            item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
            SetVirtualItemSlot(0,item && !item->IsBroken() && IsUseEquipedWeapon(true) ? item : NULL);
            item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
            SetVirtualItemSlot(1,item && !item->IsBroken() && IsUseEquipedWeapon(false) ? item : NULL);
            SetVirtualItemSlot(2,NULL);
        };  break;
        case 2:                                             // prepeared ranged weapon
            SetVirtualItemSlot(0,NULL);
            SetVirtualItemSlot(1,NULL);
            item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
            SetVirtualItemSlot(2,item && !item->IsBroken() && IsUseEquipedWeapon(false) ? item : NULL);
            break;
        default:
            SetVirtualItemSlot(0,NULL);
            SetVirtualItemSlot(1,NULL);
            SetVirtualItemSlot(2,NULL);
            break;
    }
    SetUInt32Value(UNIT_FIELD_BYTES_2, 0x2800+sheathed);    // this must visualize Sheath changing for other players...
}

uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
{
    uint8 pClass = getClass();

    uint8 slots[4];
    slots[0] = NULL_SLOT;
    slots[1] = NULL_SLOT;
    slots[2] = NULL_SLOT;
    slots[3] = NULL_SLOT;
    switch( proto->InventoryType )
    {
        case INVTYPE_HEAD:
            slots[0] = EQUIPMENT_SLOT_HEAD;
            break;
        case INVTYPE_NECK:
            slots[0] = EQUIPMENT_SLOT_NECK;
            break;
        case INVTYPE_SHOULDERS:
            slots[0] = EQUIPMENT_SLOT_SHOULDERS;
            break;
        case INVTYPE_BODY:
            slots[0] = EQUIPMENT_SLOT_BODY;
            break;
        case INVTYPE_CHEST:
            slots[0] = EQUIPMENT_SLOT_CHEST;
            break;
        case INVTYPE_ROBE:
            slots[0] = EQUIPMENT_SLOT_CHEST;
            break;
        case INVTYPE_WAIST:
            slots[0] = EQUIPMENT_SLOT_WAIST;
            break;
        case INVTYPE_LEGS:
            slots[0] = EQUIPMENT_SLOT_LEGS;
            break;
        case INVTYPE_FEET:
            slots[0] = EQUIPMENT_SLOT_FEET;
            break;
        case INVTYPE_WRISTS:
            slots[0] = EQUIPMENT_SLOT_WRISTS;
            break;
        case INVTYPE_HANDS:
            slots[0] = EQUIPMENT_SLOT_HANDS;
            break;
        case INVTYPE_FINGER:
            slots[0] = EQUIPMENT_SLOT_FINGER1;
            slots[1] = EQUIPMENT_SLOT_FINGER2;
            break;
        case INVTYPE_TRINKET:
            slots[0] = EQUIPMENT_SLOT_TRINKET1;
            slots[1] = EQUIPMENT_SLOT_TRINKET2;
            break;
        case INVTYPE_CLOAK:
            slots[0] =  EQUIPMENT_SLOT_BACK;
            break;
        case INVTYPE_WEAPON:
        {
            slots[0] = EQUIPMENT_SLOT_MAINHAND;

            // suggest offhand slot only if know dual wielding
            // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
            if(CanDualWield())
                slots[1] = EQUIPMENT_SLOT_OFFHAND;
        };break;
        case INVTYPE_SHIELD:
            slots[0] = EQUIPMENT_SLOT_OFFHAND;
            break;
        case INVTYPE_RANGED:
            slots[0] = EQUIPMENT_SLOT_RANGED;
            break;
        case INVTYPE_2HWEAPON:
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
            break;
        case INVTYPE_TABARD:
            slots[0] = EQUIPMENT_SLOT_TABARD;
            break;
        case INVTYPE_WEAPONMAINHAND:
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
            break;
        case INVTYPE_WEAPONOFFHAND:
            slots[0] = EQUIPMENT_SLOT_OFFHAND;
            break;
        case INVTYPE_HOLDABLE:
            slots[0] = EQUIPMENT_SLOT_OFFHAND;
            break;
        case INVTYPE_THROWN:
            slots[0] = EQUIPMENT_SLOT_RANGED;
            break;
        case INVTYPE_RANGEDRIGHT:
            slots[0] = EQUIPMENT_SLOT_RANGED;
            break;
        case INVTYPE_BAG:
            slots[0] = INVENTORY_SLOT_BAG_1;
            slots[1] = INVENTORY_SLOT_BAG_2;
            slots[2] = INVENTORY_SLOT_BAG_3;
            slots[3] = INVENTORY_SLOT_BAG_4;
            break;
        case INVTYPE_RELIC:
        {
            switch(proto->SubClass)
            {
                case ITEM_SUBCLASS_ARMOR_LIBRAM:
                    if (pClass == CLASS_PALADIN)
                        slots[0] = EQUIPMENT_SLOT_RANGED;
                    break;
                case ITEM_SUBCLASS_ARMOR_IDOL:
                    if (pClass == CLASS_DRUID)
                        slots[0] = EQUIPMENT_SLOT_RANGED;
                    break;
                case ITEM_SUBCLASS_ARMOR_TOTEM:
                    if (pClass == CLASS_SHAMAN)
                        slots[0] = EQUIPMENT_SLOT_RANGED;
                    break;
                case ITEM_SUBCLASS_ARMOR_MISC:
                    if (pClass == CLASS_WARLOCK)
                        slots[0] = EQUIPMENT_SLOT_RANGED;
                    break;
            }
            break;
        }
        default :
            return NULL_SLOT;
    }

    if( slot != NULL_SLOT )
    {
        if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
        {
            for (int i = 0; i < 4; i++)
            {
                if ( slots[i] == slot )
                    return slot;
            }
        }
    }
    else
    {
        // search free slot at first
        for (int i = 0; i < 4; i++)
        {
            if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
            {
                // in case 2hand equipped weapon offhand slot empty but not free
                if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
                {
                    Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
                    if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
                        return slots[i];
                }
                else
                    return slots[i];
            }
        }

        // if not found free and can swap return first appropriate from used
        for (int i = 0; i < 4; i++)
        {
            if ( slots[i] != NULL_SLOT && swap )
                return slots[i];
        }
    }

    // no free position
    return NULL_SLOT;
}

Item* Player::CreateItem( uint32 item, uint32 count ) const
{
    ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
    if( pProto )
    {
        Item *pItem = NewItemOrBag( pProto );
        if ( count > pProto->Stackable )
            count = pProto->Stackable;
        if ( count < 1 )
            return NULL;                                    //don'n create item at zero count
        if( pItem->Create(objmgr.GenerateLowGuid(HIGHGUID_ITEM), item, const_cast<Player*>(this)) )
        {
            pItem->SetCount( count );
            return pItem;
        }
        else
            delete pItem;
    }
    return NULL;
}

uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
{
    Item *pItem;
    uint32 tempcount = 0;

    uint8 res = EQUIP_ERR_OK;

    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
            if(ires==EQUIP_ERR_OK)
            {
                tempcount += pItem->GetCount();
                if( tempcount >= count )
                    return EQUIP_ERR_OK;
            }
            else
                res = ires;
        }
    }
    for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            tempcount += pItem->GetCount();
            if( tempcount >= count )
                return EQUIP_ERR_OK;
        }
    }
    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            tempcount += pItem->GetCount();
            if( tempcount >= count )
                return EQUIP_ERR_OK;
        }
    }
    Bag *pBag;
    ItemPrototype const *pBagProto;
    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    pItem = GetItemByPos( i, j );
                    if( pItem && pItem->GetEntry() == item )
                    {
                        tempcount += pItem->GetCount();
                        if( tempcount >= count )
                            return EQUIP_ERR_OK;
                    }
                }
            }
        }
    }

    // not found req. item count and have unequippable items
    return res;
}

uint32 Player::GetItemCount( uint32 item, Item* eItem ) const
{
    Item *pItem;
    uint32 count = 0;
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem != eItem &&  pItem->GetEntry() == item )
            count += pItem->GetCount();
    }
    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem != eItem && pItem->GetEntry() == item )
            count += pItem->GetCount();
    }
    Bag *pBag;
    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
            count += pBag->GetItemCount(item,eItem);
    }

    if(eItem && eItem->GetProto()->GemProperties)
    {
        for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
        {
            pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
            if( pItem && pItem != eItem && pItem->GetProto()->Socket[0].Color )
                count += pItem->GetGemCountWithID(item);
        }
    }

    return count;
}

uint32 Player::GetBankItemCount( uint32 item, Item* eItem ) const
{
    Item *pItem;
    uint32 count = 0;
    for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem != eItem && pItem->GetEntry() == item )
            count += pItem->GetCount();
    }
    Bag *pBag;
    for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
    {
        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
            count += pBag->GetItemCount(item,eItem);
    }

    if(eItem && eItem->GetProto()->GemProperties)
    {
        for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
        {
            pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
            if( pItem && pItem != eItem && pItem->GetProto()->Socket[0].Color )
                count += pItem->GetGemCountWithID(item);
        }
    }

    return count;
}

Item* Player::GetItemByGuid( uint64 guid ) const
{
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetGUID() == guid )
            return pItem;
    }
    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetGUID() == guid )
            return pItem;
    }

    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            ItemPrototype const *pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    Item* pItem = pBag->GetItemByPos( j );
                    if( pItem && pItem->GetGUID() == guid )
                        return pItem;
                }
            }
        }
    }
    for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
    {
        Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            ItemPrototype const *pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    Item* pItem = pBag->GetItemByPos( j );
                    if( pItem && pItem->GetGUID() == guid )
                        return pItem;
                }
            }
        }
    }

    return NULL;
}

Item* Player::GetItemByPos( uint16 pos ) const
{
    uint8 bag = pos >> 8;
    uint8 slot = pos & 255;
    return GetItemByPos( bag, slot );
}

Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
{
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
        return m_items[slot];
    else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
        || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
    {
        Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
        if ( pBag )
            return pBag->GetItemByPos(slot);
    }
    return NULL;
}

bool Player::HasBankBagSlot( uint8 slot ) const
{
    uint32 maxslot = ((GetUInt32Value(PLAYER_BYTES_2) & 0x70000) >> 16) + BANK_SLOT_BAG_START;
    if( slot < maxslot )
        return true;
    return false;
}

bool Player::IsInventoryPos( uint8 bag, uint8 slot )
{
    if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
        return true;
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
        return true;
    if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
        return true;
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
        return true;
    return false;
}

bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
{
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
        return true;
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
        return true;
    return false;
}

bool Player::IsBankBagPos( uint8 bag, uint8 slot )
{
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
        return true;
    return false;
}

bool Player::IsBankPos( uint8 bag, uint8 slot )
{
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
        return true;
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
        return true;
    if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
        return true;
    return false;
}

bool Player::IsBagPos( uint16 pos )
{
    uint8 bag = pos >> 8;
    uint8 slot = pos & 255;
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
        return true;
    if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
        return true;
    return false;
}

bool Player::HasItemCount( uint32 item, uint32 count ) const
{
    Item *pItem;
    uint32 tempcount = 0;
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            tempcount += pItem->GetCount();
            if( tempcount >= count )
                return true;
        }
    }
    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            tempcount += pItem->GetCount();
            if( tempcount >= count )
                return true;
        }
    }
    Bag *pBag;
    ItemPrototype const *pBagProto;
    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    pItem = GetItemByPos( i, j );
                    if( pItem && pItem->GetEntry() == item )
                    {
                        tempcount += pItem->GetCount();
                        if( tempcount >= count )
                            return true;
                    }
                }
            }
        }
    }
    return false;
}

Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
{
    Item *pItem;
    for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
            return pItem;
    }

    ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
    if (pProto && pProto->GemProperties)
    {
        for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
        {
            pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
            if( pItem && pItem->GetProto()->Socket[0].Color )
            {
                if (pItem->GetGemCountWithID(item) > 0 )
                    return pItem;
            }
        }
    }

    return NULL;
}

uint8 Player::CanStoreNewItem( uint8 bag, uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
{
    dest = 0;
    Item *pItem = CreateItem( item, count );
    if( pItem )
    {
        uint8 result = CanStoreItem( bag, slot, dest, pItem, swap );
        delete pItem;
        return result;
    }
    if( !swap )
        return EQUIP_ERR_ITEM_NOT_FOUND;
    else
        return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}

uint8 Player::CanTakeMoreSimilarItems(Item* pItem) const
{
    ItemPrototype const *pProto = pItem->GetProto();
    if( !pProto )
        return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;

    // no maximum
    if(pProto->MaxCount == 0)
        return EQUIP_ERR_OK;

    uint32 curcount = GetItemCount(pProto->ItemId,pItem) + GetBankItemCount(pProto->ItemId,pItem);

    if( curcount + pItem->GetCount() > pProto->MaxCount )
        return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;

    return EQUIP_ERR_OK;
}

bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
{
    Item *pItem;
    for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
            return true;
    }
    for(uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
            return true;
    }
    Bag *pBag;
    ItemPrototype const *pBagProto;
    for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; ++j)
                {
                    pItem = GetItemByPos( i, j );
                    if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
                        return true;
                }
            }
        }
    }
    return false;
}

uint8 Player::CanStoreItem( uint8 bag, uint8 slot, uint16 &dest, Item *pItem, bool swap ) const
{
    dest = 0;
    if( pItem )
    {
        sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
        ItemPrototype const *pProto = pItem->GetProto();
        if( pProto )
        {
            Item *pItem2;
            Bag *pBag;
            ItemPrototype const *pBagProto;
            uint16 pos;
            if(pItem->IsBindedNotWith(GetGUID()))
                return EQUIP_ERR_DONT_OWN_THAT_ITEM;

            // check count of items (skip for auto move for same player from bank)
            uint8 res = CanTakeMoreSimilarItems(pItem);
            if(res != EQUIP_ERR_OK)
                return res;

            if( bag == NULL_BAG )
            {
                // search stack for merge to
                if( pProto->Stackable > 1 )
                {
                    for(uint32 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
                    {
                        pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        pItem2 = GetItemByPos( pos );
                        if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                        {
                            dest = pos;
                            return EQUIP_ERR_OK;
                        }
                    }

                    for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
                    {
                        pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        pItem2 = GetItemByPos( pos );
                        if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                        {
                            dest = pos;
                            return EQUIP_ERR_OK;
                        }
                    }
                    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
                    {
                        pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        pBag = (Bag*)GetItemByPos( pos );
                        if( pBag )
                        {
                            pBagProto = pBag->GetProto();
                            if( pBagProto )
                            {
                                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                {
                                    pos = ( (i << 8) | j );
                                    pItem2 = GetItemByPos( pos );
                                    if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                                    {
                                        dest = pos;
                                        return EQUIP_ERR_OK;
                                    }
                                }
                            }
                        }
                    }
                }

                // search free slot - special bag case
                if( pProto->BagFamily )
                {
                    if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
                    {
                        uint32 keyringSize = GetMaxKeyringSize();
                        for(uint32 j = KEYRING_SLOT_START; j < KEYRING_SLOT_START+keyringSize; j++)
                        {
                            pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
                            if( !pItem2 )
                            {
                                dest = ( (INVENTORY_SLOT_BAG_0 << 8) | j );
                                return EQUIP_ERR_OK;
                            }
                        }
                    }

                    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
                    {
                        pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                        if( pBag )
                        {
                            pBagProto = pBag->GetProto();

                            // not plain container check
                            if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
                                pItem->CanGoIntoBag(pBagProto) )
                            {
                                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                {
                                    pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                                    pItem2 = GetItemByPos( i, j );
                                    if( !pItem2 )
                                    {
                                        dest = ( (i << 8) | j );
                                        return EQUIP_ERR_OK;
                                    }
                                }
                            }
                        }
                    }
                }

                // search free slot
                for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
                {
                    pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                    if( !pItem2 )
                    {
                        dest = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        return EQUIP_ERR_OK;
                    }
                }

                for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
                {
                    pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                    if( pBag )
                    {
                        pBagProto = pBag->GetProto();
                        if( pBagProto && pItem->CanGoIntoBag(pBagProto))
                        {
                            for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                            {
                                pItem2 = GetItemByPos( i, j );
                                if( !pItem2 )
                                {
                                    dest = ( (i << 8) | j );
                                    return EQUIP_ERR_OK;
                                }
                            }
                        }
                    }
                }
                return EQUIP_ERR_INVENTORY_FULL;
            }
            else                                            // in specific bag
            {
                if( slot == NULL_SLOT )
                {
                    if( pProto->InventoryType == INVTYPE_BAG )
                    {
                        Bag *pBag = (Bag*)pItem;
                        if( pBag && !pBag->IsEmpty() )
                            return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
                    }

                    // search stack in bag for merge to
                    if( pProto->Stackable > 1 )
                    {
                        if( bag == INVENTORY_SLOT_BAG_0 )
                        {
                            for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
                            {
                                pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                                if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                                {
                                    dest = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                                    return EQUIP_ERR_OK;
                                }
                            }

                            for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
                            {
                                pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                                if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                                {
                                    dest = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                                    return EQUIP_ERR_OK;
                                }
                            }
                        }
                        else
                        {
                            pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
                            if( pBag )
                            {
                                pBagProto = pBag->GetProto();
                                if( pBagProto )
                                {
                                    for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                    {
                                        pItem2 = GetItemByPos( bag, j );
                                        if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                                        {
                                            dest = ( (bag << 8) | j );
                                            return EQUIP_ERR_OK;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if( bag == INVENTORY_SLOT_BAG_0 )
                    {
                        // search free slot - keyring case
                        if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
                        {
                            uint32 keyringSize = GetMaxKeyringSize();
                            for(uint32 j = KEYRING_SLOT_START; j < KEYRING_SLOT_START+keyringSize; j++)
                            {
                                pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
                                if( !pItem2 )
                                {
                                    dest = ( (INVENTORY_SLOT_BAG_0 << 8) | j );
                                    return EQUIP_ERR_OK;
                                }
                            }
                        }

                        for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
                        {
                            pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                            if( !pItem2 )
                            {
                                dest = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                                return EQUIP_ERR_OK;
                            }
                        }
                    }
                    else
                    {
                        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
                        if( pBag )
                        {
                            pBagProto = pBag->GetProto();
                            if( pBagProto )
                            {
                                if( pBagProto->Class == ITEM_CLASS_QUIVER && pBagProto->SubClass != pProto->SubClass )
                                    return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
                                if( !pItem->CanGoIntoBag(pBagProto) )
                                    return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
                                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                {
                                    pItem2 = GetItemByPos( bag, j );
                                    if( !pItem2 )
                                    {
                                        dest = ( (bag << 8) | j );
                                        return EQUIP_ERR_OK;
                                    }
                                }
                            }
                        }
                    }
                    return EQUIP_ERR_BAG_FULL;
                }
                else                                        // specific bag and slot
                {
                    if( pProto->InventoryType == INVTYPE_BAG )
                    {
                        Bag *pBag = (Bag*)pItem;
                        if( pBag && !pBag->IsEmpty() )
                            return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
                    }
                    pItem2 = GetItemByPos( bag, slot );
                    if( pItem2 && !swap )
                    {
                        if( pProto->Stackable > 1 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() < pProto->Stackable )
                        {
                            dest = ( (bag << 8) | slot );
                            return EQUIP_ERR_OK;
                        }
                        else
                            return EQUIP_ERR_COULDNT_SPLIT_ITEMS;
                    }
                    else
                    {
                        if( bag == INVENTORY_SLOT_BAG_0 )
                        {

                            // keyring case
                            if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
                                return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;

                            // prevent cheating
                            if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
                                return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;

                            dest = ( (bag << 8) | slot );
                            return EQUIP_ERR_OK;
                        }
                        else
                        {
                            pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
                            if( pBag )
                            {
                                pBagProto = pBag->GetProto();
                                if( pBagProto )
                                {
                                    if( pBagProto->Class == ITEM_CLASS_QUIVER && pBagProto->SubClass != pProto->SubClass )
                                        return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
                                    if( !pItem->CanGoIntoBag(pBagProto) )
                                        return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
                                    dest = ( (bag << 8) | slot );
                                    return EQUIP_ERR_OK;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if( !swap )
        return EQUIP_ERR_ITEM_NOT_FOUND;
    else
        return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}

//////////////////////////////////////////////////////////////////////////
uint8 Player::CanStoreItems( Item **pItems,int count) const
{
    Item    *pItem2;

    // fill space table
    int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
    int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
    int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];

    memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
    memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
    memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));

    for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );

        if (pItem2 && !pItem2->IsInTrade())
        {
            inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
        }
    }

    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );

        if (pItem2 && !pItem2->IsInTrade())
        {
            inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
        }
    }

    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        Bag     *pBag;
        ItemPrototype const *pBagProto;

        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            pBagProto = pBag->GetProto();

            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    pItem2 = GetItemByPos( i, j );
                    if (pItem2 && !pItem2->IsInTrade())
                    {
                        inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
                    }
                }
            }
        }
    }

    // check free space for all items
    for (int k=0;k<count;k++)
    {
        Item  *pItem = pItems[k];

        // no item
        if (!pItem)  continue;

        sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
        ItemPrototype const *pProto = pItem->GetProto();

        // strange item
        if( !pProto )
            return EQUIP_ERR_ITEM_NOT_FOUND;

        // item it 'bind'
        if(pItem->IsBindedNotWith(GetGUID()))
            return EQUIP_ERR_DONT_OWN_THAT_ITEM;

        Bag *pBag;
        ItemPrototype const *pBagProto;

        // item is 'one item only'
        uint8 res = CanTakeMoreSimilarItems(pItem);
        if(res != EQUIP_ERR_OK)
            return res;

        // search stack for merge to
        if( pProto->Stackable > 1 )
        {
            bool b_found = false;

            for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
            {
                pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
                if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
                {
                    inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
                    b_found = true;
                    break;
                }
            }
            if (b_found) continue;

            for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
            {
                pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
                if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
                {
                    inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
                    b_found = true;
                    break;
                }
            }
            if (b_found) continue;

            for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
            {
                pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
                if( pBag )
                {
                    pBagProto = pBag->GetProto();
                    if( pBagProto )
                    {
                        for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                        {
                            pItem2 = GetItemByPos( t, j );
                            if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
                            {
                                inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
                                b_found = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (b_found) continue;
        }

        // special bag case
        if( pProto->BagFamily )
        {
            bool b_found = false;
            if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
            {
                uint32 keyringSize = GetMaxKeyringSize();
                for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
                {
                    if( inv_keys[t-KEYRING_SLOT_START] == 0 )
                    {
                        inv_keys[t-KEYRING_SLOT_START] = 1;
                        b_found = true;
                        break;
                    }
                }
            }

            if (b_found) continue;

            for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
            {
                pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
                if( pBag )
                {
                    pBagProto = pBag->GetProto();

                    // not plain container check
                    if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) && pItem->CanGoIntoBag(pBagProto) )
                    {
                        for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                        {
                            if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
                            {
                                inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
                                b_found = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (b_found) continue;
        }

        // search free slot
        bool b_found = false;
        for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
        {
            if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
            {
                inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
                b_found = true;
                break;
            }
        }
        if (b_found) continue;

        // search free slot in bags
        for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
        {
            pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
            if( pBag )
            {
                pBagProto = pBag->GetProto();
                if( pBagProto && pItem->CanGoIntoBag(pBagProto))
                {
                    for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                    {
                        if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
                        {
                            inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
                            b_found = true;
                            break;
                        }
                    }
                }
            }
        }

        // no free slot found?
        if (!b_found)
            return EQUIP_ERR_INVENTORY_FULL;
    }

    return EQUIP_ERR_OK;
}

//////////////////////////////////////////////////////////////////////////
uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
{
    dest = 0;
    Item *pItem = CreateItem( item, count );
    if( pItem )
    {
        uint8 result = CanEquipItem(slot, dest, pItem, swap );
        delete pItem;
        return result;
    }

    return EQUIP_ERR_ITEM_NOT_FOUND;
}

uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
{
    dest = 0;
    if( pItem )
    {
        sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
        ItemPrototype const *pProto = pItem->GetProto();
        if( pProto )
        {
            if(pItem->IsBindedNotWith(GetGUID()))
                return EQUIP_ERR_DONT_OWN_THAT_ITEM;

            // check count of items (skip for auto move for same player from bank)
            uint8 res = CanTakeMoreSimilarItems(pItem);
            if(res != EQUIP_ERR_OK)
                return res;

            if( isInCombat()&& pProto->Class != ITEM_CLASS_WEAPON && pProto->Class != ITEM_CLASS_PROJECTILE &&
                pProto->SubClass != ITEM_SUBCLASS_ARMOR_SHIELD && pProto->InventoryType != INVTYPE_RELIC)
                return EQUIP_ERR_NOT_IN_COMBAT;

            // do not allow gear change during in-progress arena matches, only weapons / offhands / relics / ammo
            if( InBattleGround() && GetBattleGround() && GetBattleGround()->isArena() && 
                (GetBattleGround()->GetStatus() == STATUS_IN_PROGRESS) &&
                (pProto->Class != ITEM_CLASS_WEAPON) && (pProto->Class != ITEM_CLASS_PROJECTILE) &&
                (pProto->SubClass != ITEM_SUBCLASS_ARMOR_SHIELD) && (pProto->InventoryType != INVTYPE_RELIC))
                return EQUIP_ERR_NOT_DURING_ARENA_MATCH;

            if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
                return EQUIP_ERR_CANT_DO_RIGHT_NOW;         // maybe exist better err

            uint8 eslot = FindEquipSlot( pProto, slot, swap );
            if( eslot == NULL_SLOT )
                return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;

            uint8 msg = CanUseItem( pItem , not_loading );
            if( msg != EQUIP_ERR_OK )
                return msg;
            if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
                return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;

            // check unique-equipped on item
            if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
            {
                // there is an equip limit on this item
                Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
                if (tItem && (!swap || tItem->GetSlot() != eslot ) )
                    return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
            }

            // check unique-equipped on gems
            for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
            {
                uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
                if(!enchant_id)
                    continue;
                SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
                if(!enchantEntry)
                    continue;

                ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
                if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
                {
                    Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
                    if(tItem && (!swap || tItem->GetSlot() != eslot ))
                        return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
                }
            }

            // check unique-equipped special item classes
            if (pProto->Class == ITEM_CLASS_QUIVER)
            {
                for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
                {
                    if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
                    {
                        if( ItemPrototype const* pBagProto = pBag->GetProto() )
                        {
                            if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
                                (!swap || pBag->GetSlot() != eslot ) )
                            {
                                if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
                                    return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
                                else
                                    return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
                            }
                        }
                    }
                }
            }

            uint32 type = pProto->InventoryType;

            if(eslot == EQUIPMENT_SLOT_OFFHAND)
            {
                if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
                {
                    if(!CanDualWield())
                        return EQUIP_ERR_CANT_DUAL_WIELD;
                }

                Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
                if(mainItem)
                {
                    if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
                        return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
                }
            }

            // equip two-hand weapon case (with possible unequip 2 items)
            if( type == INVTYPE_2HWEAPON )
            {
                if(eslot != EQUIPMENT_SLOT_MAINHAND)
                    return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;

                // offhand item must can be stored in inventitory for offhand item and it also must be unequipped
                Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
                uint16 off_dest;
                if( offItem && (!not_loading ||
                    CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) !=  EQUIP_ERR_OK ||
                    CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) !=  EQUIP_ERR_OK ) )
                    return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
            }
            dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
            return EQUIP_ERR_OK;
        }
    }
    if( !swap )
        return EQUIP_ERR_ITEM_NOT_FOUND;
    else
        return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}

uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
{
    // Applied only to equipped items and bank bags
    if(!IsEquipmentPos(pos) && !IsBagPos(pos))
        return EQUIP_ERR_OK;

    Item* pItem = GetItemByPos(pos);

    // Applied only to existed equipped item
    if( !pItem )
        return EQUIP_ERR_OK;

    sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());

    ItemPrototype const *pProto = pItem->GetProto();
    if( !pProto )
        return EQUIP_ERR_ITEM_NOT_FOUND;

    if( isInCombat()&& pProto->Class != ITEM_CLASS_WEAPON && pProto->Class != ITEM_CLASS_PROJECTILE &&
        pProto->SubClass != ITEM_SUBCLASS_ARMOR_SHIELD && pProto->InventoryType != INVTYPE_RELIC )
        return EQUIP_ERR_NOT_IN_COMBAT;

    // do not allow unequipping gear in in-progress arenas, except weapons, offhands, projectiles, relics
    if( InBattleGround() && GetBattleGround() && GetBattleGround()->isArena() && 
        (GetBattleGround()->GetStatus() == STATUS_IN_PROGRESS) &&
        (pProto->Class != ITEM_CLASS_WEAPON) && (pProto->Class != ITEM_CLASS_PROJECTILE) &&
        (pProto->SubClass != ITEM_SUBCLASS_ARMOR_SHIELD) && (pProto->InventoryType != INVTYPE_RELIC))
        return EQUIP_ERR_NOT_DURING_ARENA_MATCH;

    if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
        return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;

    return EQUIP_ERR_OK;
}

uint8 Player::CanBankItem( uint8 bag, uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
{
    dest = 0;
    if( pItem )
    {
        sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
        ItemPrototype const *pProto = pItem->GetProto();
        if( pProto )
        {
            Item *pItem2;
            Bag *pBag;
            ItemPrototype const *pBagProto;
            uint16 pos;
            if( pItem->IsBindedNotWith(GetGUID()) )
                return EQUIP_ERR_DONT_OWN_THAT_ITEM;

            // check count of items (skip for auto move for same player from bank)
            uint8 res = CanTakeMoreSimilarItems(pItem);
            if(res != EQUIP_ERR_OK)
                return res;

            if( bag == NULL_BAG )
            {
                if( pProto->Stackable > 1 )
                {
                    for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
                    {
                        pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        pItem2 = GetItemByPos( pos );
                        if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                        {
                            dest = pos;
                            return EQUIP_ERR_OK;
                        }
                    }
                    for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
                    {
                        pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        pBag = (Bag*)GetItemByPos( pos );
                        if( pBag )
                        {
                            pBagProto = pBag->GetProto();
                            if( pBagProto )
                            {
                                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                {
                                    pos = ( (i << 8) | j );
                                    pItem2 = GetItemByPos( pos );
                                    if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                                    {
                                        dest = pos;
                                        return EQUIP_ERR_OK;
                                    }
                                }
                            }
                        }
                    }
                }

                // search place in special bag
                if( pProto->BagFamily )
                {
                    for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
                    {
                        pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                        if( pBag )
                        {
                            pBagProto = pBag->GetProto();
                            // not plain container check
                            if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
                                pItem->CanGoIntoBag(pBagProto) )
                            {
                                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                {
                                    pos = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                                    pItem2 = GetItemByPos( i, j );
                                    if( !pItem2 )
                                    {
                                        dest = ( (i << 8) | j );
                                        return EQUIP_ERR_OK;
                                    }
                                }
                            }
                        }
                    }
                }

                // search free space
                for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
                {
                    pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                    if( !pItem2 )
                    {
                        dest = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                        return EQUIP_ERR_OK;
                    }
                }
                for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
                {
                    pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                    if( pBag )
                    {
                        pBagProto = pBag->GetProto();
                        if( pBagProto && pItem->CanGoIntoBag(pBagProto) )
                        {
                            for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                            {
                                pItem2 = GetItemByPos( i, j );
                                if( !pItem2 )
                                {
                                    dest = ( (i << 8) | j );
                                    return EQUIP_ERR_OK;
                                }
                            }
                        }
                    }
                }
                return EQUIP_ERR_BANK_FULL;
            }
            else
            {
                if( slot == NULL_SLOT )
                {
                    if( pProto->InventoryType == INVTYPE_BAG )
                    {
                        Bag *pBag = (Bag*)pItem;
                        if( pBag && !pBag->IsEmpty() )
                            return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
                    }
                    if( pProto->Stackable > 1 )
                    {
                        if( bag == INVENTORY_SLOT_BAG_0 )
                        {
                            for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
                            {
                                pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                                if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                                {
                                    dest = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                                    return EQUIP_ERR_OK;
                                }
                            }
                        }
                        else
                        {
                            pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
                            if( pBag )
                            {
                                pBagProto = pBag->GetProto();
                                if( pBagProto )
                                {
                                    for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                    {
                                        pItem2 = GetItemByPos( bag, j );
                                        if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() + pItem->GetCount() <= pProto->Stackable )
                                        {
                                            dest = ( (bag << 8) | j );
                                            return EQUIP_ERR_OK;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if( bag == INVENTORY_SLOT_BAG_0 )
                    {
                        for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
                        {
                            pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
                            if( !pItem2 )
                            {
                                dest = ( (INVENTORY_SLOT_BAG_0 << 8) | i );
                                return EQUIP_ERR_OK;
                            }
                        }
                    }
                    else
                    {
                        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
                        if( pBag )
                        {
                            pBagProto = pBag->GetProto();
                            if( pBagProto )
                            {
                                if( pBagProto->Class == ITEM_CLASS_QUIVER && pBagProto->SubClass != pProto->SubClass )
                                    return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
                                if( !pItem->CanGoIntoBag(pBagProto) )
                                    return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
                                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                                {
                                    pItem2 = GetItemByPos( bag, j );
                                    if( !pItem2 )
                                    {
                                        dest = ( (bag << 8) | j );
                                        return EQUIP_ERR_OK;
                                    }
                                }
                            }
                        }
                    }
                    return EQUIP_ERR_BAG_FULL;
                }
                else
                {
                    if( pProto->InventoryType == INVTYPE_BAG )
                    {
                        Bag *pBag = (Bag*)pItem;
                        if( pBag )
                        {
                            if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
                            {
                                if( !HasBankBagSlot( slot ) )
                                    return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
                                if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
                                    return cantuse;
                            }
                            else
                            {
                                if( !pBag->IsEmpty() )
                                    return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
                            }
                        }
                    }
                    else
                    {
                        if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
                            return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
                    }
                    pItem2 = GetItemByPos( bag, slot );
                    if( pItem2 && !swap )
                    {
                        if( pProto->Stackable > 1 && pItem2->GetEntry() == pItem->GetEntry() && pItem2->GetCount() < pProto->Stackable )
                        {
                            dest = ( (bag << 8) | slot );
                            return EQUIP_ERR_OK;
                        }
                        else
                            return EQUIP_ERR_COULDNT_SPLIT_ITEMS;
                    }
                    else
                    {
                        if( bag == INVENTORY_SLOT_BAG_0 )
                        {
                            dest = ( (bag << 8) | slot );
                            return EQUIP_ERR_OK;
                        }
                        else
                        {
                            pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
                            if( pBag )
                            {
                                pBagProto = pBag->GetProto();
                                if( pBagProto )
                                {
                                    if( pBagProto->Class == ITEM_CLASS_QUIVER && pBagProto->SubClass != pProto->SubClass )
                                        return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
                                    if( !pItem->CanGoIntoBag(pBagProto) )
                                        return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
                                    dest = ( (bag << 8) | slot );
                                    return EQUIP_ERR_OK;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if( !swap )
        return EQUIP_ERR_ITEM_NOT_FOUND;
    else
        return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}

uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
{
    if( pItem )
    {
        sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
        if( !isAlive() && not_loading )
            return EQUIP_ERR_YOU_ARE_DEAD;
        //if( isStunned() )
        //    return EQUIP_ERR_YOU_ARE_STUNNED;
        ItemPrototype const *pProto = pItem->GetProto();
        if( pProto )
        {
            if( pItem->IsBindedNotWith(GetGUID()) )
                return EQUIP_ERR_DONT_OWN_THAT_ITEM;
            if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
                return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
            if( pItem->GetSkill() != 0  )
            {
                if( GetSkillValue( pItem->GetSkill() ) == 0 )
                    return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
            }
            if( pProto->RequiredSkill != 0  )
            {
                if( GetSkillValue( pProto->RequiredSkill ) == 0 )
                    return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
                else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
                    return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
            }
            if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
                return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
            if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
                return EQUIP_ERR_CANT_EQUIP_REPUTATION;
            if( getLevel() < pProto->RequiredLevel )
                return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
            return EQUIP_ERR_OK;
        }
    }
    return EQUIP_ERR_ITEM_NOT_FOUND;
}

bool Player::CanUseItem( ItemPrototype const *pProto )
{
    // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player

    if( pProto )
    {
        if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
            return false;
        if( pProto->RequiredSkill != 0  )
        {
            if( GetSkillValue( pProto->RequiredSkill ) == 0 )
                return false;
            else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
                return false;
        }
        if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
            return false;
        if( getLevel() < pProto->RequiredLevel )
            return false;
        return true;
    }
    return false;
}

uint8 Player::CanUseAmmo( uint32 item ) const
{
    sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
    if( !isAlive() )
        return EQUIP_ERR_YOU_ARE_DEAD;
    //if( isStunned() )
    //    return EQUIP_ERR_YOU_ARE_STUNNED;
    ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
    if( pProto )
    {
        if( pProto->InventoryType!= INVTYPE_AMMO )
            return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
        if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
            return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
        if( pProto->RequiredSkill != 0  )
        {
            if( GetSkillValue( pProto->RequiredSkill ) == 0 )
                return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
            else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
                return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
        }
        if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
            return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
        /*if( GetReputation() < pProto->RequiredReputation )
        return EQUIP_ERR_CANT_EQUIP_REPUTATION;
        */
        if( getLevel() < pProto->RequiredLevel )
            return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
        return EQUIP_ERR_OK;
    }
    return EQUIP_ERR_ITEM_NOT_FOUND;
}

void Player::SetAmmo( uint32 item )
{
    if(!item)
        return;

    // already set
    if( GetUInt32Value(PLAYER_AMMO_ID) == item )
        return;

    // check ammo
    if(item)
    {
        uint8 msg = CanUseAmmo( item );
        if( msg != EQUIP_ERR_OK )
        {
            SendEquipError( msg, NULL, NULL );
            return;
        }
    }

    SetUInt32Value(PLAYER_AMMO_ID, item);

    _ApplyAmmoBonuses();
}

void Player::RemoveAmmo()
{
    SetUInt32Value(PLAYER_AMMO_ID, 0);

    m_ammoDPS = 0.0f;

    if(CanModifyStats())
        UpdateDamagePhysical(RANGED_ATTACK);
}

// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::StoreNewItem( uint16 pos, uint32 item, uint32 count, bool update ,int32 randomPropertyId )
{
    Item *pItem = CreateItem( item, count );
    if( pItem )
    {
        ItemAddedQuestCheck( item, count );
        if(randomPropertyId)
            pItem->SetItemRandomProperties(randomPropertyId);
        Item * retItem = StoreItem( pos, pItem, update );

        return retItem;
    }
    return NULL;
}

// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::StoreItem( uint16 pos, Item *pItem, bool update )
{
    if( pItem )
    {
        uint8 bag = pos >> 8;
        uint8 slot = pos & 255;

        if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
            pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
            pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBankBagPos(bag,slot) )
            pItem->SetBinding( true );

        sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());

        Item *pItem2 = GetItemByPos( bag, slot );

        if( !pItem2 )
        {
            if( bag == INVENTORY_SLOT_BAG_0 )
            {
                m_items[slot] = pItem;
                SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
                pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
                pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );

                pItem->SetSlot( slot );
                pItem->SetContainer( NULL );

                if( IsInWorld() && update )
                {
                    pItem->AddToWorld();
                    pItem->SendUpdateToPlayer( this );
                }

                pItem->SetState(ITEM_CHANGED, this);
            }
            else
            {
                Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
                if( pBag )
                {
                    pBag->StoreItem( slot, pItem, update );
                    if( IsInWorld() && update )
                    {
                        pItem->AddToWorld();
                        pItem->SendUpdateToPlayer( this );
                    }
                    pItem->SetState(ITEM_CHANGED, this);
                    pBag->SetState(ITEM_CHANGED, this);
                }
            }

            AddEnchantmentDurations(pItem);
            AddItemDurations(pItem);
        }
        else
        {
            pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
            if( IsInWorld() && update )
                pItem2->SendUpdateToPlayer( this );

            // delete item (it not in any slot currently)
            //pItem->DeleteFromDB();
            if( IsInWorld() && update )
            {
                pItem->RemoveFromWorld();
                pItem->DestroyForPlayer( this );
            }

            RemoveEnchantmentDurations(pItem);
            RemoveItemDurations(pItem);
            // AddItemDurations(pItem2); - pItem2 already have duration listed for player
            AddEnchantmentDurations(pItem2);

            pItem->SetOwnerGUID(GetGUID());                 // prevent error at next SetState in case trade/mail/buy from vendor
            pItem->SetState(ITEM_REMOVED, this);
            pItem2->SetState(ITEM_CHANGED, this);

            return pItem2;
        }
    }

    return pItem;
}

Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
{
    Item *pItem = CreateItem( item, count );
    if( pItem )
    {
        ItemAddedQuestCheck( item, count );
        Item * retItem = EquipItem( pos, pItem, update );

        return retItem;
    }
    return NULL;
}

Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
{
    if( pItem )
    {
        AddEnchantmentDurations(pItem);

        uint8 bag = pos >> 8;
        uint8 slot = pos & 255;

        Item *pItem2 = GetItemByPos( bag, slot );

        if( !pItem2 )
        {
            VisualizeItem( pos, pItem);
            uint8 slot = pos & 255;

            if(isAlive())
            {
                _ApplyItemMods(pItem, slot, true);

                ItemPrototype const *pProto = pItem->GetProto();
                if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
                {
                    m_weaponChangeTimer = DEFAULT_SWITCH_WEAPON;
                    if (getClass() == CLASS_ROGUE)
                        m_weaponChangeTimer = ROGUE_SWITCH_WEAPON;
                }
            }

            if( IsInWorld() && update )
            {
                pItem->AddToWorld();
                pItem->SendUpdateToPlayer( this );
            }

            ApplyEquipCooldown(pItem);
        }
        else
        {
            pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
            if( IsInWorld() && update )
                pItem2->SendUpdateToPlayer( this );

            // delete item (it not in any slot currently)
            //pItem->DeleteFromDB();
            if( IsInWorld() && update )
            {
                pItem->RemoveFromWorld();
                pItem->DestroyForPlayer( this );
            }

            RemoveEnchantmentDurations(pItem);
            // AddItemDurations(pItem2); - pItem2 already have duration listed for player

            pItem->SetOwnerGUID(GetGUID());                 // prevent error at next SetState in case trade/mail/buy from vendor
            pItem->SetState(ITEM_REMOVED, this);
            pItem2->SetState(ITEM_CHANGED, this);

            ApplyEquipCooldown(pItem2);
            return pItem2;
        }
    }

    return pItem;
}

void Player::QuickEquipItem( uint16 pos, Item *pItem)
{
    if( pItem )
    {
        VisualizeItem( pos, pItem);

        if( IsInWorld() )
        {
            pItem->AddToWorld();
            pItem->SendUpdateToPlayer( this );
        }
    }
}

void Player::VisualizeItem( uint16 pos, Item *pItem)
{
    if(!pItem)
        return;

    // check also  BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
    if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
        pItem->SetBinding( true );

    uint8 bag = pos >> 8;
    uint8 slot = pos & 255;

    sLog.outDebug( "STORAGE: EquipItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());

    m_items[slot] = pItem;
    SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
    pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
    pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
    pItem->SetSlot( slot );
    pItem->SetContainer( NULL );

    if( slot < EQUIPMENT_SLOT_END )
    {
        int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
        SetUInt32Value(VisibleBase, pItem->GetEntry());

        for(int i = 0; i < MAX_ENCHANTMENT_SLOT; ++i)
            SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));

        SetUInt32Value(VisibleBase + 8, uint32(pItem->GetItemRandomPropertyId()));
    }

    pItem->SetState(ITEM_CHANGED, this);
}

// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::BankItem( uint16 pos, Item *pItem, bool update )
{
    return StoreItem( pos, pItem, update);
}

void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
{
    // note: removeitem does not actually change the item
    // it only takes the item out of storage temporarily
    // note2: if removeitem is to be used for delinking
    // the item must be removed from the player's updatequeue

    Item *pItem = GetItemByPos( bag, slot );
    if( pItem )
    {
        sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());

        RemoveEnchantmentDurations(pItem);
        RemoveItemDurations(pItem);

        if( bag == INVENTORY_SLOT_BAG_0 )
        {
            if ( slot < INVENTORY_SLOT_BAG_END )
            {
                _ApplyItemMods(pItem, slot, false);

                // remove item dependent auras and casts (only weapon and armor slots)
                if(slot < EQUIPMENT_SLOT_END)
                    RemoveItemDependentAurasAndCasts(pItem);

                // remove held enchantments
                if ( slot == EQUIPMENT_SLOT_MAINHAND )
                {
                    if (pItem->GetItemSuffixFactor())
                    {
                        pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
                        pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
                    }
                    else
                    {
                        pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
                        pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
                    }
                }
            }

            m_items[slot] = NULL;
            SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);

            if ( slot < EQUIPMENT_SLOT_END )
            {
                int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
                for (int i = VisibleBase; i < VisibleBase + 12; ++i)
                    SetUInt32Value(i, 0);
            }
        }
        else
        {
            Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
            if( pBag )
                pBag->RemoveItem(slot, update);
        }
        pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
        // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
        pItem->SetSlot( NULL_SLOT );
        if( IsInWorld() && update )
            pItem->SendUpdateToPlayer( this );
    }
}

void Player::RemoveItemCount( uint32 item, uint32 count, bool update )
{
    sLog.outDebug( "STORAGE: RemoveItemCount item = %u, count = %u", item, count);
    Item *pItem;
    uint32 remcount = 0;
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            if( pItem->GetCount() + remcount <= count )
            {
                remcount += pItem->GetCount();
                RemoveItem( INVENTORY_SLOT_BAG_0, i, update );

                if(remcount >=count)
                    return;
            }
            else
            {
                pItem->SetCount( pItem->GetCount() - count + remcount );
                if( IsInWorld() && update )
                    pItem->SendUpdateToPlayer( this );
                pItem->SetState(ITEM_CHANGED, this);
                return;
            }
        }
    }
    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            if( pItem->GetCount() + remcount <= count )
            {
                remcount += pItem->GetCount();
                RemoveItem( INVENTORY_SLOT_BAG_0, i, update );

                if(remcount >=count)
                    return;
            }
            else
            {
                pItem->SetCount( pItem->GetCount() - count + remcount );
                if( IsInWorld() && update )
                    pItem->SendUpdateToPlayer( this );
                pItem->SetState(ITEM_CHANGED, this);
                return;
            }
        }
    }
    Bag *pBag;
    ItemPrototype const *pBagProto;
    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    pItem = GetItemByPos( i, j );
                    if( pItem && pItem->GetEntry() == item )
                    {
                        if( pItem->GetCount() + remcount <= count )
                        {
                            remcount += pItem->GetCount();
                            RemoveItem( i, j, update );

                            if(remcount >=count)
                                return;
                        }
                        else
                        {
                            pItem->SetCount( pItem->GetCount() - count + remcount );
                            if( IsInWorld() && update )
                                pItem->SendUpdateToPlayer( this );
                            pItem->SetState(ITEM_CHANGED, this);
                            return;
                        }
                    }
                }
            }
        }
    }
}

void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
{
    Item *pItem = GetItemByPos( bag, slot );
    if( pItem )
    {
        sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());

        // start from destroy contained items (only equipped bag can have its)
        if (pItem->IsBag() && pItem->IsEquipped())          // this also prevent infinity loop if empty bag stored in bag==slot
        {
            for (int i = 0; i < MAX_BAG_SIZE; i++)
                DestroyItem(slot,i,update);
        }

        if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
            CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());

        ItemPrototype const *pProto = pItem->GetProto();

        RemoveEnchantmentDurations(pItem);
        RemoveItemDurations(pItem);

        ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );

        if( bag == INVENTORY_SLOT_BAG_0 )
        {

            SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);

            // equipment and equipped bags can have applied bonuses
            if ( slot < INVENTORY_SLOT_BAG_END )
                _ApplyItemMods(pItem, slot, false);

            if ( slot < EQUIPMENT_SLOT_END )
            {
                // remove item dependent auras and casts (only weapon and armor slots)
                RemoveItemDependentAurasAndCasts(pItem);

                // equipment visual show
                int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
                for (int i = VisibleBase; i < VisibleBase + 12; ++i)
                    SetUInt32Value(i, 0);
            }

            m_items[slot] = NULL;
        }
        else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
            pBag->RemoveItem(slot, update);

        if( IsInWorld() && update )
        {
            pItem->RemoveFromWorld();
            pItem->DestroyForPlayer(this);
        }

        //pItem->SetOwnerGUID(0);
        pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
        pItem->SetSlot( NULL_SLOT );
        pItem->SetState(ITEM_REMOVED, this);
    }
}

void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
{
    sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
    Item *pItem;
    ItemPrototype const *pProto;
    uint32 remcount = 0;

    // in inventory
    for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            if( pItem->GetCount() + remcount <= count )
            {
                // all items in inventory can unequipped
                remcount += pItem->GetCount();
                DestroyItem( INVENTORY_SLOT_BAG_0, i, update);

                if(remcount >=count)
                    return;
            }
            else
            {
                pProto = pItem->GetProto();
                ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
                pItem->SetCount( pItem->GetCount() - count + remcount );
                if( IsInWorld() & update )
                    pItem->SendUpdateToPlayer( this );
                pItem->SetState(ITEM_CHANGED, this);
                return;
            }
        }
    }
    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            if( pItem->GetCount() + remcount <= count )
            {
                // all keys can be unequipped
                remcount += pItem->GetCount();
                DestroyItem( INVENTORY_SLOT_BAG_0, i, update);

                if(remcount >=count)
                    return;
            }
            else
            {
                pProto = pItem->GetProto();
                ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
                pItem->SetCount( pItem->GetCount() - count + remcount );
                if( IsInWorld() & update )
                    pItem->SendUpdateToPlayer( this );
                pItem->SetState(ITEM_CHANGED, this);
                return;
            }
        }
    }

    // in inventory bags
    Bag *pBag;
    ItemPrototype const *pBagProto;
    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    pItem = pBag->GetItemByPos(j);
                    if( pItem && pItem->GetEntry() == item )
                    {
                        // all items in bags can be unequipped
                        if( pItem->GetCount() + remcount <= count )
                        {
                            remcount += pItem->GetCount();
                            DestroyItem( i, j, update );

                            if(remcount >=count)
                                return;
                        }
                        else
                        {
                            pProto = pItem->GetProto();
                            ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
                            pItem->SetCount( pItem->GetCount() - count + remcount );
                            if( IsInWorld() && update )
                                pItem->SendUpdateToPlayer( this );
                            pItem->SetState(ITEM_CHANGED, this);
                            return;
                        }
                    }
                }
            }
        }
    }

    // in equipment and bag list
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetEntry() == item )
        {
            if( pItem->GetCount() + remcount <= count )
            {
                if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
                {
                    remcount += pItem->GetCount();
                    DestroyItem( INVENTORY_SLOT_BAG_0, i, update);

                    if(remcount >=count)
                        return;
                }
            }
            else
            {
                pProto = pItem->GetProto();
                ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
                pItem->SetCount( pItem->GetCount() - count + remcount );
                if( IsInWorld() & update )
                    pItem->SendUpdateToPlayer( this );
                pItem->SetState(ITEM_CHANGED, this);
                return;
            }
        }
    }
}

void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
{
    sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );

    // in inventory
    for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
            DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
    }
    for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
    {
        Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
            DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
    }

    // in inventory bags
    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            ItemPrototype const *pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    Item* pItem = pBag->GetItemByPos(j);
                    if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
                        DestroyItem( i, j, update);
                }
            }
        }
    }

    // in equipment and bag list
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
            DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
    }
}

void Player::DestroyConjuredItems( bool update )
{
    // used when entering arena
    // distroys all conjured items
    sLog.outDebug( "STORAGE: DestroyConjuredItems" );

    // in inventory
    for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetProto() &&
            (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) && 
            (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
            DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
    }

    // in inventory bags
    for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pBag )
        {
            ItemPrototype const *pBagProto = pBag->GetProto();
            if( pBagProto )
            {
                for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
                {
                    Item* pItem = pBag->GetItemByPos(j);
                    if( pItem && pItem->GetProto() &&
                        (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) && 
                        (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
                        DestroyItem( i, j, update);
                }
            }
        }
    }

    // in equipment and bag list
    for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if( pItem && pItem->GetProto() &&
            (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) && 
            (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
            DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
    }
}

void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
{
    if(!pItem)
        return;

    sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);

    if( pItem->GetCount() <= count )
    {
        count-= pItem->GetCount();

        DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
    }
    else
    {
        ItemRemovedQuestCheck( pItem->GetEntry(), count);
        pItem->SetCount( pItem->GetCount() - count );
        count = 0;
        if( IsInWorld() & update )
            pItem->SendUpdateToPlayer( this );
        pItem->SetState(ITEM_CHANGED, this);
    }
}

void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
{
    uint8 srcbag = src >> 8;
    uint8 srcslot = src & 255;

    uint8 dstbag = dst >> 8;
    uint8 dstslot = dst & 255;

    Item *pSrcItem = GetItemByPos( srcbag, srcslot );
    if( pSrcItem )
    {
        // not let split all items (can be only at cheating)
        if(pSrcItem->GetCount() == count)
        {
            SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
            return;
        }

        // not let split more existed items (can be only at cheating)
        if(pSrcItem->GetCount() < count)
        {
            SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
            return;
        }

        if(pSrcItem->m_lootGenerated)                       // prevent split looting item (item
        {
                                                            //best error message found for attempting to split while looting
            SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
            return;
        }

        sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
        Item *pNewItem = CreateItem( pSrcItem->GetEntry(), count );
        if( pNewItem )
        {
            uint16 dest;
            uint8 msg;
            if( IsInventoryPos( dst ) )
            {
                // change item amount before check (for unique max count check)
                pSrcItem->SetCount( pSrcItem->GetCount() - count );
                msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
                if( msg == EQUIP_ERR_OK )
                {
                    Item *pDstItem = GetItemByPos(dstbag, dstslot);
                    if (!pDstItem || pDstItem && pDstItem->GetCount() + count <= pDstItem->GetProto()->Stackable)
                    {
                        if( IsInWorld() )
                            pSrcItem->SendUpdateToPlayer( this );
                        pSrcItem->SetState(ITEM_CHANGED, this);
                        StoreItem( dest, pNewItem, true);
                    }
                    else
                    {
                        delete pNewItem;
                        pSrcItem->SetCount( pSrcItem->GetCount() + count );
                        SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
                    }
                }
                else
                {
                    delete pNewItem;
                    pSrcItem->SetCount( pSrcItem->GetCount() + count );
                    SendEquipError( msg, pSrcItem, NULL );
                }
            }
            else if( IsBankPos ( dst ) )
            {
                // change item amount before check (for unique max count check)
                pSrcItem->SetCount( pSrcItem->GetCount() - count );
                msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
                if( msg == EQUIP_ERR_OK )
                {
                    Item *pDstItem = GetItemByPos(dstbag, dstslot);
                    if (!pDstItem || pDstItem && pDstItem->GetCount() + count <= pDstItem->GetProto()->Stackable)
                    {
                        if( IsInWorld() )
                            pSrcItem->SendUpdateToPlayer( this );
                        pSrcItem->SetState(ITEM_CHANGED, this);
                        BankItem( dest, pNewItem, true);
                    }
                    else
                    {
                        delete pNewItem;
                        pSrcItem->SetCount( pSrcItem->GetCount() + count );
                        SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
                    }
                }
                else
                {
                    delete pNewItem;
                    pSrcItem->SetCount( pSrcItem->GetCount() + count );
                    SendEquipError( msg, pSrcItem, NULL );
                }
            }
            else if( IsEquipmentPos ( dst ) )
            {
                // change item amount before check (for unique max count check)
                pSrcItem->SetCount( pSrcItem->GetCount() + count );
                msg = CanEquipItem( dstslot, dest, pNewItem, false );
                if( msg == EQUIP_ERR_OK )
                {
                    Item *pDstItem = GetItemByPos(dstbag, dstslot);
                    if (!pDstItem || pDstItem && pDstItem->GetCount() + count <= pDstItem->GetProto()->Stackable)
                    {
                        if( IsInWorld() )
                            pSrcItem->SendUpdateToPlayer( this );
                        pSrcItem->SetState(ITEM_CHANGED, this);
                        EquipItem( dest, pNewItem, true);
                        AutoUnequipOffhandIfNeed();
                    }
                    else
                    {
                        delete pNewItem;
                        pSrcItem->SetCount( pSrcItem->GetCount() + count );
                        SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
                    }
                }
                else
                {
                    delete pNewItem;
                    pSrcItem->SetCount( pSrcItem->GetCount() + count );
                    SendEquipError( msg, pSrcItem, NULL );
                }
            }
            return;
        }
    }
    SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
}

void Player::SwapItem( uint16 src, uint16 dst )
{
    uint8 srcbag = src >> 8;
    uint8 srcslot = src & 255;

    uint8 dstbag = dst >> 8;
    uint8 dstslot = dst & 255;

    Item *pSrcItem = GetItemByPos( srcbag, srcslot );
    Item *pDstItem = GetItemByPos( dstbag, dstslot );

    if( pSrcItem )
    {
        sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());

        if(!isAlive() )
        {
            SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
            return;
        }

        if(pSrcItem->m_lootGenerated)                       // prevent swap looting item
        {
            //best error message found for attempting to swap while looting
            SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
            return;
        }

        // check unequip potability for equipped items and bank bags
        if(IsEquipmentPos ( src ) || IsBagPos ( src ))
        {
            // bags can be swapped with empty bag slots
            uint8 msg = CanUnequipItem( src, pDstItem != NULL || IsBagPos ( src ) && IsBagPos ( dst ));
            if(msg != EQUIP_ERR_OK)
            {
                SendEquipError( msg, pSrcItem, pDstItem );
                return;
            }

        }

        // prevent put equipped/bank bag in self
        if( IsBagPos ( src ) && srcslot == dstbag)
        {
            SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
            return;
        }

        uint16 dest;
        uint8 msg;
        if( !pDstItem )
        {
            if( IsInventoryPos( dst ) )
            {
                msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
                if( msg == EQUIP_ERR_OK )
                {
                    RemoveItem(srcbag, srcslot, true);
                    StoreItem( dest, pSrcItem, true);
                    return;
                }
                else
                    SendEquipError( msg, pSrcItem, NULL );
            }
            else if( IsBankPos ( dst ) )
            {
                msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
                if( msg == EQUIP_ERR_OK )
                {
                    RemoveItem(srcbag, srcslot, true);
                    BankItem( dest, pSrcItem, true);
                    return;
                }
                else
                    SendEquipError( msg, pSrcItem, NULL );
            }
            else if( IsEquipmentPos ( dst ) )
            {
                msg = CanEquipItem( dstslot, dest, pSrcItem, false );
                if( msg == EQUIP_ERR_OK )
                {
                    RemoveItem(srcbag, srcslot, true);
                    EquipItem( dest, pSrcItem, true);
                    AutoUnequipOffhandIfNeed();
                    return;
                }
                else
                    SendEquipError( msg, pSrcItem, NULL );
            }
        }
        else
        {
            if(pDstItem->m_lootGenerated)                   // prevent swap looting item
            {
                //best error message found for attempting to swap while looting
                SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
                return;
            }

            if( IsInventoryPos( dst ) )
            {
                if( CanStoreItem( dstbag, dstslot, dest, pSrcItem, false ) == EQUIP_ERR_OK )
                {
                    if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
                    {
                        RemoveItem(srcbag, srcslot, true);
                        StoreItem( dest, pSrcItem, true);
                    }
                    else
                    {
                        pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
                        pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
                        pSrcItem->SetState(ITEM_CHANGED, this);
                        pDstItem->SetState(ITEM_CHANGED, this);
                        if( IsInWorld() )
                        {
                            pSrcItem->SendUpdateToPlayer( this );
                            pDstItem->SendUpdateToPlayer( this );
                        }
                    }
                    return;
                }
            }
            else if( IsBankPos ( dst ) )
            {
                if( CanBankItem( dstbag, dstslot, dest, pSrcItem, false ) == EQUIP_ERR_OK )
                {
                    if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
                    {
                        RemoveItem(srcbag, srcslot, true);
                        BankItem( dest, pSrcItem, true);
                    }
                    else
                    {
                        pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
                        pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
                        pSrcItem->SetState(ITEM_CHANGED, this);
                        pDstItem->SetState(ITEM_CHANGED, this);
                        if( IsInWorld() )
                        {
                            pSrcItem->SendUpdateToPlayer( this );
                            pDstItem->SendUpdateToPlayer( this );
                        }
                    }
                    return;
                }
            }
            else if( IsEquipmentPos ( dst ) )
            {
                if( CanEquipItem( dstslot, dest, pSrcItem, false ) == EQUIP_ERR_OK )
                {
                    if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
                    {
                        RemoveItem(srcbag, srcslot, true);
                        EquipItem( dest, pSrcItem, true);
                        AutoUnequipOffhandIfNeed();
                    }
                    else
                    {
                        pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
                        pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
                        pSrcItem->SetState(ITEM_CHANGED, this);
                        pDstItem->SetState(ITEM_CHANGED, this);
                        if( IsInWorld() )
                        {
                            pSrcItem->SendUpdateToPlayer( this );
                            pDstItem->SendUpdateToPlayer( this );
                        }
                    }
                    return;
                }
            }
            if( IsInventoryPos( dst ) )
                msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, true );
            else if( IsBankPos( dst ) )
                msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, true );
            else if( IsEquipmentPos( dst ) )
            {
                msg = CanEquipItem( dstslot, dest, pSrcItem, true );
                if( msg == EQUIP_ERR_OK )
                    msg = CanUnequipItem( dest, true );
            }

            if( msg == EQUIP_ERR_OK )
            {
                uint16 dest2;
                if( IsInventoryPos( src ) )
                {
                    msg = CanStoreItem( srcbag, srcslot, dest2, pDstItem, true );
                    if( msg != EQUIP_ERR_OK )
                    {
                        SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG, pSrcItem, pDstItem );
                        return;
                    }
                }
                else if( IsBankPos( src ) )
                {
                    msg = CanBankItem( srcbag, srcslot, dest2, pDstItem, true );
                    if( msg != EQUIP_ERR_OK )
                    {
                        SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG, pSrcItem, pDstItem );
                        return;
                    }
                }
                else if( IsEquipmentPos( src ) )
                {
                    msg = CanEquipItem( srcslot, dest2, pDstItem, true);
                    if( msg == EQUIP_ERR_OK )
                        msg = CanUnequipItem( dest2, true);

                    if( msg != EQUIP_ERR_OK )
                    {
                        SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, pSrcItem, pDstItem );
                        return;
                    }
                }
                RemoveItem(dstbag, dstslot, false);
                RemoveItem(srcbag, srcslot, false);
                if( IsInventoryPos( dst ) )
                    StoreItem(dest, pSrcItem, true);
                else if( IsBankPos( dst ) )
                    BankItem(dest, pSrcItem, true);
                else if( IsEquipmentPos( dst ) )
                    EquipItem(dest, pSrcItem, true);
                if( IsInventoryPos( src ) )
                    StoreItem(dest2, pDstItem, true);
                else if( IsBankPos( src ) )
                    BankItem(dest2, pDstItem, true);
                else if( IsEquipmentPos( src ) )
                    EquipItem(dest2, pDstItem, true);
                AutoUnequipOffhandIfNeed();
                return;
            }
            else
                SendEquipError( msg, pSrcItem, pDstItem );
            return;
        }
    }
}

void Player::AddItemToBuyBackSlot( Item *pItem )
{
    if( pItem )
    {
        uint32 slot = m_currentBuybackSlot;
        // if current back slot non-empty search oldest or free
        if(m_items[slot])
        {
            uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
            uint32 oldest_slot = BUYBACK_SLOT_START;

            for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
            {
                // found empty
                if(!m_items[i])
                {
                    slot = i;
                    break;
                }

                uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);

                if(oldest_time > i_time)
                {
                    oldest_time = i_time;
                    oldest_slot = i;
                }
            }

            // find oldest
            slot = oldest_slot;
        }

        RemoveItemFromBuyBackSlot( slot, true );
        sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);

        m_items[slot] = pItem;
        time_t base = time(NULL);
        uint32 etime = uint32(base - m_logintime + (30 * 3600));
        uint32 eslot = slot - BUYBACK_SLOT_START;

        SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
        ItemPrototype const *pProto = pItem->GetProto();
        if( pProto )
            SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
        else
            SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
        SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );

        // move to next (for non filled list is move most optimized choice)
        if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
            ++m_currentBuybackSlot;
    }
}

Item* Player::GetItemFromBuyBackSlot( uint32 slot )
{
    sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
    if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
        return m_items[slot];
    return NULL;
}

void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
{
    sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
    if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
    {
        Item *pItem = m_items[slot];
        if( pItem )
        {
            pItem->RemoveFromWorld();
            if(del) pItem->SetState(ITEM_REMOVED, this);
        }

        m_items[slot] = NULL;

        uint32 eslot = slot - BUYBACK_SLOT_START;
        SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
        SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
        SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );

        // if current backslot is filled set to now free slot
        if(m_items[m_currentBuybackSlot])
            m_currentBuybackSlot = slot;
    }
}

void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
{
    sLog.outDebug(  "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE" );
    WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, ((msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)?22:18) );
    data << msg;
    if( msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I )
        data << (pItem && pItem->GetProto() ? pItem->GetProto()->RequiredLevel : uint32(0));
    data << (pItem ? pItem->GetGUID() : uint64(0));
    data << (pItem2 ? pItem2->GetGUID() : uint64(0));
    data << uint8(0);                                       // not 0 there...
    GetSession()->SendPacket(&data);
}

void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
{
    sLog.outDebug(  "WORLD: Sent SMSG_BUY_FAILED" );
    WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
    data << (pCreature ? pCreature->GetGUID() : uint64(0));
    data << item;
    if( param > 0 )
        data << param;
    data << msg;
    GetSession()->SendPacket(&data);
}

void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
{
    sLog.outDebug(  "WORLD: Sent SMSG_SELL_ITEM" );
    WorldPacket data( SMSG_SELL_ITEM, (8+4+4+1) );          // last check 2.0.10
    data << (pCreature ? pCreature->GetGUID() : uint64(0));
    data << guid;
    if( param > 0 )
        data << param;
    data << msg;
    GetSession()->SendPacket(&data);
}

void Player::ClearTrade()
{
    tradeGold = 0;
    acceptTrade = false;
    for(int i = 0; i < TRADE_SLOT_COUNT; i++)
        tradeItems[i] = NULL_SLOT;
}

void Player::TradeCancel(bool sendback)
{
    if(pTrader)
    {
        // send yellow "Trade cancelled" message to both traders
        WorldSession* ws;
        ws = GetSession();
        if(sendback)
            ws->SendCancelTrade();
        ws = pTrader->GetSession();
        if(!ws->PlayerLogout())
            ws->SendCancelTrade();

        // cleanup
        ClearTrade();
        pTrader->ClearTrade();
        // prevent loss of reference
        pTrader->pTrader = NULL;
        pTrader = NULL;
    }
}

void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
{
    if(m_itemDuration.empty())
        return;

    sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);

    for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
    {
        Item* item = *itr;
        ++itr;                                              // current element can be erased in UpdateDuration

        if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
            item->UpdateDuration(this,time);
    }
}

void Player::UpdateEnchantTime(uint32 time)
{
    for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
    {
        assert(itr->item);
        next=itr;
        if(!itr->item->GetEnchantmentId(itr->slot))
        {
            next = m_enchantDuration.erase(itr);
        }
        else if(itr->leftduration <= time)
        {
            ApplyEnchantment(itr->item,itr->slot,false,false);
            itr->item->ClearEnchantment(itr->slot);
            next = m_enchantDuration.erase(itr);
        }
        else if(itr->leftduration > time)
        {
            itr->leftduration -= time;
            ++next;
        }
    }
}

void Player::AddEnchantmentDurations(Item *item)
{
    for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
    {
        if(!item->GetEnchantmentId(EnchantmentSlot(x)))
            continue;

        uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
        if( duration > 0 )
            AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
    }
}

void Player::RemoveEnchantmentDurations(Item *item)
{
    for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
    {
        if(itr->item == item)
        {
            // save duration in item
            item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
            itr = m_enchantDuration.erase(itr);
        }
        else
            ++itr;
    }
}

// duration == 0 will remove item enchant
void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
{
    if(!item)
        return;

    if(slot >= MAX_ENCHANTMENT_SLOT)
        return;

    for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
    {
        if(itr->item == item && itr->slot == slot)
        {
            itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
            m_enchantDuration.erase(itr);
            break;
        }
    }
    if(item && duration > 0 )
    {
        GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
        m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
    }
}

void Player::ApplyEnchantment(Item *item,bool apply)
{
    for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
        ApplyEnchantment(item, EnchantmentSlot(slot), apply);
}

void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
{
    if(!item)
        return;

    if(!item->IsEquipped())
        return;

    if(slot > MAX_ENCHANTMENT_SLOT)
        return;

    uint32 enchant_id = item->GetEnchantmentId(slot);
    if(!enchant_id)
        return;

    SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
    if(!pEnchant)
        return;

    if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
        return;

    for (int s=0; s<3; s++)
    {
        uint32 enchant_display_type = pEnchant->type[s];
        uint32 enchant_amount = pEnchant->amount[s];
        uint32 enchant_spell_id = pEnchant->spellid[s];

        switch(enchant_display_type)
        {
            case ITEM_ENCHANTMENT_TYPE_NONE:
                break;
            case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
                // processed in Player::CastItemCombatSpell
                break;
            case ITEM_ENCHANTMENT_TYPE_DAMAGE:
                if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
                    HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
                else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
                    HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
                else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
                    HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
                break;
            case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
                if(enchant_spell_id)
                {
                    if(apply)
                    {
                        ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
                        if (item_rand)
                        {
                            // Search enchant_amount
                            if (!enchant_amount)
                            {
                                for (int k=0; k<3; k++)
                                {
                                    if(item_rand->enchant_id[k] == enchant_id)
                                    {
                                        enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
                                        break;
                                    }
                                }
                            }
                            // Cast custom spell vs all equal basepoints getted from enchant_amount
                            int32 basepoints = int32(enchant_amount);
                            CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
                        }
                        else
                            CastSpell(this,enchant_spell_id,true,item);
                    }
                    else
                        RemoveAurasDueToItem(item);
                }
                break;
            case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
                if (!enchant_amount)
                {
                    ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
                    if(item_rand)
                    {
                        for (int k=0; k<3; k++)
                        {
                            if(item_rand->enchant_id[k] == enchant_id)
                            {
                                enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
                                break;
                            }
                        }
                    }
                }

                HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
                break;
            case ITEM_ENCHANTMENT_TYPE_STAT:
            {
                if (!enchant_amount)
                {
                    ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
                    if(item_rand_suffix)
                    {
                        for (int k=0; k<3; k++)
                        {
                            if(item_rand_suffix->enchant_id[k] == enchant_id)
                            {
                                enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
                                break;
                            }
                        }
                    }
                }

                sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
                switch (enchant_spell_id)
                {
                    case ITEM_MOD_AGILITY:
                        sLog.outDebug("+ %u AGILITY",enchant_amount);
                        HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
                        ApplyPosStatMod(STAT_AGILITY, enchant_amount, apply);
                        break;
                    case ITEM_MOD_STRENGTH:
                        sLog.outDebug("+ %u STRENGTH",enchant_amount);
                        HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
                        ApplyPosStatMod(STAT_STRENGTH, enchant_amount, apply);
                        break;
                    case ITEM_MOD_INTELLECT:
                        sLog.outDebug("+ %u INTELLECT",enchant_amount);
                        HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
                        ApplyPosStatMod(STAT_INTELLECT, enchant_amount, apply);
                        break;
                    case ITEM_MOD_SPIRIT:
                        sLog.outDebug("+ %u SPIRIT",enchant_amount);
                        HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
                        ApplyPosStatMod(STAT_SPIRIT, enchant_amount, apply);
                        break;
                    case ITEM_MOD_STAMINA:
                        sLog.outDebug("+ %u STAMINA",enchant_amount);
                        HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
                        ApplyPosStatMod(STAT_STAMINA, enchant_amount, apply);
                        break;
                    case ITEM_MOD_DEFENSE_SKILL_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_DEFENCE_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u DEFENCE", enchant_amount);
                        break;
                    case  ITEM_MOD_DODGE_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_DODGE_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u DODGE", enchant_amount);
                        break;
                    case ITEM_MOD_PARRY_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_PARRY_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u PARRY", enchant_amount);
                        break;
                    case ITEM_MOD_BLOCK_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_BLOCK_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
                        break;
                    case ITEM_MOD_HIT_MELEE_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_MELEE_HIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
                        break;
                    case ITEM_MOD_HIT_RANGED_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_RANGED_HIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
                        break;
                    case ITEM_MOD_HIT_SPELL_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_SPELL_HIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
                        break;
                    case ITEM_MOD_CRIT_MELEE_RATING:        // CS = Critical Strike
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_MELEE_CRIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
                        break;
                    case ITEM_MOD_CRIT_RANGED_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_RANGED_CRIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
                        break;
                    case ITEM_MOD_CRIT_SPELL_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_SPELL_CRIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
                        break;
//                    Values from ITEM_STAT_MELEE_HA_RATING to ITEM_STAT_SPELL_HASTE_RATING are never used
//                    in Enchantments
//                    case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_MELEE_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_RANGED_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_SPELL_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_HASTE_MELEE_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_MELEE_HASTE_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_HASTE_RANGED_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_RANGED_HIT_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_HASTE_SPELL_RATING:
//                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_SPELL_HIT_RATING, enchant_amount, apply);
//                        break;
                    case ITEM_MOD_HIT_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_MELEE_HIT_RATING, enchant_amount, apply);
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_RANGED_HIT_RATING, enchant_amount, apply);
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_SPELL_HIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u HIT", enchant_amount);
                        break;
                    case ITEM_MOD_CRIT_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_MELEE_CRIT_RATING, enchant_amount, apply);
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_RANGED_CRIT_RATING, enchant_amount, apply);
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_SPELL_CRIT_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u CRITICAL", enchant_amount);
                        break;
//                    Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
//                    case ITEM_MOD_HIT_TAKEN_RATING:
//                          ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_MELEE_RATING, enchant_amount, apply);
//                          ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_RANGED_RATING, enchant_amount, apply);
//                          ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_HIT_TAKEN_SPELL_RATING, enchant_amount, apply);
//                        break;
//                    case ITEM_MOD_CRIT_TAKEN_RATING:
//                          ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING, enchant_amount, apply);
//                          ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING, enchant_amount, apply);
//                          ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING, enchant_amount, apply);
//                        break;
                    case ITEM_MOD_RESILIENCE_RATING:
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_MELEE_RATING, enchant_amount, apply);
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_RANGED_RATING, enchant_amount, apply);
                        ((Player*)this)->ApplyRatingMod(PLAYER_FIELD_CRIT_TAKEN_SPELL_RATING, enchant_amount, apply);
                        sLog.outDebug("+ %u RESILIENCE", enchant_amount);
                        break;
                        // Value ITEM_STAT_HASTE_RATING is never used in Enchantment
                    default:
                        break;
                }
                break;
            }
            case ITEM_ENCHANTMENT_TYPE_TOTEM:               // Shaman Rockbiter Weapon
            {
                if(getClass() == CLASS_SHAMAN)
                {
                    float addValue = 0.0f;
                    if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
                    {
                        addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
                        HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
                    }
                    else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
                    {
                        addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
                        HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
                    }
                }
                break;
            }
            default:
                sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
                break;
        }                                                   /*switch(enchant_display_type)*/
    }                                                       /*for*/

    // visualize enchantment at player and equipped items
    int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * 16);
    SetUInt32Value(VisibleBase+1 + slot +1, apply? item->GetEnchantmentId(slot) : 0);

    if(apply_dur)
    {
        if(apply)
        {
            // set duration
            uint32 duration = item->GetEnchantmentDuration(slot);
            if(duration > 0)
                AddEnchantmentDuration(item,slot,duration);
        }
        else
        {
            // duration == 0 will remove EnchantDuration
            AddEnchantmentDuration(item,slot,0);
        }
    }
}

void Player::SendEnchantmentDurations()
{
    for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
    {
        GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
    }
}

void Player::SendItemDurations()
{
    for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
    {
        (*itr)->SendTimeUpdate(this);
    }
}

void Player::ReducePoisonCharges(uint32 enchantId)
{
    if(!enchantId)
        return;
    uint32 charges = 0;
    Item *pItem;

    for(int i = EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_RANGED; i++)
    {
        pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if(!pItem)
            continue;
        for(int x=0;x<MAX_ENCHANTMENT_SLOT;x++)
        {
            charges = pItem->GetEnchantmentCharges(EnchantmentSlot(x));
            if(charges == 0)
                continue;
            if(charges <= 1)
            {
                ApplyEnchantment(pItem,EnchantmentSlot(x),false);
                pItem->ClearEnchantment(EnchantmentSlot(x));
                break;
            }
            else
            {
                pItem->SetEnchantmentCharges(EnchantmentSlot(x),charges-1);
                break;
            }
        }
    }
}

void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
{
    if(!item)                                               // prevent crash
        return;

                                                            // last check 2.0.10
    WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
    data << GetGUID();                                      // player GUID
    data << uint32(received);                               // 0=looted, 1=from npc
    data << uint32(created);                                // 0=received, 1=created
    data << uint32(1);                                      // always 0x01 (probably meant to be count of listed items)
    data << (uint8)item->GetBagSlot();                      // bagslot
                                                            // item slot, but when added to stack: 0xFFFFFFFF
    data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
    data << uint32(item->GetEntry());                       // item id
    data << uint32(item->GetItemSuffixFactor());            // SuffixFactor
    data << uint32(item->GetItemRandomPropertyId());        // random item property id
    data << uint32(count);                                  // count of items
    data << GetItemCount(item->GetEntry());                 // count of items in inventory

    if (broadcast && GetGroup())
        GetGroup()->BroadcastPacket(&data);
    else
        GetSession()->SendPacket(&data);
}

/*********************************************************/
/***                    QUEST SYSTEM                   ***/
/*********************************************************/

void Player::PrepareQuestMenu( uint64 guid )
{
    Object *pObject;
    QuestRelations* pObjectQR;
    QuestRelations* pObjectQIR;
    Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
    if( pCreature )
    {
        pObject = (Object*)pCreature;
        pObjectQR  = &objmgr.mCreatureQuestRelations;
        pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
    }
    else
    {
        GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
        if( pGameObject )
        {
            pObject = (Object*)pGameObject;
            pObjectQR  = &objmgr.mGOQuestRelations;
            pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
        }
        else
            return;
    }

    QuestMenu *qm = PlayerTalkClass->GetQuestMenu();
    qm->ClearMenu();

    for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
    {
        uint32 quest_id = i->second;
        QuestStatus status = GetQuestStatus( quest_id );
        if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
            qm->AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
        else if ( status == QUEST_STATUS_INCOMPLETE )
            qm->AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
        else if (status == QUEST_STATUS_AVAILABLE )
            qm->AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
    }

    for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
    {
        uint32 quest_id = i->second;
        Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
        if(!pQuest) continue;

        QuestStatus status = GetQuestStatus( quest_id );

        if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
            qm->AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
        else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
            qm->AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
    }
}

void Player::SendPreparedQuest( uint64 guid )
{
    QuestMenu* pQuestMenu = PlayerTalkClass->GetQuestMenu();
    if( !pQuestMenu || pQuestMenu->MenuItemCount() < 1 )
        return;

    uint32 status = pQuestMenu->GetItem(0).m_qIcon;
    if ( pQuestMenu->MenuItemCount() == 1 )
    {
        // Auto open -- maybe also should verify there is no greeting
        uint32 quest_id = pQuestMenu->GetItem(0).m_qId;
        Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
        if ( pQuest )
        {
            if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
                PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
            else if( status == DIALOG_STATUS_INCOMPLETE )
                PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
            // Send completable on repeatable quest if player don't have quest
            else if( pQuest->IsRepeatable() )
                PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
            else
                PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
        }
    }
    else
    {
        QEmote qe;
        qe._Delay = 0;
        qe._Emote = 0;
        std::string title = "";
        Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
        if( pCreature )
        {
            uint32 textid = pCreature->GetNpcTextId();
            GossipText * gossiptext = objmgr.GetGossipText(textid);
            if( !gossiptext )
            {
                qe._Delay = 0;                              //TEXTEMOTE_MESSAGE;              //zyg: player emote
                qe._Emote = 0;                              //TEXTEMOTE_HELLO;                //zyg: NPC emote
                title = "";
            }
            else
            {
                qe = gossiptext->Options[0].Emotes[0];

                if(!gossiptext->Options[0].Text_0.empty())
                {
                    title = gossiptext->Options[0].Text_0;

                    int loc_idx = GetSession()->GetSessionLocaleIndex();
                    if (loc_idx >= 0)
                    {
                        NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
                        if (nl)
                        {
                            if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
                                title = nl->Text_0[0][loc_idx];
                        }
                    }
                }
                else
                {
                    title = gossiptext->Options[0].Text_1;

                    int loc_idx = GetSession()->GetSessionLocaleIndex();
                    if (loc_idx >= 0)
                    {
                        NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
                        if (nl)
                        {
                            if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
                                title = nl->Text_1[0][loc_idx];
                        }
                    }
                }
            }
        }
        PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
    }
}

bool Player::IsActiveQuest( uint32 quest_id ) const
{
    QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);

    return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
}

Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
{
    Object *pObject;
    QuestRelations* pObjectQR;
    QuestRelations* pObjectQIR;

    Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
    if( pCreature )
    {
        pObject = (Object*)pCreature;
        pObjectQR  = &objmgr.mCreatureQuestRelations;
        pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
    }
    else
    {
        GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
        if( pGameObject )
        {
            pObject = (Object*)pGameObject;
            pObjectQR  = &objmgr.mGOQuestRelations;
            pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
        }
        else
            return NULL;
    }

    uint32 nextQuestID = pQuest->GetNextQuestInChain();
    for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
    {
        if (itr->second == nextQuestID)
            return objmgr.GetQuestTemplate(nextQuestID);
    }

    return NULL;
}

bool Player::CanSeeStartQuest( Quest const *pQuest )
{
    if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestClass( pQuest, false ) &&
        SatisfyQuestExclusiveGroup( pQuest, false ) &&
        SatisfyQuestSkill( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
        SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
        SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
    {
        return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
    }

    return false;
}

bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
{
    return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
        && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg ) && SatisfyQuestClass( pQuest, msg )
        && SatisfyQuestSkill( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
        && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
        && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
        && SatisfyQuestDay( pQuest, msg );
}

bool Player::CanAddQuest( Quest const *pQuest, bool msg )
{
    if( !SatisfyQuestLog( msg ) )
        return false;

    uint32 srcitem = pQuest->GetSrcItemId();
    if( srcitem > 0 )
    {
        uint32 count = pQuest->GetSrcItemCount();
        uint16 dest;
        uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count, false );

        // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
        if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
            return true;
        else if( msg != EQUIP_ERR_OK )
        {
            SendEquipError( msg, NULL, NULL );
            return false;
        }
    }
    return true;
}

bool Player::CanCompleteQuest( uint32 quest_id )
{
    if( quest_id )
    {
        QuestStatus qStatus = mQuestStatus[quest_id].m_status;
        if( qStatus == QUEST_STATUS_COMPLETE )
            return true;

        Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);

        if(!qInfo)
            return false;

        // auto complete quest
        if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
            return true;

        if ( mQuestStatus[quest_id].m_status == QUEST_STATUS_INCOMPLETE )
        {

            if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
            {
                for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
                {
                    if( qInfo->ReqItemCount[i]!= 0 && mQuestStatus[quest_id].m_itemcount[i] < qInfo->ReqItemCount[i] )
                        return false;
                }
            }

            if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
            {
                for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
                {
                    if( qInfo->ReqCreatureOrGOId[i] == 0 )
                        continue;

                    if( qInfo->ReqCreatureOrGOCount[i] != 0 && mQuestStatus[quest_id].m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
                        return false;
                }
            }

            if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !mQuestStatus[quest_id].m_explored )
                return false;

            if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && mQuestStatus[quest_id].m_timer == 0 )
                return false;

            if ( qInfo->GetRewOrReqMoney() < 0 )
            {
                if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
                    return false;
            }

            uint32 repFacId = qInfo->GetRepObjectiveFaction();
            if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
                return false;

            return true;
        }
    }
    return false;
}

bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
{
    // Solve problem that player don't have the quest and try complete it.
    // if repeatable she must be able to complete event if player don't have it.
    // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
    if( !CanTakeQuest(pQuest, false) )
        return false;

    if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
        for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
            if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
                return false;

    if( !CanRewardQuest(pQuest, false) )
        return false;

    return true;
}

bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
{
    // not auto complete quest and not completed quest (only cheating case, then ignore without message)
    if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
        return false;

    // daily quest can't be rewarded (10 daily quest already completed)
    if(!SatisfyQuestDay(pQuest,true))
        return false;

    // rewarded and not repeatable quest (only cheating case, then ignore without message)
    if(GetQuestRewardStatus(pQuest->GetQuestId()))
        return false;

    // prevent receive reward with quest items in bank
    if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
    {
        for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
        {
            if( pQuest->ReqItemCount[i]!= 0 &&
                GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
            {
                if(msg)
                    SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
                return false;
            }
        }
    }

    // prevent receive reward with low money and GetRewOrReqMoney() < 0
    if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
        return false;

    return true;
}

bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
{
    // prevent receive reward with quest items in bank or for not completed quest
    if(!CanRewardQuest(pQuest,msg))
        return false;

    uint16 dest;

    if ( pQuest->GetRewChoiceItemsCount() > 0 )
    {
        if( pQuest->RewChoiceItemId[reward] )
        {
            uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward], false );
            if( res != EQUIP_ERR_OK )
            {
                SendEquipError( res, NULL, NULL );
                return false;
            }
        }
    }

    if ( pQuest->GetRewItemsCount() > 0 )
    {
        for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
        {
            if( pQuest->RewItemId[i] )
            {
                uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i], false );
                if( res != EQUIP_ERR_OK )
                {
                    SendEquipError( res, NULL, NULL );
                    return false;
                }
            }
        }
    }

    return true;
}

void Player::AddQuest( Quest const *pQuest, Object *questGiver )
{
    uint16 log_slot = GetQuestSlot( 0 );
    assert(log_slot);

    uint32 quest_id = pQuest->GetQuestId();

    // check for repeatable quests status
    QuestUpdateState uState;
    if (mQuestStatus.find(quest_id)==mQuestStatus.end())
    {
        uState = QUEST_NEW;
        mQuestStatus[quest_id].m_rewarded = false;
    }
    else
    {
        if (mQuestStatus[quest_id].uState != QUEST_NEW)
            uState = QUEST_CHANGED;
        else
            uState = QUEST_NEW;
    }

    QuestStatusData& questStatusData = mQuestStatus[quest_id];

    questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
    questStatusData.m_explored = false;

    questStatusData.uState = uState;                        // mark quest as new or changed

    if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
    {
        for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
            questStatusData.m_itemcount[i] = 0;
    }

    if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
    {
        for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
            questStatusData.m_creatureOrGOcount[i] = 0;
    }

    GiveQuestSourceItem( pQuest );
    AdjustQuestReqItemCount( pQuest );

    SetUInt32Value(log_slot + 0, quest_id);
    SetUInt32Value(log_slot + 1, 0);

    if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
    {
        uint32 limittime = pQuest->GetLimitTime();
        AddTimedQuest( quest_id );
        mQuestStatus[quest_id].m_timer = limittime * 1000;
        uint32 qtime = static_cast<uint32>(time(NULL)) + limittime;
        SetUInt32Value( log_slot + 2, qtime );
    }
    else
    {
        questStatusData.m_timer = 0;
        SetUInt32Value( log_slot + 2, 0 );
    }

    //starting initial quest script
    if(questGiver && pQuest->GetQuestStartScript()!=0)
        sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);

    UpdateForQuestsGO();
}

void Player::CompleteQuest( uint32 quest_id )
{
    if( quest_id )
    {
        SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );

        uint16 log_slot = GetQuestSlot( quest_id );
        if( log_slot )
        {
            uint32 state = GetUInt32Value( log_slot + 1 );
            state |= 1 << 24;
            SetUInt32Value( log_slot + 1, state );
        }

        SendQuestComplete( quest_id );
    }
}

void Player::IncompleteQuest( uint32 quest_id )
{
    if( quest_id )
    {
        SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );

        uint16 log_slot = GetQuestSlot( quest_id );
        if( log_slot )
        {
            uint32 state = GetUInt32Value( log_slot + 1 );
            state &= ~(1 << 24);
            SetUInt32Value( log_slot + 1, state );
        }
    }
}

void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver )
{
    uint32 quest_id = pQuest->GetQuestId();

    uint16 dest;
    for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
    {
        if ( pQuest->ReqItemId[i] )
            DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
    }

    //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
    //    SetTimedQuest( 0 );
    m_timedquests.erase(pQuest->GetQuestId());

    Item * item;
    if ( pQuest->GetRewChoiceItemsCount() > 0 )
    {
        if( pQuest->RewChoiceItemId[reward] )
        {
            if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward], false ) == EQUIP_ERR_OK )
            {
                item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward], true);
                SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
            }
        }
    }

    if ( pQuest->GetRewItemsCount() > 0 )
    {
        for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
        {
            if( pQuest->RewItemId[i] )
            {
                if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i], false ) == EQUIP_ERR_OK )
                {
                    item = StoreNewItem( dest, pQuest->RewItemId[i], pQuest->RewItemCount[i], true);
                    SendNewItem(item, pQuest->RewItemCount[i], true, false);
                }
            }
        }
    }

    RewardReputation( pQuest );

    if( pQuest->GetRewSpell() > 0 )
        CastSpell( this, pQuest->GetRewSpell(), true);

    uint16 log_slot = GetQuestSlot( quest_id );
    if( log_slot )
    {
        SetUInt32Value(log_slot + 0, 0);
        SetUInt32Value(log_slot + 1, 0);
        SetUInt32Value(log_slot + 2, 0);
    }

    // Not give XP in case already completed once repeatable quest
    uint32 XP = mQuestStatus[quest_id].m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));

    if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
        GiveXP( XP , NULL );
    else
        ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );

    // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
    ModifyMoney( pQuest->GetRewOrReqMoney() );

    if(pQuest->IsDaily())
        SetDailyQuestStatus(quest_id);

    if ( !pQuest->IsRepeatable() )
        SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
    else
        SetQuestStatus(quest_id, QUEST_STATUS_NONE);

    mQuestStatus[quest_id].m_rewarded = true;
    SendQuestReward( pQuest, XP, questGiver );
    if (mQuestStatus[quest_id].uState != QUEST_NEW) mQuestStatus[quest_id].uState = QUEST_CHANGED;
}

void Player::FailQuest( uint32 quest_id )
{
    if( quest_id )
    {
        IncompleteQuest( quest_id );

        uint16 log_slot = GetQuestSlot( quest_id );
        if( log_slot )
        {
            SetUInt32Value( log_slot + 2, 1 );

            uint32 state = GetUInt32Value( log_slot + 1 );
            state |= 1 << 25;
            SetUInt32Value( log_slot + 1, state );
        }
        SendQuestFailed( quest_id );
    }
}

void Player::FailTimedQuest( uint32 quest_id )
{
    if( quest_id )
    {
        if (mQuestStatus[quest_id].uState != QUEST_NEW) mQuestStatus[quest_id].uState = QUEST_CHANGED;
        mQuestStatus[quest_id].m_timer = 0;

        IncompleteQuest( quest_id );

        uint16 log_slot = GetQuestSlot( quest_id );
        if( log_slot )
        {
            SetUInt32Value( log_slot + 2, 1 );

            uint32 state = GetUInt32Value( log_slot + 1 );
            state |= 1 << 25;
            SetUInt32Value( log_slot + 1, state );
        }
        SendQuestTimerFailed( quest_id );
    }
}

bool Player::SatisfyQuestClass( Quest const* qInfo, bool msg )
{
    int32 zoneOrSort = qInfo->GetZoneOrSort();

    // skip zone case
    if ( zoneOrSort >= 0 )
        return true;

    int32 questSort = -zoneOrSort;

    uint8 reqClass = ClassByQuestSort(questSort);

    if(reqClass != 0 && getClass() != reqClass)
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
        return false;
    }

    return true;
}

bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
{
    if( getLevel() < qInfo->GetMinLevel() )
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
        return false;
    }
    return true;
}

bool Player::SatisfyQuestLog( bool msg )
{
    if( GetQuestSlot(0) )
        return true;
    else
    {
        if( msg )
        {
            WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
            GetSession()->SendPacket( &data );
            sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
        }
        return false;
    }
}

bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
{
    // No previous quest (might be first quest in a series)
    if( qInfo->prevQuests.empty())
        return true;

    for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
    {
        uint32 prevId = abs(*iter);

        QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
        Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);

        if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
        {
            // If any of the positive previous quests completed, return true
            if( *iter > 0 && i_prevstatus->second.m_rewarded )
            {
                // skip one-from-all exclusive group
                if(qPrevInfo->GetExclusiveGroup() >= 0)
                    return true;

                // each-from-all exclusive group ( < 0)
                // can be start if only all quests in prev quest exclusive group complited and rewarded
                ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
                ObjectMgr::ExclusiveQuestGroups::iterator end  = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());

                assert(iter!=end);                          // always must be found if qPrevInfo->ExclusiveGroup != 0

                for(; iter != end; ++iter)
                {
                    uint32 exclude_Id = iter->second;

                    // skip checked quest id, only state of other quests in group is interesting
                    if(exclude_Id == prevId)
                        continue;

                    QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );

                    // alternative quest from group also must be completed and rewarded(reported)
                    if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
                    {
                        if( msg )
                            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
                        return false;
                    }
                }
                return true;
            }
            // If any of the negative previous quests active, return true
            if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
                || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
            {
                // skip one-from-all exclusive group
                if(qPrevInfo->GetExclusiveGroup() >= 0)
                    return true;

                // each-from-all exclusive group ( < 0)
                // can be start if only all quests in prev quest exclusive group active
                ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
                ObjectMgr::ExclusiveQuestGroups::iterator end  = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());

                assert(iter!=end);                          // always must be found if qPrevInfo->ExclusiveGroup != 0

                for(; iter != end; ++iter)
                {
                    uint32 exclude_Id = iter->second;

                    // skip checked quest id, only state of other quests in group is interesting
                    if(exclude_Id == prevId)
                        continue;

                    QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );

                    // alternative quest from group also must be active
                    if( i_exstatus == mQuestStatus.end() ||
                        i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
                        (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
                    {
                        if( msg )
                            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
                        return false;
                    }
                }
                return true;
            }
        }
    }

    // Has only positive prev. quests in non-rewarded state
    // and negative prev. quests in non-active state
    if( msg )
        SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );

    return false;
}

bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
{
    uint32 reqraces = qInfo->GetRequiredRaces();
    if ( reqraces == 0 )
        return true;
    if( (reqraces & getRaceMask()) == 0 )
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
        return false;
    }
    return true;
}

bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
{
    uint32 fIdMin = qInfo->GetRequiredMinRepFaction();      //Min required rep
    if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
        return false;
    }

    uint32 fIdMax = qInfo->GetRequiredMaxRepFaction();      //Max required rep
    if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
        return false;
    }

    return true;
}

bool Player::SatisfyQuestSkill( Quest const* qInfo, bool msg )
{
    int32 zoneOrSort = qInfo->GetZoneOrSort();

    // skip zone case
    if ( zoneOrSort >= 0 )
        return true;

    int32 questSort = -zoneOrSort;

    uint32 reqskill = SkillByQuestSort(questSort);

    if( reqskill != 0 && GetSkillValue( reqskill ) < qInfo->GetRequiredSkillValue() )
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
        return false;
    }
    return true;
}

bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
{
    QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
    if  ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
        return false;
    }
    return true;
}

bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
{
    if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
        return false;
    }
    return true;
}

bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
{
    // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
    if(qInfo->GetExclusiveGroup() <= 0)
        return true;

    ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
    ObjectMgr::ExclusiveQuestGroups::iterator end  = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());

    assert(iter!=end);                                      // always must be found if qInfo->ExclusiveGroup != 0

    for(; iter != end; ++iter)
    {
        uint32 exclude_Id = iter->second;

        // skip checked quest id, only state of other quests in group is interesting
        if(exclude_Id == qInfo->GetQuestId())
            continue;

        QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );

        // alternative quest already started or completed
        if( i_exstatus != mQuestStatus.end()
            && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
        {
            if( msg )
                SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
            return false;
        }
    }
    return true;
}

bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
{
    if(!qInfo->GetNextQuestInChain())
        return true;

    // next quest in chain already started or completed
    QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
    if( itr != mQuestStatus.end()
        && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
        return false;
    }

    // check for all quests further up the chain
    // only necessary if there are quest chains with more than one quest that can be skipped
    //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
    return true;
}

bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
{
    // No previous quest in chain
    if( qInfo->prevChainQuests.empty())
        return true;

    for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
    {
        uint32 prevId = *iter;

        QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );

        if( i_prevstatus != mQuestStatus.end() )
        {
            // If any of the previous quests in chain active, return false
            if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
                || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
            {
                if( msg )
                    SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
                return false;
            }
        }

        // check for all quests further down the chain
        // only necessary if there are quest chains with more than one quest that can be skipped
        //if( !SatisfyQuestPrevChain( prevId, msg ) )
        //    return false;
    }

    // No previous quest in chain active
    return true;
}

bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
{
    if(!qInfo->IsDaily())
        return true;

    bool have_slot = false;
    for(uint32 quest_daily_idx = 0; quest_daily_idx < 10; ++quest_daily_idx)
    {
        uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
        if(qInfo->GetQuestId()==id)
            return false;

        if(!id)
            have_slot = true;
    }

    if(!have_slot)
    {
        if( msg )
            SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
        return false;
    }

    return true;
}

bool Player::GiveQuestSourceItem( Quest const *pQuest )
{
    uint32 srcitem = pQuest->GetSrcItemId();
    if( srcitem > 0 )
    {
        uint16 dest;
        uint32 count = pQuest->GetSrcItemCount();
        if( count <= 0 )
            count = 1;
        uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count, false );
        if( msg == EQUIP_ERR_OK )
        {
            Item * item = StoreNewItem(dest, srcitem, count, true);
            SendNewItem(item, count, true, false);
            return true;
        }
        // player already have max amount required item, just report success
        else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
            return true;
        else
            SendEquipError( msg, NULL, NULL );
        return false;
    }

    return true;
}

bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
{
    Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
    if( qInfo )
    {
        uint32 srcitem = qInfo->GetSrcItemId();
        if( srcitem > 0 )
        {
            uint32 count = qInfo->GetSrcItemCount();
            if( count <= 0 )
                count = 1;

            // exist one case when destroy source quest item not possible:
            // non un-equippable item (equipped non-empty bag, for example)
            uint8 res = CanUnequipItems(srcitem,count);
            if(res != EQUIP_ERR_OK)
            {
                if(msg)
                    SendEquipError( res, NULL, NULL );
                return false;
            }

            DestroyItemCount(srcitem, count, true, true);
        }
    }
    return true;
}

bool Player::GetQuestRewardStatus( uint32 quest_id )
{
    Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
    if( qInfo )
    {
        // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
        QuestStatusMap::iterator itr = mQuestStatus.find( quest_id );
        if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
            && !qInfo->IsRepeatable() )
            return itr->second.m_rewarded;

        return false;
    }
    return false;
}

QuestStatus Player::GetQuestStatus( uint32 quest_id )
{
    if( quest_id )
    {
        QuestStatusMap::iterator itr = mQuestStatus.find( quest_id );
        if( itr != mQuestStatus.end() )
            return itr->second.m_status;
    }
    return QUEST_STATUS_NONE;
}

bool Player::CanShareQuest(uint32 quest_id)
{
    if( quest_id )
    {
        QuestStatusMap::iterator itr = mQuestStatus.find( quest_id );
        if( itr != mQuestStatus.end() )
            return itr->second.m_status == QUEST_STATUS_NONE ||
                itr->second.m_status == QUEST_STATUS_INCOMPLETE;
    }

    return false;
}

void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
{
    Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
    if( qInfo )
    {
        if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
        {
            if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
                m_timedquests.erase(qInfo->GetQuestId());
        }

        mQuestStatus[quest_id].m_status = status;
        if (mQuestStatus[quest_id].uState != QUEST_NEW) mQuestStatus[quest_id].uState = QUEST_CHANGED;
    }

    UpdateForQuestsGO();
}

// not used in MaNGOS, but used in scripting code
uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
{
    Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);

    if( !qInfo )
        return 0;

    uint32 curkillcount;
    int32 reqkill;

    for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
    {
        reqkill = qInfo->ReqCreatureOrGOId[j];

        if ( reqkill == entry )
        {
            curkillcount = mQuestStatus[quest_id].m_creatureOrGOcount[j];
            return curkillcount;
        }
    }
    return 0;
}

void Player::AdjustQuestReqItemCount( Quest const* pQuest )
{
    if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
    {
        for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
        {
            uint32 reqitemcount = pQuest->ReqItemCount[i];
            if( reqitemcount != 0 )
            {
                uint32 quest_id = pQuest->GetQuestId();
                uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i]) + GetBankItemCount(pQuest->ReqItemId[i]);
                mQuestStatus[quest_id].m_itemcount[i] = std::min(curitemcount, reqitemcount);
                if (mQuestStatus[quest_id].uState != QUEST_NEW) mQuestStatus[quest_id].uState = QUEST_CHANGED;
            }
        }
    }
}

uint16 Player::GetQuestSlot( uint32 quest_id )
{
    for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
    {
        if ( GetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i) == quest_id )
            return PLAYER_QUEST_LOG_1_1 + 3*i;
    }
    return 0;
}

void Player::AreaExploredOrEventHappens( uint32 questId )
{
    if( questId )
    {
        uint16 log_slot = GetQuestSlot( questId );
        if( log_slot )
        {
            mQuestStatus[questId].m_explored = true;
            if (mQuestStatus[questId].uState != QUEST_NEW) mQuestStatus[questId].uState = QUEST_CHANGED;
        }
        if( CanCompleteQuest( questId ) )
            CompleteQuest( questId );
    }
}

void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
{
    uint32 questid;
    uint32 reqitem;
    uint32 reqitemcount;
    uint32 curitemcount;
    uint32 additemcount;
    for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
    {
        questid = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i);
        if ( questid != 0 && mQuestStatus[questid].m_status == QUEST_STATUS_INCOMPLETE )
        {
            Quest const* qInfo = objmgr.GetQuestTemplate(questid);
            if( qInfo && qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
            {
                for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
                {
                    reqitem = qInfo->ReqItemId[j];
                    if ( reqitem == entry )
                    {
                        reqitemcount = qInfo->ReqItemCount[j];
                        curitemcount = mQuestStatus[questid].m_itemcount[j];
                        if ( curitemcount < reqitemcount )
                        {
                            additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
                            mQuestStatus[questid].m_itemcount[j] += additemcount;
                            if (mQuestStatus[questid].uState != QUEST_NEW) mQuestStatus[questid].uState = QUEST_CHANGED;

                            SendQuestUpdateAddItem( qInfo, j, additemcount );
                        }
                        if ( CanCompleteQuest( questid ) )
                            CompleteQuest( questid );
                        return;
                    }
                }
            }
        }
    }
    UpdateForQuestsGO();
}

void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
{
    uint32 questid;
    uint32 reqitem;
    uint32 reqitemcount;
    uint32 curitemcount;
    uint32 remitemcount;
    for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
    {
        questid = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i);
        Quest const* qInfo = objmgr.GetQuestTemplate(questid);
        if ( qInfo )
        {
            if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
            {
                for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
                {
                    reqitem = qInfo->ReqItemId[j];
                    if ( reqitem == entry )
                    {
                        reqitemcount = qInfo->ReqItemCount[j];
                        if( mQuestStatus[questid].m_status != QUEST_STATUS_COMPLETE )
                            curitemcount = mQuestStatus[questid].m_itemcount[j];
                        else
                            curitemcount = GetItemCount(entry) + GetBankItemCount(entry);
                        if ( curitemcount < reqitemcount + count )
                        {
                            remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
                            mQuestStatus[questid].m_itemcount[j] = curitemcount - remitemcount;
                            if (mQuestStatus[questid].uState != QUEST_NEW) mQuestStatus[questid].uState = QUEST_CHANGED;

                            IncompleteQuest( questid );
                        }
                        return;
                    }
                }
            }
        }
    }
    UpdateForQuestsGO();
}

void Player::KilledMonster( uint32 entry, uint64 guid )
{
    uint32 questid;
    uint32 reqkill;
    uint32 reqkillcount;
    uint32 curkillcount;
    uint32 addkillcount = 1;
    for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
    {
        questid = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i);

        if(!questid)
            continue;

        Quest const* qInfo = objmgr.GetQuestTemplate(questid);
        // just if !ingroup || !noraidgroup || raidgroup
        if ( qInfo && mQuestStatus[questid].m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
        {
            if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
            {
                for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
                {
                    // skip GO activate objective or none
                    if(qInfo->ReqCreatureOrGOId[j] <=0)
                        continue;

                    // skip Cast at creature objective
                    if(qInfo->ReqSpell[j] !=0 )
                        continue;

                    reqkill = qInfo->ReqCreatureOrGOId[j];

                    if ( reqkill == entry )
                    {
                        reqkillcount = qInfo->ReqCreatureOrGOCount[j];
                        curkillcount = mQuestStatus[questid].m_creatureOrGOcount[j];
                        if ( curkillcount < reqkillcount )
                        {
                            mQuestStatus[questid].m_creatureOrGOcount[j] = curkillcount + addkillcount;
                            if (mQuestStatus[questid].uState != QUEST_NEW) mQuestStatus[questid].uState = QUEST_CHANGED;

                            SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
                        }
                        if ( CanCompleteQuest( questid ) )
                            CompleteQuest( questid );

                        // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
                        continue;
                    }
                }
            }
        }
    }
}

void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
{
    uint32 questid;
    uint32 reqCastCount;
    uint32 curCastCount;
    uint32 addCastCount = 1;
    for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
    {
        questid = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i);

        if(!questid)
            continue;

        Quest const* qInfo = objmgr.GetQuestTemplate(questid);
        if ( qInfo && mQuestStatus[questid].m_status == QUEST_STATUS_INCOMPLETE )
        {
            if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
            {
                for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
                {
                    // skip kill creature objective (0) or wrong spell casts
                    if(qInfo->ReqSpell[j] != spell_id )
                        continue;

                    uint32 reqTarget = 0;
                    // GO activate objective
                    if(qInfo->ReqCreatureOrGOId[j] < 0)
                    {
                        // checked at quest_template loading
                        reqTarget = - qInfo->ReqCreatureOrGOId[j];
                    }
                    // creature activate objectives
                    else if(qInfo->ReqCreatureOrGOId[j] > 0)
                    {
                        // checked at quest_template loading
                        reqTarget = qInfo->ReqCreatureOrGOId[j];
                    }
                    // other not creature/GO related objectives
                    else
                        continue;

                    if ( reqTarget == entry )
                    {
                        reqCastCount = qInfo->ReqCreatureOrGOCount[j];
                        curCastCount = mQuestStatus[questid].m_creatureOrGOcount[j];
                        if ( curCastCount < reqCastCount )
                        {
                            mQuestStatus[questid].m_creatureOrGOcount[j] = curCastCount + addCastCount;
                            if (mQuestStatus[questid].uState != QUEST_NEW) mQuestStatus[questid].uState = QUEST_CHANGED;

                            SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
                        }
                        if ( CanCompleteQuest( questid ) )
                            CompleteQuest( questid );

                        // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
                        continue;
                    }
                }
            }
        }
    }
}

void Player::TalkedToCreature( uint32 entry, uint64 guid )
{
    uint32 questid;
    uint32 reqTalkCount;
    uint32 curTalkCount;
    uint32 addTalkCount = 1;
    for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
    {
        questid = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i);

        if(!questid)
            continue;

        Quest const* qInfo = objmgr.GetQuestTemplate(questid);
        if ( qInfo && mQuestStatus[questid].m_status == QUEST_STATUS_INCOMPLETE )
        {
            if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
            {
                for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
                {
                                                            // skip spell casts and Gameobject objectives
                    if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
                        continue;

                    uint32 reqTarget = 0;

                    if(qInfo->ReqCreatureOrGOId[j] > 0)     // creature activate objectives
                                                            // checked at quest_template loading
                        reqTarget = qInfo->ReqCreatureOrGOId[j];
                    else
                        continue;

                    if ( reqTarget == entry )
                    {
                        reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
                        curTalkCount = mQuestStatus[questid].m_creatureOrGOcount[j];
                        if ( curTalkCount < reqTalkCount )
                        {
                            mQuestStatus[questid].m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
                            if (mQuestStatus[questid].uState != QUEST_NEW) mQuestStatus[questid].uState = QUEST_CHANGED;

                            SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
                        }
                        if ( CanCompleteQuest( questid ) )
                            CompleteQuest( questid );

                        // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
                        continue;
                    }
                }
            }
        }
    }
}

void Player::MoneyChanged( uint32 count )
{
    uint32 questid;
    for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
    {
        questid = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i);
        if ( questid != 0 )
        {
            Quest const* qInfo = objmgr.GetQuestTemplate(questid);
            if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
            {
                if( mQuestStatus[questid].m_status == QUEST_STATUS_INCOMPLETE )
                {
                    if(int32(count) >= -qInfo->GetRewOrReqMoney())
                    {
                        if ( CanCompleteQuest( questid ) )
                            CompleteQuest( questid );
                    }
                }
                else if( mQuestStatus[questid].m_status == QUEST_STATUS_COMPLETE )
                {
                    if(int32(count) < -qInfo->GetRewOrReqMoney())
                        IncompleteQuest( questid );
                }
            }
        }
    }
}

bool Player::HasQuestForItem( uint32 itemid )
{
    for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
    {
        QuestStatusData qs=i->second;

        if (qs.m_status == QUEST_STATUS_INCOMPLETE)
        {
            Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
            if(!qinfo)
                continue;

            // hide quest if player is in raid-group and quest is no raid quest
            if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
                continue;

            // There should be no mixed ReqItem/ReqSource drop
            // This part for ReqItem drop
            for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
            {
                if(itemid == qinfo->ReqItemId[j] && qs.m_itemcount[j] < qinfo->ReqItemCount[j] )
                    return true;
            }
            // This part - for ReqSource
            for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
            {
                // examined item is a source item
                if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
                {
                    uint32 idx = qinfo->ReqSourceRef[j]-1;

                    // total count of created ReqItems and SourceItems is less than ReqItemCount
                    if(qinfo->ReqItemId[idx] != 0 &&
                        qs.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid) + GetBankItemCount(itemid) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
                        return true;

                    // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
                    if (qinfo->ReqCreatureOrGOId[idx] != 0)
                    {
                        if(qs.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid) + GetBankItemCount(itemid) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
                            return true;
                    }
                    // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
                    else if(qinfo->ReqSpell[idx] != 0)
                    {
                        // not casted and need more reagents/item for use.
                        if(!qs.m_explored && GetItemCount(itemid) + GetBankItemCount(itemid) < qinfo->ReqSourceCount[j])
                            return true;
                    }
                }
            }
        }
    }
    return false;
}

void Player::SendQuestComplete( uint32 quest_id )
{
    if( quest_id )
    {
        WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
        data << quest_id;
        GetSession()->SendPacket( &data );
        sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
    }
}

void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
{
    uint32 questid = pQuest->GetQuestId();
    sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
    WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (8+8+4+pQuest->GetRewItemsCount()*8) );
    data << questid;
    data << uint32(0x03);

    if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
    {
        data << XP;
        data << uint32(pQuest->GetRewOrReqMoney());
    }
    else
    {
        data << uint32(0);
        data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
    }
    data << uint32(0);                                      // new 2.3.0, HonorPoints?
    data << uint32( pQuest->GetRewItemsCount() );

    for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
    {
        if ( pQuest->RewItemId[i] > 0 )
            data << pQuest->RewItemId[i] << pQuest->RewItemCount[i];
    }
    data << uint32(0);
    GetSession()->SendPacket( &data );

    if (pQuest->GetQuestCompleteScript() != 0)
        sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
}

void Player::SendQuestFailed( uint32 quest_id )
{
    if( quest_id )
    {
        WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4 );
        data << quest_id;
        GetSession()->SendPacket( &data );
        sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
    }
}

void Player::SendQuestTimerFailed( uint32 quest_id )
{
    if( quest_id )
    {
        WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
        data << quest_id;
        GetSession()->SendPacket( &data );
        sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
    }
}

void Player::SendCanTakeQuestResponse( uint32 msg )
{
    WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
    data << msg;
    GetSession()->SendPacket( &data );
    sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
}

void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
{
    if( pPlayer )
    {
        WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+4+1) );
        data << pPlayer->GetGUID();
        data << msg;
        data << uint8(0);
        GetSession()->SendPacket( &data );
        sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
    }
}

void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
{
    WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, (4+4) );
    sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
    data << pQuest->ReqItemId[item_idx];
    data << count;
    GetSession()->SendPacket( &data );
}

void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
{
    assert(old_count + add_count < 64 && "mob/GO count store in 6 bits 2^6 = 64 (0..63)");

    int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
    if (entry < 0)
        // client expected gameobject template id in form (id|0x80000000)
        entry = (-entry) | 0x80000000;

    WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
    sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
    data << uint32(pQuest->GetQuestId());
    data << uint32(entry);
    data << uint32(old_count + add_count);
    data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
    data << uint64(guid);
    GetSession()->SendPacket(&data);

    uint16 log_slot = GetQuestSlot( pQuest->GetQuestId() );
    uint32 kills = GetUInt32Value( log_slot + 1 );
    kills = kills + (add_count << ( 6 * creatureOrGO_idx ));
    SetUInt32Value( log_slot + 1, kills );
}

/*********************************************************/
/***                   LOAD SYSTEM                     ***/
/*********************************************************/

bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
{
    bool delete_result = true;
    if(!result)
    {
        //                                        0     1     2           3           4           5    6          7          8
        result = CharacterDatabase.PQuery("SELECT data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
        if(!result) return false;
    }
    else delete_result = false;

    Field *fields = result->Fetch();

    if(!LoadValues( fields[0].GetString()))
    {
        sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
        if(delete_result) delete result;
        return false;
    }

    // overwrite possible wrong/corrupted guid
    SetUInt64Value(OBJECT_FIELD_GUID,MAKE_GUID(guid,HIGHGUID_PLAYER));

    m_name = fields[1].GetCppString();

    Relocate(fields[2].GetFloat(),fields[3].GetFloat(),fields[4].GetFloat());
    SetMapId(fields[5].GetUInt32());

    m_Played_time[0] = fields[6].GetUInt32();
    m_Played_time[1] = fields[7].GetUInt32();

    m_atLoginFlags = fields[8].GetUInt32();

    // I don't see these used anywhere ..
    /*_LoadGroup();

    _LoadBoundInstances();*/

    if (delete_result) delete result;

    for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
        m_items[i] = NULL;

    if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
        m_deathState = DEAD;

    return true;
}

bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
{
    QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
    if(!result)
        return false;

    Field *fields = result->Fetch();

    x = fields[0].GetFloat();
    y = fields[1].GetFloat();
    z = fields[2].GetFloat();
    o = fields[3].GetFloat();
    mapid = fields[4].GetUInt32();
    in_flight = !fields[5].GetCppString().empty();

    delete result;
    return true;
}

bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
{
    QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
    if( !result )
        return false;

    Field *fields = result->Fetch();

    data = StrSplit(fields[0].GetCppString(), " ");

    delete result;

    return true;
}

uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
{
    if(index >= data.size())
        return 0;

    return (uint32)atoi(data[index].c_str());
}

float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
{
    float result;
    uint32 temp = Player::GetUInt32ValueFromArray(data,index);
    memcpy(&result, &temp, sizeof(result));

    return result;
}

uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
{
    Tokens data;
    if(!LoadValuesArrayFromDB(data,guid))
        return 0;

    return GetUInt32ValueFromArray(data,index);
}

float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
{
    float result;
    uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
    memcpy(&result, &temp, sizeof(result));

    return result;
}

bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
{
    ////                                                     0     1        2     3     4     5      6           7           8           9    10           11        12         13         14         15          16           17                 18                 19                 20       21       22       23       24         25       26            27        [28]  [29]    30             31               32              33
    //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, gmstate, stable_slots, at_login, zone, online, pending_honor, last_honor_date, last_kill_date, taxi_path FROM characters WHERE guid = '%u'", guid);
    QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);

    if(!result)
    {
        sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
        return false;
    }

    Field *fields = result->Fetch();

    uint32 dbAccountId = fields[1].GetUInt32();

    // check if the character's account in the db and the logged in account match.
    // player should be able to load/delete character only with correct account!
    if( dbAccountId != GetSession()->GetAccountId() )
    {
        sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
        delete result;
        return false;
    }

    Object::_Create( guid, HIGHGUID_PLAYER );

    if(!LoadValues( fields[2].GetString()))
    {
        sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
        delete result;
        return false;
    }

    // overwrite possible wrong/corrupted guid
    SetUInt64Value(OBJECT_FIELD_GUID,MAKE_GUID(guid,HIGHGUID_PLAYER));

    // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
    for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
    {
        SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );

        int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
        for(int i = 0; i < 11; ++i )
            SetUInt32Value(VisibleBase + i, 0);

        if (m_items[slot])
        {
            delete m_items[slot];
            m_items[slot] = NULL;
        }
    }

    // update money limits
    if(GetMoney() > MAX_MONEY_AMOUNT)
        SetMoney(MAX_MONEY_AMOUNT);

    // set value, including drunk invisibility detection
    SetDrunkValue(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE);

    m_name = fields[3].GetCppString();

    sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
    outDebugValues();

    m_race = fields[4].GetUInt8();
    //Need to call it to initialize m_team (m_team can be calculated from m_race)
    //Other way is to saves m_team into characters table.
    setFactionForRace(m_race);
    SetCharm(0);

    m_class = fields[5].GetUInt8();

    PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
    if(!info)
    {
        sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
        delete result;
        return false;
    }

    InitPrimaryProffesions();                               // to max set before any spell loaded

    uint32 transGUID = fields[24].GetUInt32();
    Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
    SetMapId(fields[9].GetUInt32());

    _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));

    _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));

    SaveRecallPosition();

    if (transGUID != 0)
    {
        m_movementInfo.t_x = fields[20].GetFloat();
        m_movementInfo.t_y = fields[21].GetFloat();
        m_movementInfo.t_z = fields[22].GetFloat();
        m_movementInfo.t_o = fields[23].GetFloat();

        for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
        {
            if( (*iter)->GetGUIDLow() == transGUID)
            {
                m_transport = *iter;
                m_transport->AddPassenger(this);
                SetMapId(m_transport->GetMapId());
            }
        }
    }

    // since last logout (in seconds)
    uint32 time_diff = (time(NULL) - fields[16].GetUInt32());

    m_rest_bonus = fields[15].GetFloat();
    //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
    float bubble0 = 0.031;
    //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
    float bubble1 = 0.125;

    if((int32)fields[16].GetUInt32() > 0)
    {
        float bubble = fields[17].GetUInt32() > 0
            ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
            : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);

        SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
    }

    if(!IsPositionValid())
    {
        sLog.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY());

        SetMapId(info->mapId);
        Relocate(info->positionX,info->positionY,info->positionZ);
    }

    m_cinematic = fields[12].GetUInt32();
    m_Played_time[0]= fields[13].GetUInt32();
    m_Played_time[1]= fields[14].GetUInt32();

    m_resetTalentsCost = fields[18].GetUInt32();
    m_resetTalentsTime = fields[19].GetUInt64();

    // reserve some flags
    uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );

    if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
        SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);

    _LoadTaxiMask( fields[11].GetString() );

    uint32 gmstate = fields[25].GetUInt32();

    m_stableSlots = fields[26].GetUInt32();
    if(m_stableSlots > 2)
    {
        sLog.outError("Player can have not more 2 stable slots, but have in DB %u",uint32(m_stableSlots));
        m_stableSlots = 2;
    }

    m_atLoginFlags = fields[27].GetUInt32();

    // Honor system
    m_honorPending = fields[30].GetFloat();
    m_lastHonorDate = fields[31].GetUInt32();
    m_lastKillDate = fields[32].GetUInt32();

    std::string taxi_nodes = fields[33].GetCppString();

    delete result;

    // clear channel spell data (if saved at channel spell casting)
    SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
    SetUInt32Value(UNIT_CHANNEL_SPELL,0);

    // clear charm/summon related fields
    SetUInt64Value(UNIT_FIELD_CHARM,0);
    SetUInt64Value(UNIT_FIELD_SUMMON,0);
    SetUInt64Value(UNIT_FIELD_CHARMEDBY,0);
    SetUInt64Value(UNIT_FIELD_SUMMONEDBY,0);
    SetUInt64Value(UNIT_FIELD_CREATEDBY,0);

    // reset some aura modifiers before aura apply
    SetUInt64Value(PLAYER_FARSIGHT, 0);
    SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
    SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );

    // reset skill modifiers and set correct unlearn flags
    for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
    {
        SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);

        // set correct unlearn bit
        uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
        if(!id) continue;

        SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
        if(!pSkill) continue;

        // enable unlearn button for primary professions only
        if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
            SetUInt32Value(PLAYER_SKILL_INDEX(i), id | (1 << 16));
        else
            SetUInt32Value(PLAYER_SKILL_INDEX(i), id);
    }

    // make sure the unit is considered out of combat for proper loading
    ClearInCombat();

    // make sure the unit is considered not in duel for proper loading
    SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
    SetUInt32Value(PLAYER_DUEL_TEAM, 0);

    // remember loaded power/health values to restore after stats initialization and modifier applying
    uint32 savedHealth = GetHealth();
    uint32 savedPower[MAX_POWERS];
    for(uint32 i = 0; i < MAX_POWERS; ++i)
        savedPower[i] = GetPower(Powers(i));

    // reset stats before loading any modifiers
    InitStatsForLevel();

    // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()

    //mails are loaded only when needed ;-) - when player in game click on mailbox.
    //_LoadMail();

    _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);

    // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
    if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
        m_deathState = DEAD;

    _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));

    // after spell load
    InitTalentForLevel();

    _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
    _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));

    _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));

    // must be before inventory (some items required reputation check)
    _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));

    _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);

    // update items with duration and realtime
    UpdateItemDuration(time_diff, true);

    _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));

    // unread mails and next delivery time, actual mails not loaded
    _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));

    _LoadIgnoreList(holder->GetResult(PLAYER_LOGIN_QUERY_LOADIGNORELIST));
    _LoadFriendList(holder->GetResult(PLAYER_LOGIN_QUERY_LOADFRIENDLIST));

    if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
        return false;

    // Not finish taxi flight path
    if(!LoadTaxiDestinationsFromString(taxi_nodes))
    {
        // problems with taxi path loading
        TaxiNodesEntry const* nodeEntry = NULL;
        if(!m_TaxiDestinations.empty())
        {
            uint32 node_id = m_TaxiDestinations[0];
            nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
        }

        if(!nodeEntry)                                      // don't know taxi start node, to homebind
        {
            sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
            SetMapId(m_homebindMapId);
            Relocate( m_homebindX, m_homebindY, m_homebindZ);
            SaveRecallPosition();                           // save as recall also to prevent recall and fall from sky
        }
        else                                                // have start node, to it
        {
            sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
            SetMapId(nodeEntry->map_id);
            Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z);
            SaveRecallPosition();                           // save as recall also to prevent recall and fall from sky
        }
        ClearTaxiDestinations();
    }
    else if(!m_TaxiDestinations.empty())
    {
        // save source node as recall coord to prevent recall and fall from sky
        uint32 node_id = m_TaxiDestinations[0];
        TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);

        m_recallMap = nodeEntry->map_id;
        m_recallX = nodeEntry->x;
        m_recallY = nodeEntry->y;
        m_recallZ = nodeEntry->z;

        // flight will started later
    }

    _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));

    _LoadHonor(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHONOR));

    // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
    // Do now before stats re-calculation cleanup for ghost state unexpected auras
    if(!isAlive())
        RemoveAllAurasOnDeath();

    //apply all stat bonuses from items and auras
    SetCanModifyStats(true);
    UpdateAllStats();

    // restore remembered power/health values (but not more max values)
    SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
    for(uint32 i = 0; i < MAX_POWERS; ++i)
        SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);

    sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
    outDebugValues();

    // GM state
    if(GetSession()->GetSecurity() > SEC_PLAYER)
    {
        switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
        {
            case 0:                                         // disable
                break;
            case 1:                                         // enable
                SetGameMaster(true);
                break;
            case 2:                                         // save state
                if(gmstate)
                    SetGameMaster(true);
                break;
            default:
                break;
        }
    }

    //Unmount Player from previous mount, so speed bug with mount is no more...
    if(IsMounted())
    {
        Unmount();
        RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
    }
    UpdateManaRegen();
    m_Loaded = true;

    return true;
}

void Player::_LoadActions(QueryResult *result)
{
    m_actionButtons.clear();

    //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());

    if(result)
    {
        do
        {
            Field *fields = result->Fetch();

            uint8 button = fields[0].GetUInt8();

            addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());

            m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
        }
        while( result->NextRow() );

        delete result;
    }
}

void Player::_LoadAuras(QueryResult *result, uint32 timediff)
{
    m_Auras.clear();
    for (int i = 0; i < TOTAL_AURAS; i++)
        m_modAuras[i].clear();

    // all aura related fields
    for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
        SetUInt32Value(i, 0);

    //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());

    if(result)
    {
        do
        {
            Field *fields = result->Fetch();
            uint64 caster_guid = fields[0].GetUInt64();
            uint32 spellid = fields[1].GetUInt32();
            uint32 effindex = fields[2].GetUInt32();
            int32 damage     = (int32)fields[3].GetUInt32();
            int32 maxduration = (int32)fields[4].GetUInt32();
            int32 remaintime = (int32)fields[5].GetUInt32();
            int32 remaincharges = (int32)fields[6].GetUInt32();

            SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
            if(!spellproto)
            {
                sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
                continue;
            }

            if(effindex >= 3)
            {
                sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
                continue;
            }

            // negative effects should continue counting down after logout
            if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
            {
                if(remaintime  <= int32(timediff))
                    continue;

                remaintime -= timediff;
            }

            // prevent wrong values of remaincharges
            if(spellproto->procCharges)
            {
                if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
                    remaincharges = spellproto->procCharges;
            }
            else
                remaincharges = -1;

            Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
            if(!damage)
                damage = aura->GetModifier()->m_amount;
            aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
            AddAura(aura);
        }
        while( result->NextRow() );

        delete result;
    }

    if(m_class == CLASS_WARRIOR)
        CastSpell(this,SPELL_PASSIVE_BATTLE_STANCE,true);
}

void Player::LoadCorpse()
{
    if( isAlive() )
    {
        ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
    }
    else
    {
        if(Corpse *corpse = GetCorpse())
        {
            if( corpse->GetType() == CORPSE_RESURRECTABLE && IsWithinDistInMap(corpse,0.0))
                RepopAtGraveyard();
        }
        else
        {
            //Prevent Dead Player login without corpse
            ResurrectPlayer(0.5f);
        }
    }
}

void Player::_LoadHonor(QueryResult *result)
{
    uint32 today = uint32(time(NULL) / DAY) * DAY;
    uint32 yesterday = today - DAY;

    if (m_honorPending && m_lastHonorDate < today)
    {
        if(m_lastHonorDate >= yesterday)
        {
            // the honorPending is always for one day
            // if honor was last gained yesterday then
            // honorPending is the total honor yesterday
            SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, (uint32)(m_honorPending*10));
        }
        else
        {
            // no honor yesterday, reset yesterday's contribution
            SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
        }

        // add the pending honor points, a day has passed
        SetHonorPoints(GetHonorPoints()+uint32(m_honorPending));
        // this is the first login today, reset today's contribution and pending honor
        SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
        m_honorPending = 0;
    }

    // load kills today
    uint32 kills = GetUInt32Value(PLAYER_FIELD_KILLS);      // today + yesterday << 16
    uint16 kills_today = kills & 0xFFFF;
    if(kills_today)
    {
        if (m_lastKillDate >= today)
        {
            // kills in the DB are for one day always
            // so if the last was today then they all were
            // QueryResult *result = CharacterDatabase.PQuery("SELECT victim_guid,count FROM character_kill WHERE guid='%u'", GetGUIDLow());
            if (result && sWorld.getConfig(CONFIG_HONOR_KILL_LIMIT))
            {
                do
                {
                    Field *fields  = result->Fetch();
                    uint32 victim_guid = fields[0].GetUInt32();
                    uint8 count = fields[1].GetUInt8();

                    KillInfo &info = m_killsPerPlayer[victim_guid];
                    info.state = KILL_UNCHANGED;
                    info.count = count;
                }
                while( result->NextRow() );
            }
        }
        else
        {
            if(m_lastKillDate >= yesterday)
            {
                // if the last victim was killed yesterday then
                // kills_today is actually the total kills yesterday
                SetUInt32Value(PLAYER_FIELD_KILLS, kills_today << 16);
            }
            else
            {
                // no kills yesterday or today, reset
                SetUInt32Value(PLAYER_FIELD_KILLS, 0);
            }
        }
    }

    if(result)
        delete result;
}

void Player::_LoadInventory(QueryResult *result, uint32 timediff)
{
    //QueryResult *result = CharacterDatabase.PQuery("SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
    std::map<uint64, Bag*> bagMap;                          // fast guid lookup for bags
    //NOTE: the "order by `bag`" is important because it makes sure
    //the bagMap is filled before items in the bags are loaded
    //NOTE2: the "order by `slot`" is needed becaue mainhand weapons are (wrongly?)
    //expected to be equipped before offhand items (TODO: fixme)

    uint32 zone = GetZoneId();

    if (result)
    {
        std::list<Item*> problematicItems;

        // prevent items from being added to the queue when stored
        m_itemUpdateQueueBlocked = true;
        do
        {
            Field *fields = result->Fetch();
            uint32 bag_guid  = fields[1].GetUInt32();
            uint8  slot      = fields[2].GetUInt8();
            uint32 item_guid = fields[3].GetUInt32();
            uint32 item_id   = fields[4].GetUInt32();

            ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);

            if(!proto)
            {
                CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
                CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
                sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
                continue;
            }

            Item *item = NewItemOrBag(proto);

            if(!item->LoadFromDB(item_guid, GetGUID(), result))
            {
                sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
                CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
                item->FSetState(ITEM_REMOVED);
                item->SaveToDB();                           // it also deletes item object !
                continue;
            }

            // not allow have in alive state item limited to another map/zone
            if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
            {
                CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
                item->FSetState(ITEM_REMOVED);
                item->SaveToDB();                           // it also deletes item object !
                continue;
            }

            // "Conjured items disappear if you are logged out for more than 15 minutes"
            if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
            {
                CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
                item->FSetState(ITEM_REMOVED);
                item->SaveToDB();                           // it also deletes item object !
                continue;
            }

            bool success = true;

            if (!bag_guid)
            {
                // the item is not in a bag
                item->SetContainer( NULL );
                item->SetSlot(slot);

                // destinated position
                uint16 dest = ((INVENTORY_SLOT_BAG_0 << 8) | slot);

                if( IsInventoryPos( dest ) )
                {
                    if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
                        item = StoreItem(dest, item, true);
                    else
                        success = false;
                }
                else if( IsEquipmentPos( dest ) )
                {
                    if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
                        QuickEquipItem(dest, item);
                    else
                        success = false;
                }
                else if( IsBankPos( dest ) )
                {
                    if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
                        item = BankItem(dest, item, true);
                    else
                        success = false;
                }

                if(success)
                {
                    // store bags that may contain items in them
                    if(item->IsBag() && IsBagPos(dest))
                        bagMap[item_guid] = (Bag*)item;
                }
            }
            else
            {
                item->SetSlot(NULL_SLOT);
                // the item is in a bag, find the bag
                std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
                if(itr != bagMap.end())
                    itr->second->StoreItem(slot, item, true );
                else
                    success = false;
            }

            // item's state may have changed after stored
            if (success)
                item->SetState(ITEM_UNCHANGED, this);
            else
            {
                sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_guid, item_id, bag_guid, slot);
                CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
                problematicItems.push_back(item);
            }
        } while (result->NextRow());

        delete result;
        m_itemUpdateQueueBlocked = false;

        // send by mail problematic items
        while(!problematicItems.empty())
        {
            // fill mail
            MailItemsInfo mi;                               // item list prepering

            for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
            {
                Item* item = problematicItems.front();
                problematicItems.pop_front();

                mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
            }

            std::string subject = objmgr.GetMangosString(LANG_NOT_EQUIPPED_ITEM, GetSession()->GetSessionLocaleIndex());

            WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, NOT_READ);
        }
    }
    //if(isAlive())
    _ApplyAllItemMods();
}

// load mailed item which should receive current player
void Player::_LoadMailedItems(Mail *mail)
{
    QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
    if(!result)
        return;

    do
    {
        Field *fields = result->Fetch();
        uint32 item_guid_low = fields[0].GetUInt32();
        uint32 item_template = fields[1].GetUInt32();

        mail->AddItem(item_guid_low, item_template);

        ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);

        if(!proto)
        {
            sLog.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail, skipped.", GetGUIDLow(), item_guid_low, item_template);
            continue;
        }
        Item *item = NewItemOrBag(proto);
        if(!item->LoadFromDB(item_guid_low, 0))
        {
            sLog.outError( "Player::_LoadMailedItems - Mailed Item doesn't exist!!!! - item guid: %u", item_guid_low);
            delete item;
            continue;
        }
        AddMItem(item);
    } while (result->NextRow());

    delete result;
}

void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
{
    //set a count of unread mails
    //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND checked = 0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
    if (resultUnread)
    {
        Field *fieldMail = resultUnread->Fetch();
        unReadMails = fieldMail[0].GetUInt8();
        delete resultUnread;
    }

    // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
    //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND checked = 0", GUID_LOPART(playerGuid));
    if (resultDelivery)
    {
        Field *fieldMail = resultDelivery->Fetch();
        m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
        delete resultDelivery;
    }
}

void Player::_LoadMail()
{
    m_mail.clear();
    //mails are in right order
    QueryResult *result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
    if(result)
    {
        do
        {
            Field *fields = result->Fetch();
            Mail *m = new Mail;
            m->messageID = fields[0].GetUInt32();
            m->messageType = fields[1].GetUInt8();
            m->sender = fields[2].GetUInt32();
            m->receiver = fields[3].GetUInt32();
            m->subject = fields[4].GetCppString();
            m->itemTextId = fields[5].GetUInt32();
            bool has_items = fields[6].GetBool();
            m->expire_time = (time_t)fields[7].GetUInt64();
            m->deliver_time = (time_t)fields[8].GetUInt64();
            m->money = fields[9].GetUInt32();
            m->COD = fields[10].GetUInt32();
            m->checked = fields[11].GetUInt32();
            m->stationery = fields[12].GetUInt8();
            m->state = MAIL_STATE_UNCHANGED;

            if (has_items)
                _LoadMailedItems(m);

            m_mail.push_back(m);
        } while( result->NextRow() );
        delete result;
    }
    m_mailsLoaded = true;
}

void Player::LoadPet()
{
    Pet *pet = new Pet(this);
    if(!pet->LoadPetFromDB(this,0,0,true))
        delete pet;
}

void Player::_LoadQuestStatus(QueryResult *result)
{
    mQuestStatus.clear();

    uint32 slot = 0;

    ////                                                     0      1       2         3         4      5          6          7          8          9           10          11          12
    //QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());

    if(result)
    {
        do
        {
            Field *fields = result->Fetch();

            uint32 quest_id = fields[0].GetUInt32();
                                                            // used to be new, no delete?
            Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
            if( pQuest )
            {
                // find or create
                QuestStatusData& questStatusData = mQuestStatus[quest_id];

                uint32 qstatus = fields[1].GetUInt32();
                if(qstatus < MAX_QUEST_STATUS)
                    questStatusData.m_status = QuestStatus(qstatus);
                else
                {
                    questStatusData.m_status = QUEST_STATUS_NONE;
                    sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
                }

                questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
                questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );

                time_t quest_time = time_t(fields[4].GetUInt64());

                if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) &&  questStatusData.m_status != QUEST_STATUS_NONE )
                {
                    AddTimedQuest( quest_id );

                    if (quest_time <= sWorld.GetGameTime())
                        questStatusData.m_timer = 1;
                    else
                        questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
                }
                else
                    quest_time = 0;

                questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
                questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
                questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
                questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
                questStatusData.m_itemcount[0] = fields[9].GetUInt32();
                questStatusData.m_itemcount[1] = fields[10].GetUInt32();
                questStatusData.m_itemcount[2] = fields[11].GetUInt32();
                questStatusData.m_itemcount[3] = fields[12].GetUInt32();

                questStatusData.uState = QUEST_UNCHANGED;

                // add to quest log
                if( slot < MAX_QUEST_LOG_SIZE &&
                    ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
                    questStatusData.m_status==QUEST_STATUS_COMPLETE && !questStatusData.m_rewarded ) )
                {
                    uint32 state = 0;
                    if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
                        state |= 1 << 24;

                    for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
                    {
                        if(questStatusData.m_creatureOrGOcount[idx])
                            state += (questStatusData.m_creatureOrGOcount[idx] << ( 6 * idx ));
                    }

                    SetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*slot+0,quest_id);
                    SetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*slot+1,state);
                    SetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*slot+2,quest_time);

                    ++slot;
                }

                sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", mQuestStatus[quest_id].m_status, quest_id, GetGUIDLow());
            }
        }
        while( result->NextRow() );

        delete result;
    }

    // clear quest log tail
    for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
    {
        SetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i+0,0);
        SetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i+1,0);
        SetUInt32Value(PLAYER_QUEST_LOG_1_1 + 3*i+2,0);
    }
}

void Player::_LoadDailyQuestStatus(QueryResult *result)
{
    for(uint32 quest_daily_idx = 0; quest_daily_idx < 10; ++quest_daily_idx)
        SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);

    //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());

    if(result)
    {
        uint32 quest_daily_idx = 0;

        do
        {
            if(quest_daily_idx >= 10)                       // max amount with exist data in query
            {
                sLog.outError("Player (GUID: %u) have more 10 daily quest records in charcter_queststatus_daily",GetGUIDLow());
                break;
            }

            Field *fields = result->Fetch();

            uint32 quest_id = fields[0].GetUInt32();

            // save _any_ from daily quest times (it must be after last reset anyway)
            m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();

            Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
            if( !pQuest )
                continue;

            SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
            ++quest_daily_idx;

            sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
        }
        while( result->NextRow() );

        delete result;
    }

    m_DailyQuestChanged = false;
}

void Player::_LoadReputation(QueryResult *result)
{
    m_factions.clear();

    // Set initial reputations (so everything is nifty before DB data load)
    SetInitialFactions();

    //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());

    if(result)
    {
        do
        {
            Field *fields = result->Fetch();

            FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
            if( factionEntry && (factionEntry->reputationListID >= 0))
            {
                Faction* oldFaction = &m_factions[factionEntry->reputationListID];
                uint32 oldFlags = oldFaction ? oldFaction->Flags : 0;

                Faction newFaction;
                newFaction.ID               = factionEntry->ID;
                newFaction.ReputationListID = factionEntry->reputationListID;
                newFaction.Standing         = int32(fields[1].GetUInt32());
                newFaction.Flags            = fields[2].GetUInt32();
                newFaction.Changed          = false;

                // fix flags base at initial values
                if((oldFlags & FACTION_FLAG_OWN_TEAM) != 0)
                {
                    newFaction.Flags |= (FACTION_FLAG_OWN_TEAM | FACTION_FLAG_VISIBLE);
                    newFaction.Flags &= ~FACTION_FLAG_AT_WAR;
                }

                m_factions[newFaction.ReputationListID] = newFaction;

                // set atWar for hostile
                if(GetReputationRank(factionEntry) <= REP_HOSTILE)
                    SetFactionAtWar(factionEntry->reputationListID,true);
            }
        }
        while( result->NextRow() );

        delete result;
    }
}

void Player::_LoadSpells(QueryResult *result)
{
    for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
        delete itr->second;
    m_spells.clear();

    //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());

    if(result)
    {
        do
        {
            Field *fields = result->Fetch();

            addSpell(fields[0].GetUInt16(), fields[2].GetUInt8(), PLAYERSPELL_UNCHANGED, fields[1].GetUInt16());
        }
        while( result->NextRow() );

        delete result;
    }
}

void Player::_LoadTaxiMask(const char* data)
{
    Tokens tokens = StrSplit(data, " ");

    int index;
    Tokens::iterator iter;
    for (iter = tokens.begin(), index = 0;
        (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
    {
        // load and set bits only for existed taxi nodes
        m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
    }
}

void Player::_LoadTutorials(QueryResult *result)
{
    //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE guid = '%u'",GetGUIDLow());

    if(result)
    {
        do
        {
            Field *fields = result->Fetch();

            for (int iI=0; iI<8; iI++)
                m_Tutorials[iI] = fields[iI].GetUInt32();
        }
        while( result->NextRow() );

        delete result;
    }

    m_TutorialsChanged = false;
}

void Player::_LoadGroup(QueryResult *result)
{
    //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
    if(result)
    {
        uint64 leaderGuid = MAKE_GUID((*result)[0].GetUInt32(),HIGHGUID_PLAYER);
        delete result;
        Group* group = objmgr.GetGroupByLeader(leaderGuid);
        if(group)
        {
            uint8 subgroup = group->GetMemberGroup(GetGUID());
            SetGroup(group, subgroup);
        }
    }
}

void Player::_LoadBoundInstances(QueryResult *result)
{
    m_BoundInstances.clear();

    //QueryResult *result = CharacterDatabase.PQuery("SELECT map,instance,leader FROM character_instance WHERE guid = '%u'", GetGUIDLow());
    if(result)
    {
        do
        {
            Field *fields = result->Fetch();
            m_BoundInstances[fields[0].GetUInt32()] = std::pair< uint32, uint32 >(fields[1].GetUInt32(), fields[2].GetUInt32());
        } while(result->NextRow());
        delete result;
    }

    // correctly set current instance (if needed)
    BoundInstancesMap::iterator i = m_BoundInstances.find(GetMapId());
    if (i != m_BoundInstances.end()) SetInstanceId(i->second.first); else SetInstanceId(0);
}

bool Player::_LoadHomeBind(QueryResult *result)
{
    //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
    if (result)
    {
        Field *fields = result->Fetch();
        m_homebindMapId = fields[0].GetUInt32();
        m_homebindZoneId = fields[1].GetUInt16();
        m_homebindX = fields[2].GetFloat();
        m_homebindY = fields[3].GetFloat();
        m_homebindZ = fields[4].GetFloat();
        delete result;
    }
    else
    {
        uint32 plrace = getRace();
        uint32 plclass = getClass();
        QueryResult *result1 = WorldDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM playercreateinfo WHERE race = '%u' AND class = '%u'", plrace, plclass);

        if(!result1)
        {
            sLog.outErrorDb("Table playercreateinfo not have data for race %u class %u , character can't be loaded.",plrace, plclass);
            return false;
        }

        Field *fields = result1->Fetch();
        m_homebindMapId = fields[0].GetUInt32();
        m_homebindZoneId = fields[1].GetUInt16();
        m_homebindX = fields[2].GetFloat();
        m_homebindY = fields[3].GetFloat();
        m_homebindZ = fields[4].GetFloat();
        CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
        delete result1;
    }
    DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
        m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
    return true;
}

/*********************************************************/
/***                   SAVE SYSTEM                     ***/
/*********************************************************/

void Player::SaveToDB()
{
    // delay auto save at any saves (manual, in code, or autosave)
    m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);

    // Must saved before enter into BattleGround
    if(InBattleGround())
        return;

    int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
                                                            //save, far from tavern/city
                                                            //save, but in tavern/city
    sLog.outDebug("The value of player %s at save: ", m_name.c_str());
    outDebugValues();

    // save state (after auras removing), if aura remove some flags then it must set it back by self)
    uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
    uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
    uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
    uint32 tmp_displayid = GetUInt32Value(UNIT_FIELD_DISPLAYID);

    // Set player sit state to standing on save, also stealth and shifted form
    RemoveFlag(UNIT_FIELD_BYTES_1,PLAYER_STATE_SIT | PLAYER_STATE_FORM_ALL | PLAYER_STATE_FLAG_CREEP);
    RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
    SetUInt32Value(UNIT_FIELD_DISPLAYID,GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID));

    bool inworld = IsInWorld();

    CharacterDatabase.BeginTransaction();

    CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());

    std::ostringstream ss;
    ss << "INSERT INTO characters (guid,account,name,race,class,"
        "map,position_x,position_y,position_z,orientation,data,"
        "taximask,online,cinematic,"
        "totaltime,leveltime,rest_bonus,logout_time,is_logout_resting,resettalents_cost,resettalents_time,"
        "trans_x, trans_y, trans_z, trans_o, transguid, gmstate, stable_slots,at_login,zone,"
        "pending_honor, last_honor_date, last_kill_date,taxi_path) VALUES ("
        << GetGUIDLow() << ", "
        << GetSession()->GetAccountId() << ", '"
        << m_name << "', "
        << m_race << ", "
        << m_class << ", "
        << GetMapId() << ", "
        << GetPositionX() << ", "
        << GetPositionY() << ", "
        << GetPositionZ() << ", "
        << GetOrientation() << ", '";

    uint16 i;
    for( i = 0; i < m_valuesCount; i++ )
    {
        ss << GetUInt32Value(i) << " ";
    }

    ss << "', '";

    for( i = 0; i < 8; i++ )
        ss << m_taximask[i] << " ";

    ss << "', ";
    ss << (inworld ? 1 : 0);

    ss << ", ";
    ss << m_cinematic;

    ss << ", ";
    ss << m_Played_time[0];
    ss << ", ";
    ss << m_Played_time[1];

    ss << ", ";
    ss << m_rest_bonus;
    ss << ", ";
    ss << time(NULL);
    ss << ", ";
    ss << is_save_resting;
    ss << ", ";
    ss << m_resetTalentsCost;
    ss << ", ";
    ss << (uint64)m_resetTalentsTime;

    ss << ", ";
    ss << m_movementInfo.t_x;
    ss << ", ";
    ss << m_movementInfo.t_y;
    ss << ", ";
    ss << m_movementInfo.t_z;
    ss << ", ";
    ss << m_movementInfo.t_o;
    ss << ", ";
    if (m_transport)
        ss << m_transport->GetGUIDLow();
    else
        ss << "0";

    ss << ", ";
    ss << (isGameMaster()? 1 : 0);

    ss << ", ";
    ss << uint32(m_stableSlots);                            // to prevent save uint8 as char

    ss << ", ";
    ss << uint32(m_atLoginFlags);

    ss << ", ";
    ss << GetZoneId();

    ss << ", ";
    ss << m_honorPending;
    ss << ", ";
    ss << m_lastHonorDate;
    ss << ", ";
    ss << m_lastKillDate;
    ss << ", '";
    ss << SaveTaxiDestinationsToString();
    ss << "' )";

    CharacterDatabase.Execute( ss.str().c_str() );

    if(m_mailsUpdated)                                      //save mails only when needed
        _SaveMail();

    _SaveInventory();
    _SaveQuestStatus();
    _SaveDailyQuestStatus();
    _SaveTutorials();
    _SaveSpells();
    _SaveSpellCooldowns();
    _SaveActions();
    _SaveAuras();
    _SaveReputation();
    _SaveBoundInstances();
    _SaveHonor();

    CharacterDatabase.CommitTransaction();

    // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
    SetUInt32Value(UNIT_FIELD_DISPLAYID, tmp_displayid);
    SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
    SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
    SetUInt32Value(PLAYER_FLAGS, tmp_pflags);

    // save pet (hunter pet level and experience and all type pets health/mana).
    if(Pet* pet = GetPet())
        pet->SavePetToDB(PET_SAVE_AS_CURRENT);
}

// fast save function for item/money cheating preventing - save only inventory and money state
void Player::SaveInventoryAndGoldToDB()
{
    _SaveInventory();
    SetUInt32ValueInDB(PLAYER_FIELD_COINAGE,GetMoney(),GetGUID());
}

void Player::_SaveActions()
{
    for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
    {
        switch (itr->second.uState)
        {
            case ACTIONBUTTON_NEW:
                CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
                    GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
                itr->second.uState = ACTIONBUTTON_UNCHANGED;
                ++itr;
                break;
            case ACTIONBUTTON_CHANGED:
                CharacterDatabase.PExecute("UPDATE character_action  SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
                    (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
                itr->second.uState = ACTIONBUTTON_UNCHANGED;
                ++itr;
                break;
            case ACTIONBUTTON_DELETED:
                CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
                m_actionButtons.erase(itr++);
                break;
            default:
                ++itr;
                break;
        };
    }
}

void Player::_SaveAuras()
{
    CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());

    AuraMap const& auras = GetAuras();
    for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
    {
        SpellEntry const *spellInfo = itr->second->GetSpellProto();

        //skip all auras from spells that are passive or need a shapeshift
        if (itr->second->IsPassive() || itr->second->IsRemovedOnShapeLost())
            continue;

        uint8 i;
        // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
        for (i = 0; i < 3; i++)
            if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
            spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
                break;

        if (i == 3)
        {
            CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u' and spell = '%u' and  effect_index= '%u'",GetGUIDLow(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex());
            CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
                "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%d', '%d', '%d', '%d')",
                GetGUIDLow(), itr->second->GetCasterGUID(), (uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(), (*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
        }
    }
}

void Player::_SaveInventory()
{
    // force items in buyback slots to new state
    // and remove those that aren't already
    for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
    {
        Item *item = m_items[i];
        if (!item || item->GetState() == ITEM_NEW) continue;
        CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
        CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
        m_items[i]->FSetState(ITEM_NEW);
    }

    // update enchantment durations
    for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
    {
        itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
    }

    // if no changes
    if (m_itemUpdateQueue.empty()) return;

    // do not save if the update queue is corrupt
    bool error = false;
    for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
    {
        Item *item = m_itemUpdateQueue[i];
        if(!item || item->GetState() == ITEM_REMOVED) continue;
        Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());

        if (test == NULL)
        {
            sLog.outError("Player::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
            error = true;
        }
        else if (test != item)
        {
            sLog.outError("Player::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
            error = true;
        }
    }

    if (error)
    {
        sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
        ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
        return;
    }

    for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
    {
        Item *item = m_itemUpdateQueue[i];
        if(!item) continue;

        Bag *container = item->GetContainer();
        uint32 bag_guid = container ? container->GetGUIDLow() : 0;

        switch(item->GetState())
        {
            case ITEM_NEW:
                CharacterDatabase.PExecute("INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES ('%u', '%u', '%u', '%u', '%u')", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetGUIDLow(), item->GetEntry());
                break;
            case ITEM_CHANGED:
                CharacterDatabase.PExecute("UPDATE character_inventory SET guid='%u', bag='%u', slot='%u', item_template='%u' WHERE item='%u'", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetEntry(), item->GetGUIDLow());
                break;
            case ITEM_REMOVED:
                CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
                break;
            case ITEM_UNCHANGED:
                break;
        }

        item->SaveToDB();
    }
    m_itemUpdateQueue.clear();
}

void Player::_SaveMail()
{
    if (!m_mailsLoaded)
        return;

    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
    {
        Mail *m = (*itr);
        if (m->state == MAIL_STATE_CHANGED)
        {
            CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
                m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
            if(m->removedItems.size())
            {
                for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
                    CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
                m->removedItems.clear();
            }
            m->state = MAIL_STATE_UNCHANGED;
        }
        else if (m->state == MAIL_STATE_DELETED)
        {
            if (m->HasItems())
                for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
                    CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
            if (m->itemTextId)
                CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
            CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
            CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
        }
    }

    //deallocate deleted mails...
    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
    {
        if ((*itr)->state == MAIL_STATE_DELETED)
        {
            Mail* m = *itr;
            m_mail.erase(itr);
            delete m;
            itr = m_mail.begin();
        }
        else
            ++itr;
    }

    m_mailsUpdated = false;
}

void Player::_SaveQuestStatus()
{
    // we don't need transactions here.
    for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
    {
        switch (i->second.uState)
        {
            case QUEST_NEW :
                CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
                    "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
                    GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
                break;
            case QUEST_CHANGED :
                CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u'  WHERE guid = '%u' AND quest = '%u' ",
                    i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
                break;
            case QUEST_UNCHANGED:
                break;
        };
        i->second.uState = QUEST_UNCHANGED;
    }
}

void Player::_SaveDailyQuestStatus()
{
    if(!m_DailyQuestChanged)
        return;

    m_DailyQuestChanged = false;

    // save last daily quest time for all quests: we need only mostly reset time for reset check anyway

    // we don't need transactions here.
    CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
    for(uint32 quest_daily_idx = 0; quest_daily_idx < 10; ++quest_daily_idx)
        if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
            CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
                GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
}

void Player::_SaveReputation()
{
    for(FactionsList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
    {
        if (itr->second.Changed)
        {
            CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
            CharacterDatabase.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr->second.ID, itr->second.Standing, itr->second.Flags);
            itr->second.Changed = false;
        }
    }
}

void Player::_SaveSpells()
{
    for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
    {
        ++next;
        if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
            CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
        if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
            CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,slot,active) VALUES ('%u', '%u', '%u','%u')", GetGUIDLow(), itr->first, itr->second->slotId,itr->second->active);

        if (itr->second->state == PLAYERSPELL_REMOVED)
            _removeSpell(itr->first);
        else
            itr->second->state = PLAYERSPELL_UNCHANGED;
    }
}

void Player::_SaveTutorials()
{
    if(!m_TutorialsChanged)
        return;

    uint32 Rows=0;
    // it's better than rebuilding indexes multiple times
    QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE guid = '%u'", GetGUIDLow() );
    if(result)
    {
        Rows = result->Fetch()[0].GetUInt32();
        delete result;
    }

    if (Rows)
    {
        CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE guid = '%u'",
            m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetGUIDLow() );
    }
    else
    {
        CharacterDatabase.PExecute("INSERT INTO character_tutorial (guid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetGUIDLow(), m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
    };

    m_TutorialsChanged = false;
}

void Player::_SaveHonor()
{
    // first save/honor gain after midnight will also update the player's honor fields
    UpdateHonorFields();

    // the character_kill tables are not used if the config is set to 0
    if(!sWorld.getConfig(CONFIG_HONOR_KILL_LIMIT))
        return;

    // flush all kills from the DB at midnight
    if(m_flushKills)
    {
        CharacterDatabase.PExecute("DELETE FROM character_kill WHERE guid = '%u'", GetGUIDLow());
        m_flushKills = false;
    }

    // only if there's something to save
    if(m_saveKills)
    {
        for(KillInfoMap::iterator itr = m_killsPerPlayer.begin(); itr != m_killsPerPlayer.end(); ++itr)
        {
            switch(itr->second.state)
            {
                case KILL_NEW:
                    CharacterDatabase.PExecute("DELETE FROM character_kill WHERE guid = '%u' AND victim_guid = '%u'", GetGUIDLow(), itr->first);
                    CharacterDatabase.PExecute("INSERT INTO character_kill VALUES ('%u','%u','%u')", GetGUIDLow(), itr->first, itr->second.count);
                    break;
                case KILL_CHANGED:
                    CharacterDatabase.PExecute("UPDATE character_kill SET count='%u' WHERE guid = '%u' AND victim_guid = '%u'", itr->second.count, GetGUIDLow(), itr->first);
                    break;
            }
            itr->second.state = KILL_UNCHANGED;
        }
        m_saveKills = false;
    }
}

void Player::outDebugValues() const
{
    if(!sLog.IsOutDebug())                                  // optimize disabled debug output
        return;

    sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
    sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
    sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
    sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
    sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
    sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
    sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
    sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
    sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
    sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
    sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
    sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
}

/*********************************************************/
/***               FLOOD FILTER SYSTEM                 ***/
/*********************************************************/

void Player::UpdateSpeakTime()
{
    time_t current = time (NULL);
    if(m_speakTime > current)
    {
        uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
        if(!max_count)
            return;

        ++m_speakCount;
        if(m_speakCount >= max_count)
        {
            // prevent overwrite mute time, if message send just before mutes set, for example.
            time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
            if(GetSession()->m_muteTime < new_mute)
                GetSession()->m_muteTime = new_mute;

            m_speakCount = 0;
        }
    }
    else
        m_speakCount = 0;

    m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
}

bool Player::CanSpeak() const
{
    return  GetSession()->m_muteTime <= time (NULL);
}

/*********************************************************/
/***              LOW LEVEL FUNCTIONS:Notifiers        ***/
/*********************************************************/

void Player::SendAttackSwingNotInRange()
{
    WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
    GetSession()->SendPacket( &data );
}

void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
{
    std::ostringstream ss;
    ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
        << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
        << "',zone='"<<zone<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
    CharacterDatabase.Execute(ss.str().c_str());
}

bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
{
    std::ostringstream ss2;
    ss2<<"UPDATE characters SET data='";
    int i=0;
    for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
    {
        ss2<<tokens[i]<<" ";
    }
    ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";

    return CharacterDatabase.Execute(ss2.str().c_str());
}

void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
{
    char buf[11];
    snprintf(buf,11,"%u",value);

    if(index >= tokens.size())
        return;

    tokens[index] = buf;
}

void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
{
    Tokens tokens;
    if(!LoadValuesArrayFromDB(tokens,guid))
        return;

    if(index >= tokens.size())
        return;

    char buf[11];
    snprintf(buf,11,"%u",value);
    tokens[index] = buf;

    SaveValuesArrayInDB(tokens,guid);
}

void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
{
    uint32 temp;
    memcpy(&temp, &value, sizeof(value));
    Player::SetUInt32ValueInDB(index, temp, guid);
}

void Player::SendAttackSwingNotStanding()
{
    WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
    GetSession()->SendPacket( &data );
}

void Player::SendAttackSwingDeadTarget()
{
    WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
    GetSession()->SendPacket( &data );
}

void Player::SendAttackSwingCantAttack()
{
    WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
    GetSession()->SendPacket( &data );
}

void Player::SendAttackSwingCancelAttack()
{
    WorldPacket data(SMSG_CANCEL_COMBAT, 0);
    GetSession()->SendPacket( &data );
}

void Player::SendAttackSwingBadFacingAttack()
{
    WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
    GetSession()->SendPacket( &data );
}

void Player::SendAutoRepeatCancel()
{
    WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, 0);
    GetSession()->SendPacket( &data );
}

void Player::PlaySound(uint32 Sound, bool OnlySelf)
{
    WorldPacket data(SMSG_PLAY_SOUND, 4);
    data << Sound;
    if (OnlySelf)
        GetSession()->SendPacket( &data );
    else
        SendMessageToSet( &data, true );
}

void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
{
    WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
    data << Area;
    data << Experience;
    GetSession()->SendPacket(&data);
}

void Player::SendDungeonDifficulty()
{
    WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
    data << m_dungeonDifficulty;
    data << uint32(0x00000001);
    data << uint32(0x00000000);
    GetSession()->SendPacket(&data);
}

/*********************************************************/
/***              Update timers                        ***/
/*********************************************************/

void Player::UpdatePvPFlag(time_t currTime)
{
    if(!IsPvP() || pvpInfo.endTimer == 0) return;
    if(currTime < (pvpInfo.endTimer + 300)) return;

    UpdatePvP(false);
}

void Player::UpdateDuelFlag(time_t currTime)
{
    if(!duel || duel->startTimer == 0) return;
    if(currTime < duel->startTimer + 3) return;

    SetUInt32Value(PLAYER_DUEL_TEAM, 1);
    duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);

    duel->startTimer = 0;
    duel->startTime  = currTime;
    duel->opponent->duel->startTimer = 0;
    duel->opponent->duel->startTime  = currTime;
}

void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
{
    if(!pet)
        pet = GetPet();

    if(returnreagent && (pet || m_oldpetnumber))
    {
        //returning of reagents only for players, so best done here
        uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
        SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);

        if(spellInfo)
        {
            for(uint32 i = 0; i < 7; ++i)
            {
                if(spellInfo->Reagent[i] > 0)
                {
                    uint16 dest;                            //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
                    uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i], false );
                    if( msg == EQUIP_ERR_OK )
                    {
                        Item* item = StoreNewItem( dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i], true);
                        if(IsInWorld())
                            SendNewItem(item,spellInfo->ReagentCount[i],true,false);
                    }
                }
            }
        }
        m_oldpetnumber = 0;
    }

    if(!pet || pet->GetOwnerGUID()!=GetGUID())
        return;

    // only if current pet in slot
    if(GetPetGUID()==pet->GetGUID())
        SetPet(0);

    pet->CombatStop();

    if(returnreagent)
    {
        switch(pet->GetEntry())
        {
            //warlock pets except imp are removed(?) when logging out
            case 1860:
            case 1863:
            case 417:
            case 17252:
                mode = PET_SAVE_NOT_IN_SLOT;
                break;
        }
    }

    pet->SavePetToDB(mode);

    pet->CleanupsBeforeDelete();
    ObjectAccessor::Instance().AddObjectToRemoveList(pet);
    pet->m_removed = true;

    if(pet->isControlled())
    {
        WorldPacket data(SMSG_PET_SPELLS, 8);
        data << uint64(0);
        GetSession()->SendPacket(&data);
    }
}

void Player::Uncharm()
{
    Unit* charm = GetCharm();
    if(!charm) return;

    charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
    charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);

}

void Player::Say(const std::string text, const uint32 language)
{
    WorldPacket data(SMSG_MESSAGECHAT, 200);
    data << (uint8)CHAT_MSG_SAY;
    data << (uint32)language;
    data << (uint64)GetGUID();
    data << (uint32)language;                               //language 2.1.0 ?
    data << (uint64)GetGUID();
    data << (uint32)(text.length()+1);
    data << text;
    data << (uint8)chatTag();

    SendMessageToSet(&data, true);
}

void Player::Yell(const std::string text, const uint32 language)
{
    WorldPacket data(SMSG_MESSAGECHAT, 200);
    data << (uint8)CHAT_MSG_YELL;
    data << (uint32)language;
    data << (uint64)GetGUID();
    data << (uint32)language;                               //language 2.1.0 ?
    data << (uint64)GetGUID();
    data << (uint32)(text.length()+1);
    data << text;
    data << (uint8)chatTag();

    SendMessageToSet(&data, true);
}

void Player::TextEmote(const std::string text)
{
    WorldPacket data(SMSG_MESSAGECHAT, 200);
    data << (uint8)CHAT_MSG_EMOTE;
    data << (uint32)LANG_UNIVERSAL;
    data << (uint64)GetGUID();
    data << (uint32)0;
    data << (uint64)GetGUID();
    data << (uint32)(text.length()+1);
    data << text;
    data << (uint8)chatTag();

    if(sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT))
        SendMessageToSet(&data, true);
    else
        SendMessageToOwnTeamSet(&data,true);
}

void Player::Whisper(const uint64 receiver, const std::string text, uint32 language)
{
    if (language != LANG_ADDON)                             // if not addon data
        language = LANG_UNIVERSAL;                          // whispers should always be readable

    Player *rPlayer = objmgr.GetPlayer(receiver);

    // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
    if(!rPlayer->isDND() || isGameMaster())
    {
        WorldPacket data(SMSG_MESSAGECHAT, 200);
        data << (uint8)CHAT_MSG_WHISPER;
        data << (uint32)language;
        data << (uint64)GetGUID();
        data << (uint32)0;
        data << (uint64)GetGUID();
        data << (uint32)(text.length()+1);
        data << text;
        data << (uint8)chatTag();
        rPlayer->GetSession()->SendPacket(&data);

        data.Initialize(SMSG_MESSAGECHAT, 200);
        data << (uint8)CHAT_MSG_WHISPER_INFORM;
        data << (uint32)language;
        data << (uint64)rPlayer->GetGUID();
        data << (uint32)0;
        data << (uint64)rPlayer->GetGUID();
        data << (uint32)(text.length()+1);
        data << text;
        data << (uint8)rPlayer->chatTag();
        GetSession()->SendPacket(&data);
    }
    else
    {
        // announce to player that player he is whispering to is dnd and cannot receive his message
        ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
    }

    if(!isAcceptWhispers())
    {
        SetAcceptWhispers(true);
        ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
    }

    // announce to player that player he is whispering to is afk
    if(rPlayer->isAFK())
        ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());

    // if player whisper someone, auto turn of dnd to be able to receive an answer
    if(isDND() && !rPlayer->isGameMaster())
        ToggleDND();
}

void Player::PetSpellInitialize()
{
    Pet* pet = GetPet();

    if(pet)
    {
        uint8 addlist = 0;

        sLog.outDebug("Pet Spells Groups");

        CreatureInfo const *cinfo = pet->GetCreatureInfo();

        if(pet->isControlled() && (pet->getPetType() == HUNTER_PET || cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK))
        {
            for(PetSpellMap::iterator itr = pet->m_spells.begin();itr != pet->m_spells.end();itr++)
            {
                if(itr->second->state == PETSPELL_REMOVED)
                    continue;
                ++addlist;
            }
        }

        // first line + actionbar + spellcount + spells + last adds
        WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);

        CharmInfo *charmInfo = pet->GetCharmInfo();

                                                            //16
        data << (uint64)pet->GetGUID() << uint32(0x00000000) << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);

        for(uint32 i = 0; i < 10; i++)                      //40
        {
            data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
        }

        data << uint8(addlist);                             //1

        if(addlist && pet->isControlled())
        {
            for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
            {
                if(itr->second->state == PETSPELL_REMOVED)
                    continue;

                data << uint16(itr->first);
                data << uint16(itr->second->active);
            }
        }

        //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00);    //15
        uint8 count = 3;                                    //1+8+8+8=25

        // if count = 0, then end of packet...
        data << count;
        // uint32 value is spell id...
        // uint64 value is constant 0, unknown...
        data << uint32(0x6010) << uint64(0);                // if count = 1, 2 or 3
        //data << uint32(0x5fd1) << uint64(0);  // if count = 2
        data << uint32(0x8e8c) << uint64(0);                // if count = 3
        data << uint32(0x8e8b) << uint64(0);                // if count = 3

        GetSession()->SendPacket(&data);
    }
}

void Player::PossessSpellInitialize()
{
    Unit* charm = GetCharm();

    if(!charm)
        return;

    CharmInfo *charmInfo = charm->GetCharmInfo();

    if(!charmInfo)
    {
        sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
        return;
    }

    uint8 addlist = 0;
    WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds

                                                            //16
    data << (uint64)charm->GetGUID() << uint32(0x00000000) << uint8(0) << uint8(0) << uint16(0);

    for(uint32 i = 0; i < 10; i++)                          //40
    {
        data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
    }

    data << uint8(addlist);                                 //1

    uint8 count = 3;
    data << count;
    data << uint32(0x6010) << uint64(0);                    // if count = 1, 2 or 3
    data << uint32(0x8e8c) << uint64(0);                    // if count = 3
    data << uint32(0x8e8b) << uint64(0);                    // if count = 3

    GetSession()->SendPacket(&data);
}

void Player::CharmSpellInitialize()
{
    Unit* charm = GetCharm();

    if(!charm)
        return;

    CharmInfo *charmInfo = charm->GetCharmInfo();
    if(!charmInfo)
    {
        sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
        return;
    }

    uint8 addlist = 0;

    if(charm->GetTypeId() != TYPEID_PLAYER)
    {
        CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();

        if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
        {
            for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
            {
                if(charmInfo->GetCharmSpell(i)->spellId)
                    ++addlist;
            }
        }
    }

    WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds

    data << (uint64)charm->GetGUID() << uint32(0x00000000);

    if(charm->GetTypeId() != TYPEID_PLAYER)
        data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
    else
        data << uint8(0) << uint8(0);

    data << uint16(0);

    for(uint32 i = 0; i < 10; i++)                          //40
    {
        data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
    }

    data << uint8(addlist);                                 //1

    if(addlist)
    {
        for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
        {
            CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
            if(cspell->spellId)
            {
                data << uint16(cspell->spellId);
                data << uint16(cspell->active);
            }
        }
    }

    uint8 count = 3;
    data << count;
    data << uint32(0x6010) << uint64(0);                    // if count = 1, 2 or 3
    data << uint32(0x8e8c) << uint64(0);                    // if count = 3
    data << uint32(0x8e8b) << uint64(0);                    // if count = 3

    GetSession()->SendPacket(&data);
}

int32 Player::GetTotalFlatMods(uint32 spellId, uint8 op)
{
    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
    if (!spellInfo) return 0;
    int32 total = 0;
    for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
    {
        SpellModifier *mod = *itr;

        if(!IsAffectedBySpellmod(spellInfo,mod))
            continue;

        if (mod->type == SPELLMOD_FLAT)
            total += mod->value;
    }
    return total;
}

int32 Player::GetTotalPctMods(uint32 spellId, uint8 op)
{
    SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
    if (!spellInfo) return 0;
    int32 total = 0;
    for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
    {
        SpellModifier *mod = *itr;

        if(!IsAffectedBySpellmod(spellInfo,mod))
            continue;

        if (mod->type == SPELLMOD_PCT)
            total += mod->value;
    }
    return total;
}

bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
{
    if (!mod || !spellInfo)
        return false;

    if(mod->charges == -1 && mod->lastAffected )            // marked as expired but locked until spell casting finish
    {
        // prevent apply to any spell except spell that trigger expire
        if(spell)
        {
            if(mod->lastAffected != spell)
                return false;
        }
        else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
            return false;
    }

    return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
}

void Player::AddSpellMod(SpellModifier* mod, bool apply)
{
    uint64 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;

    for(int eff=0;eff<64;++eff)
    {
        if ( mod->mask & (uint64(1) << eff) )
        {
            m_totalSpellMod[mod->op][eff] += apply ? mod->value : -(mod->value);
            WorldPacket data(Opcode, (1+1+4));
            data << uint8(eff);
            data << uint8(mod->op);
            data << int32(m_totalSpellMod[mod->op][eff]);
            SendDirectMessage(&data);
        }
    }

    if (apply)
        m_spellMods[mod->op].push_back(mod);
    else
    {
        if (mod->charges == -1)
            --m_SpellModRemoveCount;
        m_spellMods[mod->op].remove(mod);
        delete mod;
    }
}

void Player::RemoveSpellMods(Spell const* spell)
{
    if(!spell || (m_SpellModRemoveCount == 0))
        return;

    for(int i=0;i<MAX_SPELLMOD;++i)
    {
        for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
        {
            SpellModifier *mod = *itr;
            ++itr;

            if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
            {
                RemoveAurasDueToSpell(mod->spellId);
                if (m_spellMods[i].empty())
                    break;
                else
                    itr = m_spellMods[i].begin();
            }
        }
    }
}

void Player::RemoveAreaAurasFromGroup()
{
    Group* pGroup = GetGroup();
    if(!pGroup)
        return;

    for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
    {
        Player* Member = itr->getSource();
        if(!Member || !pGroup->SameSubGroup(this, Member))
            continue;

        Member->RemoveAreaAurasByOthers(GetGUID());
        for (uint8 i = 0; i < 4; i++)
            if (m_TotemSlot[i])
                Member->RemoveAreaAurasByOthers(m_TotemSlot[i]);
    }
}

// send Proficiency
void Player::SendProficiency(uint8 pr1, uint32 pr2)
{
    WorldPacket data(SMSG_SET_PROFICIENCY, 8);
    data << pr1 << pr2;
    GetSession()->SendPacket (&data);
}

void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
{
    QueryResult *result = NULL;
    if(type==10)
        result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
    else
        result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
    if(result)
    {
        do    // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
        {     // and SendPetitionQueryOpcode reads data from the DB
            Field *fields = result->Fetch();
            uint64 ownerguid   = MAKE_GUID(fields[0].GetUInt32(), HIGHGUID_PLAYER);
            uint64 petitionguid = MAKE_GUID(fields[1].GetUInt32(), HIGHGUID_ITEM);

            // send update if charter owner in game
            Player* owner = objmgr.GetPlayer(ownerguid);
            if(owner)
                owner->GetSession()->SendPetitionQueryOpcode(petitionguid);

        } while ( result->NextRow() );

        delete result;

        if(type==10)
            CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
        else
            CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
    }

    CharacterDatabase.BeginTransaction();
    if(type == 10)
    {
        CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
        CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
    }
    else
    {
        CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
        CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
    }
    CharacterDatabase.CommitTransaction();
}

void Player::SetRestBonus (float rest_bonus_new)
{
    // Prevent resting on max level
    if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
        rest_bonus_new = 0;

    if(rest_bonus_new < 0)
        rest_bonus_new = 0;

    float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;

    if(rest_bonus_new > rest_bonus_max)
        m_rest_bonus = rest_bonus_max;
    else
        m_rest_bonus = rest_bonus_new;

    // update data for client
    if(m_rest_bonus>10)
    {
        SetFlag(PLAYER_BYTES_2, 0x1000000);                 // Set Reststate = Rested
        RemoveFlag(PLAYER_BYTES_2, 0x2000000);              // Remove Reststate = Normal
    }
    else if(m_rest_bonus<=1)
    {
        SetFlag(PLAYER_BYTES_2, 0x2000000);                 // Set Reststate = Normal
        RemoveFlag(PLAYER_BYTES_2, 0x1000000);              // Remove Reststate = Rested
    }

    //RestTickUpdate
    SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
}

void Player::HandleStealthedUnitsDetection()
{
    std::list<Unit*> stealthedUnits;

    CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
    Cell cell(p);
    cell.data.Part.reserved = ALL_DISTRICT;
    cell.SetNoCreate();

    MaNGOS::AnyStealthedCheck u_check;
    MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);

    TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
    TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer >  grid_unit_searcher(searcher);

    CellLock<GridReadGuard> cell_lock(cell, p);
    cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
    cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));

    for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
    {
        if((*i)==this)
        {
            i = stealthedUnits.erase(i);
            continue;
        }

        if ((*i)->isVisibleForOrDetect(this,true))
        {

            (*i)->SendUpdateToPlayer(this);
            m_clientGUIDs.insert((*i)->GetGUID());

            #ifdef MANGOS_DEBUG
            if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
                sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
            #endif

            // target aura duration for caster show only if target exist at caster client
            // send data at target visibility change (adding to client)
            if((*i)!=this && (*i)->isType(TYPE_UNIT))
                SendAuraDurationsForTarget(*i);

            i = stealthedUnits.erase(i);
            continue;
        }

        ++i;
    }
}

bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes)
{
    if(nodes.size() < 2)
        return false;

    // not let cheating with start flight mounted
    if(IsMounted())
    {
        WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
        data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
        GetSession()->SendPacket(&data);
        return false;
    }

    if( m_ShapeShiftForm && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
    {
        WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
        data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
        GetSession()->SendPacket(&data);
        return false;
    }

    // not let cheating with start flight in time of logout process
    if(GetSession()->isLogingOut())
    {
        WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
        data << uint32(ERR_TAXIPLAYERBUSY);
        GetSession()->SendPacket(&data);
        return false;
    }

    if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
        return false;

    // not let flight if casting not finished
    if(IsNonMeleeSpellCasted(false))
    {
        WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
        data << uint32(ERR_TAXIPLAYERBUSY);
        GetSession()->SendPacket(&data);
        return false;
    }

    uint32 sourcenode = nodes[0];

    // starting node too far away (cheat?)
    TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
    if( !node || node->map_id != GetMapId() ||
        (node->x - GetPositionX())*(node->x - GetPositionX())+
        (node->y - GetPositionY())*(node->y - GetPositionY())+
        (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
        (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
    {
        WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
        data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
        GetSession()->SendPacket(&data);
        return false;
    }

    // Prepare to flight start now

    // stop combat at start taxi flight if any
    CombatStop();

    // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
    TradeCancel(true);

    // clean not finished taxi path if any
    ClearTaxiDestinations();

    // 0 element current node
    AddTaxiDestination(sourcenode);

    // fill destinations path tail
    uint32 sourcepath = 0;
    uint32 totalcost = 0;

    uint32 prevnode = sourcenode;
    uint32 lastnode = 0;

    for(uint32 i = 1; i < nodes.size(); ++i)
    {
        uint32 path, cost;

        lastnode = nodes[i];
        objmgr.GetTaxiPath(prevnode, lastnode, path, cost);

        if(!path)
        {
            ClearTaxiDestinations();
            return false;
        }

        totalcost += cost;

        if(prevnode == sourcenode)
            sourcepath = path;

        AddTaxiDestination(lastnode);

        prevnode = lastnode;
    }

    uint16 MountId = objmgr.GetTaxiMount(sourcenode, GetTeam());

    if (MountId == 0 || sourcepath == 0)
    {
        WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
        data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
        GetSession()->SendPacket(&data);
        ClearTaxiDestinations();
        return false;
    }

    uint32 money = GetMoney();
    if(money < totalcost)
    {
        WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
        data << uint32(ERR_TAXINOTENOUGHMONEY);
        GetSession()->SendPacket(&data);
        ClearTaxiDestinations();
        return false;
    }

    //Checks and preparations done, DO FLIGHT
    ModifyMoney(-(int32)totalcost);

    // prevent stealth flight
    RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);

    WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
    data << uint32(ERR_TAXIOK);
    GetSession()->SendPacket(&data);

    sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");

    GetSession()->SendDoFlight(MountId, sourcepath);

    return true;
}

void Player::ProhibitSpellScholl(SpellSchools idSchool, uint32 unTimeMs )
{
                                                            // last check 2.0.10
    WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
    data << GetGUID();
    data << uint8(0x0);
    time_t curTime = time(NULL);
    for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
    {
        if (itr->second->state == PLAYERSPELL_REMOVED)
            continue;
        uint32 unSpellId = itr->first;
        SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
        if (!spellInfo)
        {
            ASSERT(spellInfo);
            continue;
        }
        if(idSchool == SpellSchools(spellInfo->School) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
        {
            data << unSpellId;
            data << unTimeMs;                               // in m.secs
            AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
        }
    }
    GetSession()->SendPacket(&data);
}

void Player::InitDataForForm()
{
    SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
    if(ssEntry && ssEntry->attackSpeed)
    {
        SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
        SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
        SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
    }
    else
        SetRegularAttackTime();

    switch(m_form)
    {
        case FORM_CAT:
        {
            if(getPowerType()!=POWER_ENERGY)
                setPowerType(POWER_ENERGY);
            break;
        }
        case FORM_BEAR:
        case FORM_DIREBEAR:
        {
            if(getPowerType()!=POWER_RAGE)
                setPowerType(POWER_RAGE);
            break;
        }
        default:                                            // 0, for example
        {
            ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
            if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
                setPowerType(Powers(cEntry->powerType));
            break;
        }
    }

    UpdateAttackPowerAndDamage();
    UpdateAttackPowerAndDamage(true);
}

void Player::ApplySpeedMod(UnitMoveType mtype, float rate, bool forced, bool apply)
{
    // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
    // and do it only for real sent packets and use run for run/mounted as client expected
    if( forced )
    {
        if( mtype == MOVE_MOUNTED &&  ((Player*)this)->IsMounted() ||
            mtype == MOVE_RUN     && !((Player*)this)->IsMounted() )
            ++m_forced_speed_changes[MOVE_RUN];
        else if(mtype != MOVE_RUN && mtype != MOVE_MOUNTED )
            ++m_forced_speed_changes[mtype];
    }

    Unit::ApplySpeedMod(mtype,rate,forced,apply);
}

// Return true is the bought item has a max count to force refresh of window by caller
bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
{
    // cheating attempt
    if(count < 1) count = 1;

    if(!isAlive())
        return false;

    ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
    if( pProto )
    {
        Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
        if (!pCreature)
        {
            sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
            SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
            return false;
        }

        // load vendor items if not yet
        pCreature->LoadGoods();

        CreatureItem* crItem = pCreature->FindItem(item);
        if(!crItem)
        {
            SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
            return false;
        }

        if( crItem->maxcount != 0 && crItem->count < count )
        {
            SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
            return false;
        }
        if( getLevel() < pProto->RequiredLevel )
        {
            SendBuyError( BUY_ERR_LEVEL_REQUIRE, pCreature, item, 0);
            return false;
        }
        if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
        {
            SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
            return false;
        }
        if(pProto->ExtendedCost)
        {
            ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(pProto->ExtendedCost);
            uint32 mask = 0;
            if(pProto->CondExtendedCost)
                mask = GetItemCondExtCostsMask(pProto->CondExtendedCost, pProto->ExtendedCost);
            if(iece)
            {
                if(GetHonorPoints() < (iece->reqhonorpoints * count))
                {
                    SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
                    return false;
                }
                if(GetArenaPoints() < (iece->reqarenapoints * count))
                {
                    SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
                    return false;
                }
                if( (iece->reqitem1 && !HasItemCount(iece->reqitem1, (iece->reqitemcount1 * count))) ||
                    (iece->reqitem2 && !HasItemCount(iece->reqitem2, (iece->reqitemcount2 * count))) ||
                    (iece->reqitem3 && !HasItemCount(iece->reqitem3, (iece->reqitemcount3 * count))) )
                {
                    SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
                    return false;
                }
                // check for personal arena rating requirement
                if( (mask & (1<<3)) && (GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating) )
                {
                    // probably not the proper equip err
                    SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
                    return false;
                }
            }
            else
            {
                sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, pProto->ExtendedCost);
                return false;
            }
        }

        // reputation discount
        uint32 price  = pProto->BuyPrice * count;

        price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));

        if( GetMoney() < price )
        {
            SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
            return false;
        }

        uint8 bag = 0;                                      // init for case invalid bagGUID
        uint16 dest = 0;

        if (bagguid != NULL_BAG && slot != NULL_SLOT)
        {
            Bag *pBag;
            if( bagguid == GetGUID() )
            {
                bag = INVENTORY_SLOT_BAG_0;
            }
            else
            {
                for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
                {
                    pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
                    if( pBag )
                    {
                        if( bagguid == pBag->GetGUID() )
                        {
                            bag = i;
                            break;
                        }
                    }
                }
            }
            dest = ((bag << 8) | slot);
        }

        uint8 msg;
        if( IsInventoryPos( dest ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
        {
            msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count, false );
            if( msg == EQUIP_ERR_OK )
            {
                ModifyMoney( -(int32)price );
                if(pProto->ExtendedCost)                    // case for new honor system
                {
                    ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(pProto->ExtendedCost);
                    if(iece->reqhonorpoints)
                        SetHonorPoints(GetHonorPoints() - (iece->reqhonorpoints * count));
                    if(iece->reqarenapoints)
                        SetArenaPoints(GetArenaPoints() - (iece->reqarenapoints * count));
                    if(iece->reqitem1)
                        DestroyItemCount(iece->reqitem1, (iece->reqitemcount1 * count), true);
                    if(iece->reqitem2)
                        DestroyItemCount(iece->reqitem2, (iece->reqitemcount2 * count), true);
                    if(iece->reqitem3)
                        DestroyItemCount(iece->reqitem3, (iece->reqitemcount3 * count), true);
                }
                Item *it = StoreNewItem( dest, item, pProto->BuyCount * count, true );
                if( crItem->maxcount != 0 )
                    crItem->count -= pProto->BuyCount * count;

                WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
                data << pCreature->GetGUID();
                data << (uint32)crItem->id;                 // entry
                data << (uint32)crItem->count;
                data << (uint32)count;
                GetSession()->SendPacket(&data);

                SendNewItem(it, count, true, false, false);
            }
            else
                SendEquipError( msg, NULL, NULL );
        }
        else if( IsEquipmentPos( dest ) )
        {
            msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
            if( msg == EQUIP_ERR_OK )
            {
                ModifyMoney( -(int32)price );
                if(pProto->ExtendedCost)                    // case for new honor system
                {
                    ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(pProto->ExtendedCost);
                    if(iece->reqhonorpoints)
                        SetHonorPoints(GetHonorPoints() - iece->reqhonorpoints);
                    if(iece->reqarenapoints)
                        SetArenaPoints(GetArenaPoints() - iece->reqarenapoints);
                    if(iece->reqitem1)
                        DestroyItemCount(iece->reqitem1, iece->reqitemcount1, true);
                    if(iece->reqitem2)
                        DestroyItemCount(iece->reqitem2, iece->reqitemcount2, true);
                    if(iece->reqitem3)
                        DestroyItemCount(iece->reqitem3, iece->reqitemcount3, true);
                }
                Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true );
                if( crItem->maxcount != 0 )
                    crItem->count -= pProto->BuyCount * count;

                WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
                data << pCreature->GetGUID();
                data << (uint32)crItem->id;                 // entry
                data << (uint32)crItem->count;
                data << (uint32)count;
                GetSession()->SendPacket(&data);

                SendNewItem(it, count, true, false, false);
            }
            else
            {
                SendEquipError( msg, NULL, NULL );
                return false;
            }
        }
        else
        {
            SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
            return false;
        }
        return crItem->maxcount!=0?true:false;
    }
    else
        SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
    return false;
}

uint32 Player::GetMaxPersonalArenaRatingRequirement()
{
    // returns the maximal personal arena rating that can be used to purchase items requiring this condition
    // the personal rating of the arena team must match the required limit as well
    // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
    uint32 max_personal_rating = 0;
    for(int i = 0; i < 3; ++i)
    {
        if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
        {
            uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
            uint32 t_rating = at->GetRating();
            p_rating = p_rating<t_rating? p_rating : t_rating;
            if(max_personal_rating < p_rating)
                max_personal_rating = p_rating;
        }
    }
    return max_personal_rating;
}

void Player::_SaveBoundInstances()
{
    CharacterDatabase.PExecute("DELETE FROM character_instance WHERE (guid = '%u')", GetGUIDLow());
    for(BoundInstancesMap::iterator i = m_BoundInstances.begin(); i != m_BoundInstances.end(); i++)
    {
        CharacterDatabase.PExecute("INSERT INTO character_instance (guid,map,instance,leader) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), i->first, i->second.first, i->second.second);
    }
}

void Player::UpdateHomebindTime(uint32 time)
{
    // GMs never get homebind timer online
    if (m_InstanceValid || isGameMaster())
    {
        if(m_HomebindTimer)                                 // instance valid, but timer not reset
        {
            // hide reminder
            WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
            data << uint32(0);
            data << uint32(0);
            GetSession()->SendPacket(&data);
        }
        // instance is valid, reset homebind timer
        m_HomebindTimer = 0;
    }
    else if (m_HomebindTimer > 0)
    {
        if (time >= m_HomebindTimer)
        {
            // teleport to homebind location
            TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
        }
        else
            m_HomebindTimer -= time;
    }
    else
    {
        // instance is invalid, start homebind timer
        m_HomebindTimer = 60000;
        // send message to player
        WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
        data << m_HomebindTimer;
        data << uint32(1);
        GetSession()->SendPacket(&data);
        sLog.outDebug("PLAYER: Player '%s' will be teleported to homebind in 60 seconds", GetName());
    }
}

void Player::UpdatePvP(bool state, bool ovrride)
{
    if(!state || ovrride)
    {
        SetPvP(state);
        if(Pet* pet = GetPet())
            pet->SetPvP(state);
        if(Unit* charmed = GetCharm())
            charmed->SetPvP(state);

        pvpInfo.endTimer = 0;
    }
    else
    {
        if(pvpInfo.endTimer != 0)
            pvpInfo.endTimer = time(NULL);
        else
        {
            SetPvP(state);

            if(Pet* pet = GetPet())
                pet->SetPvP(state);
            if(Unit* charmed = GetCharm())
                charmed->SetPvP(state);
        }
    }
}

void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
{
    SpellCooldown sc;
    sc.end = end_time;
    sc.itemid = itemid;
    m_spellCooldowns[spellid] = sc;
}

                                                            //slot to be excluded while counting
bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
{
    if(!enchantmentcondition)
        return true;

    SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);

    if(!Condition)
        return true;

    uint8 curcount[4] = {0, 0, 0, 0};

    //counting current equipped gem colors
    for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        if(i == slot)
            continue;
        Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
        if(pItem2 && pItem2->GetProto()->Socket[0].Color)
        {
            for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
            {
                uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
                if(!enchant_id)
                    continue;

                SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
                if(!enchantEntry)
                    continue;

                uint32 gemid = enchantEntry->GemID;
                if(!gemid)
                    continue;

                ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
                if(!gemProto)
                    continue;

                GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
                if(!gemProperty)
                    continue;

                uint8 GemColor = gemProperty->color;

                for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
                {
                    if(tmpcolormask & GemColor)
                        ++curcount[b];
                }
            }
        }
    }

    bool activate = true;

    for(int i = 0; i < 5; i++)
    {
        if(!Condition->Color[i])
            continue;

        uint32 _cur_gem = curcount[Condition->Color[i] - 1];

        // if have <CompareColor> use them as count, else use <value> from Condition
        uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];

        switch(Condition->Comparator[i])
        {
            case 2:                                         // requires less <color> than (<value> || <comparecolor>) gems
                activate &= (_cur_gem < _cmp_gem) ? true : false;
                break;
            case 3:                                         // requires more <color> than (<value> || <comparecolor>) gems
                activate &= (_cur_gem > _cmp_gem) ? true : false;
                break;
            case 5:                                         // requires at least <color> than (<value> || <comparecolor>) gems
                activate &= (_cur_gem >= _cmp_gem) ? true : false;
                break;
        }
    }

    sLog.outDebug("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");

    return activate;
}

void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
{
                                                            //cycle all equipped items
    for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
    {
        //enchants for the slot being socketed are handled by Player::ApplyItemMods
        if(slot == exceptslot)
            continue;

        Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );

        if(!pItem || !pItem->GetProto()->Socket[0].Color)
            continue;

        for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
        {
            uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
            if(!enchant_id)
                continue;

            SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
            if(!enchantEntry)
                continue;

            uint32 condition = enchantEntry->EnchantmentCondition;
            if(condition)
            {
                                                            //was enchant active with/without item?
                bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
                                                            //should it now be?
                if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
                {
                    // ignore item gem conditions
                                                            //if state changed, (dis)apply enchant
                    ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
                }
            }
        }
    }
}

                                                            //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
{
    //cycle all equipped items
    for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
    {
        //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
        if(slot == exceptslot)
            continue;

        Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );

        if(!pItem || !pItem->GetProto()->Socket[0].Color)   //if item has no sockets or no item is equipped go to next item
            continue;

        //cycle all (gem)enchants
        for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
        {
            uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
            if(!enchant_id)                                 //if no enchant go to next enchant(slot)
                continue;

            SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
            if(!enchantEntry)
                continue;

            //only metagems to be (de)activated, so only enchants with condition
            uint32 condition = enchantEntry->EnchantmentCondition;
            if(condition)
                ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
        }
    }
}

void Player::LeaveBattleground()
{
    if(BattleGround *bg = GetBattleGround())
    {
        bg->RemovePlayerAtLeave(GetGUID(), true, true);

        if(bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER))
            CastSpell(this, 26013, true);                   // Deserter
    }
}

bool Player::CanJoinToBattleground() const
{
    // check Deserter debuff
    AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
    for(AuraList::const_iterator i = mDummyAuras.begin();i != mDummyAuras.end(); ++i)
        if((*i)->GetId() == 26013)
            return false;

    return true;
}

bool Player::IsVisibleInGridForPlayer( Player* pl ) const
{
    // gamemaster in GM mode see all, including ghosts
    if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
        return true;

    // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
    if (InBattleGround())
    {
        if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
            return false;
        return true;
    }

    // Live player see live player or dead player with not realized corpse
    if(pl->isAlive() || pl->m_deathTimer > 0)
    {
        return isAlive() || m_deathTimer > 0;
    }

    // Ghost see other friendly ghosts, that's for sure
    if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
        return true;

    // Dead player see live players near own corpse
    if(isAlive())
    {
        Corpse *corpse = pl->GetCorpse();
        if(corpse)
        {
            // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
            if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
                return true;
        }
    }

    // and not see any other
    return false;
}

bool Player::IsVisibleGloballyFor( Player* u ) const
{
    if(!u)
        return false;

    // Always can see self
    if (u==this)
        return true;

    // Visible units, always are visible for all players
    if (GetVisibility() == VISIBILITY_ON)
        return true;

    // GMs are visible for higher gms (or players are visible for gms)
    if (u->GetSession()->GetSecurity() > SEC_PLAYER)
        return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();

    // non faction visibility non-breakable for non-GMs
    if (GetVisibility() == VISIBILITY_OFF)
        return false;

    // non-gm stealth/invisibility not hide from global player lists
    return true;
}

void Player::UpdateVisibilityOf(WorldObject* target)
{
    if(HaveAtClient(target))
    {
        if(!target->isVisibleForInState(this,true))
        {
            target->DestroyForPlayer(this);
            m_clientGUIDs.erase(target->GetGUID());

            #ifdef MANGOS_DEBUG
            if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
                sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
            #endif
        }
    }
    else
    {
        if(target->isVisibleForInState(this,false))
        {
            target->SendUpdateToPlayer(this);
            if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
                m_clientGUIDs.insert(target->GetGUID());

            #ifdef MANGOS_DEBUG
            if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
                sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
            #endif

            // target aura duration for caster show only if target exist at caster client
            // send data at target visibility change (adding to client)
            if(target!=this && target->isType(TYPE_UNIT))
                SendAuraDurationsForTarget((Unit*)target);
        }
    }
}

template<class T>
inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
{
    s64.insert(target->GetGUID());
}

template<>
inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
{
    if(!target->IsTransport())
        s64.insert(target->GetGUID());
}

template<class T>
void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
{
    if(HaveAtClient(target))
    {
        if(!target->isVisibleForInState(this,true))
        {
            target->BuildOutOfRangeUpdateBlock(&data);
            m_clientGUIDs.erase(target->GetGUID());

            #ifdef MANGOS_DEBUG
            if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
                sLog.outDebug("Object %u (Type: %u) is out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
            #endif
        }
    }
    else
    {
        if(target->isVisibleForInState(this,false))
        {
            visibleNow.insert(target);
            target->BuildUpdate(data_updates);
            target->BuildCreateUpdateBlockForPlayer(&data, this);
            UpdateVisibilityOf_helper(m_clientGUIDs,target);

            #ifdef MANGOS_DEBUG
            if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
                sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
            #endif
        }
    }
}

template void Player::UpdateVisibilityOf(Player*        target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(Creature*      target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(Corpse*        target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(GameObject*    target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);

void Player::InitPrimaryProffesions()
{
    SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
}

void Player::SendComboPoints()
{
    Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
    if (combotarget)
    {
        WorldPacket data(SMSG_SET_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
        data.append(combotarget->GetPackGUID());
        data << uint8(m_comboPoints);
        GetSession()->SendPacket(&data);
    }
}

void Player::AddComboPoints(Unit* target, int8 count)
{
    if(!count)
        return;

    // without combo points lost (duration checked in aura)
    RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);

    if(target->GetGUID() == m_comboTarget)
    {
        m_comboPoints += count;
    }
    else
    {
        if(m_comboTarget)
            if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
                target->RemoveComboPointHolder(GetGUIDLow());

        m_comboTarget = target->GetGUID();
        m_comboPoints = count;

        target->AddComboPointHolder(GetGUIDLow());
    }

    if (m_comboPoints > 5) m_comboPoints = 5;
    if (m_comboPoints < 0) m_comboPoints = 0;

    SendComboPoints();
}

void Player::ClearComboPoints()
{
    if(!m_comboTarget)
        return;

    // without combopoints lost (duration checked in aura)
    RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);

    m_comboPoints = 0;

    SendComboPoints();

    if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
        target->RemoveComboPointHolder(GetGUIDLow());

    m_comboTarget = 0;
}

void Player::SetStandState(uint8 state)
{
    WorldPacket data(SMSG_STANDSTATE_CHANGE_ACK, 1);
    data << (uint8)state;
    GetSession()->SendPacket(&data);
}

void Player::SetGroup(Group *group, int8 subgroup)
{
    if(group == NULL) m_group.unlink();
    else
    {
        // never use SetGroup without a subgroup unless you specify NULL for group
        assert(subgroup >= 0);
        m_group.link(group, this);
        m_group.setSubGroup((uint8)subgroup);
    }
}

void Player::SendInitialPacketsBeforeAddToMap()
{
    WorldPacket data(SMSG_SET_REST_START, 4);
    data << uint32(0);                                      // unknown, may be rest state time or expirience
    GetSession()->SendPacket(&data);

    // Homebind
    data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
    data << m_homebindX << m_homebindY << m_homebindZ;
    data << (uint32) m_homebindMapId;
    data << (uint32) m_homebindZoneId;
    GetSession()->SendPacket(&data);

    // SMSG_SET_PROFICIENCY
    // SMSG_UPDATE_AURA_DURATION

    // tutorial stuff
    data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
    for (int i = 0; i < 8; ++i)
        data << uint32( GetTutorialInt(i) );
    GetSession()->SendPacket(&data);

    SendInitialSpells();
    SendInitialActionButtons();
    SendInitialReputations();
    UpdateZone(GetZoneId());
    SendInitWorldStates();

    // SMSG_SET_AURA_SINGLE

    data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
    time_t gameTime = sWorld.GetGameTime();
    struct tm *lt = localtime(&gameTime);
    uint32 xmitTime = (lt->tm_year - 100) << 24 | lt->tm_mon  << 20 |
        (lt->tm_mday - 1) << 14 | lt->tm_wday << 11 |
        lt->tm_hour << 6 | lt->tm_min;
    data << xmitTime;
    data << (float)0.01666667f;                             // game speed
    GetSession()->SendPacket( &data );

    CastSpell(this, 836, true);                             // LOGINEFFECT
}

void Player::SendInitialPacketsAfterAddToMap()
{
    // set some aura effects that send packet to player client after add player to map
    // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
    // same auras state lost at far teleport, send it one more time in this case also
    static const AuraType auratypes[] =
    {
        SPELL_AURA_MOD_FEAR,     SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
        SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER,     SPELL_AURA_SAFE_FALL,
        SPELL_AURA_FLY,          SPELL_AURA_NONE
    };
    for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
    {
        Unit::AuraList const& auraList = GetAurasByType(*itr);
        if(!auraList.empty())
            auraList.front()->ApplyModifier(true,true);
    }

    if(HasAuraType(SPELL_AURA_MOD_STUN))
        SetMovement(MOVE_ROOT);

    // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
    if(HasAuraType(SPELL_AURA_MOD_ROOT))
    {
        WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
        data.append(GetPackGUID());
        data << (uint32)2;
        SendMessageToSet(&data,true);
    }

    SendEnchantmentDurations();                             // must be after add to map
    SendItemDurations();                                    // must be after add to map
}

void Player::SendUpdateToOutOfRangeGroupMembers()
{
    if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
        return;
    if(Group* group = GetGroup())
        group->UpdatePlayerOutOfRange(this, m_groupUpdateMask);

    m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
}

void Player::SendTransferAborted(uint32 mapid, uint16 reason)
{
    WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
    data << uint32(mapid);
    data << uint16(reason);                                 // transfer abort reason
    GetSession()->SendPacket(&data);
}

void Player::SendRaidInstanceResetWarning(uint32 type, uint32 mapid, uint32 time)
{
    WorldPacket data(SMSG_INSTANCE_RESET_SCHEDULED, 4+4+4);
    data << uint32(type);
    data << uint32(mapid);
    data << uint32(time);
    GetSession()->SendPacket(&data);
}

void Player::ApplyEquipCooldown( Item * pItem )
{
    for(int i = 0; i <5; ++i)
    {
        _Spell const& spellData = pItem->GetProto()->Spells[i];

        // no spell
        if( !spellData.SpellId )
            continue;

        // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
        if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
            continue;

        AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);

        WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
        data << pItem->GetGUID();
        data << uint32(spellData.SpellId);
        GetSession()->SendPacket(&data);
    }
}

void Player::resetSpells()
{
    // not need after this call
    if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
    {
        m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
        CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
    }

    // make full copy of map (spells removed and marked as deleted at another spell remove
    // and we can't use original map for safe iterative with visit each spell at loop end
    PlayerSpellMap smap = GetSpellMap();

    for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
        removeSpell(iter->first);                           // only iter->first can be accessed, object by iter->second can be deleted already

    // learn default race/class spells
    PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
    std::list<CreateSpellPair>::const_iterator spell_itr;
    for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); spell_itr++)
    {
        uint16 tspell = spell_itr->first;
        if (tspell)
        {
            sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
            learnSpell(tspell);
        }
    }

    // learn spells received from quest completing
    for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
    {
        // skip no rewarded quests
        if(!itr->second.m_rewarded)
            continue;

        Quest const* quest = objmgr.GetQuestTemplate(itr->first);

        // skip quests without rewarded spell
        if( !quest || !quest->GetRewSpell() )
            continue;

        uint32 spell_id = quest->GetRewSpell();

        // skip quests with not teaching spell
        SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
        if(spellInfo->Effect[0] != SPELL_EFFECT_LEARN_SPELL)
            continue;

        CastSpell( this, spell_id, true);
    }
}

void Player::SendAuraDurationsForTarget(Unit* target)
{
    for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
    {
        Aura* aura = itr->second;
        if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
            continue;

        aura->SendAuraDurationForCaster(this);
    }
}

void Player::SetDailyQuestStatus( uint32 quest_id )
{
    for(uint32 quest_daily_idx = 0; quest_daily_idx < 10; ++quest_daily_idx)
    {
        if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
        {
            SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
            m_lastDailyQuestTime = time(NULL);              // last daily quest time
            m_DailyQuestChanged = true;
            break;
        }
    }
}

void Player::ResetDailyQuestStatus()
{
    for(uint32 quest_daily_idx = 0; quest_daily_idx < 10; ++quest_daily_idx)
        SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);

    // DB data deleted in caller
    m_DailyQuestChanged = false;
    m_lastDailyQuestTime = 0;
}

BattleGround* Player::GetBattleGround() const
{
    if(GetBattleGroundId()==0)
        return NULL;

    return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
}

bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
{
    // get a template bg instead of running one
    BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
    if(!bg)
        return false;

    if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
        return false;

    return true;
}

uint32 Player::GetBattleGroundQueueIdFromLevel() const
{
    uint32 level = getLevel();
    if(level <= 19)
        return 0;
    else if (level > 69)
        return 6;
    else
        return level/10 - 1;                                // 20..29 -> 1, 30-39 -> 2, ...
}

float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
{
    FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
    if(!vendor_faction)
        return 1.0f;

    ReputationRank rank = GetReputationRank(vendor_faction->faction);
    if(rank <= REP_NEUTRAL)
        return 1.0f;

    return 1.0f - 0.05f* (rank - REP_NEUTRAL);
}

bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
{
    uint32 racemask  = getRaceMask();
    uint32 classmask = getClassMask();

    SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(spell_id);
    if(!skillLine)
        return false;

    // skip wrong race skills
    if( skillLine->racemask && (skillLine->racemask & racemask) == 0)
        return false;

    // skip wrong class skills
    if( skillLine->classmask && (skillLine->classmask & classmask) == 0)
        return false;

    return true;
}

bool Player::HasQuestForGO(int32 GOId)
{
    for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
    {
        QuestStatusData qs=i->second;
        if (qs.m_status == QUEST_STATUS_INCOMPLETE)
        {
            Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
            if(!qinfo)
                continue;

            if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
                continue;

            for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
            {
                if (qinfo->ReqCreatureOrGOId[j]>=0)         //skip non GO case
                    continue;

                if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
                    return true;
            }
        }
    }
    return false;
}

void Player::UpdateForQuestsGO()
{
    if(m_clientGUIDs.size() == 0)
        return;

    UpdateData udata;
    WorldPacket packet;
    for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
    {
        if(GUID_HIPART(*itr)==HIGHGUID_GAMEOBJECT)
        {
            GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
            if(obj)
                obj->BuildValuesUpdateBlockForPlayer(&udata,this);
        }
    }
    udata.BuildPacket(&packet);
    GetSession()->SendPacket(&packet);
}

void Player::SummonIfPossible()
{
    // expire and auto declined
    if(m_summon_expire < time(NULL))
        return;

    // stop taxi flight at summon
    if(isInFlight())
    {
        GetMotionMaster()->MovementExpired();
        FlightComplete();
        ClearTaxiDestinations();
        StopMoving();
    }

    // drop flag at summon
    if(BattleGround *bg = GetBattleGround())
        bg->HandleDropFlag(this);

    m_summon_expire = 0;

    TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
}

void Player::RemoveItemDurations( Item *item )
{
    for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
    {
        if(*itr==item)
        {
            m_itemDuration.erase(itr);
            break;
        }
    }
}

void Player::AddItemDurations( Item *item )
{
    if(item->GetUInt32Value(ITEM_FIELD_DURATION))
    {
        m_itemDuration.push_back(item);
        item->SendTimeUpdate(this);
    }
}

void Player::AutoUnequipOffhandIfNeed()
{
    Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
    if(!offItem)
        return;

    Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );

    if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
        return;

    uint16 off_dest;
    uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
    if( off_msg == EQUIP_ERR_OK )
    {
        RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
        StoreItem( off_dest, offItem, true );
    }
    else
    {
        sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
    }
}

bool Player::LoadTaxiDestinationsFromString( std::string values )
{
    ClearTaxiDestinations();

    Tokens tokens = StrSplit(values," ");

    for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
    {
        uint32 node = uint32(atol(iter->c_str()));
        AddTaxiDestination(node);
    }

    if(m_TaxiDestinations.empty())
        return true;

    // Check integrity
    if(m_TaxiDestinations.size() < 2)
        return false;

    for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
    {
        uint32 cost;
        uint32 path;
        objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
        if(!path)
            return false;
    }

    return true;
}

std::string Player::SaveTaxiDestinationsToString()
{
    if(m_TaxiDestinations.empty())
        return "";

    std::ostringstream ss;

    for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
        ss << m_TaxiDestinations[i] << " ";

    return ss.str();
}

uint32 Player::GetCurrentTaxiPath() const
{
    if(m_TaxiDestinations.size() < 2)
        return 0;

    uint32 path;
    uint32 cost;

    objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);

    return path;
}

bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
{
    if(spellInfo->EquippedItemClass < 0)
        return true;

    // scan other equipped items for same requirements (mostly 2 daggers/etc)
    // for optimize check 2 used cases only
    switch(spellInfo->EquippedItemClass)
    {
        case ITEM_CLASS_WEAPON:
        {
            for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
                if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
                    if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                        return true;
            break;
        }
        case ITEM_CLASS_ARMOR:
        {
            // tabard not have dependent spells
            for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
                if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
                    if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                        return true;

            // shields can be equipped to offhand slot
            if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
                if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                    return true;

            // ranged slot can have some armor subclasses
            if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
                if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                    return true;

            break;
        }
        default:
            sLog.outError("HasItemFitToSpellReqirements: Not handeled spell reqirement for item class %u",spellInfo->EquippedItemClass);
            break;
    }

    return false;
}

void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
{
    AuraMap& auras = GetAuras();
    for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
    {
        Aura* aura = itr->second;

        // skip persistent and not item class dependent and not self applied auras
        SpellEntry const* spellInfo = aura->GetSpellProto();
        if(aura->IsPermanent() ||  aura->GetCasterGUID()!=GetGUID())
        {
            ++itr;
            continue;
        }

        // skip if have alternative item
        if(HasItemFitToSpellReqirements(spellInfo,pItem))
        {
            ++itr;
            continue;
        }

        // no alt item, remove aura, restart check
        RemoveAurasDueToSpell(aura->GetId());
        itr = auras.begin();
    }

    // currently casted spells can be dependent from item
    for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
    {
        if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
            !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
            InterruptSpell(i);
    }
}

uint32 Player::GetResurrectionSpellId()
{
    // search priceless resurrection possabilities
    uint32 prio = 0;
    uint32 spell_id = 0;
    AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
    for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
    {
        // Soulstone Resurrection                           // prio: 3 (max, non death persistent)
        if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
        {
            switch((*itr)->GetId())
            {
                case 20707: spell_id =  3026; break;        // rank 1
                case 20762: spell_id = 20758; break;        // rank 2
                case 20763: spell_id = 20759; break;        // rank 3
                case 20764: spell_id = 20760; break;        // rank 4
                case 20765: spell_id = 20761; break;        // rank 5
                case 27239: spell_id = 27240; break;        // rank 6
                default: 
                    sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
                    continue;
            }

            prio = 3;
        }
        // Twisting Nether                                  // prio: 2 (max)
        else if((*itr)->GetId()==23701 && roll_chance_i(10))
        {
            prio = 2;
            spell_id = 23700;
        }
    }

    // Reincarnation (passive spell)                        // prio: 1
    if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
        spell_id = 21169;

    return spell_id;
}