/// BOAL Верфь
#define sailCostPercent		10
#define hullCostPercent		20

//===============================
#define HULL			0
#define SAILS			1
#define CANNONS			2
int iUpgradeMode = HULL;
int iCannonMaterial;
int shipsCount= 0;
int nCurSScrollNum = 0;
int iHullRepairCost = 0;
int iSailsRepairCost = 0;
int iCannonsRepairCost = 0;
int iFullPrice = 0;
int iCost;
int irestoreCode = -1;//<<==Philippe
float newRepairHullValuePercent = 0.0;
float newRepairSailValuePercent = 0.0;

float newRepairSailValue = 0;
float newRepairHullValue = 0;
int newRepairCannonValue = 0;
int isFirstTimeSlider = 0;
int iShipStoreListIndex=0;

int	iGameArcade = 4;

bool g_bToolTipStarted = false;
//==================================

int nCurScrollNum;
ref xi_refCharacter;
ref refNPCShipyard;
int shipIndex;

int nCurScrollOfficerNum;

string CurTable, CurRow;
int iSelected; // курсор в таблице

string sMessageMode, sFrom_sea, sShipId;

float shipCostRate;
bool  bShipyardOnTop, bEmptySlot;

int RepairHull, RepairSail;
int timeHull, timeRig;

void InitInterface_R(string iniName, ref _shipyarder)
{
	GameInterface.title = "titleShipyard";

	xi_refCharacter = pchar;

    iCannonMaterial = Xi_refCharacter.ship.upgrades.cannons;

    refNPCShipyard  = _shipyarder;
    SetShipyardStore(refNPCShipyard);

    shipCostRate = stf(refNPCShipyard.ShipCostRate);

    int iTest = FindColony(refNPCShipyard.City); // город магазина
    ref rColony;
    sFrom_sea = "";
	if (iTest != -1)
	{
		rColony = GetColonyByIndex(iTest);
		sFrom_sea = rColony.from_sea; // ветка верфи, в сухопутных верфи нет, значит везде правильная
	}

	FillShipsScroll();
     //  Philippe
         FillSailsColorScroll();
        FillEmblemesScroll();
        UpdateCharacterInfo();
	FillUpgradeScroll("Hull");

	SendMessage(&GameInterface,"ls",MSG_INTERFACE_INIT,iniName);

	SetEventHandler("InterfaceBreak","ProcessExitCancel",0);
	SetEventHandler("exitCancel","ProcessExitCancel",0);
    SetEventHandler("ievnt_command","ProcessCommandExecute",0);
    SetEventHandler("frame","ProcessFrame",1);
    SetEventHandler("confirmShipChangeName","confirmShipChangeName",0);
	SetEventHandler("CheckForRename","CheckForRename",0);
	SetEventHandler("ShowInfoWindow","ShowInfoWindow",0);
	SetEventHandler("MouseRClickUp","HideInfoWindow",0);
	SetEventHandler("TableSelectChange", "TableSelectChange", 0);
	SetEventHandler("ExitMsgMenu", "ExitMsgMenu", 0);
	SetEventHandler("ExitRepairMenu", "ExitRepairMenu", 0);
	SetEventHandler("ShowOtherClick", "ShowOtherClick", 0);
	SetEventHandler("ExitCannonsMenu", "ExitCannonsMenu", 0);
    SetEventHandler("ExitOfficerMenu","ExitOfficerMenu",0);
	SetEventHandler("acceptaddofficer","AcceptAddOfficer",0);
	SetEventHandler("BuyShipEvent","BuyShipEvent",0);
//===================
        SetEventHandler("ConfirmUpgradeShip","ConfirmUpgradeShip",0);
	SetEventHandler("CancelUpgradeShip","CancelUpgradeShip",0);
	SetEventHandler("PrepareUpgrade","PrepareUpgrade",0);
	SetEventHandler("ClickHullUpgrade","ClickHullUpgrade",0);
	SetEventHandler("ClickSailsUpgrade","ClickSailsUpgrade",0);
	SetEventHandler("ClickCannonsUpgrade","ClickCannonsUpgrade",0);
     /*   SetEventHandler("AddHull", "AddHull",0);
	SetEventHandler("RemoveHull", "RemoveHull",0);
	SetEventHandler("AddSails", "AddSails",0);
	SetEventHandler("RemoveSails", "RemoveSails",0);
	SetEventHandler("AddCannons", "AddCannons",0);
	SetEventHandler("RemoveCannons", "RemoveCannons",0);*/

///////////////// PHILIPPE==========>>>>>>>>>>>>>>>>>>>>>>>>>>>
        SetEventHandler("GetInterfaceTexture", "ScrollGetTexture", 0);
        SetEventHandler("wndChangeSails", "wndChangeSails", 0);
	SetEventHandler("ChangeSails", "ChangeSails", 0);
      //  SetEventHandler("ExitSailscolorsMenu", "ExitSailscolorsMenu", 0);
	SetEventHandler("ChangeSelectScrollImage", "ChangeSelectScrollImage", 0);
     //   SetEventHandler("ShowUpgradeInfo", "ShowUpgradeInfo", 0);
/////////////=========================<<<<<<<<<<<<<<<<<<<<<<<<<<

        SetSelectable("UPGRADE_WINDOW_OK_BUTTON", false);
	SetNodeUsing("CANNONS_CALIBER", false);
//===================
    //////////////////
    EI_CreateFrame("SHIP_BIG_PICTURE_BORDER",156,40,366,275); // tak from SHIP_BIG_PICTURE
    EI_CreateHLine("SHIP_BIG_PICTURE_BORDER", 161,246,361,1, 4);
    EI_CreateFrame("SHIP_BIG_PICTURE_BORDER",20,46,134,161);
    EI_CreateHLine("SHIP_BIG_PICTURE_BORDER", 8,187,147,1, 4);
    EI_CreateHLine("SHIP_BIG_PICTURE_BORDER", 8,166,147,1, 4);

    SetNewGroupPicture("Money_PIC", "ICONS_CHAR", "Money");
    SetNewGroupPicture("REPAIR_Money_PIC", "ICONS_CHAR", "Money");
    
    SetNewGroupPicture("REPAIR_Hull_PIC", "SHIP_STATE_ICONS", "Hull");
    SetNewGroupPicture("REPAIR_Sails_PIC", "SHIP_STATE_ICONS", "Sails");

    FillShipyardTable();

	SetCurrentNode("SHIPS_SCROLL");
	bShipyardOnTop = false;
	OnShipScrollChange();
	bEmptySlot = false;
	sMessageMode = "";
	SetButtionsAccess();
	timeHull = 0;
	timeRig = 0;
}

void ProcessExitCancel()
{
    // boal время на ремонт -->
    if (timeRig > 0 || timeHull > 0)
    {
        LAi_Fade("", "");
        bQuestCheckProcessFreeze = true;
    	WaitDate("",0,0,0, 0, makeint( (timeHull/4.0 + timeRig/6.0) * 60.0));
    	RecalculateJumpTable();
    	bQuestCheckProcessFreeze = false;
    	RefreshLandTime();
	}
	IDoExit(RC_INTERFACE_ANY_EXIT);
}

void IDoExit(int exitCode)
{
	DelEventHandler("InterfaceBreak","ProcessExitCancel");
	DelEventHandler("exitCancel","ProcessExitCancel");
    DelEventHandler("ievnt_command","ProcessCommandExecute");
    DelEventHandler("frame","ProcessFrame");
    DelEventHandler("confirmShipChangeName","confirmShipChangeName");
	DelEventHandler("CheckForRename","CheckForRename");
	DelEventHandler("ShowInfoWindow","ShowInfoWindow");
	DelEventHandler("MouseRClickUp","HideInfoWindow");
	DelEventHandler("TableSelectChange", "TableSelectChange");
	DelEventHandler("ExitMsgMenu", "ExitMsgMenu");
	DelEventHandler("ShowOtherClick", "ShowOtherClick");
	DelEventHandler("ExitCannonsMenu", "ExitCannonsMenu");
    DelEventHandler("ExitOfficerMenu","ExitOfficerMenu");
	DelEventHandler("acceptaddofficer","AcceptAddOfficer");
	DelEventHandler("ExitRepairMenu", "ExitRepairMenu");
	DelEventHandler("BuyShipEvent","BuyShipEvent");

//========================================
        DelEventHandler("ConfirmUpgradeShip","ConfirmUpgradeShip");
	DelEventHandler("CancelUpgradeShip","CancelUpgradeShip");
	DelEventHandler("PrepareUpgrade","PrepareUpgrade");
	DelEventHandler("ClickHullUpgrade","ClickHullUpgrade");
	DelEventHandler("ClickSailsUpgrade","ClickSailsUpgrade");
	DelEventHandler("ClickCannonsUpgrade","ClickCannonsUpgrade");
   /*     DelEventHandler("AddHull", "AddHull");
	DelEventHandler("RemoveHull", "RemoveHull");
	DelEventHandler("AddSails", "AddSails");
	DelEventHandler("RemoveSails", "RemoveSails");
	DelEventHandler("AddCannons", "AddCannons");
	DelEventHandler("RemoveCannons", "RemoveCannons");*/
//========================================

/////////////////////// PHILIPPE======================>>>>>>>>>>>>>>>>
        DelEventHandler("GetInterfaceTexture", "ScrollGetTexture");
        DelEventHandler("wndChangeSails", "wndChangeSails");
	DelEventHandler("ChangeSails", "ChangeSails");
     //   DelEventHandler("ExitSailscolorsMenu", "ExitSailscolorsMenu");
    	DelEventHandler("ChangeSelectScrollImage", "ChangeSelectScrollImage");
     //   DelEventHandler("ShowUpgradeInfo", "ShowUpgradeInfo");
/////////////////////=================================<<<<<<<<<<<<<<<<<<<



	interfaceResultCommand = exitCode;
	if( CheckAttribute(&InterfaceStates,"ReloadMenuExit"))
	{
        DeleteAttribute(&InterfaceStates,"ReloadMenuExit");
		EndCancelInterface(false);
	}
	else
	{
		EndCancelInterface(true);
	}
}
void ProcessCommandExecute()
{
	string comName = GetEventData();
	string nodName = GetEventData();

    switch(nodName)
	{
        case "BUTTON_SELL":
			if (comName=="click" || comName=="activate")
			{
			    ShowMessageInfo();
			}
		break;

		case "BUTTON_BUY":
			if (comName=="click" || comName=="activate")
			{
			    ShowMessageInfo();
			}
		break;

		case "MSG_OK":
			if (comName=="click" || comName=="activate")
			{
			    MessageOk();
			}
		break;
		
		case "BUTTON_REPAIR":
			if (comName=="click" || comName=="activate")
			{
			    ShowRepairMenu();
			}
		break;
		
		case "REPAIR_LEFT_H":
			if (comName=="click" || comName=="activate")
			{
			    ClickRepairArror("hull", -1);
			}
			if (comName=="rclick")
			{
			    ClickRepairArror("hull", -5);
			}
		break;
		
		case "REPAIR_RIGHT_H":
			if (comName=="click" || comName=="activate")
			{
			    ClickRepairArror("hull", 1);
			}
			if (comName=="rclick")
			{
			    ClickRepairArror("hull", 5);
			}
		break;
		
		case "REPAIR_LEFT_S":
			if (comName=="click" || comName=="activate")
			{
			    ClickRepairArror("sail", -1);
			}
			if (comName=="rclick")
			{
			    ClickRepairArror("sail", -5);
			}
		break;
		
		case "REPAIR_RIGHT_S":
			if (comName=="click" || comName=="activate")
			{
			    ClickRepairArror("sail", 1);
			}
			if (comName=="rclick")
			{
			    ClickRepairArror("sail", 5);
			}
		break;
		
		case "REPAIR_OK":
			if (comName=="click" || comName=="activate")
			{
			    RepairOk();
			}
		break;
		
		case "REPAIR_ALL":
			if (comName=="click" || comName=="activate")
			{
			    RepairAll();
			}
		break;

                case "BUTTON_UPGRADE":
			if (comName=="click" || comName=="activate")
			{
			    PrepareUpgrade();
			}
		break;
	}
}
///////////////////////////////////////////////////////////////////////////////////////////
void FillShipsScroll()
{
    DeleteAttribute(&GameInterface, "SHIPS_SCROLL");
	nCurScrollNum = -1;
	if(!CheckAttribute(&GameInterface,"SHIPS_SCROLL.current"))
	{
		GameInterface.SHIPS_SCROLL.current = 0;
	}

	string attributeName;
	string shipName;
	int iShipType, cn;
	GameInterface.SHIPS_SCROLL.ImagesGroup.t0 = "BLANK_SHIP2";

	FillShipList("SHIPS_SCROLL.ImagesGroup", xi_refCharacter);
	GameInterface.SHIPS_SCROLL.BadTex1 = 0;
	GameInterface.SHIPS_SCROLL.BadPic1 = "Not Used2";

	int m = 0;
	for(int i = 0; i < COMPANION_MAX; i++)
	{
		cn = GetCompanionIndex(pchar, i);
		if(cn != -1)
		{
			iShipType = sti(characters[cn].ship.type);
			if(iShipType != SHIP_NOTUSED)
			{
				attributeName = "pic" + (m+1);
				iShipType = sti(RealShips[iShipType].basetype);
				shipName = ShipsTypes[iShipType].Name;

				GameInterface.SHIPS_SCROLL.(attributeName).character = cn;
				GameInterface.SHIPS_SCROLL.(attributeName).str1 = "#"+ xiStr("Class_") +ShipsTypes[iShipType].Class;
				GameInterface.SHIPS_SCROLL.(attributeName).str4 = shipName;
				GameInterface.SHIPS_SCROLL.(attributeName).str3 = "#" + MakeMoneyShow(GetSellPrice(&characters[cn]), MONEY_SIGN,MONEY_DELIVER);
				GameInterface.SHIPS_SCROLL.(attributeName).img1 = "ship";
				GameInterface.SHIPS_SCROLL.(attributeName).tex1 = FindFaceGroupNum("SHIPS_SCROLL.ImagesGroup","SHIPS_"+shipName);
				m++;
			}
			else
			{
				attributeName = "pic" + (m+1);
				GameInterface.SHIPS_SCROLL.(attributeName).character = cn;
				GameInterface.SHIPS_SCROLL.(attributeName).str1 = "#";
				GameInterface.SHIPS_SCROLL.(attributeName).str2 = "NoneBoat";
				GameInterface.SHIPS_SCROLL.(attributeName).img1 = "Not Used2";
				GameInterface.SHIPS_SCROLL.(attributeName).tex1 = "BLANK_SHIP2";
				m++;
			}
		}
		else
		{
		    attributeName = "pic" + (m+1);
			GameInterface.SHIPS_SCROLL.(attributeName).character = -1;
			GameInterface.SHIPS_SCROLL.(attributeName).str1 = "#";
			GameInterface.SHIPS_SCROLL.(attributeName).str2 = "";
			GameInterface.SHIPS_SCROLL.(attributeName).img1 = "Not Used2";
			GameInterface.SHIPS_SCROLL.(attributeName).tex1 = "BLANK_SHIP2";
			m++;
		}
	}

	GameInterface.SHIPS_SCROLL.ListSize = m;
	//GameInterface.SHIPS_SCROLL.NotUsed = 5 - m + 1;
	GameInterface.SHIPS_SCROLL.NotUsed = 0;
}

