require( "scripts/style.lua" );
DebugOut("ChooseTribe");

ButtonXpage1 = 80;
ButtonXpage2 = 480;

ButtonY = 90;
ButtonYSpace = 90;
kMaxUsersPerPage = 4;

NameButtonGraphics = {
	"buttons/zone_texte_tribu.png",
	"buttons/zone_texte_tribu_over.png",
	"buttons/zone_texte_tribu_over.png",
	"buttons/zone_texte_tribu_over.png"	
};	

NameStyle= {
	flags = kHAlignCenter + kVAlignCenter,
	font = StandardButtonFont,
	graphics = NameButtonGraphics,
	sound = kDefaultButtonSound
};

function AddButtons( N )

	t = { SetStyle(NameStyle) };

	for i = 0,N-1 do
		if( i < N / 2 ) then
			posx=ButtonXpage1;
			j = i;
		else
			posx=ButtonXpage2;
			j = i - ( N / 2 );
		end
		local tribeidx = i;
		table.insert(t,
			Bitmap
			{
				name = "cadre"..i,
				image = "buttons/cadre_tribu.png",
				x=posx,
				y=ButtonY+(ButtonYSpace*j),
				
				SetStyle(NameStyle);
				Button
				{
					name="button"..i,
					x=12,
					y=8,
					command =
						function()
							if( GetTribeName( tribeidx ) == "" ) then
								name = DoModal("scripts/entername.lua");
								if( not( name == nil ) ) then
									play = DoModal("scripts/playverify.lua");
									if( not ( play == nil ) ) then
										CloseWindow( name );
									else
										CreateNewTribe( name );
										Refresh();
									end
								end
							else
								gEnterNameValue = GetTribeName( tribeidx );
								name = DoModal( "scripts/entername.lua" );
								if( not( name == nil ) ) then
									ChangeTribeName( tribeidx, name );
									Refresh();
								end
								gEnterNameValue = "";
							end						
						end,
        
					Text
					{
						name="text",
						x = 0,
						y = 0,
						w = kMax,
						h = kMax,
						flags = kHAlignCenter + kVAlignCenter,
						label="createtribe",
					},
				},
				SetStyle( OptionsValidationButtonStyle );
				Button
				{
					name = "erase"..i,
					label = "erase",
					x = 215,
					y = 14,
        
					command =
						function()
							result = DisplayDialog
							{ 
								"scripts/yesno.lua", 
								body ="deleteconfirm",
								title = "deletetitle" 
							};
							if( result== 'yes' ) then
								DeleteTribe( tribeidx );
								Refresh();
							end
						end
				},
			}
		);	
	end

	return Group(t);
end

MakeDialog
{
	-- Name the modal dialog
	name="chooseplayer",
	Bitmap
	{ 
		image="backgrounds/options",
		x=kCenter,
		y=kCenter,
		
		ChooseTribeWindow
		{
			x = 0, y = 0, w=kMax, h=kMax,
			
			Text
			{
				font = BookAntiquaTitle36Font,
				name = "selectatribe",
				x=110,y=40,w=kMax,h=kMax,
				flags = kHAlignLeft + kVAlignTop,
				label = "selectatribe"
			},

			AddButtons( 2 * kMaxUsersPerPage );
			SetStyle( OptionsCancelButtonStyle );
			Button
			{
				name = "quit",
				label = "quit",
				x = 707,
				y = 450,
				command = 
				function()
					CloseWindow( nil );
				end
			},
			SetStyle( OptionsValidationButtonStyle );
		}
	}
}
