gt: 		if (player.getPledgeType() == 0)
context: /*
   * This file is part of the L2J Global project.
   * 
   * 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 3 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, see <http://www.gnu.org/licenses/>.
   */
  package com.l2jglobal.gameserver.model;
  
  import java.sql.Connection;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  import java.util.Collection;
  import java.util.LinkedList;
  import java.util.List;
  import java.util.Map;
  import java.util.concurrent.ConcurrentHashMap;
  import java.util.concurrent.ConcurrentSkipListMap;
  import java.util.concurrent.atomic.AtomicInteger;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  import java.util.stream.Collectors;
  
  import com.l2jglobal.Config;
  import com.l2jglobal.commons.database.DatabaseFactory;
  import com.l2jglobal.gameserver.ThreadPoolManager;
  import com.l2jglobal.gameserver.communitybbs.BB.Forum;
  import com.l2jglobal.gameserver.communitybbs.Manager.ForumsBBSManager;
  import com.l2jglobal.gameserver.data.sql.impl.CharNameTable;
  import com.l2jglobal.gameserver.data.sql.impl.ClanTable;
  import com.l2jglobal.gameserver.data.sql.impl.CrestTable;
  import com.l2jglobal.gameserver.data.xml.impl.SkillData;
  import com.l2jglobal.gameserver.enums.ClanRewardType;
  import com.l2jglobal.gameserver.enums.UserInfoType;
  import com.l2jglobal.gameserver.instancemanager.CastleManager;
  import com.l2jglobal.gameserver.instancemanager.FortManager;
  import com.l2jglobal.gameserver.instancemanager.SiegeManager;
  import com.l2jglobal.gameserver.model.actor.L2Npc;
  import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance;
  import com.l2jglobal.gameserver.model.events.EventDispatcher;
  import com.l2jglobal.gameserver.model.events.impl.character.player.OnPlayerClanJoin;
  import com.l2jglobal.gameserver.model.events.impl.character.player.OnPlayerClanLeaderChange;
  import com.l2jglobal.gameserver.model.events.impl.character.player.OnPlayerClanLeft;
  import com.l2jglobal.gameserver.model.events.impl.character.player.OnPlayerClanLvlUp;
  import com.l2jglobal.gameserver.model.interfaces.IIdentifiable;
  import com.l2jglobal.gameserver.model.interfaces.INamable;
  import com.l2jglobal.gameserver.model.itemcontainer.ClanWarehouse;
  import com.l2jglobal.gameserver.model.itemcontainer.ItemContainer;
  import com.l2jglobal.gameserver.model.pledge.ClanRewardBonus;
  import com.l2jglobal.gameserver.model.skills.Skill;
  import com.l2jglobal.gameserver.model.variables.ClanVariables;
  import com.l2jglobal.gameserver.model.zone.ZoneId;
  import com.l2jglobal.gameserver.network.SystemMessageId;
  import com.l2jglobal.gameserver.network.serverpackets.CreatureSay;
  import com.l2jglobal.gameserver.network.serverpackets.ExSubPledgeSkillAdd;
  import com.l2jglobal.gameserver.network.serverpackets.IClientOutgoingPacket;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeReceiveSubPledgeCreated;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeShowInfoUpdate;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeShowMemberListAll;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeShowMemberListDeleteAll;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeShowMemberListUpdate;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeSkillList;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeSkillList.SubPledgeSkill;
  import com.l2jglobal.gameserver.network.serverpackets.PledgeSkillListAdd;
  import com.l2jglobal.gameserver.network.serverpackets.SystemMessage;
  import com.l2jglobal.gameserver.network.serverpackets.UserInfo;
  import com.l2jglobal.gameserver.network.serverpackets.pledgebonus.ExPledgeBonusMarkReset;
  import com.l2jglobal.gameserver.util.EnumIntBitmask;
  import com.l2jglobal.gameserver.util.Util;
  
  public class L2Clan implements IIdentifiable, INamable
  {
  	private static final Logger _log = Logger.getLogger(L2Clan.class.getName());
  	
  	// SQL queries
  	private static final String INSERT_CLAN_DATA = "INSERT INTO clan_data (clan_id,clan_name,clan_level,hasCastle,blood_alliance_count,blood_oath_count,ally_id,ally_name,leader_id,crest_id,crest_large_id,ally_crest_id,new_leader_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
  	private static final String SELECT_CLAN_DATA = "SELECT * FROM clan_data where clan_id=?";
  	
  	// Ally Penalty Types
  	/** Clan leaved ally */
  	public static final int PENALTY_TYPE_CLAN_LEAVED = 1;
  	/** Clan was dismissed from ally */
  	public static final int PENALTY_TYPE_CLAN_DISMISSED = 2;
  	/** Leader clan dismiss clan from ally */
  	public static final int PENALTY_TYPE_DISMISS_CLAN = 3;
  	/** Leader clan dissolve ally */
  	public static final int PENALTY_TYPE_DISSOLVE_ALLY = 4;
  	// Sub-unit types
  	/** Clan subunit type of Academy */
  	public static final int SUBUNIT_ACADEMY = -1;
  	/** Clan subunit type of Royal Guard A */
  	public static final int SUBUNIT_ROYAL1 = 100;
  	/** Clan subunit type of Royal Guard B */
  	public static final int SUBUNIT_ROYAL2 = 200;
  	/** Clan subunit type of Order of Knights A-1 */
  	public static final int SUBUNIT_KNIGHT1 = 1001;
  	/** Clan subunit type of Order of Knights A-2 */
  	public static final int SUBUNIT_KNIGHT2 = 1002;
  	/** Clan subunit type of Order of Knights B-1 */
  	public static final int SUBUNIT_KNIGHT3 = 2001;
  	/** Clan subunit type of Order of Knights B-2 */
  	public static final int SUBUNIT_KNIGHT4 = 2002;
  	
  	private String _name;
  	private int _clanId;
  	private L2ClanMember _leader;
  	private final Map<Integer, L2ClanMember> _members = new ConcurrentHashMap<>();
  	
  	private String _allyName;
  	private int _allyId;
  	private int _level;
  	private int _castleId;
  	private int _fortId;
  	private int _hideoutId;
  	private int _hiredGuards;
  	private int _crestId;
  	private int _crestLargeId;
  	private int _allyCrestId;
  	private int _auctionBiddedAt = 0;
  	private long _allyPenaltyExpiryTime;
  	private int _allyPenaltyType;
  	private long _charPenaltyExpiryTime;
  	private long _dissolvingExpiryTime;
  	private int _bloodAllianceCount;
  	private int _bloodOathCount;
  	
  	private final ItemContainer _warehouse = new ClanWarehouse(this);
  	private final ConcurrentHashMap<Integer, ClanWar> _atWarWith = new ConcurrentHashMap<>();
  	
  	private Forum _forum;
  	
  	private final Map<Integer, Skill> _skills = new ConcurrentSkipListMap<>();
  	private final Map<Integer, RankPrivs> _privs = new ConcurrentSkipListMap<>();
  	private final Map<Integer, SubPledge> _subPledges = new ConcurrentSkipListMap<>();
  	private final Map<Integer, Skill> _subPledgeSkills = new ConcurrentSkipListMap<>();
  	
  	private int _reputationScore = 0;
  	private int _rank = 0;
  	
  	private String _notice;
  	private boolean _noticeEnabled = false;
  	private static final int MAX_NOTICE_LENGTH = 8192;
  	private int _newLeaderId;
  	
  	private final AtomicInteger _siegeKills = new AtomicInteger();
  	private final AtomicInteger _siegeDeaths = new AtomicInteger();
  	
  	private ClanRewardBonus _lastMembersOnlineBonus = null;
  	private ClanRewardBonus _lastHuntingBonus = null;
  	
  	private volatile ClanVariables _vars;
  	
  	/**
  	 * Called if a clan is referenced only by id. In this case all other data needs to be fetched from db
  	 * @param clanId A valid clan Id to create and restore
  	 */
  	public L2Clan(int clanId)
  	{
  		_clanId = clanId;
  		initializePrivs();
  		restore();
  		getWarehouse().restore();
  		
  		final ClanRewardBonus availableOnlineBonus = ClanRewardType.MEMBERS_ONLINE.getAvailableBonus(this);
  		if ((_lastMembersOnlineBonus == null) && (availableOnlineBonus != null))
  		{
  			_lastMembersOnlineBonus = availableOnlineBonus;
  		}
  		
  		final ClanRewardBonus availableHuntingBonus = ClanRewardType.HUNTING_MONSTERS.getAvailableBonus(this);
  		if ((_lastHuntingBonus == null) && (availableHuntingBonus != null))
  		{
  			_lastHuntingBonus = availableHuntingBonus;
  		}
  	}
  	
  	/**
  	 * Called only if a new clan is created
  	 * @param clanId A valid clan Id to create
  	 * @param clanName A valid clan name
  	 */
  	public L2Clan(int clanId, String clanName)
  	{
  		_clanId = clanId;
  		_name = clanName;
  		initializePrivs();
  	}
  	
  	/**
  	 * @return Returns the clanId.
  	 */
  	@Override
  	public int getId()
  	{
  		return _clanId;
  	}
  	
  	/**
  	 * @param clanId The clanId to set.
  	 */
  	public void setClanId(int clanId)
  	{
  		_clanId = clanId;
  	}
  	
  	/**
  	 * @return Returns the leaderId.
  	 */
  	public int getLeaderId()
  	{
  		return (_leader != null ? _leader.getObjectId() : 0);
  	}
  	
  	/**
  	 * @return L2ClanMember of clan leader.
  	 */
  	public L2ClanMember getLeader()
  	{
  		return _leader;
  	}
  	
  	/**
  	 * @param leader the leader to set.
  	 */
  	public void setLeader(L2ClanMember leader)
  	{
  		_leader = leader;
  		_members.put(leader.getObjectId(), leader);
  	}
  	
  	public void setNewLeader(L2ClanMember member)
  	{
  		final L2PcInstance newLeader = member.getPlayerInstance();
  		final L2ClanMember exMember = getLeader();
  		final L2PcInstance exLeader = exMember.getPlayerInstance();
  		
  		// Notify to scripts
  		EventDispatcher.getInstance().notifyEventAsync(new OnPlayerClanLeaderChange(exMember, member, this));
  		
  		if (exLeader != null)
  		{
  			if (exLeader.isFlying())
  			{
  				exLeader.dismount();
  			}
  			
  			if (getLevel() >= SiegeManager.getInstance().getSiegeClanMinLevel())
  			{
  				SiegeManager.getInstance().removeSiegeSkills(exLeader);
  			}
  			exLeader.getClanPrivileges().clear();
  			exLeader.broadcastUserInfo();
  			
  		}
  		else
  		{
  			try (Connection con = DatabaseFactory.getInstance().getConnection();
  				PreparedStatement ps = con.prepareStatement("UPDATE characters SET clan_privs = ? WHERE charId = ?"))
  			{
  				ps.setInt(1, 0);
  				ps.setInt(2, getLeaderId());
  				ps.execute();
  			}
  			catch (Exception e)
  			{
  				_log.log(Level.WARNING, "Couldn't update clan privs for old clan leader", e);
  			}
  		}
  		
  		setLeader(member);
  		if (getNewLeaderId() != 0)
  		{
  			setNewLeaderId(0, true);
  		}
  		updateClanInDB();
  		
  		if (exLeader != null)
  		{
  			exLeader.setPledgeClass(L2ClanMember.calculatePledgeClass(exLeader));
  			exLeader.broadcastUserInfo();
  			exLeader.checkItemRestriction();
  		}
  		
  		if (newLeader != null)
  		{
  			newLeader.setPledgeClass(L2ClanMember.calculatePledgeClass(newLeader));
  			newLeader.getClanPrivileges().setAll();
  			
  			if (getLevel() >= SiegeManager.getInstance().getSiegeClanMinLevel())
  			{
  				SiegeManager.getInstance().addSiegeSkills(newLeader);
  			}
  			newLeader.broadcastUserInfo();
  		}
  		else
  		{
  			try (Connection con = DatabaseFactory.getInstance().getConnection();
  				PreparedStatement ps = con.prepareStatement("UPDATE characters SET clan_privs = ? WHERE charId = ?"))
  			{
  				ps.setInt(1, EnumIntBitmask.getAllBitmask(ClanPrivilege.class));
  				ps.setInt(2, getLeaderId());
  				ps.execute();
  			}
  			catch (Exception e)
  			{
  				_log.log(Level.WARNING, "Couldn't update clan privs for new clan leader", e);
  			}
  		}
  		
  		broadcastClanStatus();
  		broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.CLAN_LEADER_PRIVILEGES_HAVE_BEEN_TRANSFERRED_TO_C1).addString(member.getName()));
  		
  		_log.info("Leader of Clan: " + getName() + " changed to: " + member.getName() + " ex leader: " + exMember.getName());
  	}
  	
  	/**
  	 * @return the clan leader's name.
  	 */
  	public String getLeaderName()
  	{
  		if (_leader == null)
  		{
  			_log.warning("Clan " + getName() + " without clan leader!");
  			return "";
  		}
  		return _leader.getName();
  	}
  	
  	/**
  	 * @return the clan name.
  	 */
  	@Override
  	public String getName()
  	{
  		return _name;
  	}
  	
  	/**
  	 * @param name The name to set.
  	 */
  	public void setName(String name)
  	{
  		_name = name;
  	}
  	
  	/**
  	 * Adds a clan member to the clan.
  	 * @param member the clan member.
  	 */
  	private void addClanMember(L2ClanMember member)
  	{
  		_members.put(member.getObjectId(), member);
  	}
  	
  	/**
  	 * Adds a clan member to the clan.<br>
  	 * Using a different constructor, to make it easier to read.
  	 * @param player the clan member
  	 */
  	public void addClanMember(L2PcInstance player)
  	{
  		final L2ClanMember member = new L2ClanMember(this, player);
  		// store in memory
  		addClanMember(member);
  		member.setPlayerInstance(player);
  		player.setClan(this);
  		player.setPledgeClass(L2ClanMember.calculatePledgeClass(player));
  		player.sendPacket(new PledgeShowMemberListUpdate(player));
  		player.sendPacket(new PledgeSkillList(this));
  		addSkillEffects(player);
  		
  		// Notify to scripts
  		EventDispatcher.getInstance().notifyEventAsync(new OnPlayerClanJoin(member, this));
  	}
  	
  	/**
  	 * Updates player status in clan.
  	 * @param player the player to be updated.
  	 */
  	public void updateClanMember(L2PcInstance player)
  	{
  		final L2ClanMember member = new L2ClanMember(player.getClan(), player);
  		if (player.isClanLeader())
  		{
  			setLeader(member);
  		}
  		
  		addClanMember(member);
  	}
  	
  	/**
  	 * @param name the name of the required clan member.
  	 * @return the clan member for a given name.
  	 */
  	public L2ClanMember getClanMember(String name)
  	{
  		for (L2ClanMember temp : _members.values())
  		{
  			if (temp.getName().equals(name))
  			{
  				return temp;
  			}
  		}
  		return null;
  	}
  	
  	/**
  	 * @param objectId the required clan member object Id.
  	 * @return the clan member for a given {@code objectId}.
  	 */
  	public L2ClanMember getClanMember(int objectId)
  	{
  		return _members.get(objectId);
  	}
  	
  	/**
  	 * @param objectId the object Id of the member that will be removed.
  	 * @param clanJoinExpiryTime time penalty to join a clan.
  	 */
  	public void removeClanMember(int objectId, long clanJoinExpiryTime)
  	{
  		final L2ClanMember exMember = _members.remove(objectId);
  		if (exMember == null)
  		{
  			_log.warning("Member Object ID: " + objectId + " not found in clan while trying to remove");
  			return;
  		}
  		final int leadssubpledge = getLeaderSubPledge(objectId);
  		if (leadssubpledge != 0)
  		{
  			// Sub-unit leader withdraws, position becomes vacant and leader
  			// should appoint new via NPC
  			getSubPledge(leadssubpledge).setLeaderId(0);
  			updateSubPledgeInDB(leadssubpledge);
  		}
  		
  		if (exMember.getApprentice() != 0)
  		{
  			final L2ClanMember apprentice = getClanMember(exMember.getApprentice());
  			if (apprentice != null)
  			{
  				if (apprentice.getPlayerInstance() != null)
  				{
  					apprentice.getPlayerInstance().setSponsor(0);
  				}
  				else
  				{
  					apprentice.setApprenticeAndSponsor(0, 0);
  				}
  				
  				apprentice.saveApprenticeAndSponsor(0, 0);
  			}
  		}
  		if (exMember.getSponsor() != 0)
  		{
  			final L2ClanMember sponsor = getClanMember(exMember.getSponsor());
  			if (sponsor != null)
  			{
  				if (sponsor.getPlayerInstance() != null)
  				{
  					sponsor.getPlayerInstance().setApprentice(0);
  				}
  				else
  				{
  					sponsor.setApprenticeAndSponsor(0, 0);
  				}
  				
  				sponsor.saveApprenticeAndSponsor(0, 0);
  			}
  		}
  		exMember.saveApprenticeAndSponsor(0, 0);
  		if (Config.REMOVE_CASTLE_CIRCLETS)
  		{
  			CastleManager.getInstance().removeCirclet(exMember, getCastleId());
  		}
  		if (exMember.isOnline())
  		{
  			final L2PcInstance player = exMember.getPlayerInstance();
  			if (!player.isNoble())
  			{
  				player.setTitle("");
  			}
  			player.setApprentice(0);
  			player.setSponsor(0);
  			
  			if (player.isClanLeader())
  			{
  				SiegeManager.getInstance().removeSiegeSkills(player);
  				player.setClanCreateExpiryTime(System.currentTimeMillis() + (Config.ALT_CLAN_CREATE_DAYS * 86400000L)); // 24*60*60*1000 = 86400000
  			}
  			// remove Clan skills from Player
  			removeSkillEffects(player);
  			
  			// remove Residential skills
  			if (player.getClan().getCastleId() > 0)
  			{
  				CastleManager.getInstance().getCastleByOwner(player.getClan()).removeResidentialSkills(player);
  			}
  			if (player.getClan().getFortId() > 0)
  			{
  				FortManager.getInstance().getFortByOwner(player.getClan()).removeResidentialSkills(player);
  			}
  			player.sendSkillList();
  			
  			player.setClan(null);
  			
  			// players leaving from clan academy have no penalty
  			if (exMember.getPledgeType() != -1)
  			{
  				player.setClanJoinExpiryTime(clanJoinExpiryTime);
  			}
  			
  			player.setPledgeClass(L2ClanMember.calculatePledgeClass(player));
  			player.broadcastUserInfo();
  			// disable clan tab
  			player.sendPacket(PledgeShowMemberListDeleteAll.STATIC_PACKET);
  		}
  		else
  		{
  			removeMemberInDatabase(exMember, clanJoinExpiryTime, getLeaderId() == objectId ? System.currentTimeMillis() + (Config.ALT_CLAN_CREATE_DAYS * 86400000L) : 0);
  		}
  		
  		// Notify to scripts
  		EventDispatcher.getInstance().notifyEventAsync(new OnPlayerClanLeft(exMember, this));
  	}
  	
  	public Collection<L2ClanMember> getMembers()
  	{
  		return _members.values();
  	}
  	
  	public int getMembersCount()
  	{
  		return _members.size();
  	}
  	
  	public int getSubPledgeMembersCount(int subpl)
  	{
  		int result = 0;
  		for (L2ClanMember temp : _members.values())
  		{
  			if (temp.getPledgeType() == subpl)
  			{
  				result++;
  			}
  		}
  		return result;
  	}
  	
  	/**
  	 * @param pledgeType the Id of the pledge type.
  	 * @return the maximum number of members allowed for a given {@code pledgeType}.
  	 */
  	public int getMaxNrOfMembers(int pledgeType)
  	{
  		int limit = 0;
  		
  		switch (pledgeType)
  		{
  			case 0:
  				switch (getLevel())
  				{
  					case 3:
  						limit = 30;
  						break;
  					case 2:
  						limit = 20;
  						break;
  					case 1:
  						limit = 15;
  						break;
  					case 0:
  						limit = 10;
  						break;
  					default:
  						limit = 40;
  						break;
  				}
  				break;
  			case -1:
  				limit = 20;
  				break;
  			case 100:
  			case 200:
  				switch (getLevel())
  				{
  					case 11:
  						limit = 30;
  						break;
  					default:
  						limit = 20;
  						break;
  				}
  				break;
  			case 1001:
  			case 1002:
  			case 2001:
  			case 2002:
  				switch (getLevel())
  				{
  					case 9:
  					case 10:
  					case 11:
  						limit = 25;
  						break;
  					default:
  						limit = 10;
  						break;
  				}
  				break;
  			default:
  				break;
  		}
  		
  		return limit;
  	}
  	
  	/**
  	 * @param exclude the object Id to exclude from list.
  	 * @return all online members excluding the one with object id {code exclude}.
  	 */
  	public List<L2PcInstance> getOnlineMembers(int exclude)
  	{
  		//@formatter:off
  		return _members.values().stream()
  			.filter(member -> member.getObjectId() != exclude)
  			.filter(L2ClanMember::isOnline)
  			.map(L2ClanMember::getPlayerInstance)
  			.collect(Collectors.toList());
  		//@formatter:on
  	}
  	
  	/**
  	 * @return the online clan member count.
  	 */
  	public int getOnlineMembersCount()
  	{
  		//@formatter:off
  		return (int) _members.values().stream()
  			.filter(L2ClanMember::isOnline)
  			.count();
  		//@formatter:on
  	}
  	
  	/**
  	 * @return the alliance Id.
  	 */
  	public int getAllyId()
  	{
  		return _allyId;
  	}
  	
  	/**
  	 * @return the alliance name.
  	 */
  	public String getAllyName()
  	{
  		return _allyName;
  	}
  	
  	/**
  	 * @param allyCrestId the alliance crest Id to be set.
  	 */
  	public void setAllyCrestId(int allyCrestId)
  	{
  		_allyCrestId = allyCrestId;
  	}
  	
  	/**
  	 * @return the alliance crest Id.
  	 */
  	public int getAllyCrestId()
  	{
  		return _allyCrestId;
  	}
  	
  	/**
  	 * @return the clan level.
  	 */
  	public int getLevel()
  	{
  		return _level;
  	}
  	
  	/**
  	 * Sets the clan level and updates the clan forum if it's needed.
  	 * @param level the clan level to be set.
  	 */
  	public void setLevel(int level)
  	{
  		_level = level;
  		if ((_level >= 2) && (_forum == null) && Config.ENABLE_COMMUNITY_BOARD)
  		{
  			final Forum forum = ForumsBBSManager.getInstance().getForumByName("ClanRoot");
  			if (forum != null)
  			{
  				_forum = forum.getChildByName(_name);
  				if (_forum == null)
  				{
  					_forum = ForumsBBSManager.getInstance().createNewForum(_name, ForumsBBSManager.getInstance().getForumByName("ClanRoot"), Forum.CLAN, Forum.CLANMEMBERONLY, getId());
  				}
  			}
  		}
  	}
  	
  	/**
  	 * @return the castle Id for this clan if owns a castle, zero otherwise.
  	 */
  	public int getCastleId()
  	{
  		return _castleId;
  	}
  	
  	/**
  	 * @return the fort Id for this clan if owns a fort, zero otherwise.
  	 */
  	public int getFortId()
  	{
  		return _fortId;
  	}
  	
  	/**
  	 * @return the hideout Id for this clan if owns a hideout, zero otherwise.
  	 */
  	public int getHideoutId()
  	{
  		return _hideoutId;
  	}
  	
  	/**
  	 * @param crestId the Id of the clan crest to be set.
  	 */
  	public void setCrestId(int crestId)
  	{
  		_crestId = crestId;
  	}
  	
  	/**
  	 * @return Returns the clanCrestId.
  	 */
  	public int getCrestId()
  	{
  		return _crestId;
  	}
  	
  	/**
  	 * @param crestLargeId The id of pledge LargeCrest.
  	 */
  	public void setCrestLargeId(int crestLargeId)
  	{
  		_crestLargeId = crestLargeId;
  	}
  	
  	/**
  	 * @return Returns the clan CrestLargeId
  	 */
  	public int getCrestLargeId()
  	{
  		return _crestLargeId;
  	}
  	
  	/**
  	 * @param allyId The allyId to set.
  	 */
  	public void setAllyId(int allyId)
  	{
  		_allyId = allyId;
  	}
  	
  	/**
  	 * @param allyName The allyName to set.
  	 */
  	public void setAllyName(String allyName)
  	{
  		_allyName = allyName;
  	}
  	
  	/**
  	 * @param castleId the castle Id to set.
  	 */
  	public void setCastleId(int castleId)
  	{
  		_castleId = castleId;
  	}
  	
  	/**
  	 * @param fortId the fort Id to set.
  	 */
  	public void setFortId(int fortId)
  	{
  		_fortId = fortId;
  	}
  	
  	/**
  	 * @param hideoutId the hideout Id to set.
  	 */
  	public void setHideoutId(int hideoutId)
  	{
  		_hideoutId = hideoutId;
  	}
  	
  	/**
  	 * @param id the Id of the player to be verified.
  	 * @return {code true} if the player belongs to the clan.
  	 */
  	public boolean isMember(int id)
  	{
  		return ((id != 0) && _members.containsKey(id));
  	}
  	
  	/**
  	 * @return the Blood Alliance count for this clan
  	 */
  	public int getBloodAllianceCount()
  	{
  		return _bloodAllianceCount;
  	}
  	
  	/**
  	 * Increase Blood Alliance count by config predefined count and updates the database.
  	 */
  	public void increaseBloodAllianceCount()
  	{
  		_bloodAllianceCount += SiegeManager.getInstance().getBloodAllianceReward();
  		updateBloodAllianceCountInDB();
  	}
  	
  	/**
  	 * Reset the Blood Alliance count to zero and updates the database.
  	 */
  	public void resetBloodAllianceCount()
  	{
  		_bloodAllianceCount = 0;
  		updateBloodAllianceCountInDB();
  	}
  	
  	/**
  	 * Store current Bloood Alliances count in database.
  	 */
  	public void updateBloodAllianceCountInDB()
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement("UPDATE clan_data SET blood_alliance_count=? WHERE clan_id=?"))
  		{
  			ps.setInt(1, getBloodAllianceCount());
  			ps.setInt(2, getId());
  			ps.execute();
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.WARNING, "Exception on updateBloodAllianceCountInDB(): " + e.getMessage(), e);
  		}
  	}
  	
  	/**
  	 * @return the Blood Oath count for this clan
  	 */
  	public int getBloodOathCount()
  	{
  		return _bloodOathCount;
  	}
  	
  	/**
  	 * Increase Blood Oath count by config predefined count and updates the database.
  	 */
  	public void increaseBloodOathCount()
  	{
  		_bloodOathCount += Config.FS_BLOOD_OATH_COUNT;
  		updateBloodOathCountInDB();
  	}
  	
  	/**
  	 * Reset the Blood Oath count to zero and updates the database.
  	 */
  	public void resetBloodOathCount()
  	{
  		_bloodOathCount = 0;
  		updateBloodOathCountInDB();
  	}
  	
  	/**
  	 * Store current Bloood Alliances count in database.
  	 */
  	public void updateBloodOathCountInDB()
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement("UPDATE clan_data SET blood_oath_count=? WHERE clan_id=?"))
  		{
  			ps.setInt(1, getBloodOathCount());
  			ps.setInt(2, getId());
  			ps.execute();
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.WARNING, "Exception on updateBloodAllianceCountInDB(): " + e.getMessage(), e);
  		}
  	}
  	
  	public void updateInDB()
  	{
  		// Update reputation
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement("UPDATE clan_data SET reputation_score=? WHERE clan_id=?"))
  		{
  			ps.setInt(1, getReputationScore());
  			ps.setInt(2, getId());
  			ps.execute();
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.WARNING, "Exception on updateClanScoreInDb(): " + e.getMessage(), e);
  		}
  		
  		// Update variables at database
  		if (_vars != null)
  		{
  			_vars.storeMe();
  		}
  	}
  	
  	/**
  	 * Updates in database clan information:
  	 * <ul>
  	 * <li>Clan leader Id</li>
  	 * <li>Alliance Id</li>
  	 * <li>Alliance name</li>
  	 * <li>Clan's reputation</li>
  	 * <li>Alliance's penalty expiration time</li>
  	 * <li>Alliance's penalty type</li>
  	 * <li>Character's penalty expiration time</li>
  	 * <li>Dissolving expiration time</li>
  	 * <li>Clan's id</li>
  	 * </ul>
  	 */
  	public void updateClanInDB()
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement("UPDATE clan_data SET leader_id=?,ally_id=?,ally_name=?,reputation_score=?,ally_penalty_expiry_time=?,ally_penalty_type=?,char_penalty_expiry_time=?,dissolving_expiry_time=?,new_leader_id=? WHERE clan_id=?"))
  		{
  			ps.setInt(1, getLeaderId());
  			ps.setInt(2, getAllyId());
  			ps.setString(3, getAllyName());
  			ps.setInt(4, getReputationScore());
  			ps.setLong(5, getAllyPenaltyExpiryTime());
  			ps.setInt(6, getAllyPenaltyType());
  			ps.setLong(7, getCharPenaltyExpiryTime());
  			ps.setLong(8, getDissolvingExpiryTime());
  			ps.setInt(9, getNewLeaderId());
  			ps.setInt(10, getId());
  			ps.execute();
  			if (Config.DEBUG)
  			{
  				_log.finer("New clan leader saved in db: " + getId());
  			}
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.SEVERE, "Error saving clan: " + e.getMessage(), e);
  		}
  	}
  	
  	/**
  	 * Stores in database clan information:
  	 * <ul>
  	 * <li>Clan Id</li>
  	 * <li>Clan name</li>
  	 * <li>Clan level</li>
  	 * <li>Has castle</li>
  	 * <li>Alliance Id</li>
  	 * <li>Alliance name</li>
  	 * <li>Clan leader Id</li>
  	 * <li>Clan crest Id</li>
  	 * <li>Clan large crest Id</li>
  	 * <li>Alliance crest Id</li>
  	 * </ul>
  	 */
  	public void store()
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement(INSERT_CLAN_DATA))
  		{
  			ps.setInt(1, getId());
  			ps.setString(2, getName());
  			ps.setInt(3, getLevel());
  			ps.setInt(4, getCastleId());
  			ps.setInt(5, getBloodAllianceCount());
  			ps.setInt(6, getBloodOathCount());
  			ps.setInt(7, getAllyId());
  			ps.setString(8, getAllyName());
  			ps.setInt(9, getLeaderId());
  			ps.setInt(10, getCrestId());
  			ps.setInt(11, getCrestLargeId());
  			ps.setInt(12, getAllyCrestId());
  			ps.setInt(13, getNewLeaderId());
  			ps.execute();
  			if (Config.DEBUG)
  			{
  				_log.finer("New clan saved in db: " + getId());
  			}
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.SEVERE, "Error saving new clan: " + e.getMessage(), e);
  		}
  	}
  	
  	/**
  	 * @param member the clan member to be removed.
  	 * @param clanJoinExpiryTime
  	 * @param clanCreateExpiryTime
  	 */
  	private void removeMemberInDatabase(L2ClanMember member, long clanJoinExpiryTime, long clanCreateExpiryTime)
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps1 = con.prepareStatement("UPDATE characters SET clanid=0, title=?, clan_join_expiry_time=?, clan_create_expiry_time=?, clan_privs=0, wantspeace=0, subpledge=0, lvl_joined_academy=0, apprentice=0, sponsor=0 WHERE charId=?");
  			PreparedStatement ps2 = con.prepareStatement("UPDATE characters SET apprentice=0 WHERE apprentice=?");
  			PreparedStatement ps3 = con.prepareStatement("UPDATE characters SET sponsor=0 WHERE sponsor=?"))
  		{
  			ps1.setString(1, "");
  			ps1.setLong(2, clanJoinExpiryTime);
  			ps1.setLong(3, clanCreateExpiryTime);
  			ps1.setInt(4, member.getObjectId());
  			ps1.execute();
  			if (Config.DEBUG)
  			{
  				_log.finer("clan member removed in db: " + getId());
  			}
  			// Remove apprentice.
  			ps2.setInt(1, member.getObjectId());
  			ps2.execute();
  			// Remove sponsor.
  			ps3.setInt(1, member.getObjectId());
  			ps3.execute();
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.SEVERE, "Error removing clan member: " + e.getMessage(), e);
  		}
  	}
  	
  	private void restore()
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement(SELECT_CLAN_DATA))
  		{
  			ps.setInt(1, getId());
  			try (ResultSet clanData = ps.executeQuery())
  			{
  				if (clanData.next())
  				{
  					setName(clanData.getString("clan_name"));
  					setLevel(clanData.getInt("clan_level"));
  					setCastleId(clanData.getInt("hasCastle"));
  					_bloodAllianceCount = clanData.getInt("blood_alliance_count");
  					_bloodOathCount = clanData.getInt("blood_oath_count");
  					setAllyId(clanData.getInt("ally_id"));
  					setAllyName(clanData.getString("ally_name"));
  					setAllyPenaltyExpiryTime(clanData.getLong("ally_penalty_expiry_time"), clanData.getInt("ally_penalty_type"));
  					if (getAllyPenaltyExpiryTime() < System.currentTimeMillis())
  					{
  						setAllyPenaltyExpiryTime(0, 0);
  					}
  					setCharPenaltyExpiryTime(clanData.getLong("char_penalty_expiry_time"));
  					if ((getCharPenaltyExpiryTime() + (Config.ALT_CLAN_JOIN_DAYS * 86400000L)) < System.currentTimeMillis()) // 24*60*60*1000 = 86400000
  					{
  						setCharPenaltyExpiryTime(0);
  					}
  					setDissolvingExpiryTime(clanData.getLong("dissolving_expiry_time"));
  					
  					setCrestId(clanData.getInt("crest_id"));
  					setCrestLargeId(clanData.getInt("crest_large_id"));
  					setAllyCrestId(clanData.getInt("ally_crest_id"));
  					
  					setReputationScore(clanData.getInt("reputation_score"), false);
  					setAuctionBiddedAt(clanData.getInt("auction_bid_at"), false);
  					setNewLeaderId(clanData.getInt("new_leader_id"), false);
  					
  					final int leaderId = (clanData.getInt("leader_id"));
  					
  					ps.clearParameters();
  					
  					try (PreparedStatement select = con.prepareStatement("SELECT char_name,level,classid,charId,title,power_grade,subpledge,apprentice,sponsor,sex,race FROM characters WHERE clanid=?"))
  					{
  						select.setInt(1, getId());
  						try (ResultSet clanMember = select.executeQuery())
  						{
  							L2ClanMember member = null;
  							while (clanMember.next())
  							{
  								member = new L2ClanMember(this, clanMember);
  								if (member.getObjectId() == leaderId)
  								{
  									setLeader(member);
  								}
  								else
  								{
  									addClanMember(member);
  								}
  							}
  						}
  					}
  				}
  			}
  			
  			if (Config.DEBUG && (getName() != null))
  			{
  				_log.info("Restored clan data for \"" + getName() + "\" from database.");
  			}
  			
  			restoreSubPledges();
  			restoreRankPrivs();
  			restoreSkills();
  			restoreNotice();
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.SEVERE, "Error restoring clan data: " + e.getMessage(), e);
  		}
  	}
  	
  	private void restoreNotice()
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement("SELECT enabled,notice FROM clan_notices WHERE clan_id=?"))
  		{
  			ps.setInt(1, getId());
  			try (ResultSet noticeData = ps.executeQuery())
  			{
  				while (noticeData.next())
  				{
  					_noticeEnabled = noticeData.getBoolean("enabled");
  					_notice = noticeData.getString("notice");
  				}
  			}
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.SEVERE, "Error restoring clan notice: " + e.getMessage(), e);
  		}
  	}
  	
  	private void storeNotice(String notice, boolean enabled)
  	{
  		if (notice == null)
  		{
  			notice = "";
  		}
  		
  		if (notice.length() > MAX_NOTICE_LENGTH)
  		{
  			notice = notice.substring(0, MAX_NOTICE_LENGTH - 1);
  		}
  		
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement("INSERT INTO clan_notices (clan_id,notice,enabled) values (?,?,?) ON DUPLICATE KEY UPDATE notice=?,enabled=?"))
  		{
  			ps.setInt(1, getId());
  			ps.setString(2, notice);
  			if (enabled)
  			{
  				ps.setString(3, "true");
  			}
  			else
  			{
  				ps.setString(3, "false");
  			}
  			ps.setString(4, notice);
  			if (enabled)
  			{
  				ps.setString(5, "true");
  			}
  			else
  			{
  				ps.setString(5, "false");
  			}
  			ps.execute();
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.WARNING, "Error could not store clan notice: " + e.getMessage(), e);
  		}
  		
  		_notice = notice;
  		_noticeEnabled = enabled;
  	}
  	
  	public void setNoticeEnabled(boolean enabled)
  	{
  		storeNotice(_notice, enabled);
  	}
  	
  	public void setNotice(String notice)
  	{
  		storeNotice(notice, _noticeEnabled);
  	}
  	
  	public boolean isNoticeEnabled()
  	{
  		return _noticeEnabled;
  	}
  	
  	public String getNotice()
  	{
  		if (_notice == null)
  		{
  			return "";
  		}
  		return _notice;
  	}
  	
  	private void restoreSkills()
  	{
  		try (Connection con = DatabaseFactory.getInstance().getConnection();
  			PreparedStatement ps = con.prepareStatement("SELECT skill_id,skill_level,sub_pledge_id FROM clan_skills WHERE clan_id=?"))
  		{
  			// Retrieve all skills of this L2PcInstance from the database
  			ps.setInt(1, getId());
  			try (ResultSet rset = ps.executeQuery())
  			{
  				// Go though the recordset of this SQL query
  				while (rset.next())
  				{
  					final int id = rset.getInt("skill_id");
  					final int level = rset.getInt("skill_level");
  					// Create a L2Skill object for each record
  					final Skill skill = SkillData.getInstance().getSkill(id, level);
  					// Add the L2Skill object to the L2Clan _skills
  					final int subType = rset.getInt("sub_pledge_id");
  					
  					if (subType == -2)
  					{
  						_skills.put(skill.getId(), skill);
  					}
  					else if (subType == 0)
  					{
  						_subPledgeSkills.put(skill.getId(), skill);
  					}
  					else
  					{
  						final SubPledge subunit = _subPledges.get(subType);
  						if (subunit != null)
  						{
  							subunit.addNewSkill(skill);
  						}
  						else
  						{
  							_log.info("Missing subpledge " + subType + " for clan " + this + ", skill skipped.");
  						}
  					}
  				}
  			}
  		}
  		catch (Exception e)
  		{
  			_log.log(Level.SEVERE, "Error restoring clan skills: " + e.getMessage(), e);
  		}
  	}
  	
  	/**
  	 * @return all the clan skills.
  	 */
  	public final Skill[] getAllSkills()
  	{
  		if (_skills == null)
  		{
  			return new Skill[0];
  		}
  		
  		return _skills.values().toArray(new Skill[_skills.values().size()]);
  	}
  	
  	/**
  	 * @return the map containing this clan skills.
  	 */
  	public Map<Integer, Skill> getSkills()
  	{
  		return _skills;
  	}
  	
  	/**
  	 * Used to add a skill to skill list of this L2Clan
  	 * @param newSkill
  	 * @return
  	 */
  	public Skill addSkill(Skill newSkill)
  	{
  		Skill oldSkill = null;
  		
  		if (newSkill != null)
  		{
  			// Replace oldSkill by newSkill or Add the newSkill
  			oldSkill = _skills.put(newSkill.getId(), newSkill);
  		}
  		
  		return oldSkill;
  	}
  	
  	public Skill addNewSkill(Skill newSkill)
  	{
  		return addNewSkill(newSkill, -2);
  	}
  	
  	/**
  	 * Used to add a new skill to the list, send a packet to all online clan members, update their stats and store it in db
  	 * @param newSkill
  	 * @param subType
  	 * @return
  	 */
  	public Skill addNewSkill(Skill newSkill, int subType)
  	{
  		Skill oldSkill = null;
  		if (newSkill != null)
  		{
  			
  			if (subType == -2)
  			{
  				oldSkill = _skills.put(newSkill.getId(), newSkill);
  			}
  			else if (subType == 0)
  			{
  				oldSkill = _subPledgeSkills.put(newSkill.getId(), newSkill);
  			}
  			else
  			{
  				final SubPledge subunit = getSubPledge(subType);
  				if (subunit != null)
  				{
  					oldSkill = subunit.addNewSkill(newSkill);
  				}
  				else
  				{
  					_log.warning("Subpledge " + subType + " does not exist for clan " + this);
  					return oldSkill;
  				}
  			}
  			
  			try (Connection con = DatabaseFactory.getInstance().getConnection())
  			{
  				if (oldSkill != null)
  				{
  					try (PreparedStatement ps = con.prepareStatement("UPDATE clan_skills SET skill_level=? WHERE skill_id=? AND clan_id=?"))
  					{
  						ps.setInt(1, newSkill.getLevel());
  						ps.setInt(2, oldSkill.getId());
  						ps.setInt(3, getId());
  						ps.execute();
  					}
  				}
  				else
  				{
  					try (PreparedStatement ps = con.prepareStatement("INSERT INTO clan_skills (clan_id,skill_id,skill_level,skill_name,sub_pledge_id) VALUES (?,?,?,?,?)"))
  					{
  						ps.setInt(1, getId());
  						ps.setInt(2, newSkill.getId());
  						ps.setInt(3, newSkill.getLevel());
  						ps.setString(4, newSkill.getName());
  						ps.setInt(5, subType);
  						ps.execute();
  					}
  				}
  			}
  			catch (Exception e)
  			{
  				_log.log(Level.WARNING, "Error could not store clan skills: " + e.getMessage(), e);
  			}
  			
  			final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.THE_CLAN_SKILL_S1_HAS_BEEN_ADDED);
  			sm.addSkillName(newSkill.getId());
  			
  			for (L2ClanMember temp : _members.values())
  			{
  				if ((temp != null) && (temp.getPlayerInstance() != null) && temp.isOnline())
  				{
  					if (subType == -2)
  					{
  						if (newSkill.getMinPledgeClass() <= temp.getPlayerInstance().getPledgeClass())
  						{
  							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
  							temp.getPlayerInstance().sendPacket(new PledgeSkillListAdd(newSkill.getId(), newSkill.getLevel()));
  							temp.getPlayerInstance().sendPacket(sm);
  							temp.getPlayerInstance().sendSkillList();
  						}
  					}
  					else
  					{
  						if (temp.getPledgeType() == subType)
  						{
  							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
  							temp.getPlayerInstance().sendPacket(new ExSubPledgeSkillAdd(subType, newSkill.getId(), newSkill.getLevel()));
  							temp.getPlayerInstance().sendPacket(sm);
  							temp.getPlayerInstance().sendSkillList();
  						}
  					}
  				}
  			}
  		}
  		
  		return oldSkill;
  	}
  	
  	public void addSkillEffects()
  	{
  		for (Skill skill : _skills.values())
  		{
  			for (L2ClanMember temp : _members.values())
  			{
  				try
  				{
  					if ((temp != null) && temp.isOnline())
  					{
  						if (skill.getMinPledgeClass() <= temp.getPlayerInstance().getPledgeClass())
  						{
  							temp.getPlayerInstance().addSkill(skill, false); // Skill is not saved to player DB
  						}
  					}
  				}
  				catch (NullPointerException e)
  				{
  					_log.log(Level.WARNING, e.getMessage(), e);
  				}
  			}
  		}
  	}
  	
  	public void addSkillEffects(L2PcInstance player)
  	{
  		if (player == null)
  		{
  			return;
  		}
  		
  		for (Skill skill : _skills.values())
  		{
  			if (skill.getMinPledgeClass() <= player.getPledgeClass())
  			{
  				player.addSkill(skill, false); // Skill is not saved to player DB
  			}
  		}
  		
  		if (player.getPledgeType() == 0)
  		{
  			for (Skill skill : _subPledgeSkills.values())
  			{
  				player.addSkill(skill, false); // Skill is not saved to player DB
  			}
  		}
  		else
  		{
  			final SubPledge subunit = getSubPledge(player.getPledgeType());
  			if (subunit == null)
  			{
  				return;
  			}
  			for (Skill skill : subunit.getSkills())
  			{
  				player.addSkill(skill, false); // Skill is not saved to player DB
  			}
  		}
  		
  		if (_reputationScore < 0)
  		{
  			skillsStatus(player, true);
  		}
  	}
  	
  	public void removeSkillEffects(L2PcInstance player)
  	{
  		if (player == null)
  		{
  			return;
  		}
  		
  		for (Skill skill : _skills.values())
  		{
  			player.removeSkill(skill, false); // Skill is not saved to player DB
  		}
  		
  		if (player.getPledgeType() == 0)
  		{
  			for (Skill skill : _subPledgeSkills.values())
  			{
  				player.removeSkill(skill, false); // Skill is not saved to player DB
  			}
  		}
  		else
  		{
  			final SubPledge subunit = getSubPledge(player.getPledgeType());
  			if (subunit == null)
  			{
  				return;
  			}
  			for (Skill skill : subunit.getSkills())
  			{
  				player.removeSkill(skill, false); // Skill is not saved to player DB
  			}
  		}
  	}
  	
  	public void skillsStatus(L2PcInstance player, boolean disable)
  	{
  		if (player == null)
  		{
  			return;
  		}
  		
  		for (Skill skill : _skills.values())
  		{
  			if (disable)
  			{
  				player.disableSkill(skill, -1);
  			}
  			else
  			{
  				player.enableSkill(skill);
  			}
  		}
  		
  