void ProcessFrame()
{
	string attributeName;
	int iCharacter;

	string sNode = GetCurrentNode();

      if(nCurScrollNum!= sti(GameInterface.UPGRADE_SCROLL.current) && GetCurrentNode() == "UPGRADE_SCROLL")
	{
		nCurScrollNum = sti(GameInterface.UPGRADE_SCROLL.current);
		string sMode;
		switch(iUpgradeMode)
		{
			case HULL:
				sMode = "hull";
			break;
			case SAILS:
				sMode = "sails";
			break;
			case CANNONS:
				sMode = "cannons";
			break;
		}
		FillUpgradeInfo(sMode);
		if(CheckForUpgrade())
		{
			SetSelectable("UPGRADE_WINDOW_OK_BUTTON",true);
		}
	/*	else
		{
			SetSelectable("UPGRADE_WINDOW_OK_BUTTON",false);
		}*/
	}

    if (sNode == "PASSENGERSLIST" && sti(GameInterface.PASSENGERSLIST.current)!= nCurScrollOfficerNum)
	{
		nCurScrollOfficerNum = sti(GameInterface.PASSENGERSLIST.current);
		SetOfficersSkills();
	}
	if(sNode == "SHIPS_SCROLL")
	{
		if (sti(GameInterface.SHIPS_SCROLL.current)!= nCurScrollNum || CurTable != "")
		{
            CurTable = "";
			NullSelectTable("TABLE_SHIPYARD"); // убрать скрол
			bShipyardOnTop = false;

			nCurScrollNum = sti(GameInterface.SHIPS_SCROLL.current);

			attributeName = "pic" + (nCurScrollNum+1);

			iCharacter = sti(GameInterface.SHIPS_SCROLL.(attributeName).character);

			if(iCharacter > 0)
			{
				string sChrId = characters[iCharacter].id;

				xi_refCharacter = characterFromID(sChrId);
				bEmptySlot = false;
				shipIndex= nCurScrollNum+ 1;
				if (shipIndex< 0)
				{
					shipIndex= 0;
				}
				if (sti(xi_refCharacter.ship.type) == SHIP_NOTUSED)
				{
					shipIndex= -1;
				}
				// boal оптимизация скилов -->
			    DelBakSkillAttr(xi_refCharacter);
			    ClearCharacterExpRate(xi_refCharacter);
			    RefreshCharacterSkillExpRate(xi_refCharacter);

			    SetEnergyToCharacter(xi_refCharacter);
			    // boal оптимизация скилов <--
				OnShipScrollChange();
			}
			else
			{
				shipIndex= -1;
				bEmptySlot = true;
			}
			SetButtionsAccess();
		}
	}
}

