#include "maps\export.lgc"
#include "maps\table.lgc"
#include "maps\common_options.lgc"


#ifndef COMMON_STATISTICS_H
    #include "maps\common_statistics.lgc"
#endif

#ifndef COMMON_FAME_H
	#include "maps\common_fame.lgc"
#endif

#ifndef COMMON_MAP_H
	#include "maps\common_map.lgc"
#endif

#ifndef UTIL_USERS_H
	#include "maps\util_users.lgc"
#endif


//for MenuState
#define MENU_PLAY     0
#define MENU_CONTINUE 1
#define MENU_OPTIONS  2
#define MENU_FAME     3
#define MENU_CREDITS  4
#define MENU_EXIT     5
#define MENU_MAIN     10
#define MENU_USERS    6
#define MENU_MAP      7

//#define MENU_COMPAIGN 7
//#define MENU_SURVIVE  8
#define MENU_LOAD     11

int MenuState = MENU_MAIN;//тип меню 0-Play,1-Options,2-FameHall,3-Credits,4-Quit,5-BaseMenu
int StartEffectTime = 0;//время начала видео эффекта
static int    EnterNameOn=0;
static string PlayerName;
static string OldName;
static string SaveName[MAX_SAVE];
static int    AddOnSlide = 0;
static int    DifficultyLevel = 1;
static string DifficultyName[3];
static int    DifficultyText = 0;

ChangeMenuState(int new_menu_type)
{
	MenuState = new_menu_type;
//	Effect(EFF_FADE,0,0,FADE_GAME_TIME);
	StartEffectTime = GetTime();
}

LoadPlayer(string name)
{
//  SetReg(GetDefaultRegPath(),"LevelNumber",GetReg(load_path,"LevelNumber",1));
//  ReloadVidAndSetVidParameters();
}

//перегрузка всех VID т.к. в процессе предыдущих игр они могли поменяться
//ResetGameParameters()
//{
//}


//---------------------------------------------------------------------------------------
MMUserTact()
{
	int spr = MenuFind(3, 90);
	if(!spr)
		return;
	//
	string str = "";
	int CurUser = Call_v(EXT_GetCurUserG);
	if(CurUser >= 0)
		str += Call_i(EXT_GetUsrNameG, CurUser);
    if ( MenuState!=MENU_MAIN )
        str = "<Font=9> " + str;
	Action(spr, ACT_SET_TEXT, &str);
    if ( MenuState!=MENU_MAIN )
        return;

	//
	int x = ToScreenX(GetInputX());
	int y = ToScreenY(GetInputY());
	spr = MenuFind(712);
	if(spr)
	{
		int sprX = ToScreenX(GetX(spr));
		int sprY = ToScreenY(GetY(spr), GetZ(spr));
		//
		if( x >= sprX - 70 && x <= sprX + 70 && y >= sprY - 40 && y <= sprY + 40 )
		{
			Action(spr, ACT_CHANGE_DIRECTION, 100);
			if(GetInputState()&(INPUT_LCLICK|INPUT_RCLICK))
				ChangeMenuState(MENU_USERS);
		}
		else
			Action(spr, ACT_CHANGE_DIRECTION, 0);
	}
}


//---------------------------------------------------------------------------------------
main()
{
  int menu,i;
  iff( 1 )
  {
    Effect(EFF_FADE_OUT,0,0,FADE_GAME_TIME);
    SetCursor(CURSOR_NORMAL);
    SetMusicVolume( GetValI("MusicVolume",70) );
    SetSoundVolume( GetValI("SoundVolume",100) );
    MouseSensitivity = GetValI("MouseSensitivity",50);
    if( GetGlobValI("LastRecPos",-1) != -1 )
      ChangeMenuState(MENU_FAME);
    else
      ChangeMenuState(MENU_MAIN);
    SetVidData(705,VID_GAMMA+1,0x3f3f3f);
    PlayMusicFile(MUSIC_MENU);
    SetValI("WasFlyLevel", 0);
/*    for( i = 0; i < MAX_SAVE; i++ )
    {
      SaveName[i] = GetReg( GetDefaultRegPath(),"SaveName"+itoa(i),"" );
      if( SaveName[i]=="" )
        SaveName[i] = GetString("menu","Empty");
//      else
//        SaveName[i] = GetString("menu","Name") + SaveName[i] + " " + GetString("menu","Level") + itoa(GetReg(GetDefaultRegPath() + "\\"+SaveName[i],"LevelNumber",1));
    }*/
  }
  //
  if(MenuState != MENU_USERS)
  {
	if(Call_v(EXT_GetCurUserG) < 0)
	{
		ChangeMenuState(MENU_USERS);
		iff(1)	//самый первый раз показываем без кнопки Cancel - обычно это при первом запуске
			ShowUserNew(true);
		else
			ShowUserNew(false);
	}
	//else
	//if(GetKey()=='c')
	//	ChangeMenuState(MENU_USERS);
  }
  //
  if ( !StartEffectTime && MenuLClick() && MenuNVidUnderCursor()==705 && MenuState != MENU_USERS)
  {
    if ( GetDirection(MenuLClick()) == 0 && MenuState != MENU_PLAY )
      ChangeMenuState(MENU_PLAY);
    else if ( GetDirection(MenuLClick()) == 128 && MenuState != MENU_EXIT )
      ChangeMenuState(MENU_EXIT);
    else if ( GetDirection(MenuLClick()) == 51 && MenuState != MENU_OPTIONS )
      ChangeMenuState(MENU_OPTIONS);
    else if ( GetDirection(MenuLClick()) == 76 && MenuState != MENU_FAME )
      ChangeMenuState(MENU_FAME);
    else if ( GetDirection(MenuLClick()) == 102 && MenuState != MENU_CREDITS )
      ChangeMenuState(MENU_CREDITS);
    return;
  }

  MMUserTact();

  if(MenuState == MENU_USERS)
  {
    if(UsersMenuTact())
      ChangeMenuState(MENU_MAIN);
  }
  else
  if( MenuState==MENU_MAIN )//basemenu
  {
    if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& (GetTime()-StartEffectTime) > FADE_GAME_TIME/2 )
    {
      StartEffectTime = 0;
      MenuRelease();
      MenuLoad("maps\\mainmenu.men");
      MMUserTact();
/*      if( GetReg( GetDefaultRegPath(),"SaveLevel0","" )=="" )//for not demo
//      if( 1 )// for demo
      {
        MenuAction(705,MENU_CONTINUE,ACT_SET_ARMY,1);
        MenuAction(705,MENU_CONTINUE,ANI_MENUDISABLE);
      }*/
    }
/*    if( MenuLClick() && MenuNVidUnderCursor()==705 )
    {
      // не переходим к CONTINUE если save нет
      if( MenuNDirUnderCursor()!=MENU_CONTINUE || GetReg( GetDefaultRegPath(),"SaveLevel0","" )!="" )
        ChangeMenuState(MenuNDirUnderCursor());
    }*/
    if ( GetKey()==' ' || GetKey()==13 )
      ChangeMenuState(MENU_PLAY);
    else if ( GetKey()==27 )
      ChangeMenuState(MENU_EXIT);
  }
  else if( MenuState==MENU_CONTINUE )//Continue
  {
    /*if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& GetEffectState(EFF_FADE) > 45 )
    {
      StartEffectTime = 0;
      //ResetGameParameters();
      Load("maps\\level_0" + itoa(GetMaxLevel()) + ".map");
    }*/
/*    if( StartEffectTime && GetEffectState(EFF_FADE) > 45 )
    {
      StartEffectTime = 0;
      MenuRelease();
      MenuLoad("maps\\load.men");
      for( i = 0; i < MAX_SAVE; i++ )
        if( GetReg( GetDefaultRegPath(),"SaveName"+itoa(i),"" )=="" )
          MenuAction(705,i,ANI_MENUDISABLE);
    }
    if( GetKey()==VK_ESCAPE )
      ChangeMenuState(MENU_MAIN);
    else if( MenuLClick() && MenuNVidUnderCursor()==705 )
      if( MenuNDirUnderCursor()==9 )
        ChangeMenuState(MENU_MAIN);
      else if( GetReg( GetDefaultRegPath(),"SaveName"+itoa(MenuNDirUnderCursor()),"" )!="" )
      {
        LoadPlayer(GetReg( GetDefaultRegPath(),"SaveName"+itoa(MenuNDirUnderCursor()),"" ));
        ChangeMenuState(MENU_LOAD);
      }*/
  }