void FillShipParam(ref _chr)
{
    int iShip = sti(_chr.ship.type);
	if (iShip != SHIP_NOTUSED)
	{
        if (CheckAttribute(_chr, "Ship.Cargo.RecalculateCargoLoad") && sti(_chr.Ship.Cargo.RecalculateCargoLoad))
		{
			RecalculateCargoLoad(_chr);
			_chr.Ship.Cargo.RecalculateCargoLoad = 0;
		}
		ref refBaseShip = GetRealShip(iShip);
		string sShip = refBaseShip.BaseName;
		SetNewPicture("SHIP_BIG_PICTURE", "interfaces\ships\" + sShip + ".tga");

		GameInterface.edit_box.str = _chr.ship.name;
		SetFormatedText("SHIP_RANK", refBaseShip.Class);
		SetShipOTHERTable("TABLE_OTHER", _chr);
		SetFormatedText("FRAME_INFO_CAPTION", XI_ConvertString(sShip));
		SetFormatedText("INFO_TEXT", GetConvertStr(sShip, "ShipsDescribe.txt"));
	}
	else
	{
		SetNewPicture("SHIP_BIG_PICTURE", "interfaces\blank_ship2.tga");
		GameInterface.edit_box.str = XI_Convertstring("NoneBoat");
		SetFormatedText("FRAME_INFO_CAPTION","");
		SetFormatedText("INFO_TEXT","");
	}
	Table_UpdateWindow("TABLE_OTHER");
}

void OnShipScrollChange()
{
	SetNewPicture("MAIN_CHARACTER_PICTURE", "interfaces\portraits\128\face_" + xi_refCharacter.FaceId + ".tga");
	SetFormatedText("HERO_NAME", GetFullName(xi_refCharacter));
	SetFormatedText("HERO_RANK",xi_refCharacter.Rank);
	// нулим все формы, тк корабля может не быть
	SetFormatedText("SHIP_RANK","");
	Table_Clear("TABLE_OTHER", false, true, false);
	//Ship info window
	SetFormatedText("Money_TEXT", MakeMoneyShow(sti(pchar.Money), MONEY_SIGN,MONEY_DELIVER));
    FillShipParam(xi_refCharacter);
}

void confirmShipChangeName()
{
	/*
	if (shipIndex== -1) return;
	xi_refcharacter.ship.name = GameInterface.edit_box.str;
	GameInterface.edit_box.str = xi_refcharacter.ship.name;
	SetCurrentNode("SHIP_INFO_TEXT");   */
}

void CheckForRename()
{
	/*if (GetShipRemovable(xi_refCharacter) == true && shipIndex!= -1)
	{
		SetCurrentNode("EDIT_BOX");
	}    */
}

void ShowInfoWindow()
{
	string sCurrentNode = GetCurrentNode();
	string sHeader, sText1, sText2, sText3, sPicture;
	string sGroup, sGroupPicture;
	int iItem;

	sPicture = "-1";
	string sAttributeName;
	int nChooseNum = -1;
	int iShip;
	ref refBaseShip;

	bool  bShowHint = true;

	ref rChr;
	if (bShipyardOnTop)
	{
	    rChr = refNPCShipyard;
	}
	else
	{
		rChr = xi_refCharacter;
	}
	switch (sCurrentNode)
	{
		case "SHIP_BIG_PICTURE":
			if (shipIndex != -1 || bShipyardOnTop)
			{
			    iShip = sti(rChr.ship.type);
			    refBaseShip = GetRealShip(iShip);
				sHeader = XI_ConvertString(refBaseShip.BaseName);
				sText1 = GetConvertStr(refBaseShip.BaseName, "ShipsDescribe.txt");
			}
			else
			{
				sHeader = XI_Convertstring("NoneBoat");
				sText1  = GetConvertStr("NoneBoat2", "ShipsDescribe.txt");
			}
		break;

		case "SHIPS_SCROLL":
			if (shipIndex != -1)
			{
			    iShip = sti(xi_refCharacter.ship.type);
			    refBaseShip = GetRealShip(iShip);
				sHeader = XI_ConvertString(refBaseShip.BaseName);
				sText1 = GetConvertStr(refBaseShip.BaseName, "ShipsDescribe.txt");
				//sText2 = GetRPGText("shipChoose_hint");
			}
			else
			{
				sHeader = XI_Convertstring("NoneBoat");
				sText1  = GetConvertStr("NoneBoat2", "ShipsDescribe.txt");
			}
		break;

		case "MAIN_CHARACTER_PICTURE":
			// отдельная форма
			bShowHint = false;
			ShowRPGHint();
		break;

		case "TABLE_OTHER":
			sHeader = XI_ConvertString(GameInterface.(CurTable).(CurRow).UserData.ID);
		    sText1  = GetConvertStr(GameInterface.(CurTable).(CurRow).UserData.ID, "ShipsDescribe.txt");
		    if (GameInterface.(CurTable).(CurRow).UserData.ID == "CannonType" && sti(rChr.Ship.Cannons.Type) != CANNON_TYPE_NONECANNON)
		    {
		    	ref Cannon = GetCannonByType(sti(rChr.Ship.Cannons.Type));
		    	sText2 = xiStr("MSG_Transfer_3") + XI_ConvertString(GetCannonType(sti(rChr.Ship.Cannons.Type)));
		    	sText2 = sText2 + NewStr() + xiStr("MSG_Transfer_4") + XI_ConvertString("caliber" + GetCannonCaliber(sti(rChr.Ship.Cannons.Type)));
		    	sText2 = sText2 + NewStr() + xiStr("MSG_Transfer_5")  + sti(Cannon.FireRange);
		    	sText2 = sText2 + NewStr() + xiStr("MSG_Transfer_6")  + FloatToString(stf(Cannon.DamageMultiply), 1);
		    	sText2 = sText2 + NewStr() + xiStr("MSG_Transfer_7")  + sti(GetCannonReloadTime(Cannon)) + xiStr("MSG_Transfer_8");
		    	sText2 = sText2 + NewStr() + xiStr("MSG_Transfer_9")  + sti(Cannon.Weight) + xiStr("MSG_Transfer_10");

		    	sGroup = "GOODS";
				sGroupPicture = GetCannonType(sti(rChr.Ship.Cannons.Type)) + "_" + GetCannonCaliber(sti(rChr.Ship.Cannons.Type));

				sText3 = xiStr("MSG_SHP_1");
		    }
		    if (GameInterface.(CurTable).(CurRow).UserData.ID == "Crew" && sti(rChr.ship.type) != SHIP_NOTUSED)
			{
				sText2 = xiStr("MSG_Transfer_11");
				sText2 = sText2 + NewStr() + xiStr("MSG_Transfer_12") + GetMaxCrewQuantity(rChr);
			}
			// процент ремонта
			if (GameInterface.(CurTable).(CurRow).UserData.ID == "Hull" && sti(rChr.ship.type) != SHIP_NOTUSED)
			{
				sText3 = xiStr("Hull") + ": " + FloatToString(GetHullPercent(rChr), 1)  + " %";
			}
			if (GameInterface.(CurTable).(CurRow).UserData.ID == "Sails" && sti(rChr.ship.type) != SHIP_NOTUSED)
			{
				sText3 = xiStr("Sails") + ": " + FloatToString(GetSailPercent(rChr), 1) + " %";
			}
			// трюм
			if (GameInterface.(CurTable).(CurRow).UserData.ID == "Capacity" && sti(rChr.ship.type) != SHIP_NOTUSED)
			{
				sText3 = xiStr("MSG_Transfer_20") + FloatToString((stf(GetCargoLoad(rChr))  /  stf(GetCargoMaxSpace(rChr))) * 100.0, 1)+ " %";
			}
		break;
		case "TABLE_SHIPYARD" :
		    sHeader = XI_Convertstring("Shipyard");
			sText1  = GetConvertStr("Shipyard_hint", "ShipsDescribe.txt");
		break;
	}
	if (bShowHint)
	{
		CreateTooltip("#" + sHeader, sText1, argb(255,255,255,255), sText2, argb(255,255,192,192), sText3, argb(255,192,255,192), "", argb(255,255,255,255), sPicture, sGroup, sGroupPicture, 64, 64);
	}
}

void HideInfoWindow()
{
	CloseTooltip();
	ExitRPGHint();
}

void TableSelectChange()
{
	string sControl = GetEventData();
	iSelected = GetEventData();
    CurTable = sControl;
    CurRow   =  "tr" + (iSelected);
    NullSelectTable("TABLE_OTHER");
    // не тереть скрол на верфи

    // заполнялка
    if (CurTable == "TABLE_SHIPYARD")
	{
        FillShipyardShip(refNPCShipyard, GameInterface.(CurTable).(CurRow).sShipId);
		FillShipParam(refNPCShipyard);
		bShipyardOnTop = true;
		SetButtionsAccess();
	}
}

void ExitRPGHint()
{
	if (sMessageMode == "RPG_Hint")
	{
		XI_WindowShow("RPG_WINDOW", false);
		XI_WindowDisable("RPG_WINDOW", true);
		XI_WindowDisable("MAIN_WINDOW", false);
		sMessageMode = "";
	}
}

void ShowRPGHint()
{
	SetSPECIALMiniTable("RPG_TABLE_SMALLSKILL", xi_refCharacter);
    SetOTHERMiniTable("RPG_TABLE_SMALLOTHER", xi_refCharacter);
    SetFormatedText("RPG_OFFICER_NAME", GetFullName(xi_refCharacter));

	XI_WindowShow("RPG_WINDOW", true);
	XI_WindowDisable("RPG_WINDOW", false);
	XI_WindowDisable("MAIN_WINDOW", true);
	sMessageMode = "RPG_Hint";
}


void NullSelectTable(string sControl)
{
	if (sControl != CurTable)
	{
	    GameInterface.(sControl).select = 0;
	    Table_UpdateWindow(sControl);
	}
}

void ExitMsgMenu()
{
	XI_WindowShow("MSG_WINDOW", false);
	XI_WindowDisable("MSG_WINDOW", true);
	XI_WindowDisable("MAIN_WINDOW", false);

	SetCurrentNode("SHIPS_SCROLL");
	sMessageMode = "";
}

void ShowMsgMenu()
{
	XI_WindowShow("MSG_WINDOW", true);
	XI_WindowDisable("MSG_WINDOW", false);
	XI_WindowDisable("MAIN_WINDOW", true);

	SetCurrentNode("MSG_CANCEL");
}

void ShowOtherClick()
{
	if (GameInterface.(CurTable).(CurRow).UserData.ID == "CannonType")
	{
		ShowCannonsMenu();
	}
//=============================>>>>>>>>>>>>>>>>>>>>>>>>>Philippe
        if (CheckAttribute(&GameInterface, CurTable + "." + CurRow + ".UserData.ID") && GameInterface.(CurTable).(CurRow).UserData.ID == "Sails")
	{
         // Added to pay
           if (sti(pchar.Money) >= 3000)
              {
		wndChangeSails();
              }
	}
//=============================<<<<<<<<<<<<<<<<<<<<<<<<<
}

void ShowCannonsMenu()
{
	XI_WindowShow("CANNONS_WINDOW", true);
	XI_WindowDisable("CANNONS_WINDOW", false);
	XI_WindowDisable("MAIN_WINDOW", true);

	SetCurrentNode("CANNONS_CANCEL");

    DeleteAttribute(&GameInterface, "CANNONS_TABLE.BackUp")
    CannonsMenuRefresh();
}
void CannonsMenuRefresh()
{
	ref rChr;
	if (bShipyardOnTop)
	{
	    rChr = refNPCShipyard;
	}
	else
	{
		rChr = xi_refCharacter;
	}
	int idx = GetCannonGoodsIdxByType(sti(rChr.Ship.Cannons.Type));
	if (idx != -1)
	{
	    SetNewGroupPicture("CANNONS_PIC", "GOODS", Goods[idx].Name);
		SetFormatedText("CANNONS_TEXT", XI_ConvertString(Goods[idx].Name));

		SetFormatedText("CANNONS_QTY_F", its(GetBortCannonsQty(rChr, "cannonf")));
		SetFormatedText("CANNONS_QTY_B", its(GetBortCannonsQty(rChr, "cannonb")));
		SetFormatedText("CANNONS_QTY_R", its(GetBortCannonsQty(rChr, "cannonr")));
		SetFormatedText("CANNONS_QTY_L", its(GetBortCannonsQty(rChr, "cannonl")));
		/// всего GetCannonsNum(xi_refCharacter)
	}
	else
	{
		SetNewGroupPicture("CANNONS_PIC", "GOODS", "");
		SetFormatedText("CANNONS_TEXT", "");
		SetFormatedText("CANNONS_QTY_F", "0");
		SetFormatedText("CANNONS_QTY_B", "0");
		SetFormatedText("CANNONS_QTY_R", "0");
		SetFormatedText("CANNONS_QTY_L", "0");
	}
}
void ExitCannonsMenu()
{
	HideCannonsMenu();
}

void HideCannonsMenu()
{
	XI_WindowShow("CANNONS_WINDOW", false);
	XI_WindowDisable("CANNONS_WINDOW", true);
	XI_WindowDisable("MAIN_WINDOW", false);

	SetCurrentNode("TABLE_OTHER");
	sMessageMode = "";
}

////////////// ценообразование

int GetShipPriceByType(int st)
{
	if(st==SHIP_NOTUSED) return 0;
	ref shref = GetRealShip(st);

	return makeint(shipCostRate * sti(shref.Price));
}

int GetBuyPrice(ref _chr)
{
	float nCommerce = GetSummonSkillFromNameToOld(GetMainCharacter(), SKILL_COMMERCE);

    if(CheckOfficersPerk(pchar,"AdvancedCommerce"))	{ nCommerce += 4; }
	else
	{
		if(CheckOfficersPerk(pchar,"BasicCommerce"))	{ nCommerce += 2; }
	}
	//JA 5/6/11 Add relative cannon cost to ship price
	int iShipPrice = GetShipPriceByType(sti(_chr.Ship.Type)) + CannonRelCost(_chr);
	return makeint(iShipPrice + iShipPrice/(nCommerce*10));

}

int GetSellPrice(ref _chr)
{
	int st = GetCharacterShipType(_chr);
	//JA 5/6/11 Add relative cannon cost to ship price
	

	int price = GetShipPriceByType(st);

	price = makeint(price - 1.5*GetSailRepairCost(st, GetSailDamagePercent(_chr)));
	price = makeint(price - 1.5*GetHullRepairCost(st, GetHullDamagePercent(_chr)));

	ref rRealShip = GetRealShip(st);
	if (sti(rRealShip.Stolen) == true) //проверка на ворованный
	{
		price = makeint(price/3);
	}

	float nCommerce   = GetSummonSkillFromNameToOld(GetMainCharacter(), SKILL_COMMERCE) + 0.001;

	if(CheckOfficersPerk(pchar,"AdvancedCommerce"))	{ nCommerce += 4; }
	else
	{
		if(CheckOfficersPerk(pchar,"BasicCommerce"))	{ nCommerce += 2; }
	}

	price = price - price / (nCommerce*10.5);

	price = price + CannonRelCost(_chr);

	if (price < 0 && sti(_chr.Ship.Type) != SHIP_NOTUSED)
	{
		price = 0;
	}

	return price;
}

int CannonRelCost(ref _chr) 
{
	//Get cost of cannons on board compared to stock ship
	
	int st = GetCharacterShipType(_chr);
	ref rRealShip = GetRealShip(st);
	int iBaseType = sti(rRealShip.basetype);
	ref rBaseShip = &ShipsTypes[iBaseType];
	int iBaseCannonCost = GetCannonsSellCost(sti(rBaseShip.Cannon), sti(rBaseShip.CannonsQuantity));
	int iCurCannonCost =  GetCannonsSellCost(sti(_chr.Ship.Cannons.Type), GetCannonsNum(_chr));

	int iRelCost = iCurCannonCost - iBaseCannonCost;
	
	return iRelCost;
}

int GetCannonsSellCost(int iCannonType, int iCannonNum) 
{
	if (iCannonType == CANNON_TYPE_NONECANNON || iCannonNum == 0) return 0;
	
	int iCannonGood = GetCannonGoodsIdxByType(iCannonType);
	int iStoreID = FindStore(refNPCShipyard.city)
	ref rStore = &Stores[iStoreID];

	return GetStoreGoodsPrice(rStore, iCannonGood, PRICE_TYPE_SELL, pchar, iCannonNum);
}

void FillShipyardTable()
{
    Table_Clear("TABLE_SHIPYARD", false, true, false);

	GameInterface.TABLE_SHIPYARD.hr.td1.str = xiStr("Ship");
	GameInterface.TABLE_SHIPYARD.hr.td1.scale = 0.9;
	GameInterface.TABLE_SHIPYARD.hr.td2.str = xiStr("ShipClass");
	GameInterface.TABLE_SHIPYARD.hr.td2.scale = 0.9;
	GameInterface.TABLE_SHIPYARD.hr.td3.str = xiStr("Cannons");
	GameInterface.TABLE_SHIPYARD.hr.td3.scale = 0.9;
	GameInterface.TABLE_SHIPYARD.hr.td4.str = xiStr("Capacity");
	GameInterface.TABLE_SHIPYARD.hr.td4.scale = 0.9;
	GameInterface.TABLE_SHIPYARD.hr.td5.str = xiStr("Cost");
	GameInterface.TABLE_SHIPYARD.hr.td5.scale = 0.9;
	GameInterface.TABLE_SHIPYARD.select = 0;
	GameInterface.TABLE_SHIPYARD.top = 0;

	aref   arDest, arImt;
	string sAttr;
	int    iNum, i, iShip;
	ref    refBaseShip;
	string sShip;
	string row;

	makearef(arDest, refNPCShipyard.shipyard);
	iNum = GetAttributesNum(arDest);
	for (i = 0; i < iNum; i++)
	{
        row = "tr" + (i+1);

		arImt = GetAttributeN(arDest, i);
		//Log_Info(GetAttributeName(arImt));
		sAttr = GetAttributeName(arImt);
    	FillShipyardShip(refNPCShipyard, sAttr); // скинуть в стандарт корабль из ШипХХ

    	iShip = sti(refNPCShipyard.Ship.Type);
    	refBaseShip = GetRealShip(iShip);
		sShip = refBaseShip.BaseName;
		//
		GameInterface.TABLE_SHIPYARD.(row).sShipId = sAttr;
        GameInterface.TABLE_SHIPYARD.(row).td1.icon.texture = "interfaces\ships\" + sShip + ".tga";
		GameInterface.TABLE_SHIPYARD.(row).td1.icon.uv = "0,0,1,1";
		GameInterface.TABLE_SHIPYARD.(row).td1.icon.width = 46;
    	GameInterface.TABLE_SHIPYARD.(row).td1.icon.height = 46;
    	GameInterface.TABLE_SHIPYARD.(row).td1.icon.offset = "0, 1";
    	GameInterface.TABLE_SHIPYARD.(row).td1.textoffset = "53,0";
		GameInterface.TABLE_SHIPYARD.(row).td1.str = XI_Convertstring(sShip) + "\n\n"+refNPCShipyard.ship.name;
		GameInterface.TABLE_SHIPYARD.(row).td1.align = "left";
		GameInterface.TABLE_SHIPYARD.(row).td1.scale = 0.82;
		GameInterface.TABLE_SHIPYARD.(row).td2.str = refBaseShip.Class;
		GameInterface.TABLE_SHIPYARD.(row).td3.str = sti(refBaseShip.CannonsQuantity);
		GameInterface.TABLE_SHIPYARD.(row).td4.str = GetCargoMaxSpace(refNPCShipyard);
		GameInterface.TABLE_SHIPYARD.(row).td5.str = GetBuyPrice(refNPCShipyard);
		GameInterface.TABLE_SHIPYARD.(row).td5.color = argb(255,255,228,80);
    }

	Table_UpdateWindow("TABLE_SHIPYARD");
}

void SetButtionsAccess()
{
    SetSelectable("BUTTON_REPAIR", false);
    SetSelectable("BUTTON_SELL", true);
    SetSelectable("BUTTON_BUY", true);

    if (bShipyardOnTop)
    {
        SetSelectable("BUTTON_REPAIR", false);
    	SetSelectable("BUTTON_SELL", false);
    	if (shipIndex == -1)// проверка на цену
    	{
    	    if (GetBuyPrice(refNPCShipyard) > sti(pchar.Money) )
    	    {
    	        SetSelectable("BUTTON_BUY", false);
    	    }
   			if (bEmptySlot && sti(pchar.ship.type) == SHIP_NOTUSED)
   			{ // нельзя купить корабль компаньону, если у ГГ нету
   			    SetSelectable("BUTTON_BUY", false);
   			}
    	}
    	else
    	{
    	    if (GetBuyPrice(refNPCShipyard) > (GetSellPrice(xi_refCharacter) + sti(pchar.Money)) )
    	    {
    	        SetSelectable("BUTTON_BUY", false);
    	    }
    	    if (!GetRemovable(xi_refCharacter) || !GetShipRemovable(xi_refCharacter))
    	    {
    	        SetSelectable("BUTTON_BUY", false);
    	    }
    	}
    }
    else
    {
        SetSelectable("BUTTON_BUY", false);

        if (GetHullPercent(xi_refCharacter) < 100 || GetSailPercent(xi_refCharacter) < 100)
        {
            SetSelectable("BUTTON_REPAIR", true);
        }
        if (shipIndex == -1)
        {
            SetSelectable("BUTTON_SELL", false);
            SetSelectable("BUTTON_REPAIR", false);
        }
        else
        {
            if (!GetRemovable(xi_refCharacter) || !GetShipRemovable(xi_refCharacter))
    	    {
    	        SetSelectable("BUTTON_SELL", false);
    	    }
    	    if (xi_refCharacter.id == pchar.id && GetCompanionQuantity(pchar) > 1)
    	    { // нельзя продать корабль ГГ, если есть еще компаньоны
    	        SetSelectable("BUTTON_SELL", false);
    	    }
		}
    }
}

//////////////// назначение капитана  //////////////////////////////////////////////////////////////////////
void ShipChangeCaptan()
{
	FillPassengerScroll();
    SendMessage(&GameInterface,"lsl",MSG_INTERFACE_SCROLL_CHANGE,"PASSENGERSLIST",-1);
    SetCurrentNode("PASSENGERSLIST");
	ProcessFrame();
	SetOfficersSkills();

	XI_WindowShow("OFFICERS_WINDOW", true);
	XI_WindowDisable("OFFICERS_WINDOW", false);
	XI_WindowDisable("MAIN_WINDOW", true);
}

void ExitOfficerMenu()
{
	XI_WindowShow("OFFICERS_WINDOW", false);
	XI_WindowDisable("OFFICERS_WINDOW", true);
	XI_WindowDisable("MAIN_WINDOW", false);

	SetCurrentNode("SHIPS_SCROLL");
}

void AcceptAddOfficer()
{
	string  attributeName2 = "pic"+(nCurScrollOfficerNum+1);
    ref     sld;

    if (checkAttribute(GameInterface, "PASSENGERSLIST."+attributeName2 + ".character"))
    {
		int iChar = sti(GameInterface.PASSENGERSLIST.(attributeName2).character);
        // назначение нового кэпа, возможно, если там уже не наш, те или враг или снят
        sld = GetCharacter(iChar);
		DeleteAttribute(sld, "ship");
		sld.ship.Type = SHIP_NOTUSED;

		// снимем пассажира -->
		CheckForReleaseOfficer(iChar);
		RemovePassenger(pchar, sld);
		// снимем пассажира <--
		SetCompanionIndex(pchar, -1, iChar);

		xi_refCharacter = sld;
		DoBuyShip();
	}
	ExitOfficerMenu();
}

void SetOfficersSkills()
{
	string sCharacter = "pic"+(sti(GameInterface.PASSENGERSLIST.current)+1);
	if (checkAttribute(GameInterface, "PASSENGERSLIST."+sCharacter))
	{
		if (checkAttribute(GameInterface, "PASSENGERSLIST."+sCharacter + ".character"))
		{
			sCharacter = GameInterface.PASSENGERSLIST.(sCharacter).character;
			ref otherchr = &characters[sti(sCharacter)];
	        SetSPECIALMiniTable("TABLE_SMALLSKILL", otherchr);
	        SetOTHERMiniTable("TABLE_SMALLOTHER", otherchr);
	        SetFormatedText("OFFICER_NAME", GetFullName(otherchr));
	        SetSelectable("ACCEPT_ADD_OFFICER", true);
	        return;
        }
	}
    Table_Clear("TABLE_SMALLSKILL", false, true, true);
    Table_Clear("TABLE_SMALLOTHER", false, true, true);
    SetFormatedText("OFFICER_NAME", "");
    SetSelectable("ACCEPT_ADD_OFFICER", false);
}

void FillPassengerScroll()
{
	int i, howWork;
	string faceName;
	string attributeName;
	int _curCharIdx;
	ref _refCurChar;
	bool  ok;

	DeleteAttribute(&GameInterface, "PASSENGERSLIST");

	nCurScrollOfficerNum = -1;
	GameInterface.PASSENGERSLIST.current = 0;

	int nListSize = GetPassengersQuantity(pchar);
	int nListSizeFree = nListSize;

	GameInterface.PASSENGERSLIST.NotUsed = 6;
	GameInterface.PASSENGERSLIST.ListSize = nListSizeFree + 2;

	GameInterface.PASSENGERSLIST.ImagesGroup.t0 = "EMPTYFACE";

	FillFaceList("PASSENGERSLIST.ImagesGroup", pchar, 2); // passengers

	GameInterface.PASSENGERSLIST.BadTex1 = 0;
	GameInterface.PASSENGERSLIST.BadPic1 = "emptyface";
	int m = 0;
	for(i=0; i<nListSize; i++)
	{
		attributeName = "pic" + (m+1);
		_curCharIdx = GetPassenger(pchar,i);

		if (_curCharIdx!=-1)
		{
			ok = CheckAttribute(&characters[_curCharIdx], "prisoned") && sti(characters[_curCharIdx].prisoned) == true;
			if (!ok && GetRemovable(&characters[_curCharIdx]))
			{
				GameInterface.PASSENGERSLIST.(attributeName).character = _curCharIdx;
				GameInterface.PASSENGERSLIST.(attributeName).img1 = GetFacePicName(GetCharacter(_curCharIdx));
				GameInterface.PASSENGERSLIST.(attributeName).tex1 = FindFaceGroupNum("PASSENGERSLIST.ImagesGroup", "FACE128_"+Characters[_curCharIdx].FaceID);
				m++;
			}
		}
	}
	GameInterface.PASSENGERSLIST.ListSize = m + 2; // не знаю зачем, но для совместимости с 'было'
}
// рефреш скилов офа и ГГ, если офа сняли для компаньона
void DelBakSkill()
{
	DelBakSkillAttr(xi_refCharacter);
    ClearCharacterExpRate(xi_refCharacter);
    RefreshCharacterSkillExpRate(xi_refCharacter);
    SetEnergyToCharacter(xi_refCharacter);

    DelBakSkillAttr(pchar);
    ClearCharacterExpRate(pchar);
    RefreshCharacterSkillExpRate(pchar);
    SetEnergyToCharacter(pchar);
}

void ShowMessageInfo()
{
	bool   bBuy;
	int    iMoney;
	string add = "";

	if (bShipyardOnTop) // на стороне верфи (купить)
    {
        bBuy = true;
		if (shipIndex == -1)// проверка на цену
    	{
    	    iMoney = GetBuyPrice(refNPCShipyard);
    	}
    	else
    	{
            iMoney = GetBuyPrice(refNPCShipyard) - GetSellPrice(xi_refCharacter);
    	}
    }
    else  // продать
    {
        bBuy = false;
        iMoney = GetSellPrice(xi_refCharacter);
    }
	SetFormatedText("MSG_WINDOW_CAPTION", XI_ConvertString("Ship"));

	if (bBuy)
	{
		if (iMoney < 0) add = "-";
		SetFormatedText("MSG_WINDOW_TEXT", xiStr("MSG_SHP_2") + add + FindRussianMoneyString(abs(iMoney)) + "?");
		SetSelectable("MSG_OK", true);
		sMessageMode = "ShipBuy";
	}
	else
	{
	    SetFormatedText("MSG_WINDOW_TEXT", xiStr("MSG_SHP_3") + add + FindRussianMoneyString(abs(iMoney)) + "?");
		SetSelectable("MSG_OK", true);
		sMessageMode = "ShipSell";
	}
	ShowMsgMenu();
}

void MessageOk()
{
	switch (sMessageMode)
	{
	    case "ShipSell" :
	        DoSellShip(true);
	        ExitMsgMenu();
	    break;

	    case "ShipBuy" :
	        DoBuyShipMain();
	    break;
	}
}

void DoSellShip(bool _refresh)
{
	ref chref = xi_refCharacter;
	if (shipIndex != -1 && sti(chref.ship.type) != SHIP_NOTUSED)
	{
		int sellPrice = GetSellPrice(chref);

		AddMoneyToCharacter(pchar, sellPrice);
		AddCharacterExpToSkill(pchar, "Commerce", sellPrice / 1600.0);
		Statistic_AddValue(pchar, "SellShip", 1);
		

		DeleteAttribute(chref,"ship.sails");
		DeleteAttribute(chref,"ship.blots");
		DeleteAttribute(chref,"ship.masts");

        // в списке на покупку. -->
        AddShip2Shipyard(chref);
        // в списке на покупку. <--
    	chref.ship.type = SHIP_NOTUSED;
    	// снять кэпа -->
    	if (_refresh)
		{
	    	if (sti(chref.index) != GetMainCharacterIndex())
	    	{
				MoveCrewToFleet(chref);
				RemoveCharacterCompanion(pchar, chref);
				AddPassenger(pchar, chref, false);
				DelBakSkill();
				//navy --> Фигвам, а не халява :)
				if (CheckAttribute(chref, "PGGAi") && CheckAttribute(chref, "PGGAi.OwnShip")) //за корабли данные ГГ, деньги ГГ.
				{
					chref.Payment = true;
					DeleteAttribute(chref, "PGGAi.OwnShip")
					Log_Info(xiStr("MSG_Transfer_21"));
					AddMoneyToCharacter(pchar, -(sellPrice));
				}
				//navy <--
	    	}
	    	else
	    	{
          		pchar.location.from_sea = ""; // нет корабля в порту
	    	}
    		RefreshShipLists();
    	}
	}
}

void MoveCrewToFleet(ref fromChar)
{
	int i, cn, iFreeCrew, iNewCrew;
	ref rComp;
	iNewCrew = GetCrewQuantity(fromChar);
	if (iNewCrew > 0)
	{
		for(i=0; i<COMPANION_MAX && iNewCrew > 0; i++)
		{
			cn = GetCompanionIndex(GetMainCharacter(),i);
			rComp = GetCharacter(cn);

			if(cn>=0 && GetRemovable(&Characters[cn]) && rComp.id != fromChar.id)
			{
				iNewCrew = MoveCrew(rComp, fromChar, iNewCrew);
			}
		}
	}
}


void RefreshShipLists()
{
    xi_refCharacter = pchar;
	FillShipsScroll();
   	SendMessage(&GameInterface,"lsl",MSG_INTERFACE_SCROLL_CHANGE,"SHIPS_SCROLL",-1);
    SetCurrentNode("SHIPS_SCROLL");
	ProcessFrame();

	FillShipyardTable();
	bShipyardOnTop = false;
}

void AddShip2Shipyard(ref _chr)
{
    aref    arTo, arFrom;

	aref   arDest, arImt;
	string sAttr;
	int    iNum, i, iShip;
	ref    refBaseShip;
	string sShip;
	string row;

    iShip = sti(_chr.ship.type);
    RealShips[iShip].StoreShip = true;  // кораль на верфи, трется отдельным методом
    RealShips[iShip].Stolen = 0; // уже не ворованный
	makearef(arDest, refNPCShipyard.shipyard);
	iNum = GetAttributesNum(arDest);
	if (iNum == 0)
	{
	    sAttr = "ship1";
	}
	else
	{
	    arImt = GetAttributeN(arDest, iNum - 1);
	    sAttr = GetAttributeName(arImt) + "2";
	}
	makearef(arTo,   refNPCShipyard.ship);
	makearef(arFrom, _chr.Ship);
	CopyAttributes(arTo, arFrom);
	// нулим экипаж и трюм
	SetCrewQuantity(refNPCShipyard, 0);
	DeleteAttribute(refNPCShipyard, "Ship.Cargo");  //пустой трюм
	SetGoodsInitNull(refNPCShipyard);
    RecalculateCargoLoad(refNPCShipyard);

	FillShipyardShipBack(refNPCShipyard, sAttr);
	// бакапим атрибуты груза и матросов
	DeleteAttribute(refNPCShipyard, "BakCargo");
 	DeleteAttribute(refNPCShipyard, "BakCrew");
 	refNPCShipyard.BakCargo = "";
	makearef(arTo,   refNPCShipyard.BakCargo);
	makearef(arFrom, _chr.Ship.Cargo);
	CopyAttributes(arTo, arFrom);

	refNPCShipyard.BakCrew = "";
	makearef(arTo,   refNPCShipyard.BakCrew);
	makearef(arFrom, _chr.Ship.Crew);
	CopyAttributes(arTo, arFrom);
}

void DoBuyShip()
{
    aref    arTo, arFrom;
	int     iBuyMoney = GetBuyPrice(refNPCShipyard);

 	DeleteAttribute(refNPCShipyard, "BakCargo");
 	DeleteAttribute(refNPCShipyard, "BakCrew");
	DoSellShip(false);
	AddMoneyToCharacter(pchar, -iBuyMoney);

    AddCharacterExpToSkill(pchar, "Commerce", iBuyMoney / 700.0);
    Statistic_AddValue(pchar, "BuyShip", 1);

    FillShipyardShip(refNPCShipyard, sShipId); // то, что покупаем

    makearef(arTo,   xi_refCharacter.ship);
	makearef(arFrom, refNPCShipyard.Ship);
	CopyAttributes(arTo, arFrom);

	DeleteAttribute(refNPCShipyard, "shipyard." + sShipId);

    int iShip = sti(xi_refCharacter.ship.type);
    DeleteAttribute(&RealShips[iShip], "StoreShip"); // можно тереть

	if (CheckAttribute(refNPCShipyard, "BakCargo")) // есть бакап корабля
	{
        DeleteAttribute(xi_refCharacter, "Ship.Cargo");
		DeleteAttribute(xi_refCharacter, "Ship.Crew");

		xi_refCharacter.Ship.Cargo = "";
		makearef(arTo,   xi_refCharacter.Ship.Cargo);
		makearef(arFrom, refNPCShipyard.BakCargo);
		CopyAttributes(arTo, arFrom);

        xi_refCharacter.Ship.Crew = "";
		makearef(arTo,   xi_refCharacter.Ship.Crew);
		makearef(arFrom, refNPCShipyard.BakCrew);
		CopyAttributes(arTo, arFrom);

		AddCharacterCrew(xi_refCharacter, 0); // обрезать перегруз
	    RecalculateCargoLoad(xi_refCharacter);
	}
	if (sti(xi_refCharacter.index) == GetMainCharacterIndex())
	{
  		pchar.location.from_sea = sFrom_sea; // корабль в порту
	}
	DelBakSkill();
	RefreshShipLists();
}

void DoBuyShipMain()
{
	if (CheckAttribute(&GameInterface, CurTable + "." + CurRow + ".sShipId"))
	{
	    sShipId = GameInterface.(CurTable).(CurRow).sShipId;

		if (!bEmptySlot) // был коарбль или ГГ без корабля
		{
		    DoBuyShip();
		    ExitMsgMenu();
		}
		else
		{
		    ExitMsgMenu();
		    ShipChangeCaptan();
		}
	}
}

//////////////////// ремонт ///////////////
void ExitRepairMenu()
{
	XI_WindowShow("REPAIR_WINDOW", false);
	XI_WindowDisable("REPAIR_WINDOW", true);
	XI_WindowDisable("MAIN_WINDOW", false);

	SetCurrentNode("SHIPS_SCROLL");
	sMessageMode = "";
}

void ShowRepairMenu()
{
	XI_WindowShow("REPAIR_WINDOW", true);
	XI_WindowDisable("REPAIR_WINDOW", false);
	XI_WindowDisable("MAIN_WINDOW", true);

    SetRepairData();
	SetCurrentNode("REPAIR_CANCEL");
}

void SetRepairData()
{
	RepairSail = 0;
	RepairHull = 0;
 	RepairStatShow();
}

void RepairMoneyShow()
{
    int st = GetCharacterShipType(xi_refCharacter);
    
	SetFormatedText("REPAIR_WINDOW_TEXT", its(GetSailRepairCost(st, RepairSail) + GetHullRepairCost(st, RepairHull)));
}

void RepairStatShow()
{
    int hp = MakeInt(GetHullPercent(xi_refCharacter));
	int sp = MakeInt(GetSailPercent(xi_refCharacter));
	
	SetFormatedText("REPAIR_QTY_H", (hp+RepairHull) + "%");
	SetFormatedText("REPAIR_QTY_S", (sp+RepairSail) + "%");
	RepairMoneyShow();
}

void ClickRepairArror(string _type, int add)
{
    int st = GetCharacterShipType(xi_refCharacter);
    int i;
    int hp = MakeInt(GetHullPercent(xi_refCharacter));
	int sp = MakeInt(GetSailPercent(xi_refCharacter));
	
	if (_type == "hull")
	{
		if (add > 0)
		{
			if (sti(pchar.Money) >= (GetSailRepairCost(st, RepairSail) + GetHullRepairCost(st, RepairHull + add)))
		    {
		        RepairHull = RepairHull + add;
		    }
		    else
		    {
		        i = sti(pchar.Money) - (GetSailRepairCost(st, RepairSail) + GetHullRepairCost(st, RepairHull));
		        i = i / GetHullRepairCost(st, 1); // на сколько хватит
		        RepairHull = RepairHull + i;
		    }
		    if ((RepairHull + hp) > 100)  RepairHull = 100 - hp;
	    }
	    else
	    {
            RepairHull = RepairHull + add;
			if (RepairHull < 0)  RepairHull = 0;
	    }
	}
	else
	{
	    if (add > 0)
		{
			if (sti(pchar.Money) >= (GetSailRepairCost(st, RepairSail+ add) + GetHullRepairCost(st, RepairHull)))
		    {
		        RepairSail = RepairSail + add;
		    }
		    else
		    {
		        i = sti(pchar.Money) - (GetSailRepairCost(st, RepairSail) + GetHullRepairCost(st, RepairHull));
		        i = i / GetSailRepairCost(st, 1); // на сколько хватит
		        RepairSail = RepairSail + i;
		    }
		    if ((RepairSail+sp) > 100)  RepairSail = 100 - sp;
	    }
	    else
	    {
            RepairSail = RepairSail + add;
			if (RepairSail < 0)  RepairSail = 0;
	    }
	}
	RepairStatShow();
}

void RepairOk()
{
    int st = GetCharacterShipType(xi_refCharacter);
    int hp = MakeInt(GetHullPercent(xi_refCharacter));
	int sp = MakeInt(GetSailPercent(xi_refCharacter));
	float ret;
	
	if (RepairHull > 0)
	{
		timeHull = timeHull + RepairHull * (8-GetCharacterShipClass(xi_refCharacter));
	    AddCharacterExpToSkill(pchar, "Repair", (RepairHull * (7-GetCharacterShipClass(xi_refCharacter)) / 2.5));
		AddMoneyToCharacter(pchar, -GetHullRepairCost(st, RepairHull));

		ret = ProcessHullRepair(xi_refCharacter, stf(RepairHull));
	}
	if (RepairSail > 0)
	{
	  	timeRig = timeRig + RepairSail * (8-GetCharacterShipClass(xi_refCharacter));
	    AddCharacterExpToSkill(pchar, "Repair", (RepairSail * (7-GetCharacterShipClass(xi_refCharacter)) / 3.5));
		AddMoneyToCharacter(pchar,-GetSailRepairCost(st, RepairSail));

		ret = ProcessSailRepair(xi_refCharacter, stf(RepairSail));
	}
	if ((hp + RepairHull) >= 100)
	{
        xi_refCharacter.ship.hp = GetCharacterShipHP(xi_refCharacter);
		DeleteAttribute(xi_refCharacter, "ship.blots");
	}
	if ((sp+RepairSail) >= 100)
	{
		xi_refCharacter.ship.sp = GetCharacterShipSP(xi_refCharacter);
		DeleteAttribute(xi_refCharacter, "ship.sails");
		DeleteAttribute(xi_refCharacter, "ship.masts");
	}
	///
	ExitRepairMenu();
	st = sti(GameInterface.SHIPS_SCROLL.current);
	FillShipsScroll();
	GameInterface.SHIPS_SCROLL.current = st;
	nCurScrollNum = st;
   	SendMessage(&GameInterface,"lsl",MSG_INTERFACE_SCROLL_CHANGE,"SHIPS_SCROLL",-1);
	OnShipScrollChange();
	SetButtionsAccess();
}

void RepairAll()
{
    ClickRepairArror("sail", 100);
    ClickRepairArror("hull", 100);
}

int GetSailDamagePercent(ref _chr)
{
	return 100 - MakeInt(GetSailPercent(_chr));
}

int GetHullDamagePercent(ref _chr)
{
	return 100 - MakeInt(GetHullPercent(_chr));
}

int GetSailRepairCost(int shipType, int repairPercent)
{
	int shipPrice = GetShipPriceByType(shipType);
	if(shipPrice<=0) return 0;
	float scost = (shipPrice*sailCostPercent+99.0)/100.0;
	return makeint((scost*repairPercent+99.0)/100.0);
}

int GetHullRepairCost(int shipType,int repairPercent)
{
	int shipPrice = GetShipPriceByType(shipType);
	if(shipPrice<=0) return 0;
	float scost = (shipPrice*hullCostPercent+99.0)/100.0;
	return makeint((scost*repairPercent+99.0)/100.0);
}

void BuyShipEvent()
{
	if (GetSelectable("BUTTON_BUY"))
	{
	    ShowMessageInfo();
	}
}
/////////////////////////////////////////////////
///
/////////////////////////////////////////////////
void UpdateCharacterInfo()
{

	/*if(!shipsCount || nCurSScrollNum>= shipsCount || nCurSScrollNum>= GetCompanionQuantity(pchar))
	{
		SetFormatedText("SHIP_WINDOW_INFO", " ");

		SetSelectable("REPAIR_BUTTON",   false);
		SetSelectable("SELLSHIP_BUTTON", false);
		SetSelectable("CHANGE_CAPTAIN",  false);
		SetSelectable("BUYSHIP_BUTTON",  DoBuyShip());
	}

	if (nCurSScrollNum == 0)
	{

		SetSelectable("SELLSHIP_BUTTON", false);
	} 
	else 
	{
		SetSelectable("SELLSHIP_BUTTON", DoSellShip(true));
	}
               BLOQUE

	SetNodeUsing("MAIN_CHARACTER_PICTURE", true);*/

	Xi_refCharacter = GetCharacterRefFromScroll(); 

	/*sText = XI_ConvertString("OurMoney") + ": " + FindRussianMoneyString(sti(pchar.money));
	SetFormatedText("MAIN_WINDOW_INFO", sText);
BLOQUE
	string sText;
	SetFormatedText("SHIP_WINDOW_INFO", "");
	SetFormatedText("SHIP_SELL_PRICE", "");*/
	
        string sText;// ajoutй car bloquй plus haut
	if(sti(Xi_refCharacter.ship.type) != SHIP_NOTUSED)
	{
		sText = "HULL_UPGRADE_" + Xi_refCharacter.ship.upgrades.hull;
		SendMessage(&GameInterface,"lslss",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_HULL", 6, sText, "hull");
		
		sText = "SAILS_UPGRADE_" + Xi_refCharacter.ship.upgrades.sails;
		SendMessage(&GameInterface,"lslss",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_SAILS", 6, sText, "sails");
		
		sText = "CANNONS_UPGRADE_" + Xi_refCharacter.ship.upgrades.cannons;
		string sCannonPict = Cannon[sti(Xi_refCharacter.ship.cannons.type)].picture;
		SendMessage(&GameInterface,"lslss",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_CANNONS", 6, sText, sCannonPict);

		int basetype = sti(Xi_refCharacter.ship.type);
		string sShipClassName = ShipsTypes[sti(Realships[basetype].basetype)].name;
		if(sShipClassName == "WarTartane")
		{
			sShipClassName = "Tartane";
		}
		
	/*	sText = XI_ConvertString(sShipClassName);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);

		sText = Realships[basetype].class;
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);

		sText = sti(Xi_refCharacter.ship.hp) + " / " + sti(Realships[basetype].HP);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);

		sText = sti(Xi_refCharacter.ship.sp) + " / " + sti(Realships[basetype].SP);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);

		sText = GetIntactCannonQuantity(Xi_refCharacter) + " / " + Realships[basetype].CannonsQuantity;
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);
		
		sText = XI_ConvertString(Cannon[sti(Xi_refCharacter.ship.cannons.type)].name);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);
BLOQUE
		sText = XI_ConvertString("caliber" + RealShips[basetype].MaxCaliber);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);

		sText = fts(stf(Realships[basetype].SpeedRate), 3);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);
		sText = fts(stf(Realships[basetype].TurnRate), 3);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);


		sText = GetCargoLoad(Xi_refCharacter) + " / " + Realships[basetype].Capacity;
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);

		sText = sti(Xi_refCharacter.ship.crew.quantity) + " / " + sti(Realships[basetype].maxcrew);
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 0,	&sText);*/

		/*sText = XI_ConvertString("SellCost") + "\n" + FindRussianMoneyString(GetSellPrice());
		SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"SHIP_SELL_PRICE", 0, &sText);*/


		int iRealShipType = sti(RealShips[basetype].basetype);
		string shipName = ShipsTypes[iRealShipType].name;
		SetNewPicture("SHIP_PICTURE", "interfaces\ships\" + shipName + ".tga");
		SetNewPicture("CAPTAIN_PICTURE", "interfaces\portraits\64\face_" + Xi_refCharacter.FaceId + ".tga");
	}

/*	SendMessage(&GameInterface,"lsll",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO_TEXT", 1, 0);
	SendMessage(&GameInterface,"lsll",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_INFO", 1, 0);
BLOQUE

	//SetSelectable("REPAIR_BUTTON",   IsEnableRepairShip());
	SetSelectable("SELLSHIP_BUTTON", DoSellShip(true));
	SetSelectable("UPGRADE_BUTTON",   IsEnableUpgradeShip());
	SetSelectable("BUYSHIP_BUTTON",  DoBuyShip());
	//SetSelectable("EXCHANGE_BUTTON",  IsEnableChangeCaptain());*/

	//FillShipStoreScroll();

	/*if(!CheckAttribute(refShipMaster, "shipyard.crew.quantity"))
	{
		refShipMaster.shipyard.crew.quantity = 0;
	}
	sText = XI_ConvertString("FreeCrewLeftInShipyard") + FindRussianPeoplesString(sti(refShipMaster.shipyard.crew.quantity), "Acc");
	SetFormatedText("CREW_STORE_QUANTITY", sText);
	SendMessage( &GameInterface,"lsl",MSG_INTERFACE_MSG_TO_NODE,"CREW_STORE_QUANTITY", 5 );*/
}
string GetCharacterShipHull()
{
	string sResult;
	int iShip = sti(Xi_refCharacter.ship.type);
	sResult = sti(Xi_refCharacter.ship.hp) + "/" + sti(Realships[iShip].hp);
	return sResult;
}

bool IsEnableUpgradeShip()
{
	if(GetShipBaseTypeFromScroll()== SHIP_NOTUSED) 
	{
		return false;
	}

	return true;
}
void ShowUpgradeWindow()
{
	iFullPrice = 0;
	XI_WindowDisable("MAIN_WINDOW", true);
	XI_WindowDisable("STORE_WINDOW", true);
	XI_WindowShow("UPGRADE_WINDOW", true);
	XI_WindowDisable("UPGRADE_WINDOW", false);
}

void HideUpgradeWindow()
{
	XI_WindowShow("UPGRADE_WINDOW", false);
	XI_WindowDisable("UPGRADE_WINDOW", true);
	XI_WindowDisable("MAIN_WINDOW", false);
	XI_WindowDisable("STORE_WINDOW", false);

	SetCurrentNode("SHIPS_SCROLL");
}

void CancelUpgradeShip()
{
	HideUpgradeWindow();
}

void ConfirmUpgradeShip()
{
	//HideUpgradeWindow();	
	
	SetSelectable("UPGRADE_WINDOW_OK_BUTTON", false);
	int iUpgradeStep = sti(GameInterface.UPGRADE_SCROLL.current) + 1;

	//string smode;
	switch(iUpgradeMode)
	{
		case HULL:
			Xi_refCharacter.ship.upgrades.hull = iUpgradeStep;
			DeleteAttribute(Xi_refCharacter, "ship.flow");
			//smode = "hull";
		break;

		case SAILS:
			Xi_refCharacter.ship.upgrades.sails = iUpgradeStep;
			Xi_refCharacter.ship.sp = RealShips[sti(Xi_refCharacter.ship.type)].sp;
			//smode = "sails";
		break;

		case CANNONS:
			Xi_refCharacter.ship.upgrades.cannons = iCannonMaterial;

			string attributeName = "pic" + iUpgradeStep;
			string sCannonType = GameInterface.UPGRADE_SCROLL.(attributeName).text;
			trace("sCannonType = " + sCannonType);
			int iPrevCannonType = sti(Xi_refCharacter.ship.cannons.type);
			int iCannonType = FindCannonByText(sCannonType);
			Xi_refCharacter.ship.cannons.type = iCannonType;
			
			aref arDamages;
			string sBort;
			for (int i =0; i<4; i++)
			{
				switch (i)
				{
					case 0: sBort = "cannonf"; break;
					case 1: sBort = "cannonb"; break;
					case 2: sBort = "cannonl"; break;
					case 3: sBort = "cannonr"; break;
				}
				makearef(arDamages, Xi_refCharacter.Ship.Cannons.Borts.(sBort).damages);

				int iNumRealCannons = GetAttributesNum(arDamages);
			
				int iNumIntactCannons = 0;
				string attr;
				for (int k=0; k<iNumRealCannons; k++)
				{
					attr = "c"+k;
					if(arDamages.(attr) > 0.0)
					{
						arDamages.(attr) = 0.0;
					}
				}
			}
		break;
	}

	//FillUpgradeInfo(smode);

	AddMoneyToCharacter(pchar, -iCost);
	
	//ShipCheckUpgrade(Xi_refCharacter);
	UpdateCharacterInfo();
	UpdateShipUpgrades();

	//ClickRepairOkButton();
}

void PrepareUpgrade()
{
	ShowUpgradeWindow();

	string sText = XI_ConvertString("UpgradeShip");
	SetFormatedText("UPGRADE_WINDOW_CAPTION" , sText);

	int iShip = sti(Xi_refCharacter.ship.type);
	int iBaseType = sti(RealShips[iShip].basetype);
	string sShipName = ShipsTypes[iBaseType].name;
	SetNewPicture("INFO_WINDOW_PICTURE", "interfaces\ships\" + sShipName + ".tga");

	UpdateShipUpgrades();
	
	ClickHullUpgrade();
}

void UpdateShipUpgrades()
{
	int iShip = sti(Xi_refCharacter.ship.type);
	int iBaseType = sti(RealShips[iShip].basetype);
	int iUpgrade;
	string sText;

	SetFormatedText("UPGRADE_WINDOW_HULL_VALUE", "");
	SetFormatedText("UPGRADE_WINDOW_SAILS_VALUE", "");
	SetFormatedText("UPGRADE_WINDOW_CANNONS_VALUE", "");

	sText = makeint(Xi_refCharacter.ship.hp) + "/" + makeint(RealShips[iShip].hp) + " ";
	SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_HULL_VALUE", 0,	&sText);
	iUpgrade = sti(Xi_refCharacter.ship.upgrades.hull);
	sText = XI_ConvertString("hull" + iUpgrade) + " ";
	SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_HULL_VALUE", 0,	&sText);

	sText = makeint(Xi_refCharacter.ship.sp) + " " + makeint(RealShips[iShip].sp) + " ";;
	SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_SAILS_VALUE", 0,	&sText);
	iUpgrade = sti(Xi_refCharacter.ship.upgrades.sails);
	sText = XI_ConvertString("sails" + iUpgrade) + " ";
	SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_SAILS_VALUE", 0,	&sText);

	int iCannonType = sti(Xi_refCharacter.ship.cannons.type);
	string sCannonName = XI_ConvertString(Cannon[iCannonType].name);
	string sCannonType;
	iCannonType = Cannon[iCannonType].type;
	if(iCannonType == CANNON_NAME_CULVERINE)
	{
		sCannonType = XI_ConvertString("CulverineShort");
	}
	else
	{
		sCannonType = XI_ConvertString("Cannon");
	}
	sText = " " + Realships[iShip].CannonsQuantity + " (" + sCannonType + " " + sCannonName + ")";

	//sText = Realships[iShip].CannonsQuantity + " (" + XI_ConvertString(Cannon[sti(Xi_refCharacter.ship.cannons.type)].name) + ")  ";
	SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_CANNONS_VALUE", 0,	&sText);
	iUpgrade = sti(Xi_refCharacter.ship.upgrades.cannons);
	sText = XI_ConvertString("cannons" + iUpgrade) + " ";
	SendMessage(&GameInterface,"lsle",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_CANNONS_VALUE", 0,	&sText);
}

void FillUpgradeInfo(string sMode)
{
	int iUpgrade;
	if(smode == "cannons")
	{
		iUpgrade = iCannonMaterial;
	}
	else
	{
		iUpgrade = sti(GameInterface.UPGRADE_SCROLL.(attributeName).current) + 1;
	}

	string sText = "UpgradeShipInfo" + sMode + iUpgrade;
	sText = XI_ConvertString(sText);

	string sUpgrade = sMode + iUpgrade;
	
	SetFormatedText("UPGRADE_WINDOW_TEXT", "");
	SetFormatedText("UPGRADE_WINDOW_GOLD_TEXT", "");
	
	int iShip = sti(Xi_refCharacter.ship.type);
	if(iShip < SHIP_NOTUSED)
	{
		if(sMode == "cannons")
		{
			string attributeName = "pic" + (sti(GameInterface.UPGRADE_SCROLL.(attributeName).current) + 1);
			string sCannonType = GameInterface.UPGRADE_SCROLL.(attributeName).text;
			trace("sCannonType = " + sCannonType);
			int iPrevCannonType = sti(Xi_refCharacter.ship.cannons.type);
			int iCannonType = FindCannonByText(sCannonType);
			sText = sText + " " + XI_ConvertString(GetCannonType(iCannonType)) + " " + XI_ConvertString(Cannon[iCannonType].name) + ".";
			sText = sText + " " + XI_ConvertString("Fire range") + " " + fts(stf(Cannon[iCannonType].FireRange), 4) + " " + XI_ConvertString("Reload time") + " " + Cannon[iCannonType].ReloadTime + " " + XI_ConvertString("sec.");
			iCost = (sti(ShipUpgrades[FindShipUpgrade(sUpgrade)].cost) * sti(RealShips[iShip].CannonsQuantity));
			iCost = iCost + (sti(Cannon[iCannonType].cost) * sti(RealShips[iShip].CannonsQuantity));
			
			int iRealCannons = sti(Realships[iShip].cannonsquantity);
			int iCurrentCannons = GetIntactCannonQuantity(Xi_refCharacter);

			iCost = iCost - (sti(Cannon[iPrevCannonType].cost) * sti(iCurrentCannons))/2;

			newRepairCannonValue = iRealCannons - iCurrentCannons;

			iCannonsRepairCost = GetCannonsRepairCost(newRepairCannonValue);
			iCost = iCost + iCannonsRepairCost;
			iCannonsRepairCost = 0;
		}
		SetFormatedText("UPGRADE_WINDOW_TEXT", sText);
		if(sMode == "hull")
		{
			int iRealHullHP = sti(Realships[iShip].hp);
			int iCurrentHullHP = sti(Xi_refCharacter.ship.hp);

			int iCheckValue = newRepairHullValue  + iCurrentHullHP;
			
			newRepairHullValue = iRealHullHP - iCurrentHullHP;
			newRepairHullValuePercent = makefloat(iRealHullHP - iCurrentHullHP) * 100.0 / makefloat(iRealHullHP);

			iHullRepairCost = GetHullRepairCost(iShip, makeint(newRepairHullValuePercent));

			iCost =  sti(ShipUpgrades[FindShipUpgrade(sUpgrade)].cost) * sti(RealShips[iShip].HP) / 2;
			iCost = iCost + iHullRepairCost;
			iHullRepairCost = 0;
		}
		if(sMode == "Sails")
		{
			int iRealHullSP = sti(RealShips[iShip].sp);
			int iCurrentHullSP = sti(Xi_refCharacter.ship.sp);
			iCost =  sti(ShipUpgrades[FindShipUpgrade(sUpgrade)].cost) * (7 - sti(RealShips[iShip].Class)) * iRealHullSP;
			newRepairSailValue = iRealHullSP - iCurrentHullSP;
			newRepairSailValuePercent = makefloat(iRealHullSP - iCurrentHullSP) * 100.0 / makefloat(iRealHullSP);

			iSailsRepairCost = GetSailRepairCost(iShip, makeint(newRepairSailValuePercent));
			iCost = iCost + iSailsRepairCost;
			iSailsRepairCost = 0;
		}
		sText = XI_ConvertString("UpgradeCost") + FindRussianMoneyString(iCost);
		SetFormatedText("UPGRADE_WINDOW_GOLD_TEXT", sText);
	}
}

void ClickHullUpgrade()
{
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_HULL", "TABS", "TabSelected");
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_SAILS", "TABS", "TabDeSelected");
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_CANNONS", "TABS", "TabDeSelected");
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_HULL_CAPTION", 8,0,argb(255,255,255,255));
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_SAILS_CAPTION", 8,0,argb(255,196,196,196));
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_CANNONS_CAPTION", 8,0,argb(255,196,196,196));
	FillUpgradeScroll("Hull");
	FillUpgradeInfo("Hull");
	iUpgradeMode = HULL;
	SetNodeUsing("CANNONS_CALIBER", false);
	SetCurrentNode("UPGRADE_SCROLL");
}

void ClickSailsUpgrade()
{
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_HULL", "TABS", "TabDeSelected");
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_SAILS", "TABS", "TabSelected");
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_CANNONS", "TABS", "TabDeSelected");
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_HULL_CAPTION", 8,0,argb(255,196,196,196));
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_SAILS_CAPTION", 8,0,argb(255,255,255,255));
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_CANNONS_CAPTION", 8,0,argb(255,196,196,196));
	FillUpgradeScroll("Sails");
	FillUpgradeInfo("Sails");
	iUpgradeMode = SAILS;
	SetNodeUsing("CANNONS_CALIBER", false);
	SetCurrentNode("UPGRADE_SCROLL");
}

void ClickCannonsUpgrade()
{
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_HULL", "TABS", "TabDeSelected");
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_SAILS", "TABS", "TabDeSelected");
	SetNewGroupPicture("UPGRADE_WINDOW_TAB_CANNONS", "TABS", "TabSelected");
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_HULL_CAPTION", 8,0,argb(255,196,196,196));
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_SAILS_CAPTION", 8,0,argb(255,196,196,196));
	SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"UPGRADE_WINDOW_CANNONS_CAPTION", 8,0,argb(255,255,255,255));
	FillUpgradeScroll("Cannons");
	FillUpgradeInfo("Cannons");
	iUpgradeMode = CANNONS;
	SetNodeUsing("CANNONS_CALIBER", true);
	SetCurrentNode("UPGRADE_SCROLL");
}

void FillUpgradeScroll(string smode)
{
	
	string faceName;
	string attributeName;
	
 	DeleteAttribute(&GameInterface, "UPGRADE_SCROLL");
	
	nCurScrollNum = -1;

	GameInterface.UPGRADE_SCROLL.current = 0;

	
	int nOffSize = 3;
		
	GameInterface.UPGRADE_SCROLL.NotUsed = 1;
	
	GameInterface.UPGRADE_SCROLL.ImagesGroup.t0 = "EMPTYFACE";
	
	FillUpgradesList("UPGRADE_SCROLL.ImagesGroup", smode, iCannonMaterial);
	
	GameInterface.UPGRADE_SCROLL.BadTex1 = 0;
	GameInterface.UPGRADE_SCROLL.BadPic1 = "emptyface";

	
	int m = 0;
	int iCannonsTypeQuantity = 0;
	int iCannonsStep = 0;

	int iMax;
	if(smode == "cannons")
	{
		iMax = CANNON_TYPES_QUANTITY + 1;
		SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"CANNONS_CALIBER", 2, iCannonMaterial, 1);
	}
	else
	{
		iMax = 4;
	}
	
	int k;
	for(int i = 1; i < iMax; i++)
	{
		if(smode == "cannons")
		{
			k = i - 1;
			if(sti(Cannon[k].caliber) > sti(RealShips[sti(Xi_refCharacter.ship.type)].MaxCaliber))
			{
				continue;
			}
			if(k == sti(Xi_refCharacter.ship.cannons.type))
			{
				iCannonsStep = iCannonsTypeQuantity;
			}
			iCannonsTypeQuantity = iCannonsTypeQuantity + 1;
		}
		attributeName = "pic" + (m + 1);
		GameInterface.UPGRADE_SCROLL.(attributeName).text = smode + i;
		if(smode == "cannons")
		{
			GameInterface.UPGRADE_SCROLL.(attributeName).img1 = smode + i;
			GameInterface.UPGRADE_SCROLL.(attributeName).tex1 = FindFaceGroupNum("UPGRADE_SCROLL.ImagesGroup",smode + "_UPGRADE_"+iCannonMaterial);
		}
		else
		{
			GameInterface.UPGRADE_SCROLL.(attributeName).img1 = smode;
			GameInterface.UPGRADE_SCROLL.(attributeName).tex1 = FindFaceGroupNum("UPGRADE_SCROLL.ImagesGroup",smode + "_UPGRADE_"+i);
		}
		
		m++;
	}

	switch(smode)
	{
		case "hull":
			GameInterface.UPGRADE_SCROLL.current = sti(Xi_refCharacter.ship.upgrades.hull)-1;
		break;
		case "sails":
			GameInterface.UPGRADE_SCROLL.current = sti(Xi_refCharacter.ship.upgrades.sails)-1;
		break;
		case "cannons":
			GameInterface.UPGRADE_SCROLL.current = iCannonsStep;
		break;
	}
	
	GameInterface.UPGRADE_SCROLL.ListSize = m;

	SendMessage(&GameInterface,"lsl",MSG_INTERFACE_SCROLL_CHANGE,"UPGRADE_SCROLL",-1);
	
}

bool CheckForUpgrade()
{
	string smode;
	switch(iUpgradeMode)
	{
		case HULL:
			smode = "hull";
		break;
		case SAILS:
			smode = "sails";
		break;
		case CANNONS:
			smode = "cannons";
		break;
	}

	int iCurrUpgradeStep;
	string sCharCannons, sScrollCannons;

	if(smode == "cannons")
	{
		iCurrUpgradeStep = sti(Xi_refCharacter.ship.cannons.type);
		sCharCannons = cannon[iCurrUpgradeStep].picture;
		string attributeName = "pic" + (nCurScrollNum + 1);
		sScrollCannons = GameInterface.UPGRADE_SCROLL.(attributeName).img1;
	}
	else
	{
		iCurrUpgradeStep = sti(Xi_refCharacter.ship.upgrades.(smode)) - 1;
		if(iCurrUpgradeStep == nCurScrollNum)
		{
			return false;
		}
	}
	if(smode == "cannons" && iCannonMaterial == sti(Xi_refCharacter.ship.upgrades.cannons) && sCharCannons == sScrollCannons)
	{
		return false;
	}
	if(iCost > sti(pchar.money) && iCost > 0)
	{
		return false;
	}
	return true;
}

void CannonMaterialChange()
{
	string sNode = GetEventData();
	int iButtonNumber = GetEventData();
	int iCondition = GetEventData();
	
	iCannonMaterial = iButtonNumber;

	FillUpgradeScroll("Cannons");
	FillUpgradeInfo("Cannons");
}
void ShowShipTooltip()
{
	string sNode = GetCurrentNode();
	switch(sNode)
	{
		case "SHIP_SELL_PICTURE":
			LaunchShipToolTip(iShipStoreListIndex);
		break;

		/*case "SHIPS_SCROLL":
			LaunchShipToolTip(sti(characters[GetCharacterIDFromScroll()].ship.type));
		break;*/

		case "UPGRADE_HULL":
			LaunchUpgradesToolTip();
		break;

		case "UPGRADE_SAILS":
			LaunchUpgradesToolTip();
		break;

		case "UPGRADE_CANNONS":
			LaunchUpgradesToolTip();
		break;
	}
}

void LaunchShipToolTip(int iRShipType)
{
	g_bToolTipStarted = true;
	//int iRShipType = sti(chref.ship.type);
	int iBShipType = sti(RealShips[iRShipType].basetype);
	string sHeader = XI_ConvertString(ShipsTypes[iBShipType].Name);
	string sGroupName = "SHIPS_"+ShipsTypes[iBShipType].Name;
	string sShipDescr = XI_ConvertString(ShipsTypes[iBShipType].Name+"_descr");
	string sShipParamString = XI_ConvertString("ShipClass") + ": " + ShipsTypes[iBShipType].class + "\n" +
		XI_ConvertString("Hull") + ": " + sti(RealShips[iRShipType].hp) + "\n" +
		XI_ConvertString("Cannons") + ": " + RealShips[iRShipType].CannonsQuantity + "\n" +
		XI_ConvertString("Speed") + ": " + FloatToString(stf(RealShips[iRShipType].speedrate),2) + "\n" +
		XI_ConvertString("Maneuver") + ": " + FloatToString(stf(RealShips[iRShipType].turnrate),2) + "\n" +
		XI_ConvertString("Capacity") + ": " + RealShips[iRShipType].Capacity + "\n" +
		XI_ConvertString("Max.Crew") + ": " + RealShips[iRShipType].MaxCrew;

	CreateTooltip("#"+sHeader, sShipDescr,argb(255,255,255,255), sShipParamString,argb(255,255,255,255), "",0, "",0, "", sGroupName,"ship", 64,64);
}

void EndTooltip()
{
	if(g_bToolTipStarted == true)
	{
		CloseTooltip();
		g_bToolTipStarted = false;
	}
}

void LaunchUpgradesToolTip()
{
	g_bToolTipStarted = true;

	string sHeader = "";
	string sText1 = "";
	string sText2 = "";
	string sText3 = "";
	string sPicture = "";
	string sGroupPicture = "";
	string sGroup = "";
	
	string sNode = GetCurrentNode();

	switch(sNode)
	{
		case "UPGRADE_HULL":
			sHeader = XI_ConvertString("HullUpgrade");
			sText1 = XI_ConvertString("UpgradeShipInfoHull" + Xi_refCharacter.ship.upgrades.hull);
			
			sGroup = "HULL_UPGRADE_" + Xi_refCharacter.ship.upgrades.hull;
			sGroupPicture = "hull";
		break;
		case "UPGRADE_SAILS":
			sHeader = XI_ConvertString("SailsUpgrade");
			sText1 = XI_ConvertString("UpgradeShipInfoSails" + Xi_refCharacter.ship.upgrades.sails);
			
			sGroup = "SAILS_UPGRADE_" + Xi_refCharacter.ship.upgrades.sails;
			sGroupPicture = "sails";
		break;
		case "UPGRADE_CANNONS":
			sHeader = XI_ConvertString("CannonsUpgrade");
			sText1 = XI_ConvertString("UpgradeShipInfoCannons" + Xi_refCharacter.ship.upgrades.cannons);
			
			int iOurCannonType = sti(Xi_refCharacter.ship.cannons.type);
			sGroupPicture = Cannon[iOurCannonType].picture;
			sGroup = "CANNONS_UPGRADE_" + Xi_refCharacter.ship.upgrades.cannons;

			int iCannonType =  Cannon[sti(Xi_refCharacter.ship.cannons.type)].type;
			if(iCannonType == CANNON_NAME_CULVERINE)
			{
				sText2 = XI_ConvertString("cannon type") + ": " + XI_ConvertString("Culverine");
			}
			if(iCannonType == CANNON_NAME_CANNON)
			{
				sText2 = XI_ConvertString("cannon type") + ": " + XI_ConvertString("Cannon");
			}

			sText2 = sText2 + "\n" + XI_ConvertString("Caliber_info");
			sText2 = sText2 + ": " + XI_ConvertString(Cannon[sti(Xi_refCharacter.ship.cannons.type)].name);
		break;
	}

	CreateTooltip("#" + sHeader, sText1, argb(255,255,255,255), sText2, argb(255,255,255,255), sText3, argb(255,192,255,192), "", argb(255,255,255,255), sPicture, sGroup, sGroupPicture, 64, 64);
}
ref GetCharacterRefFromScroll()
{
	int scrollIndex = nCurSScrollNum + 1;
	if (scrollIndex< 1) scrollIndex = 1;

	string attributeName = "pic" + scrollIndex;


	int cn = GetCompanionIndex(pchar, 0);

	string str = "SHIPS_SCROLL."+attributeName+".companionIndex";

	string sText = "";
	if(CheckAttribute(&GameInterface,str))
	{
		cn = sti(GameInterface.SHIPS_SCROLL.(attributeName).companionIndex);
		sText = characters[cn].ship.name;
		sText = "'" + sText + "'";
		SetFormatedText("MAIN_WINDOW_CAPTION2", sText);
	}

	return &Characters[cn];
}
int GetShipBaseTypeFromScroll()
{
	int scrollIndex = nCurSScrollNum + 1;
	if (scrollIndex< 1) scrollIndex = 1;

	string attributeName = "pic" + scrollIndex;

	int basetype = -1;
	if(CheckAttribute(&GameInterface, "SHIPS_SCROLL." + attributeName + ".companionIndex"))
	{
		int cn = sti(GameInterface.SHIPS_SCROLL.(attributeName).companionIndex);
		cn = sti(Characters[cn].ship.type);

		basetype = sti(RealShips[cn].basetype);
	}
	else
	{
		return SHIP_NOTUSED;
	}

	return basetype;
}
int GetCannonsRepairCost(int iCannonsRepair)
{
	int iCannon = sti(Xi_refCharacter.ship.cannons.type);

	int iCost = sti(cannon[iCannon].cost) * iCannonsRepair;

	iCost = iCost * (sti(Xi_refCharacter.ship.upgrades.cannons));

	float fCommerce = GetSummonSkillFromName(pchar, SKILL_COMMERCE);
	fCommerce = 0.01 * fCommerce;

	iCost = iCost - iCost * fCommerce;

	iCost = iCost -  (iCost * (0.1 * makefloat(iGameArcade)));

	return iCost;
}

//////////////////////////////////////////////////////////////////////////////////
///////// PHILIPPE COULEUR DES VOILES
///////////////////////////////////////////////////////////////////////////////////
void wndChangeSails()
{
	SetChangeSailStartData();
	ShowChangeSailWindow(true);
}
void ChangeSelectScrollImage()
{
	string sNod = GetEventData();
	int nIdx = GetEventData();
	if( sNod=="SHIP_WINDOW_SAILS_COLOR" || sNod=="SHIP_WINDOW_EMBLEME" )
	{
		if( sNod=="SHIP_WINDOW_SAILS_COLOR" ) {
			GameInterface.SHIP_WINDOW_SAILS_COLOR.current = nIdx;
		} else {
			GameInterface.SHIP_WINDOW_EMBLEME.current = nIdx;
		}
		CheckChangeSailStatus();
	}
}
void FillSailsColorScroll()
{
	// fill colors list
	for (int i = 0; i < SAILS_COLOR_QUANTITY; i++)
	{
		string attrName = "pic" + (i + 1);
		GameInterface.SHIP_WINDOW_SAILS_COLOR.(attrName).name1 = SailsColors[i].icon;
	}
	GameInterface.SHIP_WINDOW_SAILS_COLOR.ListSize = SAILS_COLOR_QUANTITY;
	GameInterface.SHIP_WINDOW_SAILS_COLOR.current = 0;
}

void FillEmblemesScroll()
{
	EnumerateIcons("resource\textures\" + sUserSailsPath, "*.tga.tx", "SHIP_WINDOW_EMBLEME", 0);
}

int ScrollGetTexture()
{
	string sName = GetEventData();
	int iPicIndex = GetEventData();
	string sScrollID = GetEventData();
	int iTexture = NFGetTexture(sScrollID, sName);
	Trace("ScrollGetTexture: " + iTexture + ", " + sName);
	
	return iTexture;
}
void CheckChangeSailStatus()
{
	bool bNewValue = true;
	if( CheckAttribute(Xi_refCharacter,"ship.sails.gerald_name") &&
		CheckAttribute(Xi_refCharacter,"ship.sails.color") )
	{
		bNewValue = false;

		int nColor = sti(GameInterface.SHIP_WINDOW_SAILS_COLOR.current);
		int nEmblem = sti(GameInterface.SHIP_WINDOW_EMBLEME.current);

		string sattr = "pic"+(nEmblem+1);
		if( GameInterface.SHIP_WINDOW_EMBLEME.(sattr).name1 != Xi_refCharacter.ship.sails.gerald_name ) {
			bNewValue = true; }
		if( SailsColors[nColor].color != Xi_refCharacter.ship.sails.color ) {
			bNewValue = true; }
	}
	SetSelectable( "CHANGE_SAILS_OK",bNewValue );
}

void SetChangeSailStartData()
{
	int n;

	int nColorIdx = -1;
	int nColor = argb(255,255,255,255);
	if( CheckAttribute(Xi_refCharacter,"ship.sails.color") ) {
		nColor = sti(Xi_refCharacter.ship.sails.color);
	}
	for(n=0; n < SAILS_COLOR_QUANTITY; n++) {
		if( sti(SailsColors[n].color) == nColor ) {
			nColorIdx = n;
			break;
		}
	}

	int nEmblemeIdx = -1;
	string sEmblemeName = "";
	if( CheckAttribute(Xi_refCharacter,"ship.sails.gerald_name") ) {
		sEmblemeName = Xi_refCharacter.ship.sails.gerald_name;
	}
	string stmp;
	for(n=0; n<1000; n++) {
		stmp = "pic" + (n+1);
		if( !CheckAttribute(&GameInterface,"SHIP_WINDOW_EMBLEME."+stmp+".name1") ) {break;}
		if( GameInterface.SHIP_WINDOW_EMBLEME.(stmp).name1 == sEmblemeName ) {
			nEmblemeIdx = n;
			break;
		}
	}

	if( nColorIdx>=0 ) {
		SendMessage(&GameInterface,"lsll",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_SAILS_COLOR", 1,nColorIdx);
	}
	if( nEmblemeIdx>=0 ) {
		SendMessage(&GameInterface,"lsll",MSG_INTERFACE_MSG_TO_NODE,"SHIP_WINDOW_EMBLEME", 1,nEmblemeIdx);
	}

	CheckChangeSailStatus();
}

void ShowChangeSailWindow(bool bShow)
{
	
	if( bShow ) 
	{
		irestoreCode = XI_StoreNodeLocksWithOff();
		//XI_WindowDisable("TABS_WINDOW", true);
		//XI_WindowDisable("GOODS_WINDOW", true);
		//XI_WindowDisable("MAIN_WINDOW", true);
		//XI_WindowDisable("CREW_WINDOW", true);
		//XI_WindowDisable("CAPTAIN_WINDOW", true);
		XI_WindowDisable("CHANGE_SAIL_WINDOW", false);
		XI_WindowShow("CHANGE_SAIL_WINDOW", true);
		SetCurrentNode("CHANGE_SAILS_CANCEL");
	} 
	else 
	{
		//XI_WindowDisable("TABS_WINDOW", false);
		//XI_WindowDisable("GOODS_WINDOW", false);
		//XI_WindowDisable("CREW_WINDOW", true);
		//XI_WindowDisable("CAPTAIN_WINDOW", true);
		//XI_WindowDisable("MAIN_WINDOW", false);
		XI_WindowDisable("CHANGE_SAIL_WINDOW", true);
		XI_WindowShow("CHANGE_SAIL_WINDOW", false);
		SetCurrentNode("MAIN_WINDOW_CHANGE_SAIL");
		XI_RestoreNodeLocks(irestoreCode);
	}
}

void ChangeSails()
{
  
	int nComName = GetEventData();
	string sNodeName = GetEventData();
	if(sNodeName=="CHANGE_SAILS_OK") 
	{
		if( nComName==ACTION_ACTIVATE ||
			nComName==ACTION_MOUSECLICK ) {
				int nColorIdx = sti(GameInterface.SHIP_WINDOW_SAILS_COLOR.current);
				int nGeraldIdx = sti(GameInterface.SHIP_WINDOW_EMBLEME.current);
				if( nColorIdx<0 || nGeraldIdx<0 ) {return;}

				Xi_refCharacter.ship.sails.color = SailsColors[nColorIdx].color;

				string attrName = "pic"+(nGeraldIdx+1);
				Xi_refCharacter.ship.sails.gerald_name = GameInterface.SHIP_WINDOW_EMBLEME.(attrName).name1;
                              AddMoneyToCharacter(pchar, -3000);// Not very expensive lol

				/*SetSelectable( "CHANGE_SAILS_OK", false );
				SetCurrentNode( "CHANGE_SAILS_CANCEL" );
				return;*/
			}
	

	ShowChangeSailWindow(false);
     }
  
}
/// Dernier ajout, avant interface ne s'ouvre pas depuis changement avec interface canons
void ShowSailscolorsMenu()
{
	XI_WindowShow("CHANGE_SAIL_WINDOW", true);
	XI_WindowDisable("CHANGE_SAIL_WINDOW", false);
	XI_WindowDisable("MAIN_WINDOW", true);

	SetCurrentNode("CHANGE_SAIL_CANCEL");
}
void ExitSailscolorsMenu()
{
	HideSailscolorsMenu();
	
	//GetBackupCannons(); // отмена
	OnShipScrollChange();
}

void HideSailscolorsMenu()
{
	XI_WindowShow("CHANGE_SAILS_WINDOW", false);
	XI_WindowDisable("CHANGE_SAILS_WINDOW", true);
	XI_WindowDisable("MAIN_WINDOW", false);

	SetCurrentNode("TABLE_OTHER");//dйbloquй<<==Dernier
	sMessageMode = "";
}