/*  else if( MenuState==MENU_PLAY )//Play
  {
    string text;
    if( StartEffectTime && GetEffectState(EFF_FADE) > 45 )
    {
      StartEffectTime = 0;
      PlayerName = GetReg(GetDefaultRegPath(),"PlayerName",GetString("menu","DefaultName"));
      DifficultyLevel = GetReg(GetDefaultRegPath(),"DifficultyLevel",1);
      MenuRelease();
      MenuLoad("maps\\Play.men");
      DifficultyName[0] =  "Easy";
      DifficultyName[1] =  "Normal";
      DifficultyName[2] =  "Hard";
      int butt;
      butt = MenuFind(717);
      DifficultyText = CreateText(3, ToScreenX(GetX(butt)), ToScreenY(GetY(butt)) - 1, GetZ(butt) + 1, GetString("menu", DifficultyName[DifficultyLevel]), BEH_CENTER);
    }
    if( MenuLClick() )
      if( MenuNVidUnderCursor()==716 )
        if( MenuNDirUnderCursor()==0 )
        {// стрелка влево для уровня сложности
          if ( DifficultyLevel ) DifficultyLevel--;
          text = GetString("menu", DifficultyName[DifficultyLevel]);
          Action(DifficultyText, ACT_SET_TEXT, &text);
        }
        else
        {// стрелка вправо для уровня сложности
          if ( DifficultyLevel < 2 ) DifficultyLevel++;
          text = GetString("menu", DifficultyName[DifficultyLevel]);
          Action(DifficultyText, ACT_SET_TEXT, &text);
        }
      else if( MenuNVidUnderCursor()==717 )
      {// смена уровня сложности
          if ( DifficultyLevel < 2 ) DifficultyLevel++;
          else                       DifficultyLevel = 0;
          text = GetString("menu", DifficultyName[DifficultyLevel]);
          Action(DifficultyText, ACT_SET_TEXT, &text);
      }
      else if( MenuNVidUnderCursor()==705 )
      {
        SetReg(GetDefaultRegPath(),"DifficultyLevel",DifficultyLevel);
        if( MenuNDirUnderCursor()==0 )
          ChangeMenuState(MENU_COMPAIGN);
      }
      else if( MenuNVidUnderCursor()==708 && !EnterNameOn )//PlayerName
      {
        EnterNameOn = 1;
        OldName = PlayerName;
        if( PlayerName==GetString("menu","DefaultName") )
          PlayerName = "";
        PlayerName += "_";
      }
    if( EnterNameOn )
    {// Ввод имени игрока в процессе
      if( GetKey()==VK_BACK && strlen(PlayerName) > 1 )
      {
        PlayerName[strlen(PlayerName)-2] = '_';
        PlayerName[strlen(PlayerName)-1] = 0;
      }
      else if( GetKey()==VK_RETURN || (MenuLClick() && MenuNVidUnderCursor()!=708) )
      {
        EnterNameOn = 0;
        PlayerName[strlen(PlayerName)-1] = 0;//убираем '_'
      }
      else if( GetKey()==VK_ESCAPE )
      {
        EnterNameOn = 0;
        PlayerName = OldName;
      }
      else if( strlen(PlayerName) < 11 && GetKey() >= 'A' && GetKey() <= 'Z' )
      {
        PlayerName[strlen(PlayerName)-1] = 0;//убираем '_'
        PlayerName += Printf("%c_",GetKey());
      }
      else if( strlen(PlayerName) < 11 && GetKey() >= 'a' && GetKey() <= 'z' )
      {
        PlayerName[strlen(PlayerName)-1] = 0;//убираем '_'
        PlayerName += Printf("%c_",GetKey()-('a'-'A'));
      }
      else if( strlen(PlayerName) < 11 && GetKey() >= '0' && GetKey() <= '9' )
      {
        PlayerName[strlen(PlayerName)-1] = 0;//убираем '_'
        PlayerName += Printf("%c_",GetKey());
      }
      else if( strlen(PlayerName) < 11 && GetKey()=='_' )
      {
        PlayerName[strlen(PlayerName)-1] = 0;//убираем '_'
        PlayerName += Printf("%c_",GetKey());
      }
      else if( GetKey() && GetKey() < 255 )
        PlaySFX(46);//нажата неверная клавиша
    }
    else if( GetKey()==VK_ESCAPE )
      ChangeMenuState(MENU_MAIN);
    else if( GetKey()==' ' || GetKey()==VK_RETURN )
      ChangeMenuState(MENU_COMPAIGN);
  }*/
  else if( MenuState==MENU_OPTIONS )//Options
  {
    if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& GetEffectState(EFF_FADE) > 45 )
    {
      StartEffectTime = 0;
      MenuRelease();
      CreateOptionsMenu("maps\\options.men");
//      Destroy(MenuFind(705, 1));// убираем кнопку mainmenu
//      Destroy(MenuFind(3, 1));
    }
    if ( GetKey()==27 || GetKey()==' '|| GetKey() == 13
         || (MenuLClick() && MenuNVidUnderCursor()==704 && GetDirection(MenuLClick()) == 0) )
        ChangeMenuState(MENU_MAIN);
    TactOptionsMenu();
  }
  else if( MenuState==MENU_FAME )//Hall of Fame
  {
    if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& GetEffectState(EFF_FADE) > 45 )
    {
      StartEffectTime = 0;
      MenuRelease();
      DrawFame();
    }
    ProcessStatistics();
    bool bCanClose = FameTact();
    if ( GetKey()// || (GetInputState()&(INPUT_LCLICK|INPUT_RCLICK))
         || (MenuLClick() && MenuNVidUnderCursor()==704 && GetDirection(MenuLClick()) == 79) )
	{
	  if(bCanClose)
      	ChangeMenuState(MENU_MAIN);
	}
  }
  else if( MenuState==MENU_CREDITS )//Credits
  {
    if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& GetEffectState(EFF_FADE) > 44 )
    {
      StartEffectTime = 0;
      MenuRelease();
      MenuLoad("maps\\credits.men");
      MMUserTact();
    }
    if ( GetKey()// || (GetInputState()&(INPUT_LCLICK|INPUT_RCLICK))
         || (MenuLClick() && MenuNVidUnderCursor()==704 && GetDirection(MenuLClick()) == 0) )
      ChangeMenuState(MENU_MAIN);
  }
  else if( MenuState==MENU_EXIT )//Quit
  {
    if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& GetEffectState(EFF_FADE) > 45 )
    {
      StartEffectTime = 0;
      MenuRelease();
      MenuLoad("maps\\quit.men");
      MMUserTact();
    }
    if ( GetKey()==27
         || (MenuLClick() && MenuNVidUnderCursor()==704 && GetDirection(MenuLClick()) == 32) )
        ChangeMenuState(MENU_MAIN);
    if ( GetKey()==' ' || GetKey() == 13
         || (MenuLClick() && MenuNVidUnderCursor()==704 && GetDirection(MenuLClick()) == 0) )
	{
		if(!DEMO_VERSION)
	        Exit();
		else
		{
			SetGlobValI("SlideFromMainMenu",1);
			Load("maps\\slide.map");
		}
	}
  }
  else if( MenuState==MENU_PLAY )//PLAY
  {
  	bool bContinue = false;
  	bool bNewGame = false;
	if(GetValI("MaxLevel", 0) == 0)
	{
		//если пользователь только что создан
		bContinue = true;
		SetValI("WasFlyLevel", 1);	//Бир сказал на New Game тоже мигать
	}
	else
	if(GetValI("GameIsNew") || GetValI("SaveLevel0")==10 || GetValI("WasGameOver"))
	{
		//если пользователь нажал new game, а потом вырубил игру - надо помнить
		//или если всю игру прошел
		bNewGame = true;
	}
	else
	{
	    if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& GetEffectState(EFF_FADE) > 45 )
	    {
			StartEffectTime = 0;
			MenuRelease();
			MenuLoad("maps\\start_new.men");
			MMUserTact();
		}
	    if ( GetKey() == 27
    	     || (MenuLClick() && MenuNVidUnderCursor()==739) )
	      ChangeMenuState(MENU_MAIN);
		else
	    if ( GetKey() == ' '
    	     || (MenuLClick() && MenuNVidUnderCursor()==704 && GetDirection(MenuLClick()) == 0) )
		{
			bContinue = true;
		}
		if ( MenuLClick() && MenuNVidUnderCursor()==704 && GetDirection(MenuLClick()) == 32 )
		{
			bNewGame = true;
		}
	}
	if(bContinue)
	{
		gbMapImmediateExit = 1;
		//
		if(DEMO_VERSION && GetMaxLevelEx(true, false) > MAX_LEVEL_NUM)
		{
			SetGlobValI("SlideFromMainMenu",0);
			Load("maps\\slide.map");
		}
		else
			ChangeMenuState(MENU_MAP);
	}
	else
	if(bNewGame)
	{
		SetValI("WasFlyLevel", 1);	//Бир сказал на New Game тоже мигать
		gbMapImmediateExit = 0;
		ClearDataForNewGame();
		ChangeMenuState(MENU_MAP);
	}
  }
  else if( MenuState==MENU_MAP )
  {
    if( StartEffectTime && (GetTime() - StartEffectTime) > 100 )//&& GetEffectState(EFF_FADE) > 45 )
    {
      StartEffectTime = 0;
      MenuRelease();
      ShowMap(true);
    }
    if(MapTact())
    {
    	HideMap();
    	ChangeMenuState(MENU_MAIN);
	}
  }
  MMUserTact();
}

//
GameBarTact()
{
}

